Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

An identity hub: a Convex app that mounts `@samebase/identity-broker`. See README.md.

- `convex/broker.ts` is the hub: connectors `google` and `github`, the registration policy (who may
register comes from `HUB_OWNERS`, parsed in `convex/owners.ts`), and the admin functions.
`convex/convex.config.ts` declares every deployment variable; `convex/http.ts` mounts the routes;
`convex/crons.ts` runs the cleanup.
- `convex/broker.ts` is the hub (`convexHub` of `@samebase/identity-broker/convex`): connectors
`google` and `github`, and the GitHub registration layer with the moderation API (who may register
comes from `HUB_OWNERS`, parsed in `convex/owners.ts`). `convex/convex.config.ts` declares every
deployment variable; `convex/http.ts` mounts the routes; `convex/crons.ts` runs the cleanup.
- Every value that differs between hubs is a GitHub variable or secret that `alchemy.run.ts` hands
to the deployment. Keep it that way: a copy of this repository changes settings, not code.
- `alchemy.run.ts` creates the Convex project and its production deployment and never adopts one
(`adopt(false)` on both). Without the four client values it pushes nothing.
- `scripts/init-keys.ts` creates `IDENTITY_BROKER_KEYS` once, by hand; `scripts/check-keys.ts`
checks it before every push and never creates it.
- `scripts/init-keys.ts` creates `IDENTITY_BROKER_KEYS` once, by hand; no push creates it, and a
push fails while it is missing (`convex/convex.config.ts` declares it required).
- Never use `npx convex import --replace-all` on a hub: it deletes the rows of the components.
- Never use the U+2014 em dash character. No `any`, no type assertions except `as const`.
- `pnpm install`, then `pnpm run check`. `convex/_generated` is committed; a push refreshes it.
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,10 @@ and needs the new callbacks.

- **Pause every app:** set `APPS_PAUSED=true` on the deployment (Convex dashboard, Environment
Variables). Remove it to resume.
- **List and delete:** `npx convex run --deployment <deployment> broker:listApps`, then
`broker:listClients '{"appId":"..."}'`, `broker:deleteClient '{"clientId":"..."}'`,
`broker:deleteApp '{"appId":"..."}'`.
- **List and delete clients:** `GET <issuer>/moderation/clients` lists the newest clients, or with
`?owner=<numeric id>` those of one GitHub account;
`DELETE <issuer>/moderation/clients/<client id>` deletes one. Both take the moderation key, as
below.
- **Block a repository or an owner** at once, whatever `HUB_OWNERS` says:

