@samebase/alchemy-convex 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,45 +1,45 @@
1
- // IdentityHub.Client: one deployment of an app as a client of the identity hub that the stack
1
+ // IdentityBroker.Client: one deployment of an app as a client of the identity broker that the stack
2
2
  // names, for an app that deploys in its own GitHub Actions run, on any host, and in development as a
3
3
  // stage of the same stack. Import it as
4
- // `import * as IdentityHub from "@samebase/alchemy-convex/identity-hub"`; `Convex.providers()`
4
+ // `import * as IdentityBroker from "@samebase/alchemy-convex/identity-broker"`; `Convex.providers()`
5
5
  // registers its provider.
6
6
  //
7
- // A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs
8
- // no key and no Samebase account. The token names the repository. The hub reads
7
+ // A run in GitHub Actions asks the broker for a new client with a GitHub OIDC token, so the stack
8
+ // needs no key and no Samebase account. The token names the repository. The broker reads
9
9
  // `/samebase-verification.json` at the origin of the return address, which must name the same
10
10
  // repository, and registers the client on that address. The answer holds the client's own
11
- // registration access token (RFC 7591), and each later deploy reads the client on the hub with that
12
- // token (RFC 7592). The hub keeps only hashes, so the state is the only record of the secret and the
13
- // token.
11
+ // registration access token (RFC 7591), and each later deploy reads the client on the broker with
12
+ // that token (RFC 7592). The broker keeps only hashes, so the state is the only record of the secret
13
+ // and the token.
14
14
  //
15
15
  // The answer to a production registration also holds the app's initial access token (RFC 7591
16
16
  // section 1.2) and the repository id. The state of stage `prod` keeps them. A development checkout
17
- // runs the stack as a stage `dev-<name>`: it reads them with `IdentityHub.Client.read`, and a client
18
- // with `deploymentType: "development"` asks the hub with the token in place of the GitHub token
19
- // (RFC 133).
17
+ // runs the stack as a stage `dev-<name>`: it reads them with `IdentityBroker.Client.read`, and a
18
+ // client with `deploymentType: "development"` asks the broker with the token in place of the GitHub
19
+ // token (RFC 133).
20
20
  //
21
- // A hub on the stack layer, which the app's own stack deploys, takes a key in place of a proof:
22
- // a client with `key` asks with it, from any run, and the hub reads no verification file.
23
- // `IdentityHub.registrationKey` makes each key in the stage that deploys the hub and reads it in
24
- // every other stage. That stage's client waits until the hub answers discovery, so one run deploys
25
- // the hub and registers its client.
21
+ // A broker on the stack layer, which the app's own stack deploys, takes a key in place of a proof:
22
+ // a client with `key` asks with it, from any run, and the broker reads no verification file.
23
+ // `IdentityBroker.registrationKey` makes each key in the stage that deploys the broker and reads it
24
+ // in every other stage. That stage's client waits until the broker answers discovery, so one run
25
+ // deploys the broker and registers its client.
26
26
  //
27
27
  // A client is enrolled in the connectors it signs in through, such as `google` and `github`, at
28
28
  // registration (RFC 137), and holds the return addresses its requests may name, one per handler of
29
- // the app, such as the sign-in callback and the connections callback. The hub records both sets on
30
- // the client and never changes them: a stack with another set registers a new client.
29
+ // the app, such as the sign-in callback and the connections callback. The broker records both sets
30
+ // on the client and never changes them: a stack with another set registers a new client.
31
31
  //
32
- // The app is the stack: its name on the hub defaults to the stack's path in the repository, as the
33
- // state store groups stacks (`owner/repo/<path>`), and `app` for a stack named after the repository.
34
- // `app` overrides it. The name groups the clients, their budgets, and the initial access token; it
35
- // plays no part in user ids, which the hub derives from the provider's own id.
32
+ // The app is the stack: its name on the broker defaults to the stack's path in the repository, as
33
+ // the state store groups stacks (`owner/repo/<path>`), and `app` for a stack named after the
34
+ // repository. `app` overrides it. The name groups the clients, their budgets, and the initial access
35
+ // token; it plays no part in user ids, which the broker derives from the provider's own id.
36
36
  //
37
37
  // A push removes a variable that a deploy stops passing, so a failure here must not drop working
38
38
  // variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that
39
39
  // cannot work asks for a new one: it is gone, or it has another app name, return address set, type,
40
40
  // or connector set. If that request fails, the run gives the off values, so the app has guest
41
- // sign-in and not a broken button. The off values are the `no-hub` variables of a checkout without
42
- // a hub: Convex needs the variables, and the app hides the button for this client ID.
41
+ // sign-in and not a broken button. The off values are the `DISABLED` variables of a checkout
42
+ // without a broker: Convex needs the variables, and the app hides the button for this client ID.
43
43
  //
44
44
  // No text in this file quotes an answer or a fetch error, so no log line can hold a secret. The one
45
45
  // exception is the connector names of an `invalid_connectors` refusal, each checked against the
@@ -61,15 +61,18 @@ import type { Providers } from "./Providers.ts";
61
61
  /** A hung service must not hold a deploy: the time limit of one request. */
62
62
  const REQUEST_TIMEOUT_MS = 30_000;
63
63
 
64
- /** The variables of a deployment without a hub client, as the starter writes them. */
65
- const OFF_VALUES = { issuer: "http://127.0.0.1:1", clientId: "no-hub", clientSecret: "no-hub" };
64
+ /** The client ID and the client secret of a deployment without a broker client. */
65
+ export const DISABLED = "broker-disabled";
66
66
 
67
- /** The name of a connector on the hub. */
67
+ /** The variables of a deployment without a broker client. */
68
+ const OFF_VALUES = { issuer: "http://127.0.0.1:1", clientId: DISABLED, clientSecret: DISABLED };
69
+
70
+ /** The name of a connector on the broker. */
68
71
  const CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;
69
72
 
70
- /** The return addresses of one client, as the hub caps them. */
73
+ /** The return addresses of one client, as the broker caps them. */
71
74
  const MAX_REDIRECT_URIS = 8;
72
- /** The app's name, as the hub caps it. A deeper stack path needs an explicit `app`. */
75
+ /** The app's name, as the broker caps it. A deeper stack path needs an explicit `app`. */
73
76
  const MAX_APP_LENGTH = 64;
74
77
 
75
78
  /**
@@ -85,13 +88,13 @@ export const defaultApp = (stackName: string): string | undefined => {
85
88
  };
86
89
 
87
90
  /**
88
- * An identity hub of @samebase/identity-broker, such as Samebase's public hub:
91
+ * An identity broker of @samebase/identity-broker, such as Samebase's public broker:
89
92
  * `{ issuer: "https://id.samebase.com" }`.
90
93
  */
91
- export interface Hub {
94
+ export interface BrokerEndpoint {
92
95
  /**
93
- * The hub's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/register`, with
94
- * a GitHub token whose audience is the issuer, so no other hub can use that token.
96
+ * The broker's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/register`,
97
+ * with a GitHub token whose audience is the issuer, so no other broker can use that token.
95
98
  */
96
99
  readonly issuer: string;
97
100
  }
@@ -103,18 +106,18 @@ interface CommonProps {
103
106
  * repository. A changed name registers a new client under the new name.
104
107
  */
105
108
  readonly app?: string;
106
- /** The hub to register at. A changed hub registers a new client there; the old one stays. */
107
- readonly hub: Hub;
109
+ /** The broker to register at. A changed broker registers a new client there; the old one stays. */
110
+ readonly broker: BrokerEndpoint;
108
111
  /**
109
- * The connectors the client signs in through, by their names on the hub, such as
110
- * `["google", "github"]`: at least one, each of `[a-z0-9-]{1,64}`. The hub refuses a name it does
111
- * not offer, or does not allow this repository, and the log then names the allowed ones. The set
112
- * is recorded on the client for good: a changed set registers a new client.
112
+ * The connectors the client signs in through, by their names on the broker, such as
113
+ * `["google", "github"]`: at least one, each of `[a-z0-9-]{1,64}`. The broker refuses a name it
114
+ * does not offer, or does not allow this repository, and the log then names the allowed ones. The
115
+ * set is recorded on the client for good: a changed set registers a new client.
113
116
  */
114
117
  readonly connectors: readonly string[];
115
118
  /**
116
119
  * The return addresses of this deployment, one to eight, such as
117
- * `[`${site.siteUrl}/auth/hub/callback`]`: each an https URL whose origin serves
120
+ * `[`${site.siteUrl}/auth/broker/callback`]`: each an https URL whose origin serves
118
121
  * `/samebase-verification.json` with the numeric GitHub id of this repository,
119
122
  * `{ "repository": "123" }`. They can come from a resource that this run creates. A development
120
123
  * client can also have http on a loopback host, which needs no file. Every request of the client
@@ -122,22 +125,23 @@ interface CommonProps {
122
125
  * client.
123
126
  */
124
127
  readonly redirectUris: string[];
125
- /** Recorded on the hub's client, such as the commit. The hub records "unknown" without it. */
128
+ /** Recorded on the broker's client, such as the commit. The broker records "unknown" without it. */
126
129
  readonly softwareVersion?: string;
127
130
  /**
128
- * The run fails unless the hub confirms the client in this run: it fails when the hub refuses or
129
- * does not answer a registration or a renewal, and when it suspended the client. Without it, such
130
- * a run gives the off values or keeps the saved client, so the app deploys anyway. Set it where
131
- * sign-in is the product. A failed run saves nothing, so the next run asks the hub again.
131
+ * The run fails unless the broker confirms the client in this run: it fails when the broker
132
+ * refuses or does not answer a registration or a renewal, and when it suspended the client.
133
+ * Without it, such a run gives the off values or keeps the saved client, so the app deploys
134
+ * anyway. Set it where sign-in is the product. A failed run saves nothing, so the next run asks
135
+ * the broker again.
132
136
  */
133
137
  readonly required?: boolean;
134
138
  }
135
139
 
136
140
  /**
137
141
  * A production or preview client asks with the GitHub OIDC token of the run. A development client
138
- * asks with the app's initial access token, which `IdentityHub.Client.read` gives from stage `prod`.
139
- * A client of any type with `key` asks with that key, a key of a hub on the stack layer, such as
140
- * `IdentityHub.registrationKey` gives.
142
+ * asks with the app's initial access token, which `IdentityBroker.Client.read` gives from stage
143
+ * `prod`. A client of any type with `key` asks with that key, a key of a broker on the stack layer,
144
+ * such as `IdentityBroker.registrationKey` gives.
141
145
  */
142
146
  export type ClientProps =
143
147
  | (CommonProps & {
@@ -155,7 +159,7 @@ export type ClientProps =
155
159
  readonly deploymentType: "production" | "preview" | "development";
156
160
  /**
157
161
  * The Bearer of `POST /register`. Undefined, as before the stage that makes the key ever
158
- * ran: the client gets the off values, or the run fails when `required`. The hub decides
162
+ * ran: the client gets the off values, or the run fails when `required`. The broker decides
159
163
  * whether this key may register a production client.
160
164
  */
161
165
  readonly key: Redacted.Redacted<string> | undefined;
@@ -167,16 +171,16 @@ const DeploymentType = Schema.Literals(["production", "preview", "development"])
167
171
  const Attributes = Schema.Struct({
168
172
  /** `off`: no client, and the values below are the off values. */
169
173
  status: Schema.Literals(["on", "off", "suspended"]),
170
- /** The issuer of the hub, which the deployment names to sign in. */
174
+ /** The issuer of the broker, which the deployment names to sign in. */
171
175
  issuer: Schema.String,
172
176
  clientId: Schema.String,
173
177
  /** Returned only at registration. */
174
178
  clientSecret: Schema.Redacted(Schema.String),
175
- /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */
179
+ /** Returned only at registration. It reads and deletes this client on the broker, and nothing else. */
176
180
  registrationAccessToken: Schema.Redacted(Schema.String),
177
181
  registrationClientUri: Schema.String,
178
182
  deploymentType: DeploymentType,
179
- /** The app's name on the hub, as sent. Empty for the off values. */
183
+ /** The app's name on the broker, as sent. Empty for the off values. */
180
184
  app: Schema.String,
181
185
  /** The return addresses the client serves, sorted, each once. Empty for the off values. */
182
186
  redirectUris: Schema.Array(Schema.String),
@@ -193,7 +197,7 @@ const Attributes = Schema.Struct({
193
197
 
194
198
  /**
195
199
  * The attributes keep the real values of a suspended client, so that an unblock needs no new client.
196
- * `IdentityHub.Client.variables` gives the values that the app gets.
200
+ * `IdentityBroker.Client.variables` gives the values that the app gets.
197
201
  */
198
202
  export interface ClientAttributes extends Schema.Schema.Type<typeof Attributes> {}
199
203
 
@@ -204,7 +208,7 @@ export interface ClientAttributes extends Schema.Schema.Type<typeof Attributes>
204
208
  */
205
209
  const savedAttributes = (value: unknown, reason: string) =>
206
210
  Schema.decodeUnknownEffect(Attributes)(value).pipe(
207
- Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason }))),
211
+ Effect.catchCause(() => Effect.die(new IdentityBrokerClientFailed({ reason }))),
208
212
  );
209
213
 
210
214
  /** The attributes of no client. */
@@ -245,12 +249,12 @@ interface Enrollment {
245
249
  }
246
250
 
247
251
  /** One request gave no usable answer. The reason holds no secret. */
248
- class IdentityHubClientFailed extends Schema.TaggedError<IdentityHubClientFailed>()(
249
- "IdentityHubClientFailed",
252
+ class IdentityBrokerClientFailed extends Schema.TaggedError<IdentityBrokerClientFailed>()(
253
+ "IdentityBrokerClientFailed",
250
254
  { reason: Schema.String },
251
255
  ) {
252
256
  override get message() {
253
- return `IdentityHub.Client: ${this.reason}.`;
257
+ return `IdentityBroker.Client: ${this.reason}.`;
254
258
  }
255
259
  }
256
260
 
@@ -258,7 +262,7 @@ const OidcToken = Schema.Struct({ value: Schema.NonEmptyString });
258
262
 
259
263
  /**
260
264
  * The 201 answer of `POST /register` (RFC 7591 section 3.2.1), in the members that this file reads.
261
- * The decoder ignores the other members, such as `software_id`, whose full form the hub writes.
265
+ * The decoder ignores the other members, such as `software_id`, whose full form the broker writes.
262
266
  */
263
267
  const NewClient = Schema.Struct({
264
268
  issuer: Schema.NonEmptyString,
@@ -266,7 +270,7 @@ const NewClient = Schema.Struct({
266
270
  client_secret: Schema.NonEmptyString,
267
271
  registration_access_token: Schema.NonEmptyString,
268
272
  registration_client_uri: Schema.NonEmptyString,
269
- /** The sets the hub recorded, which must be the sets the request sent. */
273
+ /** The sets the broker recorded, which must be the sets the request sent. */
270
274
  redirect_uris: Schema.Array(Schema.String),
271
275
  connectors: Schema.Array(Schema.String),
272
276
  /** Only in the answer to a production registration with the GitHub token. */
@@ -276,53 +280,56 @@ const NewClient = Schema.Struct({
276
280
 
277
281
  /** The other answers of `POST /register`, by status. A 401 can have no body (RFC 6750). */
278
282
  const REFUSALS: Readonly<Record<number, string>> = {
279
- 400: "the identity hub refused the client metadata, such as the app name",
280
- 401: "the identity hub refused the GitHub OIDC token",
281
- 403: "the identity hub does not allow this repository",
282
- 404: "the identity hub has no /register: it runs an identity-broker before 0.33.0",
283
- 429: "the identity hub limits new clients",
284
- 502: "GitHub's keys are not available to the identity hub",
285
- 503: "the identity hub could not apply its policy",
283
+ 400: "the identity broker refused the client metadata, such as the app name",
284
+ 401: "the identity broker refused the GitHub OIDC token",
285
+ 403: "the identity broker does not allow this repository",
286
+ 404: "the identity broker has no /register: it runs an identity-broker before 0.33.0",
287
+ 429: "the identity broker limits new clients",
288
+ 502: "GitHub's keys are not available to the identity broker",
289
+ 503: "the identity broker could not apply its policy",
286
290
  };
287
291
 
288
292
  /** The text of an `invalid_redirect_uri` 400 without a known reason. */
289
293
  const BAD_REDIRECT_URIS =
290
- "the identity hub refused the return addresses: one to eight, each https on a DNS name, or http on a loopback host for a development client";
294
+ "the identity broker refused the return addresses: one to eight, each https on a DNS name, or http on a loopback host for a development client";
291
295
 
292
296
  /**
293
297
  * The reasons of a 400 or a 403 that a log line shows. Any other text of the answer is never
294
298
  * logged.
295
299
  */
296
300
  const REASONS = new Map([
297
- ["paused", "this app is paused on the identity hub"],
298
- ["run_not_allowed", "the identity hub gives clients only to runs of main and of pull requests"],
301
+ ["paused", "this app is paused on the identity broker"],
302
+ [
303
+ "run_not_allowed",
304
+ "the identity broker gives clients only to runs of main and of pull requests",
305
+ ],
299
306
  ["blocked", "Samebase blocked this repository or its owner"],
300
- ["suspended", "the identity hub suspended this repository"],
301
- ["too_many_apps", "the repository has as many apps on the identity hub as it may"],
302
- ["too_many_clients", "the app has as many clients on the identity hub as it may"],
303
- ["app_taken", "the app's name belongs to another app on the identity hub"],
304
- ["host_unreachable", "the identity hub could not reach the host of the return address"],
307
+ ["suspended", "the identity broker suspended this repository"],
308
+ ["too_many_apps", "the repository has as many apps on the identity broker as it may"],
309
+ ["too_many_clients", "the app has as many clients on the identity broker as it may"],
310
+ ["app_taken", "the app's name belongs to another app on the identity broker"],
311
+ ["host_unreachable", "the identity broker could not reach the host of the return address"],
305
312
  [
306
313
  "verification_file_missing",
307
314
  "the host of the return address does not serve /samebase-verification.json",
308
315
  ],
309
316
  ["verification_file_invalid", "/samebase-verification.json on the host holds no repository id"],
310
317
  ["repository_mismatch", "/samebase-verification.json on the host names another repository"],
311
- ["app_mismatch", "the initial access token belongs to another app on the identity hub"],
312
- ["stale_proof", "the identity hub took a newer GitHub OIDC token of this repository"],
318
+ ["app_mismatch", "the initial access token belongs to another app on the identity broker"],
319
+ ["stale_proof", "the identity broker took a newer GitHub OIDC token of this repository"],
313
320
  ]);
314
321
 
315
322
  /** The windows of a 429, by the name that the answer gives. */
316
323
  const RATE_LIMITED = new Map([
317
- ["repository", "the identity hub gives one repository at most 30 new clients an hour"],
318
- ["owner", "the identity hub gives one owner at most 100 new clients an hour"],
319
- ["new_owners", "the identity hub takes at most 50 new owners an hour"],
324
+ ["repository", "the identity broker gives one repository at most 30 new clients an hour"],
325
+ ["owner", "the identity broker gives one owner at most 100 new clients an hour"],
326
+ ["new_owners", "the identity broker takes at most 50 new owners an hour"],
320
327
  ]);
321
328
 
322
329
  const Refusal = Schema.Struct({ reason: Schema.String });
323
330
  const InvalidRedirectUri = Schema.Struct({ error: Schema.Literal("invalid_redirect_uri") });
324
331
  const RateLimited = Schema.Struct({ window: Schema.String });
325
- /** A 400 for a connector the hub does not offer or allow, with the names it allows. */
332
+ /** A 400 for a connector the broker does not offer or allow, with the names it allows. */
326
333
  const InvalidConnectors = Schema.Struct({
327
334
  reason: Schema.Literal("invalid_connectors"),
328
335
  allowed: Schema.Array(Schema.String),
@@ -337,7 +344,7 @@ const InvalidConnectors = Schema.Struct({
337
344
  const refusalOf = (status: number, body: unknown): string => {
338
345
  const decoded = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>
339
346
  Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));
340
- const ofStatus = () => REFUSALS[status] ?? "the identity hub refused the request";
347
+ const ofStatus = () => REFUSALS[status] ?? "the identity broker refused the request";
341
348
  switch (status) {
342
349
  case 400: {
343
350
  const allowed = decoded(InvalidConnectors)?.allowed.filter((name) =>
@@ -346,7 +353,7 @@ const refusalOf = (status: number, body: unknown): string => {
346
353
  return allowed === undefined
347
354
  ? (REASONS.get(decoded(Refusal)?.reason ?? "") ??
348
355
  (decoded(InvalidRedirectUri) === undefined ? ofStatus() : BAD_REDIRECT_URIS))
349
- : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
356
+ : `the identity broker does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
350
357
  }
351
358
  case 403:
352
359
  return REASONS.get(decoded(Refusal)?.reason ?? "") ?? ofStatus();
@@ -369,7 +376,7 @@ const send = (
369
376
  ) =>
370
377
  token !== undefined && !(URL.canParse(url) && new URL(url).protocol === "https:")
371
378
  ? Effect.fail(
372
- new IdentityHubClientFailed({
379
+ new IdentityBrokerClientFailed({
373
380
  reason: `${who} is not at an https URL, so no credential was sent to it`,
374
381
  }),
375
382
  )
@@ -386,14 +393,14 @@ const send = (
386
393
  const body: unknown = await response.json().catch(() => undefined);
387
394
  return { status: response.status, body };
388
395
  },
389
- catch: () => new IdentityHubClientFailed({ reason: `${who} gave no answer` }),
396
+ catch: () => new IdentityBrokerClientFailed({ reason: `${who} gave no answer` }),
390
397
  });
391
398
 
392
399
  const decode =
393
400
  <S extends Schema.Codec<unknown, unknown>>(schema: S, who: string) =>
394
401
  (value: unknown) =>
395
402
  Schema.decodeUnknownEffect(schema)(value).pipe(
396
- Effect.mapError(() => new IdentityHubClientFailed({ reason: `${who} gave a bad answer` })),
403
+ Effect.mapError(() => new IdentityBrokerClientFailed({ reason: `${who} gave a bad answer` })),
397
404
  );
398
405
 
399
406
  /**
@@ -409,7 +416,7 @@ const readOidcToken = (requestUrl: string, requestToken: string, audience: strin
409
416
  { method: "GET" },
410
417
  );
411
418
  if (status !== 200) {
412
- return yield* new IdentityHubClientFailed({
419
+ return yield* new IdentityBrokerClientFailed({
413
420
  reason: `GitHub gave no OIDC token (HTTP ${status})`,
414
421
  });
415
422
  }
@@ -418,57 +425,64 @@ const readOidcToken = (requestUrl: string, requestToken: string, audience: strin
418
425
 
419
426
  /**
420
427
  * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial
421
- * access token: the GitHub OIDC token, the app's own token, or a key of the hub. `software_id` is
422
- * the app's name, `client_name` the stage, and `connectors` and `deployment_type` are the hub's own
423
- * metadata fields. Convex Auth posts the client's secret in the body at the token endpoint, so the
424
- * client registers that method.
428
+ * access token: the GitHub OIDC token, the app's own token, or a key of the broker. `software_id` is
429
+ * the app's name, `client_name` the stage, and `connectors` and `deployment_type` are the broker's
430
+ * own metadata fields. Convex Auth posts the client's secret in the body at the token endpoint, so
431
+ * the client registers that method.
425
432
  */
426
433
  const requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: string) =>
427
434
  Effect.gen(function* () {
428
- const { hub } = props;
435
+ const { broker } = props;
429
436
  const { app, connectors, redirectUris } = enrollment;
430
- const { body, status } = yield* send("The identity hub", `${hub.issuer}/register`, bearer, {
431
- method: "POST",
432
- body: JSON.stringify({
433
- redirect_uris: redirectUris,
434
- software_id: app,
435
- software_version: props.softwareVersion ?? "unknown",
436
- client_name: enrollment.clientName,
437
- deployment_type: props.deploymentType,
438
- connectors,
439
- token_endpoint_auth_method: "client_secret_post",
440
- }),
441
- });
437
+ const { body, status } = yield* send(
438
+ "The identity broker",
439
+ `${broker.issuer}/register`,
440
+ bearer,
441
+ {
442
+ method: "POST",
443
+ body: JSON.stringify({
444
+ redirect_uris: redirectUris,
445
+ software_id: app,
446
+ software_version: props.softwareVersion ?? "unknown",
447
+ client_name: enrollment.clientName,
448
+ deployment_type: props.deploymentType,
449
+ connectors,
450
+ token_endpoint_auth_method: "client_secret_post",
451
+ }),
452
+ },
453
+ );
442
454
  if (status !== 201) {
443
455
  const reason =
444
456
  status !== 401
445
457
  ? refusalOf(status, body)
446
458
  : "key" in props
447
- ? "the identity hub refused the registration key"
459
+ ? "the identity broker refused the registration key"
448
460
  : props.deploymentType === "development"
449
- ? "the identity hub refused the initial access token"
461
+ ? "the identity broker refused the initial access token"
450
462
  : refusalOf(status, body);
451
- return yield* new IdentityHubClientFailed({ reason: `${reason} (HTTP ${status})` });
463
+ return yield* new IdentityBrokerClientFailed({ reason: `${reason} (HTTP ${status})` });
452
464
  }
453
- const client = yield* decode(NewClient, "The identity hub")(body);
454
- // The hub registers the addresses and the connectors that the request sent, under its own
465
+ const client = yield* decode(NewClient, "The identity broker")(body);
466
+ // The broker registers the addresses and the connectors that the request sent, under its own
455
467
  // issuer. The log and the state hold the stack's values, so no value that the answer chose is
456
468
  // printed or kept.
457
469
  if (
458
- client.issuer !== hub.issuer ||
470
+ client.issuer !== broker.issuer ||
459
471
  !sameSet(sortedSet(client.redirect_uris), redirectUris) ||
460
472
  !sameSet(client.connectors, connectors)
461
473
  ) {
462
- return yield* new IdentityHubClientFailed({ reason: "The identity hub gave a bad answer" });
474
+ return yield* new IdentityBrokerClientFailed({
475
+ reason: "The identity broker gave a bad answer",
476
+ });
463
477
  }
464
478
  yield* Effect.logInfo(
465
- `IdentityHub.Client: ${where(enrollment)} has a new client of the identity hub ${hub.issuer}.`,
479
+ `IdentityBroker.Client: ${where(enrollment)} has a new client of the identity broker ${broker.issuer}.`,
466
480
  );
467
481
  // Only a production registration gives the app's token (RFC 7591); any other answer's is dropped.
468
482
  const production = props.deploymentType === "production";
469
483
  return {
470
484
  status: "on" as const,
471
- issuer: hub.issuer,
485
+ issuer: broker.issuer,
472
486
  clientId: client.client_id,
473
487
  clientSecret: Redacted.make(client.client_secret),
474
488
  registrationAccessToken: Redacted.make(client.registration_access_token),
@@ -485,9 +499,9 @@ const requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: st
485
499
  const Discovery = Schema.Struct({ issuer: Schema.String });
486
500
 
487
501
  /**
488
- * The time a hub has to answer discovery before a registration with a key: the stage that deploys
489
- * the hub registers its own client in the same run, and a new workers.dev route answers after
490
- * about a minute. Delays of 1, 2, 4, 8 and then 15 seconds, about three minutes in all.
502
+ * The time a broker has to answer discovery before a registration with a key: the stage that
503
+ * deploys the broker registers its own client in the same run, and a new workers.dev route answers
504
+ * after about a minute. Delays of 1, 2, 4, 8 and then 15 seconds, about three minutes in all.
491
505
  */
492
506
  const DISCOVERY_RETRY = {
493
507
  times: 15,
@@ -495,19 +509,21 @@ const DISCOVERY_RETRY = {
495
509
  };
496
510
 
497
511
  /**
498
- * Succeeds when the hub's discovery document names the hub's issuer, after bounded retries; fails
499
- * when it never does.
512
+ * Succeeds when the broker's discovery document names the broker's issuer, after bounded retries;
513
+ * fails when it never does.
500
514
  */
501
- const hubAnswers = (hub: Hub) =>
502
- send("The identity hub", `${hub.issuer}/.well-known/openid-configuration`, undefined, {
515
+ const brokerAnswers = (broker: BrokerEndpoint) =>
516
+ send("The identity broker", `${broker.issuer}/.well-known/openid-configuration`, undefined, {
503
517
  method: "GET",
504
518
  }).pipe(
505
519
  Effect.flatMap(({ body, status }) =>
506
520
  status === 200 &&
507
- Option.getOrUndefined(Schema.decodeUnknownOption(Discovery)(body))?.issuer === hub.issuer
521
+ Option.getOrUndefined(Schema.decodeUnknownOption(Discovery)(body))?.issuer === broker.issuer
508
522
  ? Effect.void
509
523
  : Effect.fail(
510
- new IdentityHubClientFailed({ reason: "the identity hub does not answer discovery" }),
524
+ new IdentityBrokerClientFailed({
525
+ reason: "the identity broker does not answer discovery",
526
+ }),
511
527
  ),
512
528
  ),
513
529
  Effect.retry(DISCOVERY_RETRY),
@@ -515,12 +531,12 @@ const hubAnswers = (hub: Hub) =>
515
531
 
516
532
  /** A new client, or the off values. */
517
533
  const newClient = (props: ClientProps, enrollment: Enrollment) => {
518
- const label = `IdentityHub.Client: ${where(enrollment)} deploys without the hub`;
534
+ const label = `IdentityBroker.Client: ${where(enrollment)} deploys without the broker`;
519
535
  const off = offAttributes(props.deploymentType);
520
- const request = (bearer: Effect.Effect<string, IdentityHubClientFailed>) =>
536
+ const request = (bearer: Effect.Effect<string, IdentityBrokerClientFailed>) =>
521
537
  bearer.pipe(
522
538
  Effect.flatMap((token) => requestNewClient(props, enrollment, token)),
523
- Effect.catchTag("IdentityHubClientFailed", (error) =>
539
+ Effect.catchTag("IdentityBrokerClientFailed", (error) =>
524
540
  Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(
525
541
  Effect.as(off),
526
542
  ),
@@ -532,14 +548,14 @@ const newClient = (props: ClientProps, enrollment: Enrollment) => {
532
548
  ? Effect.logInfo(
533
549
  `${label}: it has no registration key yet. Deploy the stage that makes the key first.`,
534
550
  ).pipe(Effect.as(off))
535
- : request(Effect.as(hubAnswers(props.hub), Redacted.value(props.key)));
551
+ : request(Effect.as(brokerAnswers(props.broker), Redacted.value(props.key)));
536
552
  }
537
553
 
538
554
  if (props.deploymentType === "development") {
539
555
  const token = Redacted.value(props.initialAccessToken);
540
556
  return token === ""
541
557
  ? Effect.logInfo(
542
- "IdentityHub.Client: deploy to main once for hub sign-in in development.",
558
+ "IdentityBroker.Client: deploy to main once for broker sign-in in development.",
543
559
  ).pipe(Effect.as(off))
544
560
  : request(Effect.succeed(token));
545
561
  }
@@ -555,19 +571,19 @@ const newClient = (props: ClientProps, enrollment: Enrollment) => {
555
571
  : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)
556
572
  ).pipe(Effect.as(off));
557
573
  }
558
- return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));
574
+ return request(readOidcToken(requestUrl, requestToken, props.broker.issuer));
559
575
  };
560
576
 
561
577
  /**
562
- * The client after a read on the hub, or undefined when the hub says that the client is gone. A
563
- * read with no usable answer keeps the saved client, except for a required one: a required client
564
- * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,
565
- * and did not save because that run failed, cannot pass a run that the hub does not answer.
578
+ * The client after a read on the broker, or undefined when the broker says that the client is gone.
579
+ * A read with no usable answer keeps the saved client, except for a required one: a required client
580
+ * passes a run only when the broker confirms it in that run, so a suspension that an earlier run
581
+ * saw, and did not save because that run failed, cannot pass a run that the broker does not answer.
566
582
  */
567
583
  const renew = (saved: ClientAttributes, required: boolean) =>
568
584
  Effect.gen(function* () {
569
585
  const { status } = yield* send(
570
- "The identity hub",
586
+ "The identity broker",
571
587
  saved.registrationClientUri,
572
588
  Redacted.value(saved.registrationAccessToken),
573
589
  { method: "GET" },
@@ -579,52 +595,53 @@ const renew = (saved: ClientAttributes, required: boolean) =>
579
595
  return undefined;
580
596
  case 403:
581
597
  yield* Effect.logWarning(
582
- `IdentityHub.Client: the hub suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`,
598
+ `IdentityBroker.Client: the broker suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`,
583
599
  );
584
600
  return { ...saved, status: "suspended" as const };
585
601
  default:
586
- return yield* new IdentityHubClientFailed({
587
- reason: `The identity hub answered HTTP ${status}`,
602
+ return yield* new IdentityBrokerClientFailed({
603
+ reason: `The identity broker answered HTTP ${status}`,
588
604
  });
589
605
  }
590
606
  }).pipe(
591
- Effect.catchTag("IdentityHubClientFailed", (error) =>
607
+ Effect.catchTag("IdentityBrokerClientFailed", (error) =>
592
608
  required
593
609
  ? Effect.fail(
594
- new IdentityHubClientFailed({
595
- reason: `${where(saved)} is required, and the hub did not confirm its client: ${error.reason}`,
610
+ new IdentityBrokerClientFailed({
611
+ reason: `${where(saved)} is required, and the broker did not confirm its client: ${error.reason}`,
596
612
  }),
597
613
  )
598
614
  : Effect.logWarning(
599
- `IdentityHub.Client: ${where(saved)} keeps the saved client: ${error.reason}.`,
615
+ `IdentityBroker.Client: ${where(saved)} keeps the saved client: ${error.reason}.`,
600
616
  ).pipe(Effect.as(saved)),
601
617
  ),
602
618
  );
603
619
 
604
620
  /**
605
- * The type of this resource before 0.37.0. Alchemy finds this provider for a row of that type, and
606
- * the next write of the row gives it the new type, with the same client. Remove it, here and in
607
- * `SavedRow`, once no saved row has the old type.
621
+ * The types of this resource before 0.46.0. A deploy updates a row of such a type in place and
622
+ * gives it the new type, with the same client; a destroy or an orphan delete finds this provider
623
+ * for it by these aliases. Remove them, here and in `SavedRow`, once no saved row has an old type.
608
624
  */
609
- const OLD_TYPE = "IdentityHub.SharedClient";
625
+ const OLD_TYPE = "IdentityHub.Client";
626
+ const OLDER_TYPE = "IdentityHub.SharedClient";
610
627
 
611
628
  /** A saved row of this resource, whose `attr` `savedAttributes` reads. */
612
629
  const SavedRow = Schema.Struct({
613
- resourceType: Schema.Literals(["IdentityHub.Client", OLD_TYPE]),
630
+ resourceType: Schema.Literals(["IdentityBroker.Client", OLD_TYPE, OLDER_TYPE]),
614
631
  attr: Schema.Unknown,
615
632
  });
616
633
 
617
634
  /**
618
635
  * The attributes of the client `id` in another stage of this stack, such as
619
- * `read("HubClient", { stage: "prod" })` in a development stage, as Outputs: the
636
+ * `read("BrokerClient", { stage: "prod" })` in a development stage, as Outputs: the
620
637
  * `initialAccessToken` and the `repository` of the production client. Without that row, the off
621
638
  * attributes, with `deploymentType: "production"`.
622
639
  *
623
- * `IdentityHub.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the
624
- * row is missing, and a development stage before the first deploy to main has none. This read runs
625
- * when the plan resolves it, with the State service of the running stack and its `get`, so it never
626
- * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every
627
- * read.
640
+ * `IdentityBroker.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when
641
+ * the row is missing, and a development stage before the first deploy to main has none. This read
642
+ * runs when the plan resolves it, with the State service of the running stack and its `get`, so it
643
+ * never creates or upgrades a store. The store revives each secret as `Redacted`, as it does for
644
+ * every read.
628
645
  */
629
646
  const read = (id: string, options: { readonly stage: string }) =>
630
647
  Output.fromEffect(
@@ -638,8 +655,8 @@ const read = (id: string, options: { readonly stage: string }) =>
638
655
  const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(
639
656
  Effect.catchCause(() =>
640
657
  Effect.die(
641
- new IdentityHubClientFailed({
642
- reason: `the row ${id} of stage ${options.stage} is not an IdentityHub.Client`,
658
+ new IdentityBrokerClientFailed({
659
+ reason: `the row ${id} of stage ${options.stage} is not an IdentityBroker.Client`,
643
660
  }),
644
661
  ),
645
662
  ),
@@ -658,13 +675,13 @@ const SavedKey = Schema.Struct({
658
675
  });
659
676
 
660
677
  /**
661
- * A key of a hub on the stack layer, as a redacted Output, for the hub's secret binding and for
662
- * `IdentityHub.Client`'s `key`. `id` is the key's resource id, the author's name for it, so a stack
663
- * can make several. In `options.stage`, the stage that deploys the hub, the key is an
678
+ * A key of a broker on the stack layer, as a redacted Output, for the broker's secret binding and
679
+ * for `IdentityBroker.Client`'s `key`. `id` is the key's resource id, the author's name for it, so a
680
+ * stack can make several. In `options.stage`, the stage that deploys the broker, the key is an
664
681
  * `Alchemy.Random` at the stack's root, made once and kept in state; the stack's providers need
665
682
  * Random's provider (`Convex.providers()` and `Cloudflare.providers()` hold one). Every other stage
666
- * reads that row from the state store, as `IdentityHub.Client.read` does, so it never creates the
667
- * key; before the hub's stage ran, there is no row and no key (`undefined`).
683
+ * reads that row from the state store, as `IdentityBroker.Client.read` does, so it never creates the
684
+ * key; before the broker's stage ran, there is no row and no key (`undefined`).
668
685
  */
669
686
  export const registrationKey = (id: string, options: { readonly stage: string }) =>
670
687
  Effect.gen(function* () {
@@ -684,7 +701,7 @@ export const registrationKey = (id: string, options: { readonly stage: string })
684
701
  const saved = yield* Schema.decodeUnknownEffect(SavedKey)(row).pipe(
685
702
  Effect.catchCause(() =>
686
703
  Effect.die(
687
- new IdentityHubClientFailed({
704
+ new IdentityBrokerClientFailed({
688
705
  reason: `the row ${id} of stage ${options.stage} is not an Alchemy.Random`,
689
706
  }),
690
707
  ),
@@ -696,10 +713,10 @@ export const registrationKey = (id: string, options: { readonly stage: string })
696
713
  });
697
714
 
698
715
  /**
699
- * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,
700
- * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when
701
- * `status` is `on`, else the off values, so that a suspended client gives guest sign-in and keeps
702
- * its values in state.
716
+ * The three values that the app's deployment gets, such as `IDENTITY_BROKER_ISSUER`,
717
+ * `IDENTITY_BROKER_CLIENT_ID`, and `IDENTITY_BROKER_CLIENT_SECRET`, as Outputs: the client's values
718
+ * when `status` is `on`, else the off values, so that a suspended client gives guest sign-in and
719
+ * keeps its values in state.
703
720
  */
704
721
  const variables = (client: Client) =>
705
722
  Output.map(Output.of(client), (attributes) =>
@@ -717,41 +734,43 @@ const variables = (client: Client) =>
717
734
  );
718
735
 
719
736
  export type Client = Resource<
720
- "IdentityHub.Client",
737
+ "IdentityBroker.Client",
721
738
  ClientProps,
722
739
  ClientAttributes,
723
740
  never,
724
741
  Providers
725
742
  >;
726
- export const Client = Resource<Client>("IdentityHub.Client", { aliases: [OLD_TYPE] })({
743
+ export const Client = Resource<Client>("IdentityBroker.Client", {
744
+ aliases: [OLD_TYPE, OLDER_TYPE],
745
+ })({
727
746
  read,
728
747
  variables,
729
748
  });
730
749
 
731
750
  export const ClientProvider = () =>
732
751
  Provider.succeed(Client, {
733
- // Always an update, so that each deploy reaches the hub. No attribute is stable, so a push
752
+ // Always an update, so that each deploy reaches the broker. No attribute is stable, so a push
734
753
  // reads the values that this run ended with. The same values cause no other push.
735
754
  diff: ({ news }) =>
736
755
  Effect.succeed(isResolved(news) ? ({ action: "update" } as const) : undefined),
737
756
 
738
757
  read: ({ output }) => Effect.succeed(output),
739
758
 
740
- // Only a client of the same hub (its issuer), app name, return address set, type, and
759
+ // Only a client of the same broker (its issuer), app name, return address set, type, and
741
760
  // connector set is renewed. A saved row without this version's shape stops the run with a
742
761
  // fixed message.
743
762
  reconcile: Effect.fn(function* ({ news, output }) {
744
- // A bad prop is a mistake of the stack, not of the hub: the run fails, with no request.
763
+ // A bad prop is a mistake of the stack, not of the broker: the run fails, with no request.
745
764
  const stack = yield* Stack;
746
765
  const app = news.app ?? defaultApp(stack.name);
747
766
  if (app === undefined) {
748
- return yield* new IdentityHubClientFailed({
767
+ return yield* new IdentityBrokerClientFailed({
749
768
  reason: `the stack ${stack.name} is not named owner/repo or owner/repo/<path>, so set app`,
750
769
  });
751
770
  }
752
771
  if (app.length > MAX_APP_LENGTH) {
753
- return yield* new IdentityHubClientFailed({
754
- reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the hub's limit, so set a shorter app`,
772
+ return yield* new IdentityBrokerClientFailed({
773
+ reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the broker's limit, so set a shorter app`,
755
774
  });
756
775
  }
757
776
  const enrollment: Enrollment = {
@@ -764,7 +783,7 @@ export const ClientProvider = () =>
764
783
  enrollment.connectors.length === 0 ||
765
784
  !enrollment.connectors.every((name) => CONNECTOR_NAME.test(name))
766
785
  ) {
767
- return yield* new IdentityHubClientFailed({
786
+ return yield* new IdentityBrokerClientFailed({
768
787
  reason: `${where(enrollment)} needs connectors: one or more names of [a-z0-9-]{1,64}`,
769
788
  });
770
789
  }
@@ -773,7 +792,7 @@ export const ClientProvider = () =>
773
792
  enrollment.redirectUris.length > MAX_REDIRECT_URIS ||
774
793
  !enrollment.redirectUris.every((uri) => URL.canParse(uri))
775
794
  ) {
776
- return yield* new IdentityHubClientFailed({
795
+ return yield* new IdentityBrokerClientFailed({
777
796
  reason: `${app} needs redirectUris: one to ${MAX_REDIRECT_URIS} absolute URLs`,
778
797
  });
779
798
  }
@@ -785,7 +804,7 @@ export const ClientProvider = () =>
785
804
  `the saved attributes of ${where(enrollment)} cannot be read by this version`,
786
805
  );
787
806
  const renewed =
788
- saved?.issuer === news.hub.issuer &&
807
+ saved?.issuer === news.broker.issuer &&
789
808
  saved.app === app &&
790
809
  sameSet(saved.redirectUris, enrollment.redirectUris) &&
791
810
  saved.deploymentType === news.deploymentType &&
@@ -794,7 +813,7 @@ export const ClientProvider = () =>
794
813
  : undefined;
795
814
  const client = renewed ?? (yield* newClient(news, enrollment));
796
815
  if (news.required === true && client.status !== "on") {
797
- return yield* new IdentityHubClientFailed({
816
+ return yield* new IdentityBrokerClientFailed({
798
817
  reason: `${where(enrollment)} is required and has no working client (${client.status}). The warning above names the reason`,
799
818
  });
800
819
  }
@@ -808,22 +827,22 @@ export const ClientProvider = () =>
808
827
  ? Effect.void
809
828
  : Effect.gen(function* () {
810
829
  const { status } = yield* send(
811
- "The identity hub",
830
+ "The identity broker",
812
831
  output.registrationClientUri,
813
832
  Redacted.value(output.registrationAccessToken),
814
833
  { method: "DELETE" },
815
834
  );
816
835
  // 401: the client is gone already.
817
836
  if (status !== 204 && status !== 401) {
818
- return yield* new IdentityHubClientFailed({
819
- reason: `The identity hub answered HTTP ${status}`,
837
+ return yield* new IdentityBrokerClientFailed({
838
+ reason: `The identity broker answered HTTP ${status}`,
820
839
  });
821
840
  }
822
841
  }).pipe(
823
842
  // The row can be of an earlier version's shape, so the line names only the client id.
824
- Effect.catchTag("IdentityHubClientFailed", (error) =>
843
+ Effect.catchTag("IdentityBrokerClientFailed", (error) =>
825
844
  Effect.logWarning(
826
- `IdentityHub.Client: the client ${output.clientId} stays on the hub until its removal date: ${error.reason}.`,
845
+ `IdentityBroker.Client: the client ${output.clientId} stays on the broker until its removal date: ${error.reason}.`,
827
846
  ),
828
847
  ),
829
848
  ),