```sh
Expand All @@ -161,7 +162,7 @@ and needs the new callbacks.

`"kind":"owner"` blocks every repository of an account, and `"action":"unblock"` lifts a block.
The other endpoints are in the broker's
[moderation API](https://github.com/samebase/samebase/blob/main/packages/identity-broker/src/client/moderation.ts).
[moderation API](https://github.com/samebase/samebase/blob/main/packages/identity-broker/README.md#moderation).

- A daily cron removes expired requests, old sign-in records, and preview and development clients
that no deploy renewed for 14 days. A production client stays until you delete it.
Expand All @@ -175,7 +176,9 @@ and needs the new callbacks.

Renovate opens a pull request when a new broker or alchemy-convex version is out. Read the
[broker's changelog](https://github.com/samebase/samebase/blob/main/packages/identity-broker/CHANGELOG.md)
before you merge: a release that changes stored data says what to do.
before you merge: a release that changes stored data says what to do. After the first push of
0.37.0, the old component `identityBroker` is unmounted; its rows stay in the deployment, and the
Convex dashboard can delete them.

## What the hub holds

Expand Down
4 changes: 2 additions & 2 deletions alchemy.run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ export default Alchemy.Stack(
const deployment = yield* Convex.Deployment("Deployment", {
project,
type: "prod",
// The push is the `deploy` package script, which checks the key set first. The functions,
// package.json, and the lockfile are always hashed.
// The push is the `deploy` package script. The functions, package.json, and the lockfile
// are always hashed.
source: {
path: "./convex",
command: ["node", "--run", "deploy"],
Expand Down
2 changes: 1 addition & 1 deletion convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,5 @@ export declare const internal: FilterApi<
>;

export declare const components: {
identityBroker: import("@samebase/identity-broker/_generated/component.js").ComponentApi<"identityBroker">;
identityHub: import("@samebase/identity-broker/_generated/component.js").ComponentApi<"identityHub">;
};
93 changes: 40 additions & 53 deletions convex/broker.ts
Original file line number Diff line number Diff line change
@@ -1,61 +1,48 @@
import { defineIdentityBroker, github, google } from "@samebase/identity-broker";
import { github, hubSettings } from "@samebase/identity-broker";
import { convexHub } from "@samebase/identity-broker/convex";
import { moderation } from "@samebase/identity-broker/moderation";
import { Config } from "effect";
import { components } from "./_generated/api";
import { env } from "./_generated/server";
import { mayRegister, parseOwners } from "./owners";
import { parseOwners } from "./owners";

// The whole hub. Every value that differs between hubs is a deployment variable, which the stack
// (alchemy.run.ts) sets from the repository's GitHub variables and secrets, so this file is the
// same in every copy. `http.ts` mounts the routes, `crons.ts` runs the cleanup, and
// `convex.config.ts` declares the variables.
// `convex.config.ts` declares the variables. The signing keys are IDENTITY_BROKER_KEYS.

/**
* The deployment's own convex.site URL until ISSUER names a custom domain. Every app names the
* issuer, so ISSUER is set before the first app registers (README, Custom domain).
*/
export const issuer = env.ISSUER ?? env.CONVEX_SITE_URL;
export const hub = convexHub(
components.identityHub,
hubSettings({
// The deployment's own convex.site URL until ISSUER names a custom domain. Every app names the
// issuer, so ISSUER is set before the first app registers (README, Custom domain).
issuer: env.ISSUER ?? env.CONVEX_SITE_URL,
// One Google OAuth client and one GitHub OAuth App, with the callbacks
// `<issuer>/connectors/google/callback` and `<issuer>/connectors/github/callback`. A user's
// `sub` is the provider's own id, `google:<id>` or `github:<id>`, the same at every hub. Each
// sign-in shows the provider's account screen.
connectors: {
google: {
clientId: Config.Redacted("GOOGLE_CLIENT_ID"),
clientSecret: Config.Redacted("GOOGLE_CLIENT_SECRET"),
},
github: {
clientId: Config.Redacted("AUTH_GITHUB_CLIENT_ID"),
clientSecret: Config.Redacted("AUTH_GITHUB_CLIENT_SECRET"),
},
},
service: { name: env.HUB_NAME, terms: env.HUB_TERMS_URL, privacy: env.HUB_PRIVACY_URL },
}),
// `POST /register` creates every client. A repository of an allowed owner gets both connectors;
// any other gets none, unless the moderation API granted its repository a connector.
github(parseOwners(env.HUB_OWNERS), {
moderation: moderation({ key: Config.Redacted("IDENTITY_HUB_MODERATION_KEY") }),
// The emergency brake, set by hand on the deployment: only `true` pauses every app.
paused: Config.String("APPS_PAUSED").pipe(
Config.map((value) => value === "true"),
Config.withDefault(false),
),
}),
);

const owners = parseOwners(env.HUB_OWNERS);

export const broker = defineIdentityBroker({
component: components.identityBroker,
issuer,
keys: () => env.IDENTITY_BROKER_KEYS,
// One Google OAuth client and one GitHub OAuth App, with the callbacks
// `<issuer>/connectors/google/callback` and `<issuer>/connectors/github/callback`. A user's `sub`
// is the provider's own id, `google:<id>` or `github:<id>`, the same at every hub. Each sign-in
// shows the provider's account screen, so one app of this hub never passes a user to another
// with no click.
connectors: [
google({
clientId: () => env.GOOGLE_CLIENT_ID,
clientSecret: () => env.GOOGLE_CLIENT_SECRET,
selectAccount: true,
}),
github({
clientId: () => env.AUTH_GITHUB_CLIENT_ID,
clientSecret: () => env.AUTH_GITHUB_CLIENT_SECRET,
selectAccount: true,
}),
],
// `POST /register` creates every client; `/moderation/*` answers the holder of the moderation
// key.
registration: {
name: env.HUB_NAME,
terms: env.HUB_TERMS_URL,
privacy: env.HUB_PRIVACY_URL,
moderationKey: () => env.IDENTITY_HUB_MODERATION_KEY,
policy: (registration) => ({
// Both connectors for a repository of an allowed owner. Any other gets none, so its
// registration is refused, unless the moderation API granted its repository a connector.
connectors: mayRegister(owners, registration.ownerId) ? ["google", "github"] : [],
resources: [],
// The emergency brake, set by hand on the deployment: `true` pauses every app.
paused: env.APPS_PAUSED === "true",
}),
},
});

// Administration with `npx convex run --deployment <name> broker:<name>`:
// listApps, listClients '{"appId":"..."}', deleteClient '{"clientId":"..."}', deleteApp '{"appId":"..."}'
// `crons.ts` runs `cleanup` daily.
export const { deleteApp, listApps, listClients, deleteClient, cleanup } = broker.admin();
export const cleanup = hub.cleanup;
7 changes: 4 additions & 3 deletions convex/convex.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { defineApp } from "convex/server";
import { v } from "convex/values";

// A push fails while a required variable is missing. The stack (alchemy.run.ts) sets every
// variable here but IDENTITY_BROKER_KEYS, which scripts/init-keys.ts creates once by hand and
// scripts/check-keys.ts checks before each push, and APPS_PAUSED, which is set by hand.
// variable here but IDENTITY_BROKER_KEYS, which scripts/init-keys.ts creates once by hand, and
// APPS_PAUSED, which is set by hand.
const app = defineApp({
env: {
/** The signing key set. */
Expand Down Expand Up @@ -37,6 +37,7 @@ const app = defineApp({
},
});

app.use(identityBroker);
// Not the default name: a deployment that ran 0.34.0 or earlier keeps its rows under `identityBroker`, which do not fit this schema.
app.use(identityBroker, { name: "identityHub" });

export default app;
4 changes: 2 additions & 2 deletions convex/http.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { httpRouter } from "convex/server";
import { broker } from "./broker";
import { hub } from "./broker";

const http = httpRouter();
broker.addHttpRoutes(http);
hub.addHttpRoutes(http);

export default http;
8 changes: 2 additions & 6 deletions convex/owners.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import { describe, expect, test } from "vitest";
import { mayRegister, parseOwners } from "./owners";
import { parseOwners } from "./owners";

describe("HUB_OWNERS", () => {
test("any lets every owner register", () => {
expect(parseOwners(" any ")).toBe("any");
expect(mayRegister("any", "583231")).toBe(true);
});

test("a list lets only its owners register", () => {
const owners = parseOwners("583231, 9919");
expect(owners).toEqual(["583231", "9919"]);
expect(mayRegister(owners, "9919")).toBe(true);
expect(mayRegister(owners, "1")).toBe(false);
expect(parseOwners("583231, 9919")).toEqual([{ ownerId: "583231" }, { ownerId: "9919" }]);
});

test.each(["", " ", "Any", "octocat", "583231,", "583231,,9919", "-1", "0", "1e3"])(
Expand Down
17 changes: 5 additions & 12 deletions convex/owners.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
/**
* Who may register at this hub, from HUB_OWNERS: `any`, or the numeric ids of the GitHub accounts
* (users or organizations) whose repositories may register, separated by commas. Anything else
* throws, so a typo stops the deploy instead of opening or closing the hub.
* throws, so a typo stops the deploy instead of opening or closing the hub. The owner is the one
* GitHub's token of the registering run proves: the account that owns the repository, never the
* person or bot that ran the workflow.
*/
export function parseOwners(value: string): "any" | readonly string[] {
export function parseOwners(value: string): "any" | Array<{ ownerId: string }> {
const trimmed = value.trim();
if (trimmed === "any") {
return "any";
Expand All @@ -14,14 +16,5 @@ export function parseOwners(value: string): "any" | readonly string[] {
`HUB_OWNERS is "any" or numeric GitHub owner ids separated by commas, not "${value}".`,
);
}
return ids;
}

/**
* Whether a repository of this owner may register. The owner is the one GitHub's token of the
* registering run proves: the account that owns the repository, never the person or bot that ran
* the workflow.
*/
export function mayRegister(owners: "any" | readonly string[], ownerId: string): boolean {
return owners === "any" || owners.includes(ownerId);
return ids.map((ownerId) => ({ ownerId }));
}
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"license": "MIT",
"type": "module",
"scripts": {
"deploy": "node ./scripts/check-keys.ts && convex deploy --yes",
"deploy": "convex deploy --yes",
"keys:init": "node ./scripts/init-keys.ts",
"check": "vp check && pnpm run typecheck && vp test",
"typecheck": "tsc --project convex/tsconfig.json && tsc --project tsconfig.node.json",
Expand All @@ -13,15 +13,15 @@
"test": "vp test"
},
"dependencies": {
"@samebase/identity-broker": "0.34.0",
"convex": "1.48.0"
"@samebase/identity-broker": "0.37.0",
"convex": "1.48.0",
"effect": "4.1.4"
},
"devDependencies": {
"@effect/platform-node": "4.1.4",
"@samebase/alchemy-convex": "0.44.0",
"@types/node": "26.6.6",
"alchemy": "2.0.0-beta.87",
"effect": "4.1.4",
"typescript": "7.0.2",
"vite": "catalog:",
"vite-plus": "catalog:",
Expand Down
Loading