@samebase/alchemy-convex 0.41.0 → 0.42.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.
package/README.md CHANGED
@@ -312,7 +312,7 @@ resources and output, from the store function `state:readStack({ stack })` in on
312
312
  every action, because the command can do more than a push.
313
313
 
314
314
  - `IdentityHub.Client`, from `import * as IdentityHub from "@samebase/alchemy-convex/identity-hub"`:
315
- `{ hub, redirectUris, deploymentType, connectors, app?, initialAccessToken?, softwareVersion? }`
315
+ `{ hub, redirectUris, deploymentType, connectors, app?, initialAccessToken?, key?, softwareVersion? }`
316
316
  gets a client of an identity hub, for an app that deploys in its own GitHub Actions run, on any
317
317
  host, and for development as a stage of the same stack. `deploymentType` is `production`,
318
318
  `preview`, or `development`. A production or preview client needs `permissions: id-token: write`
@@ -341,6 +341,15 @@ resources and output, from the store function `state:readStack({ stack })` in on
341
341
  client asks the hub with this token in place of the GitHub OIDC token, so it works in
342
342
  development. With an empty token, the client gets the off values, and the log says "deploy to
343
343
  main once for hub sign-in in development". See "The development stage" below.
344
+ - A client of any `deploymentType` with `key` asks a hub on the stack layer with that key, from
345
+ any run, with no GitHub token and no verification file. It waits up to about three minutes for
346
+ the hub to answer discovery, so the run that deploys the hub registers its own client. The hub
347
+ decides whether the key may register a production client. An undefined key gives the off values,
348
+ or fails a `required` client.
349
+ - `IdentityHub.registrationKey(id, { stage })` gives the key `id` as a redacted Output: in the
350
+ stage that deploys the hub it is an `Alchemy.Random`, kept in state; in any other stage it is
351
+ read from that stage's row, and it is `undefined` before that stage ran. Bind it to the hub as a
352
+ secret, and give it to `key`.
344
353
  - Each deploy reads the saved client on the hub with its own token. A client that is gone gets a
345
354
  new one, and a client with other `redirectUris`, another `app`, another `deploymentType`, or
346
355
  other `connectors` too. A replaced production client stays valid on the hub until its
@@ -6,6 +6,8 @@ import * as Redacted from "effect/Redacted";
6
6
  import { Resource } from "alchemy";
7
7
  import { isResolved } from "alchemy/Diff";
8
8
  import * as Provider from "alchemy/Provider";
9
+ import * as Schedule from "effect/Schedule";
10
+ import { Random } from "alchemy/Random";
9
11
  import * as Output from "alchemy/Output";
10
12
  import { State } from "alchemy/State";
11
13
  //#region src/IdentityHub.ts
@@ -181,12 +183,16 @@ const refusalOf = (status, body) => {
181
183
  default: return ofStatus();
182
184
  }
183
185
  };
184
- const send = (who, url, token, init) => Effect.tryPromise({
186
+ /**
187
+ * One request to `who` at `url`, with `token` as its Bearer. A token goes only to an https URL:
188
+ * to any other URL the request is not made.
189
+ */
190
+ const send = (who, url, token, init) => token !== void 0 && !(URL.canParse(url) && new URL(url).protocol === "https:") ? Effect.fail(new IdentityHubClientFailed({ reason: `${who} is not at an https URL, so no credential was sent to it` })) : Effect.tryPromise({
185
191
  try: async () => {
186
192
  const response = await fetch(url, {
187
193
  ...init,
188
194
  headers: {
189
- Authorization: `Bearer ${token}`,
195
+ ...token === void 0 ? {} : { Authorization: `Bearer ${token}` },
190
196
  "Content-Type": "application/json"
191
197
  },
192
198
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
@@ -211,9 +217,10 @@ const readOidcToken = (requestUrl, requestToken, audience) => Effect.gen(functio
211
217
  });
212
218
  /**
213
219
  * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial
214
- * access token: the GitHub OIDC token, or the app's own token. `software_id` is the app's name, and
215
- * `connectors` is the hub's own metadata field. Convex Auth posts the client's secret in the body
216
- * at the token endpoint, so the client registers that method.
220
+ * access token: the GitHub OIDC token, the app's own token, or a key of the hub. `software_id` is
221
+ * the app's name, `client_name` the stage, and `connectors` and `deployment_type` are the hub's own
222
+ * metadata fields. Convex Auth posts the client's secret in the body at the token endpoint, so the
223
+ * client registers that method.
217
224
  */
218
225
  const requestNewClient = (props, enrollment, bearer) => Effect.gen(function* () {
219
226
  const { hub } = props;
@@ -224,11 +231,13 @@ const requestNewClient = (props, enrollment, bearer) => Effect.gen(function* ()
224
231
  redirect_uris: redirectUris,
225
232
  software_id: app,
226
233
  software_version: props.softwareVersion ?? "unknown",
234
+ client_name: enrollment.clientName,
235
+ deployment_type: props.deploymentType,
227
236
  connectors,
228
237
  token_endpoint_auth_method: "client_secret_post"
229
238
  })
230
239
  });
231
- if (status !== 201) return yield* new IdentityHubClientFailed({ reason: `${status === 401 && props.deploymentType === "development" ? "the identity hub refused the initial access token" : refusalOf(status, body)} (HTTP ${status})` });
240
+ if (status !== 201) return yield* new IdentityHubClientFailed({ reason: `${status !== 401 ? refusalOf(status, body) : "key" in props ? "the identity hub refused the registration key" : props.deploymentType === "development" ? "the identity hub refused the initial access token" : refusalOf(status, body)} (HTTP ${status})` });
232
241
  const client = yield* decode(NewClient, "The identity hub")(body);
233
242
  if (client.issuer !== hub.issuer || !sameSet(sortedSet(client.redirect_uris), redirectUris) || !sameSet(client.connectors, connectors)) return yield* new IdentityHubClientFailed({ reason: "The identity hub gave a bad answer" });
234
243
  yield* Effect.logInfo(`IdentityHub.Client: ${where(enrollment)} has a new client of the identity hub ${hub.issuer}.`);
@@ -248,11 +257,27 @@ const requestNewClient = (props, enrollment, bearer) => Effect.gen(function* ()
248
257
  repository: production ? client.repository ?? "" : ""
249
258
  };
250
259
  });
260
+ const Discovery = Schema.Struct({ issuer: Schema.String });
261
+ /**
262
+ * The time a hub has to answer discovery before a registration with a key: the stage that deploys
263
+ * the hub registers its own client in the same run, and a new workers.dev route answers after
264
+ * about a minute. Delays of 1, 2, 4, 8 and then 15 seconds, about three minutes in all.
265
+ */
266
+ const DISCOVERY_RETRY = {
267
+ times: 15,
268
+ schedule: Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("15 seconds")])
269
+ };
270
+ /**
271
+ * Succeeds when the hub's discovery document names the hub's issuer, after bounded retries; fails
272
+ * when it never does.
273
+ */
274
+ const hubAnswers = (hub) => send("The identity hub", `${hub.issuer}/.well-known/openid-configuration`, void 0, { method: "GET" }).pipe(Effect.flatMap(({ body, status }) => status === 200 && Option.getOrUndefined(Schema.decodeUnknownOption(Discovery)(body))?.issuer === hub.issuer ? Effect.void : Effect.fail(new IdentityHubClientFailed({ reason: "the identity hub does not answer discovery" }))), Effect.retry(DISCOVERY_RETRY));
251
275
  /** A new client, or the off values. */
252
276
  const newClient = (props, enrollment) => {
253
277
  const label = `IdentityHub.Client: ${where(enrollment)} deploys without the hub`;
254
278
  const off = offAttributes(props.deploymentType);
255
279
  const request = (bearer) => bearer.pipe(Effect.flatMap((token) => requestNewClient(props, enrollment, token)), Effect.catchTag("IdentityHubClientFailed", (error) => Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(Effect.as(off))));
280
+ if ("key" in props) return props.key === void 0 ? Effect.logInfo(`${label}: it has no registration key yet. Deploy the stage that makes the key first.`).pipe(Effect.as(off)) : request(Effect.as(hubAnswers(props.hub), Redacted.value(props.key)));
256
281
  if (props.deploymentType === "development") {
257
282
  const token = Redacted.value(props.initialAccessToken);
258
283
  return token === "" ? Effect.logInfo("IdentityHub.Client: deploy to main once for hub sign-in in development.").pipe(Effect.as(off)) : request(Effect.succeed(token));
@@ -319,6 +344,34 @@ const read = (id, options) => Output.fromEffect(Effect.gen(function* () {
319
344
  const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason: `the row ${id} of stage ${options.stage} is not an IdentityHub.Client` }))));
320
345
  return yield* savedAttributes(attr, `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`);
321
346
  }));
347
+ /** A saved row of an `Alchemy.Random`, whose `text` the store revives as `Redacted`. */
348
+ const SavedKey = Schema.Struct({
349
+ resourceType: Schema.Literal("Alchemy.Random"),
350
+ attr: Schema.Struct({ text: Schema.Redacted(Schema.String) })
351
+ });
352
+ /**
353
+ * A key of a hub on the stack layer, as a redacted Output, for the hub's secret binding and for
354
+ * `IdentityHub.Client`'s `key`. `id` is the key's resource id, the author's name for it, so a stack
355
+ * can make several. In `options.stage`, the stage that deploys the hub, the key is an
356
+ * `Alchemy.Random` at the stack's root, made once and kept in state; the stack's providers need
357
+ * Random's provider (`Convex.providers()` and `Cloudflare.providers()` hold one). Every other stage
358
+ * reads that row from the state store, as `IdentityHub.Client.read` does, so it never creates the
359
+ * key; before the hub's stage ran, there is no row and no key (`undefined`).
360
+ */
361
+ const registrationKey = (id, options) => Effect.gen(function* () {
362
+ const { stage } = yield* Stack;
363
+ if (stage === options.stage) return (yield* Random(id)).text;
364
+ return Output.fromEffect(Effect.gen(function* () {
365
+ const stack = yield* Stack;
366
+ const row = yield* (yield* yield* State).get({
367
+ stack: stack.name,
368
+ stage: options.stage,
369
+ fqn: id
370
+ }).pipe(Effect.orDie);
371
+ if (row === void 0) return void 0;
372
+ return (yield* Schema.decodeUnknownEffect(SavedKey)(row).pipe(Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason: `the row ${id} of stage ${options.stage} is not an Alchemy.Random` }))))).attr.text;
373
+ }));
374
+ });
322
375
  /**
323
376
  * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,
324
377
  * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when
@@ -348,6 +401,7 @@ const ClientProvider = () => Provider.succeed(Client, {
348
401
  if (app.length > MAX_APP_LENGTH) return yield* new IdentityHubClientFailed({ reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the hub's limit, so set a shorter app` });
349
402
  const enrollment = {
350
403
  app,
404
+ clientName: stack.stage,
351
405
  connectors: sortedSet(news.connectors),
352
406
  redirectUris: sortedSet(news.redirectUris)
353
407
  };
@@ -364,6 +418,6 @@ const ClientProvider = () => Provider.succeed(Client, {
364
418
  }).pipe(Effect.catchTag("IdentityHubClientFailed", (error) => Effect.logWarning(`IdentityHub.Client: the client ${output.clientId} stays on the hub until its removal date: ${error.reason}.`)))
365
419
  });
366
420
  //#endregion
367
- export { ClientProvider as n, defaultApp as r, Client as t };
421
+ export { registrationKey as i, ClientProvider as n, defaultApp as r, Client as t };
368
422
 
369
- //# sourceMappingURL=IdentityHub-lx5BPjOS.js.map
423
+ //# sourceMappingURL=IdentityHub-CDG7GXm6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IdentityHub-CDG7GXm6.js","names":[],"sources":["../src/IdentityHub.ts"],"sourcesContent":["// IdentityHub.Client: one deployment of an app as a client of the identity hub that the stack\n// names, for an app that deploys in its own GitHub Actions run, on any host, and in development as a\n// stage of the same stack. Import it as\n// `import * as IdentityHub from \"@samebase/alchemy-convex/identity-hub\"`; `Convex.providers()`\n// registers its provider.\n//\n// A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs\n// no key and no Samebase account. The token names the repository. The hub reads\n// `/samebase-verification.json` at the origin of the return address, which must name the same\n// repository, and registers the client on that address. The answer holds the client's own\n// registration access token (RFC 7591), and each later deploy reads the client on the hub with that\n// token (RFC 7592). The hub keeps only hashes, so the state is the only record of the secret and the\n// token.\n//\n// The answer to a production registration also holds the app's initial access token (RFC 7591\n// section 1.2) and the repository id. The state of stage `prod` keeps them. A development checkout\n// runs the stack as a stage `dev-<name>`: it reads them with `IdentityHub.Client.read`, and a client\n// with `deploymentType: \"development\"` asks the hub with the token in place of the GitHub token\n// (RFC 133).\n//\n// A hub on the stack layer, which the app's own stack deploys, takes a key in place of a proof:\n// a client with `key` asks with it, from any run, and the hub reads no verification file.\n// `IdentityHub.registrationKey` makes each key in the stage that deploys the hub and reads it in\n// every other stage. That stage's client waits until the hub answers discovery, so one run deploys\n// the hub and registers its client.\n//\n// A client is enrolled in the connectors it signs in through, such as `google` and `github`, at\n// registration (RFC 137), and holds the return addresses its requests may name, one per handler of\n// the app, such as the sign-in callback and the connections callback. The hub records both sets on\n// the client and never changes them: a stack with another set registers a new client.\n//\n// The app is the stack: its name on the hub defaults to the stack's path in the repository, as the\n// state store groups stacks (`owner/repo/<path>`), and `app` for a stack named after the repository.\n// `app` overrides it. The name groups the clients, their budgets, and the initial access token; it\n// plays no part in user ids, which the hub derives from the provider's own id.\n//\n// A push removes a variable that a deploy stops passing, so a failure here must not drop working\n// variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that\n// cannot work asks for a new one: it is gone, or it has another app name, return address set, type,\n// or connector set. If that request fails, the run gives the off values, so the app has guest\n// sign-in and not a broken button. The off values are the `no-hub` variables of a checkout without\n// a hub: Convex needs the variables, and the app hides the button for this client ID.\n//\n// No text in this file quotes an answer or a fetch error, so no log line can hold a secret. The one\n// exception is the connector names of an `invalid_connectors` refusal, each checked against the\n// grammar of a connector name before it is printed.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Output from \"alchemy/Output\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Random } from \"alchemy/Random\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Schema from \"effect/Schema\";\nimport type { Providers } from \"./Providers.ts\";\n\n/** A hung service must not hold a deploy: the time limit of one request. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** The variables of a deployment without a hub client, as the starter writes them. */\nconst OFF_VALUES = { issuer: \"http://127.0.0.1:1\", clientId: \"no-hub\", clientSecret: \"no-hub\" };\n\n/** The name of a connector on the hub. */\nconst CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;\n\n/** The return addresses of one client, as the hub caps them. */\nconst MAX_REDIRECT_URIS = 8;\n/** The app's name, as the hub caps it. A deeper stack path needs an explicit `app`. */\nconst MAX_APP_LENGTH = 64;\n\n/**\n * The app's default name: the stack's path below `owner/repo`, or `app` for a stack named after\n * the repository. Undefined for a stack whose name is not `owner/repo` or `owner/repo/<path>`.\n */\nexport const defaultApp = (stackName: string): string | undefined => {\n const segments = stackName.split(\"/\");\n if (segments.length < 2 || segments.some((segment) => segment === \"\")) {\n return undefined;\n }\n return segments.slice(2).join(\"/\") || \"app\";\n};\n\n/**\n * An identity hub of @samebase/identity-broker, such as Samebase's public hub:\n * `{ issuer: \"https://id.samebase.com\" }`.\n */\nexport interface Hub {\n /**\n * The hub's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/register`, with\n * a GitHub token whose audience is the issuer, so no other hub can use that token.\n */\n readonly issuer: string;\n}\n\ninterface CommonProps {\n /**\n * The app's name in its repository. Default: the stack's path in the repository, `apps/samebase`\n * for the stack `samebase/samebase/apps/samebase`, and `app` for a stack named after the\n * repository. A changed name registers a new client under the new name.\n */\n readonly app?: string;\n /** The hub to register at. A changed hub registers a new client there; the old one stays. */\n readonly hub: Hub;\n /**\n * The connectors the client signs in through, by their names on the hub, such as\n * `[\"google\", \"github\"]`: at least one, each of `[a-z0-9-]{1,64}`. The hub refuses a name it does\n * not offer, or does not allow this repository, and the log then names the allowed ones. The set\n * is recorded on the client for good: a changed set registers a new client.\n */\n readonly connectors: readonly string[];\n /**\n * The return addresses of this deployment, one to eight, such as\n * `[`${site.siteUrl}/auth/hub/callback`]`: each an https URL whose origin serves\n * `/samebase-verification.json` with the numeric GitHub id of this repository,\n * `{ \"repository\": \"123\" }`. They can come from a resource that this run creates. A development\n * client can also have http on a loopback host, which needs no file. Every request of the client\n * names one of them. The set is recorded on the client for good: a changed set registers a new\n * client.\n */\n readonly redirectUris: string[];\n /** Recorded on the hub's client, such as the commit. The hub records \"unknown\" without it. */\n readonly softwareVersion?: string;\n /**\n * The run fails unless the hub confirms the client in this run: it fails when the hub refuses or\n * does not answer a registration or a renewal, and when it suspended the client. Without it, such\n * a run gives the off values or keeps the saved client, so the app deploys anyway. Set it where\n * sign-in is the product. A failed run saves nothing, so the next run asks the hub again.\n */\n readonly required?: boolean;\n}\n\n/**\n * A production or preview client asks with the GitHub OIDC token of the run. A development client\n * asks with the app's initial access token, which `IdentityHub.Client.read` gives from stage `prod`.\n * A client of any type with `key` asks with that key, a key of a hub on the stack layer, such as\n * `IdentityHub.registrationKey` gives.\n */\nexport type ClientProps =\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\";\n readonly initialAccessToken?: never;\n readonly key?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"development\";\n /** Empty before the first production registration: the client gets the off values. */\n readonly initialAccessToken: Redacted.Redacted<string>;\n readonly key?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\" | \"development\";\n /**\n * The Bearer of `POST /register`. Undefined, as before the stage that makes the key ever\n * ran: the client gets the off values, or the run fails when `required`. The hub decides\n * whether this key may register a production client.\n */\n readonly key: Redacted.Redacted<string> | undefined;\n readonly initialAccessToken?: never;\n });\n\nconst DeploymentType = Schema.Literals([\"production\", \"preview\", \"development\"]);\n\nconst Attributes = Schema.Struct({\n /** `off`: no client, and the values below are the off values. */\n status: Schema.Literals([\"on\", \"off\", \"suspended\"]),\n /** The issuer of the hub, which the deployment names to sign in. */\n issuer: Schema.String,\n clientId: Schema.String,\n /** Returned only at registration. */\n clientSecret: Schema.Redacted(Schema.String),\n /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */\n registrationAccessToken: Schema.Redacted(Schema.String),\n registrationClientUri: Schema.String,\n deploymentType: DeploymentType,\n /** The app's name on the hub, as sent. Empty for the off values. */\n app: Schema.String,\n /** The return addresses the client serves, sorted, each once. Empty for the off values. */\n redirectUris: Schema.Array(Schema.String),\n /** The connectors the client is enrolled in, sorted, each once. Empty for the off values. */\n connectors: Schema.Array(Schema.String),\n /**\n * Returned only at a production registration (RFC 7591 section 1.2). It registers development\n * clients of this app. Empty for a preview, for a development client, and for the off values.\n */\n initialAccessToken: Schema.Redacted(Schema.String),\n /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */\n repository: Schema.String,\n});\n\n/**\n * The attributes keep the real values of a suspended client, so that an unblock needs no new client.\n * `IdentityHub.Client.variables` gives the values that the app gets.\n */\nexport interface ClientAttributes extends Schema.Schema.Type<typeof Attributes> {}\n\n/**\n * The attributes of a saved row. A row that does not have this version's shape, or any other\n * failure of the decoder, stops the run with `reason`. The text of a schema issue can quote a value\n * of the row, so it is never kept.\n */\nconst savedAttributes = (value: unknown, reason: string) =>\n Schema.decodeUnknownEffect(Attributes)(value).pipe(\n Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason }))),\n );\n\n/** The attributes of no client. */\nconst offAttributes = (deploymentType: ClientAttributes[\"deploymentType\"]): ClientAttributes => ({\n status: \"off\",\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n registrationAccessToken: Redacted.make(\"\"),\n registrationClientUri: \"\",\n deploymentType,\n app: \"\",\n redirectUris: [],\n connectors: [],\n initialAccessToken: Redacted.make(\"\"),\n repository: \"\",\n});\n\n/** The set of `values`: sorted, each once. */\nconst sortedSet = (values: readonly string[]) => [...new Set(values)].sort();\n\nconst sameSet = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && a.every((name, index) => name === b[index]);\n\n/** The app and its return addresses, as every log line names a client: no secret, no answer. */\nconst where = (client: { app: string; redirectUris: readonly string[] }) =>\n `${client.app} on ${client.redirectUris.join(\", \")}`;\n\n/**\n * What one registration sends, resolved from the props: the app's name, the deployment's name (the\n * stage), and both sets.\n */\ninterface Enrollment {\n readonly app: string;\n readonly clientName: string;\n readonly connectors: readonly string[];\n readonly redirectUris: readonly string[];\n}\n\n/** One request gave no usable answer. The reason holds no secret. */\nclass IdentityHubClientFailed extends Schema.TaggedError<IdentityHubClientFailed>()(\n \"IdentityHubClientFailed\",\n { reason: Schema.String },\n) {\n override get message() {\n return `IdentityHub.Client: ${this.reason}.`;\n }\n}\n\nconst OidcToken = Schema.Struct({ value: Schema.NonEmptyString });\n\n/**\n * The 201 answer of `POST /register` (RFC 7591 section 3.2.1), in the members that this file reads.\n * The decoder ignores the other members, such as `software_id`, whose full form the hub writes.\n */\nconst NewClient = Schema.Struct({\n issuer: Schema.NonEmptyString,\n client_id: Schema.NonEmptyString,\n client_secret: Schema.NonEmptyString,\n registration_access_token: Schema.NonEmptyString,\n registration_client_uri: Schema.NonEmptyString,\n /** The sets the hub recorded, which must be the sets the request sent. */\n redirect_uris: Schema.Array(Schema.String),\n connectors: Schema.Array(Schema.String),\n /** Only in the answer to a production registration with the GitHub token. */\n initial_access_token: Schema.optionalKey(Schema.NonEmptyString),\n repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\\d+$/))),\n});\n\n/** The other answers of `POST /register`, by status. A 401 can have no body (RFC 6750). */\nconst REFUSALS: Readonly<Record<number, string>> = {\n 400: \"the identity hub refused the client metadata, such as the app name\",\n 401: \"the identity hub refused the GitHub OIDC token\",\n 403: \"the identity hub does not allow this repository\",\n 404: \"the identity hub has no /register: it runs an identity-broker before 0.33.0\",\n 429: \"the identity hub limits new clients\",\n 502: \"GitHub's keys are not available to the identity hub\",\n 503: \"the identity hub could not apply its policy\",\n};\n\n/** The text of an `invalid_redirect_uri` 400 without a known reason. */\nconst BAD_REDIRECT_URIS =\n \"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\";\n\n/**\n * The reasons of a 400 or a 403 that a log line shows. Any other text of the answer is never\n * logged.\n */\nconst REASONS = new Map([\n [\"paused\", \"this app is paused on the identity hub\"],\n [\"run_not_allowed\", \"the identity hub gives clients only to runs of main and of pull requests\"],\n [\"blocked\", \"Samebase blocked this repository or its owner\"],\n [\"suspended\", \"the identity hub suspended this repository\"],\n [\"too_many_apps\", \"the repository has as many apps on the identity hub as it may\"],\n [\"too_many_clients\", \"the app has as many clients on the identity hub as it may\"],\n [\"app_taken\", \"the app's name belongs to another app on the identity hub\"],\n [\"host_unreachable\", \"the identity hub could not reach the host of the return address\"],\n [\n \"verification_file_missing\",\n \"the host of the return address does not serve /samebase-verification.json\",\n ],\n [\"verification_file_invalid\", \"/samebase-verification.json on the host holds no repository id\"],\n [\"repository_mismatch\", \"/samebase-verification.json on the host names another repository\"],\n [\"app_mismatch\", \"the initial access token belongs to another app on the identity hub\"],\n [\"stale_proof\", \"the identity hub took a newer GitHub OIDC token of this repository\"],\n]);\n\n/** The windows of a 429, by the name that the answer gives. */\nconst RATE_LIMITED = new Map([\n [\"repository\", \"the identity hub gives one repository at most 30 new clients an hour\"],\n [\"owner\", \"the identity hub gives one owner at most 100 new clients an hour\"],\n [\"new_owners\", \"the identity hub takes at most 50 new owners an hour\"],\n]);\n\nconst Refusal = Schema.Struct({ reason: Schema.String });\nconst InvalidRedirectUri = Schema.Struct({ error: Schema.Literal(\"invalid_redirect_uri\") });\nconst RateLimited = Schema.Struct({ window: Schema.String });\n/** A 400 for a connector the hub does not offer or allow, with the names it allows. */\nconst InvalidConnectors = Schema.Struct({\n reason: Schema.Literal(\"invalid_connectors\"),\n allowed: Schema.Array(Schema.String),\n});\n\n/**\n * The text of a refusal: a known reason of a 400 or a 403, or window of a 429, the allowed\n * connectors of an `invalid_connectors` 400 (only names of the connector grammar, so no other text\n * of the answer is printed), the text of an `invalid_redirect_uri` 400, else the text of its\n * status. `body` is undefined for an answer without JSON, such as a bare 401.\n */\nconst refusalOf = (status: number, body: unknown): string => {\n const decoded = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>\n Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));\n const ofStatus = () => REFUSALS[status] ?? \"the identity hub refused the request\";\n switch (status) {\n case 400: {\n const allowed = decoded(InvalidConnectors)?.allowed.filter((name) =>\n CONNECTOR_NAME.test(name),\n );\n return allowed === undefined\n ? (REASONS.get(decoded(Refusal)?.reason ?? \"\") ??\n (decoded(InvalidRedirectUri) === undefined ? ofStatus() : BAD_REDIRECT_URIS))\n : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? \"none for this app\" : allowed.join(\", \")}`;\n }\n case 403:\n return REASONS.get(decoded(Refusal)?.reason ?? \"\") ?? ofStatus();\n case 429:\n return RATE_LIMITED.get(decoded(RateLimited)?.window ?? \"\") ?? ofStatus();\n default:\n return ofStatus();\n }\n};\n\n/**\n * One request to `who` at `url`, with `token` as its Bearer. A token goes only to an https URL:\n * to any other URL the request is not made.\n */\nconst send = (\n who: string,\n url: string,\n token: string | undefined,\n init: { method: string; body?: string },\n) =>\n token !== undefined && !(URL.canParse(url) && new URL(url).protocol === \"https:\")\n ? Effect.fail(\n new IdentityHubClientFailed({\n reason: `${who} is not at an https URL, so no credential was sent to it`,\n }),\n )\n : Effect.tryPromise({\n try: async () => {\n const response = await fetch(url, {\n ...init,\n headers: {\n ...(token === undefined ? {} : { Authorization: `Bearer ${token}` }),\n \"Content-Type\": \"application/json\",\n },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n const body: unknown = await response.json().catch(() => undefined);\n return { status: response.status, body };\n },\n catch: () => new IdentityHubClientFailed({ reason: `${who} gave no answer` }),\n });\n\nconst decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, who: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => new IdentityHubClientFailed({ reason: `${who} gave a bad answer` })),\n );\n\n/**\n * The OIDC token of this run for `audience`, read right before the call, because it lives for\n * minutes only.\n */\nconst readOidcToken = (requestUrl: string, requestToken: string, audience: string) =>\n Effect.gen(function* () {\n const { body, status } = yield* send(\n \"GitHub\",\n `${requestUrl}&audience=${encodeURIComponent(audience)}`,\n requestToken,\n { method: \"GET\" },\n );\n if (status !== 200) {\n return yield* new IdentityHubClientFailed({\n reason: `GitHub gave no OIDC token (HTTP ${status})`,\n });\n }\n return (yield* decode(OidcToken, \"GitHub\")(body)).value;\n });\n\n/**\n * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial\n * access token: the GitHub OIDC token, the app's own token, or a key of the hub. `software_id` is\n * the app's name, `client_name` the stage, and `connectors` and `deployment_type` are the hub's own\n * metadata fields. Convex Auth posts the client's secret in the body at the token endpoint, so the\n * client registers that method.\n */\nconst requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: string) =>\n Effect.gen(function* () {\n const { hub } = props;\n const { app, connectors, redirectUris } = enrollment;\n const { body, status } = yield* send(\"The identity hub\", `${hub.issuer}/register`, bearer, {\n method: \"POST\",\n body: JSON.stringify({\n redirect_uris: redirectUris,\n software_id: app,\n software_version: props.softwareVersion ?? \"unknown\",\n client_name: enrollment.clientName,\n deployment_type: props.deploymentType,\n connectors,\n token_endpoint_auth_method: \"client_secret_post\",\n }),\n });\n if (status !== 201) {\n const reason =\n status !== 401\n ? refusalOf(status, body)\n : \"key\" in props\n ? \"the identity hub refused the registration key\"\n : props.deploymentType === \"development\"\n ? \"the identity hub refused the initial access token\"\n : refusalOf(status, body);\n return yield* new IdentityHubClientFailed({ reason: `${reason} (HTTP ${status})` });\n }\n const client = yield* decode(NewClient, \"The identity hub\")(body);\n // The hub registers the addresses and the connectors that the request sent, under its own\n // issuer. The log and the state hold the stack's values, so no value that the answer chose is\n // printed or kept.\n if (\n client.issuer !== hub.issuer ||\n !sameSet(sortedSet(client.redirect_uris), redirectUris) ||\n !sameSet(client.connectors, connectors)\n ) {\n return yield* new IdentityHubClientFailed({ reason: \"The identity hub gave a bad answer\" });\n }\n yield* Effect.logInfo(\n `IdentityHub.Client: ${where(enrollment)} has a new client of the identity hub ${hub.issuer}.`,\n );\n // Only a production registration gives the app's token (RFC 7591); any other answer's is dropped.\n const production = props.deploymentType === \"production\";\n return {\n status: \"on\" as const,\n issuer: hub.issuer,\n clientId: client.client_id,\n clientSecret: Redacted.make(client.client_secret),\n registrationAccessToken: Redacted.make(client.registration_access_token),\n registrationClientUri: client.registration_client_uri,\n deploymentType: props.deploymentType,\n app,\n redirectUris,\n connectors,\n initialAccessToken: Redacted.make(production ? (client.initial_access_token ?? \"\") : \"\"),\n repository: production ? (client.repository ?? \"\") : \"\",\n };\n });\n\nconst Discovery = Schema.Struct({ issuer: Schema.String });\n\n/**\n * The time a hub has to answer discovery before a registration with a key: the stage that deploys\n * the hub registers its own client in the same run, and a new workers.dev route answers after\n * about a minute. Delays of 1, 2, 4, 8 and then 15 seconds, about three minutes in all.\n */\nconst DISCOVERY_RETRY = {\n times: 15,\n schedule: Schedule.min([Schedule.exponential(\"1 second\"), Schedule.spaced(\"15 seconds\")]),\n};\n\n/**\n * Succeeds when the hub's discovery document names the hub's issuer, after bounded retries; fails\n * when it never does.\n */\nconst hubAnswers = (hub: Hub) =>\n send(\"The identity hub\", `${hub.issuer}/.well-known/openid-configuration`, undefined, {\n method: \"GET\",\n }).pipe(\n Effect.flatMap(({ body, status }) =>\n status === 200 &&\n Option.getOrUndefined(Schema.decodeUnknownOption(Discovery)(body))?.issuer === hub.issuer\n ? Effect.void\n : Effect.fail(\n new IdentityHubClientFailed({ reason: \"the identity hub does not answer discovery\" }),\n ),\n ),\n Effect.retry(DISCOVERY_RETRY),\n );\n\n/** A new client, or the off values. */\nconst newClient = (props: ClientProps, enrollment: Enrollment) => {\n const label = `IdentityHub.Client: ${where(enrollment)} deploys without the hub`;\n const off = offAttributes(props.deploymentType);\n const request = (bearer: Effect.Effect<string, IdentityHubClientFailed>) =>\n bearer.pipe(\n Effect.flatMap((token) => requestNewClient(props, enrollment, token)),\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(\n Effect.as(off),\n ),\n ),\n );\n\n if (\"key\" in props) {\n return props.key === undefined\n ? Effect.logInfo(\n `${label}: it has no registration key yet. Deploy the stage that makes the key first.`,\n ).pipe(Effect.as(off))\n : request(Effect.as(hubAnswers(props.hub), Redacted.value(props.key)));\n }\n\n if (props.deploymentType === \"development\") {\n const token = Redacted.value(props.initialAccessToken);\n return token === \"\"\n ? Effect.logInfo(\n \"IdentityHub.Client: deploy to main once for hub sign-in in development.\",\n ).pipe(Effect.as(off))\n : request(Effect.succeed(token));\n }\n\n const requestUrl = process.env[\"ACTIONS_ID_TOKEN_REQUEST_URL\"];\n const requestToken = process.env[\"ACTIONS_ID_TOKEN_REQUEST_TOKEN\"];\n // A development machine, or another CI. In a workflow, `id-token: write` gives both, so a\n // workflow without them is a mistake to show, not a normal run.\n if (!requestUrl || !requestToken) {\n return (\n process.env[\"GITHUB_ACTIONS\"] === \"true\"\n ? Effect.logWarning(`${label}: this workflow needs the permission id-token: write.`)\n : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)\n ).pipe(Effect.as(off));\n }\n return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));\n};\n\n/**\n * The client after a read on the hub, or undefined when the hub says that the client is gone. A\n * read with no usable answer keeps the saved client, except for a required one: a required client\n * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,\n * and did not save because that run failed, cannot pass a run that the hub does not answer.\n */\nconst renew = (saved: ClientAttributes, required: boolean) =>\n Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n saved.registrationClientUri,\n Redacted.value(saved.registrationAccessToken),\n { method: \"GET\" },\n );\n switch (status) {\n case 200:\n return { ...saved, status: \"on\" as const };\n case 401:\n return undefined;\n case 403:\n yield* Effect.logWarning(\n `IdentityHub.Client: the hub suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`,\n );\n return { ...saved, status: \"suspended\" as const };\n default:\n return yield* new IdentityHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n required\n ? Effect.fail(\n new IdentityHubClientFailed({\n reason: `${where(saved)} is required, and the hub did not confirm its client: ${error.reason}`,\n }),\n )\n : Effect.logWarning(\n `IdentityHub.Client: ${where(saved)} keeps the saved client: ${error.reason}.`,\n ).pipe(Effect.as(saved)),\n ),\n );\n\n/**\n * The type of this resource before 0.37.0. Alchemy finds this provider for a row of that type, and\n * the next write of the row gives it the new type, with the same client. Remove it, here and in\n * `SavedRow`, once no saved row has the old type.\n */\nconst OLD_TYPE = \"IdentityHub.SharedClient\";\n\n/** A saved row of this resource, whose `attr` `savedAttributes` reads. */\nconst SavedRow = Schema.Struct({\n resourceType: Schema.Literals([\"IdentityHub.Client\", OLD_TYPE]),\n attr: Schema.Unknown,\n});\n\n/**\n * The attributes of the client `id` in another stage of this stack, such as\n * `read(\"HubClient\", { stage: \"prod\" })` in a development stage, as Outputs: the\n * `initialAccessToken` and the `repository` of the production client. Without that row, the off\n * attributes, with `deploymentType: \"production\"`.\n *\n * `IdentityHub.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the\n * row is missing, and a development stage before the first deploy to main has none. This read runs\n * when the plan resolves it, with the State service of the running stack and its `get`, so it never\n * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every\n * read.\n */\nconst read = (id: string, options: { readonly stage: string }) =>\n Output.fromEffect(\n Effect.gen(function* () {\n const stack = yield* Stack;\n const state = yield* yield* State;\n const row = yield* state\n .get({ stack: stack.name, stage: options.stage, fqn: id })\n .pipe(Effect.orDie);\n if (row === undefined) return offAttributes(\"production\");\n const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(\n Effect.catchCause(() =>\n Effect.die(\n new IdentityHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not an IdentityHub.Client`,\n }),\n ),\n ),\n );\n return yield* savedAttributes(\n attr,\n `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`,\n );\n }),\n );\n\n/** A saved row of an `Alchemy.Random`, whose `text` the store revives as `Redacted`. */\nconst SavedKey = Schema.Struct({\n resourceType: Schema.Literal(\"Alchemy.Random\"),\n attr: Schema.Struct({ text: Schema.Redacted(Schema.String) }),\n});\n\n/**\n * A key of a hub on the stack layer, as a redacted Output, for the hub's secret binding and for\n * `IdentityHub.Client`'s `key`. `id` is the key's resource id, the author's name for it, so a stack\n * can make several. In `options.stage`, the stage that deploys the hub, the key is an\n * `Alchemy.Random` at the stack's root, made once and kept in state; the stack's providers need\n * Random's provider (`Convex.providers()` and `Cloudflare.providers()` hold one). Every other stage\n * reads that row from the state store, as `IdentityHub.Client.read` does, so it never creates the\n * key; before the hub's stage ran, there is no row and no key (`undefined`).\n */\nexport const registrationKey = (id: string, options: { readonly stage: string }) =>\n Effect.gen(function* () {\n const { stage } = yield* Stack;\n if (stage === options.stage) {\n const key: Output.Output<Redacted.Redacted<string> | undefined> = (yield* Random(id)).text;\n return key;\n }\n return Output.fromEffect(\n Effect.gen(function* () {\n const stack = yield* Stack;\n const state = yield* yield* State;\n const row = yield* state\n .get({ stack: stack.name, stage: options.stage, fqn: id })\n .pipe(Effect.orDie);\n if (row === undefined) return undefined;\n const saved = yield* Schema.decodeUnknownEffect(SavedKey)(row).pipe(\n Effect.catchCause(() =>\n Effect.die(\n new IdentityHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not an Alchemy.Random`,\n }),\n ),\n ),\n );\n return saved.attr.text;\n }),\n );\n });\n\n/**\n * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,\n * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when\n * `status` is `on`, else the off values, so that a suspended client gives guest sign-in and keeps\n * its values in state.\n */\nconst variables = (client: Client) =>\n Output.map(Output.of(client), (attributes) =>\n attributes.status === \"on\"\n ? {\n issuer: attributes.issuer,\n clientId: attributes.clientId,\n clientSecret: attributes.clientSecret,\n }\n : {\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n },\n );\n\nexport type Client = Resource<\n \"IdentityHub.Client\",\n ClientProps,\n ClientAttributes,\n never,\n Providers\n>;\nexport const Client = Resource<Client>(\"IdentityHub.Client\", { aliases: [OLD_TYPE] })({\n read,\n variables,\n});\n\nexport const ClientProvider = () =>\n Provider.succeed(Client, {\n // Always an update, so that each deploy reaches the hub. No attribute is stable, so a push\n // reads the values that this run ended with. The same values cause no other push.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n // Only a client of the same hub (its issuer), app name, return address set, type, and\n // connector set is renewed. A saved row without this version's shape stops the run with a\n // fixed message.\n reconcile: Effect.fn(function* ({ news, output }) {\n // A bad prop is a mistake of the stack, not of the hub: the run fails, with no request.\n const stack = yield* Stack;\n const app = news.app ?? defaultApp(stack.name);\n if (app === undefined) {\n return yield* new IdentityHubClientFailed({\n reason: `the stack ${stack.name} is not named owner/repo or owner/repo/<path>, so set app`,\n });\n }\n if (app.length > MAX_APP_LENGTH) {\n return yield* new IdentityHubClientFailed({\n reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the hub's limit, so set a shorter app`,\n });\n }\n const enrollment: Enrollment = {\n app,\n clientName: stack.stage,\n connectors: sortedSet(news.connectors),\n redirectUris: sortedSet(news.redirectUris),\n };\n if (\n enrollment.connectors.length === 0 ||\n !enrollment.connectors.every((name) => CONNECTOR_NAME.test(name))\n ) {\n return yield* new IdentityHubClientFailed({\n reason: `${where(enrollment)} needs connectors: one or more names of [a-z0-9-]{1,64}`,\n });\n }\n if (\n enrollment.redirectUris.length === 0 ||\n enrollment.redirectUris.length > MAX_REDIRECT_URIS ||\n !enrollment.redirectUris.every((uri) => URL.canParse(uri))\n ) {\n return yield* new IdentityHubClientFailed({\n reason: `${app} needs redirectUris: one to ${MAX_REDIRECT_URIS} absolute URLs`,\n });\n }\n const saved =\n output === undefined || output.status === \"off\"\n ? undefined\n : yield* savedAttributes(\n output,\n `the saved attributes of ${where(enrollment)} cannot be read by this version`,\n );\n const renewed =\n saved?.issuer === news.hub.issuer &&\n saved.app === app &&\n sameSet(saved.redirectUris, enrollment.redirectUris) &&\n saved.deploymentType === news.deploymentType &&\n sameSet(saved.connectors, enrollment.connectors)\n ? yield* renew(saved, news.required === true)\n : undefined;\n const client = renewed ?? (yield* newClient(news, enrollment));\n if (news.required === true && client.status !== \"on\") {\n return yield* new IdentityHubClientFailed({\n reason: `${where(enrollment)} is required and has no working client (${client.status}). The warning above names the reason`,\n });\n }\n return client;\n }),\n\n // A failed delete does not stop a destroy: the removal date of a preview or development client\n // cleans it up. A destroy can leave a production deployment running, so its client stays.\n delete: ({ output }) =>\n output.deploymentType === \"production\" || output.status === \"off\"\n ? Effect.void\n : Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n output.registrationClientUri,\n Redacted.value(output.registrationAccessToken),\n { method: \"DELETE\" },\n );\n // 401: the client is gone already.\n if (status !== 204 && status !== 401) {\n return yield* new IdentityHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n // The row can be of an earlier version's shape, so the line names only the client id.\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n Effect.logWarning(\n `IdentityHub.Client: the client ${output.clientId} stays on the hub until its removal date: ${error.reason}.`,\n ),\n ),\n ),\n });\n"],"mappings":";;;;;;;;;;;;;;AA6DA,MAAM,qBAAqB;;AAG3B,MAAM,aAAa;CAAE,QAAQ;CAAsB,UAAU;CAAU,cAAc;AAAS;;AAG9F,MAAM,iBAAiB;;AAGvB,MAAM,oBAAoB;;AAE1B,MAAM,iBAAiB;;;;;AAMvB,MAAa,cAAc,cAA0C;CACnE,MAAM,WAAW,UAAU,MAAM,GAAG;CACpC,IAAI,SAAS,SAAS,KAAK,SAAS,MAAM,YAAY,YAAY,EAAE,GAClE;CAEF,OAAO,SAAS,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,KAAK;AACxC;AAgFA,MAAM,iBAAiB,OAAO,SAAS;CAAC;CAAc;CAAW;AAAa,CAAC;AAE/E,MAAM,aAAa,OAAO,OAAO;;CAE/B,QAAQ,OAAO,SAAS;EAAC;EAAM;EAAO;CAAW,CAAC;;CAElD,QAAQ,OAAO;CACf,UAAU,OAAO;;CAEjB,cAAc,OAAO,SAAS,OAAO,MAAM;;CAE3C,yBAAyB,OAAO,SAAS,OAAO,MAAM;CACtD,uBAAuB,OAAO;CAC9B,gBAAgB;;CAEhB,KAAK,OAAO;;CAEZ,cAAc,OAAO,MAAM,OAAO,MAAM;;CAExC,YAAY,OAAO,MAAM,OAAO,MAAM;;;;;CAKtC,oBAAoB,OAAO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EAEH,OAAO;CACT,CAAC;CAID,SAAS,EAAE,aACT,OAAO,mBAAmB,gBAAgB,OAAO,WAAW,QACxD,OAAO,OACP,OAAO,IAAI,aAAa;EACtB,MAAM,EAAE,WAAW,OAAO,KACxB,oBACA,OAAO,uBACP,SAAS,MAAM,OAAO,uBAAuB,GAC7C,EAAE,QAAQ,SAAS,CACrB;EAEA,IAAI,WAAW,OAAO,WAAW,KAC/B,OAAO,OAAO,IAAI,wBAAwB,EACxC,QAAQ,kCAAkC,SAC5C,CAAC;CAEL,CAAC,CAAC,CAAC,KAED,OAAO,SAAS,4BAA4B,UAC1C,OAAO,WACL,kCAAkC,OAAO,SAAS,4CAA4C,MAAM,OAAO,EAC7G,CACF,CACF;AACR,CAAC"}
@@ -1,9 +1,11 @@
1
1
  import { t as Providers } from "./Providers-zL1fUs0r.js";
2
2
  import { Stack } from "alchemy/Stack";
3
+ import * as Effect from "effect/Effect";
3
4
  import * as Schema from "effect/Schema";
4
5
  import * as Redacted from "effect/Redacted";
5
6
  import { Resource } from "alchemy";
6
7
  import * as Provider from "alchemy/Provider";
8
+ import { Random } from "alchemy/Random";
7
9
  import * as Output from "alchemy/Output";
8
10
  import { State } from "alchemy/State";
9
11
  //#region src/IdentityHub.d.ts
@@ -62,14 +64,27 @@ interface CommonProps {
62
64
  /**
63
65
  * A production or preview client asks with the GitHub OIDC token of the run. A development client
64
66
  * asks with the app's initial access token, which `IdentityHub.Client.read` gives from stage `prod`.
67
+ * A client of any type with `key` asks with that key, a key of a hub on the stack layer, such as
68
+ * `IdentityHub.registrationKey` gives.
65
69
  */
66
70
  export type ClientProps = (CommonProps & {
67
71
  readonly deploymentType: "production" | "preview";
68
72
  readonly initialAccessToken?: never;
73
+ readonly key?: never;
69
74
  }) | (CommonProps & {
70
75
  readonly deploymentType: "development";
71
76
  /** Empty before the first production registration: the client gets the off values. */
72
77
  readonly initialAccessToken: Redacted.Redacted<string>;
78
+ readonly key?: never;
79
+ }) | (CommonProps & {
80
+ readonly deploymentType: "production" | "preview" | "development";
81
+ /**
82
+ * The Bearer of `POST /register`. Undefined, as before the stage that makes the key ever
83
+ * ran: the client gets the off values, or the run fails when `required`. The hub decides
84
+ * whether this key may register a production client.
85
+ */
86
+ readonly key: Redacted.Redacted<string> | undefined;
87
+ readonly initialAccessToken?: never;
73
88
  });
74
89
  declare const Attributes: Schema.Struct<{
75
90
  /** `off`: no client, and the values below are the off values. */
@@ -102,6 +117,18 @@ declare const Attributes: Schema.Struct<{
102
117
  * `IdentityHub.Client.variables` gives the values that the app gets.
103
118
  */
104
119
  export interface ClientAttributes extends Schema.Schema.Type<typeof Attributes> {}
120
+ /**
121
+ * A key of a hub on the stack layer, as a redacted Output, for the hub's secret binding and for
122
+ * `IdentityHub.Client`'s `key`. `id` is the key's resource id, the author's name for it, so a stack
123
+ * can make several. In `options.stage`, the stage that deploys the hub, the key is an
124
+ * `Alchemy.Random` at the stack's root, made once and kept in state; the stack's providers need
125
+ * Random's provider (`Convex.providers()` and `Cloudflare.providers()` hold one). Every other stage
126
+ * reads that row from the state store, as `IdentityHub.Client.read` does, so it never creates the
127
+ * key; before the hub's stage ran, there is no row and no key (`undefined`).
128
+ */
129
+ export declare const registrationKey: (id: string, options: {
130
+ readonly stage: string;
131
+ }) => Effect.Effect<Output.Output<Redacted.Redacted<string> | undefined, any>, never, Stack | Provider.Provider<Random>>;
105
132
  export type Client = Resource<"IdentityHub.Client", ClientProps, ClientAttributes, never, Providers>;
106
133
  export declare const Client: import("alchemy").ResourceClassWithMethods<Client, {
107
134
  readonly read: (id: string, options: {
@@ -1 +1 @@
1
- {"version":3,"file":"IdentityHub.d.ts","names":[],"sources":["../src/IdentityHub.ts"],"mappings":";;;;;;;;;;;;;qBAsEa,aAAc;;;;;iBAYV;;;;;WAKN;;UAGD;;;;;;WAMC;;WAEA,KAAK;;;;;;;WAOL;;;;;;;;;;WAUA;;WAEA;;;;;;;WAOA;;;;;;YAOC,eACP;WACU;WACA;MAEV;WACU;;WAEA,oBAAoB,SAAS;;cAKtC,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+BC,yBAAyB,OAAO,OAAO,YAAY;YAyZxD,SAAS,+BAEnB,aACA,yBAEA;qBAEW,0BAAM,yBAAA;WArDD,OAAA,YAAM;aAAsB;QAAe,OAAA;;;;;;;;;;;;;;WA+BlC,YAAA,QAAA,WAAM,OAAA;;;;;;qBA2BpB,6CAAc,MAAA,SAAA,SAAA,gBAAA"}
1
+ {"version":3,"file":"IdentityHub.d.ts","names":[],"sources":["../src/IdentityHub.ts"],"mappings":";;;;;;;;;;;;;;;qBA8Ea,aAAc;;;;;iBAYV;;;;;WAKN;;UAGD;;;;;;WAMC;;WAEA,KAAK;;;;;;;WAOL;;;;;;;;;;WAUA;;WAEA;;;;;;;WAOA;;;;;;;;YASC,eACP;WACU;WACA;WACA;MAEV;WACU;;WAEA,oBAAoB,SAAS;WAC7B;MAEV;WACU;;;;;;WAMA,KAAK,SAAS;WACd;;cAKT,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+BC,yBAAyB,OAAO,OAAO,YAAY;;;;;;;;;;qBAudvD,kBAAmB,YAAY;WAAoB;MAAe,OAAA,OAAA,OAAA,OAAA,SAAA,2CAAA,QAAA,SAAA,SAAA;YAkDnE,SAAS,+BAEnB,aACA,yBAEA;qBAEW,0BAAM,yBAAA;WAjGD,OAAA,YAAM;aAAsB;QAAe,OAAA;;;;;;;;;;;;;;WA2ElC,YAAA,QAAA,WAAM,OAAA;;;;;;qBA2BpB,6CAAc,MAAA,SAAA,SAAA,gBAAA"}
@@ -1 +1 @@
1
- export { t as Client, n as ClientProvider, r as defaultApp } from "./IdentityHub-lx5BPjOS.js";
1
+ export { t as Client, n as ClientProvider, r as defaultApp, i as registrationKey } from "./IdentityHub-CDG7GXm6.js";
@@ -1 +1 @@
1
- {"version":3,"file":"Providers-zL1fUs0r.d.ts","names":[],"sources":["../src/Credentials.ts","../src/Providers.ts"],"mappings":";;;;;;;UA6BiB;;WAEN,aAAa,SAAS;;WAEtB;;UAGM;;WAEN,aAAa,OAAO,OAAO;;WAE3B,gBAAgB,OAAO;;WAEvB,WAAW,OAAO,OAAO,SAAS;;;cAGhC,oBAAoB;;cAKpB;;cAGA;;;;cAOA,yBAAyB;;;;;;;;;cAiCzB,kBAAiB,MAAM,MAAM;;cA0B7B,aAAc;WAChB,cAAc,SAAS;WACvB,YAAY,SAAS;MAC5B,MAAM,MAAM;;;;cC/GH,kBAAkB;;;;;;cAOlB,YAAa,cAAa,MAAM,MAAM,iBAA2B,MAAA,MAAA,oCAAA,qDAAA,kDAAA,mCAAA"}
1
+ {"version":3,"file":"Providers-zL1fUs0r.d.ts","names":[],"sources":["../src/Credentials.ts","../src/Providers.ts"],"mappings":";;;;;;;UA6BiB;;WAEN,aAAa,SAAS;;WAEtB;;UAGM;;WAEN,aAAa,OAAO,OAAO;;WAE3B,gBAAgB,OAAO;;WAEvB,WAAW,OAAO,OAAO,SAAS;;;cAGhC,oBAAoB;;cAKpB;;cAGA;;;;cAOA,yBAAyB;;;;;;;;;cAiCzB,kBAAiB,MAAM,MAAM;;cA0B7B,aAAc;WAChB,cAAc,SAAS;WACvB,YAAY,SAAS;MAC5B,MAAM,MAAM;;;;cC9GH,kBAAkB;;;;;;cAOlB,YAAa,cAAa,MAAM,MAAM,iBAA2B,MAAA,MAAA,oCAAA,qDAAA,kDAAA,mCAAA"}
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { A as Credentials, C as parseDeployOutput, D as ManagementApiLive, E as ManagementApi, M as DEPLOY_KEY_ENV, N as fromConfig, O as readLocalDeployment, P as fromValues, S as VariablesOwnedBySomeoneElse, T as ConvexApiError, _ as CodePushFailed, a as Project, b as EnvironmentNeedsDeployKey, c as ProjectProvider, d as AmbiguousDeployment, f as Deployment, g as ProductionDeploymentNotFound, h as DeploymentResource, i as CreatedProjectNotFound, j as CredentialsError, k as ACCESS_TOKEN_ENV, l as ProjectTeamChange, m as DeploymentProvider, n as state, o as ProjectDeploymentChange, p as DeploymentIdentityChange, r as AmbiguousProject, s as ProjectNotFound, t as STORE_PROJECT_NAME, u as AbsoluteRootDir, v as ConvexAppNotFound, w as push, x as PushTargetMismatch, y as ConvexCliNotFound } from "./State-Bp7iSx8T.js";
2
- import { n as ClientProvider, t as Client } from "./IdentityHub-lx5BPjOS.js";
2
+ import { n as ClientProvider, t as Client } from "./IdentityHub-CDG7GXm6.js";
3
3
  import { toPath } from "alchemy/FQN";
4
4
  import { Stack } from "alchemy/Stack";
5
5
  import * as Effect from "effect/Effect";
@@ -9,6 +9,7 @@ import { Resource } from "alchemy";
9
9
  import { isResolved } from "alchemy/Diff";
10
10
  import * as Provider from "alchemy/Provider";
11
11
  import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
+ import { Random, RandomProvider } from "alchemy/Random";
12
13
  import { RUN_RECORD_KEY, RunRecordError, runRecord, withRunRecord } from "@samebase/alchemy-kit/run-record";
13
14
  //#region src/Component.ts
14
15
  /**
@@ -97,8 +98,9 @@ const providers = (credentials = fromConfig()) => Layer.effect(Providers, Provid
97
98
  Project,
98
99
  DeploymentResource,
99
100
  LocalDeployment,
100
- Client
101
- ])).pipe(Layer.provide(Layer.mergeAll(ProjectProvider(), DeploymentProvider(), LocalDeploymentProvider(), ClientProvider())), Layer.provide(ManagementApiLive()), Layer.provide(credentials), Layer.orDie);
101
+ Client,
102
+ Random
103
+ ])).pipe(Layer.provide(Layer.mergeAll(ProjectProvider(), DeploymentProvider(), LocalDeploymentProvider(), ClientProvider(), RandomProvider())), Layer.provide(ManagementApiLive()), Layer.provide(credentials), Layer.orDie);
102
104
  //#endregion
103
105
  export { ACCESS_TOKEN_ENV, AbsoluteRootDir, AmbiguousDeployment, AmbiguousProject, CodePushFailed, ConvexApiError, ConvexAppNotFound, ConvexCliNotFound, CreatedProjectNotFound, Credentials, CredentialsError, DEPLOY_KEY_ENV, Deployment, DeploymentIdentityChange, EnvironmentNeedsDeployKey, LocalDeployment, LocalDeploymentNotFound, ManagementApi, ProductionDeploymentNotFound, Project, ProjectDeploymentChange, ProjectNotFound, ProjectTeamChange, Providers, PushTargetMismatch, RUN_RECORD_KEY, RunRecordError, STORE_PROJECT_NAME, VariablesOwnedBySomeoneElse, bindComponent, fromConfig, fromValues, parseDeployOutput, providers, runRecord, state, withRunRecord };
104
106
 
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["IdentityHub.Client","IdentityHub.ClientProvider"],"sources":["../src/Component.ts","../src/LocalDeployment.ts","../src/Providers.ts"],"sourcesContent":["import { toPath } from \"alchemy/FQN\";\nimport type { NamespaceNode } from \"alchemy/Namespace\";\nimport { Stack } from \"alchemy/Stack\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport type { Deployment } from \"./Deployment.ts\";\n\n/** A component's resources occupy this namespace in the deployment's Alchemy stack and stage. */\nexport interface ComponentBinding {\n readonly type: \"component\";\n readonly path: string;\n readonly namespace: readonly string[];\n}\n\n/**\n * Associate a native namespace with an installed component. `component` is the\n * installed name from the app's `convex.config.ts`; a nested install joins the\n * names with slashes, such as `\"workspace/mail\"`. An undefined namespace\n * associates the stack root. This records display metadata; it does not install\n * the component, set its environment, or change removal policies.\n */\nexport const bindComponent = (options: {\n deployment: Deployment;\n component: string;\n namespace: NamespaceNode | undefined;\n}) =>\n Effect.gen(function* () {\n if (options.component === \"\") {\n return yield* Effect.die(new Error(\"The component name is empty.\"));\n }\n const namespace = toPath(options.namespace);\n const sid = `convex.component:${JSON.stringify(namespace)}`;\n const stack = yield* Stack;\n const previous = stack.bindings[options.deployment.FQN]?.find((binding) => binding.sid === sid);\n // Alchemy keeps the last binding with a given sid. Reject conflicting owners before that happens.\n if (previous !== undefined) {\n const existing = Schema.decodeUnknownSync(Schema.Struct({ path: Schema.String }))(\n previous.data,\n );\n if (existing.path !== options.component) {\n return yield* Effect.die(\n new Error(\n `Alchemy namespace ${JSON.stringify(namespace)} is already bound to ${existing.path}.`,\n ),\n );\n }\n return;\n }\n yield* options.deployment.bind(sid, {\n type: \"component\",\n path: options.component,\n namespace,\n });\n });\n","// Convex.LocalDeployment: the logged-in local deployment of one folder, which\n// `npx convex deployment create <team>:<project>:local --select` makes and `npx convex dev` runs on\n// this machine. Each folder, such as each git worktree, has its own, with its own data.\n//\n// The resource writes its `env` and nothing else. The running `convex dev` owns the backend and\n// pushes the functions, so the development stage runs after `convex dev` has started, and the\n// first push of a new local deployment takes the variables that the project's default variables\n// for development gave it. The resource reads the deployment from\n// `.convex/local/default/config.json`, where the Convex CLI keeps its name, ports, and admin key,\n// and writes with that admin key through the same call as for a cloud deployment.\n//\n// A destroy changes nothing: the folder's deployment and its variables stay with the folder.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Provider from \"alchemy/Provider\";\nimport * as Effect from \"effect/Effect\";\nimport * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\nimport * as Schema from \"effect/Schema\";\nimport { readLocalDeployment } from \"./ManagementApi.ts\";\nimport type { Providers } from \"./Providers.ts\";\nimport { type EnvValue, push } from \"./Push.ts\";\n\n/** The folder has no logged-in local deployment. */\nexport class LocalDeploymentNotFound extends Schema.TaggedError<LocalDeploymentNotFound>()(\n \"LocalDeploymentNotFound\",\n { rootDir: Schema.String },\n) {\n override get message() {\n return `Convex.LocalDeployment: ${this.rootDir} has no logged-in local deployment. Run \\`npx convex deployment create <team>:<project>:local --select\\` there, then \\`npx convex dev\\`.`;\n }\n}\n\n/**\n * The folder's logged-in local deployment, read when the stack's program runs, so that a client\n * can take its `siteUrl`. Fails with `LocalDeploymentNotFound` when the folder has none.\n */\nconst of = (rootDir = \".\") => {\n const info = readLocalDeployment(rootDir);\n if (info === undefined) throw new LocalDeploymentNotFound({ rootDir });\n return { name: info.name, url: info.url, siteUrl: info.siteUrl };\n};\n\nexport interface LocalDeploymentProps {\n /** The folder of the Convex app, where `.convex/local/default` is. The working directory without it. */\n readonly rootDir?: string;\n /** The variables of the deployment. A name that leaves `env` is removed. */\n readonly env: Readonly<Record<string, EnvValue>>;\n}\n\nexport interface LocalDeploymentAttributes {\n readonly name: string;\n readonly url: string;\n readonly siteUrl: string;\n /** The names that this resource set, so a name that leaves `env` is removed. */\n readonly envNames: readonly string[];\n}\n\nexport type LocalDeployment = Resource<\n \"Convex.LocalDeployment\",\n LocalDeploymentProps,\n LocalDeploymentAttributes,\n never,\n Providers\n>;\nexport const LocalDeployment = Resource<LocalDeployment>(\"Convex.LocalDeployment\")({ of });\n\nexport const LocalDeploymentProvider = () =>\n Provider.effect(\n LocalDeployment,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return {\n // Always an update: the variables are read and only changed values are written.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n reconcile: Effect.fn(function* ({ news, output }) {\n const rootDir = news.rootDir ?? \".\";\n const info = readLocalDeployment(rootDir);\n if (info === undefined) return yield* new LocalDeploymentNotFound({ rootDir });\n // Without `source`, a push only sets the variables and removes the names that left `env`.\n yield* push(spawner, info.adminKey, {\n deployment: info.name,\n url: info.url,\n rootDir,\n source: undefined,\n env: news.env,\n previousEnvNames: output?.name === info.name ? output.envNames : [],\n adopt: true,\n previewName: undefined,\n });\n return {\n name: info.name,\n url: info.url,\n siteUrl: info.siteUrl,\n envNames: Object.keys(news.env).sort(),\n };\n }),\n\n delete: () => Effect.void,\n };\n }),\n );\n","// The provider collection users merge into a stack:\n// providers: Layer.mergeAll(Cloudflare.providers(), Convex.providers())\nimport * as Provider from \"alchemy/Provider\";\nimport * as Layer from \"effect/Layer\";\nimport { type Credentials, fromConfig } from \"./Credentials.ts\";\nimport { DeploymentProvider, DeploymentResource } from \"./Deployment.ts\";\nimport * as IdentityHub from \"./IdentityHub.ts\";\nimport { LocalDeployment, LocalDeploymentProvider } from \"./LocalDeployment.ts\";\nimport { ManagementApiLive } from \"./ManagementApi.ts\";\nimport { Project, ProjectProvider } from \"./Project.ts\";\n\nexport class Providers extends Provider.ProviderCollection<Providers>()(\"Convex\") {}\n\n/**\n * The Convex resource providers. Pass a credentials layer to override the\n * default lookup (`CONVEX_ACCESS_TOKEN`, then the Convex CLI login, and\n * `CONVEX_DEPLOY_KEY`).\n */\nexport const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>\n Layer.effect(\n Providers,\n Provider.collection([Project, DeploymentResource, LocalDeployment, IdentityHub.Client]),\n ).pipe(\n Layer.provide(\n Layer.mergeAll(\n ProjectProvider(),\n DeploymentProvider(),\n LocalDeploymentProvider(),\n IdentityHub.ClientProvider(),\n ),\n ),\n Layer.provide(ManagementApiLive()),\n Layer.provide(credentials),\n Layer.orDie,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,iBAAiB,YAK5B,OAAO,IAAI,aAAa;CACtB,IAAI,QAAQ,cAAc,IACxB,OAAO,OAAO,OAAO,oBAAI,IAAI,MAAM,8BAA8B,CAAC;CAEpE,MAAM,YAAY,OAAO,QAAQ,SAAS;CAC1C,MAAM,MAAM,oBAAoB,KAAK,UAAU,SAAS;CAExD,MAAM,YAAW,OADI,MAAA,CACE,SAAS,QAAQ,WAAW,IAAI,EAAE,MAAM,YAAY,QAAQ,QAAQ,GAAG;CAE9F,IAAI,aAAa,KAAA,GAAW;EAC1B,MAAM,WAAW,OAAO,kBAAkB,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC,CAAC,CAC/E,SAAS,IACX;EACA,IAAI,SAAS,SAAS,QAAQ,WAC5B,OAAO,OAAO,OAAO,oBACnB,IAAI,MACF,qBAAqB,KAAK,UAAU,SAAS,EAAE,uBAAuB,SAAS,KAAK,EACtF,CACF;EAEF;CACF;CACA,OAAO,QAAQ,WAAW,KAAK,KAAK;EAClC,MAAM;EACN,MAAM,QAAQ;EACd;CACF,CAAC;AACH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Ac,OAAO;CACvB;AACF,CAAC,CACH;;;AC7FF,IAAa,YAAb,cAA+B,SAAS,mBAA8B,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;;;;;;AAOnF,MAAa,aAAa,cAAwC,WAAW,MAC3E,MAAM,OACJ,WACA,SAAS,WAAW;CAAC;CAAS;CAAoB;CAAiBA;AAAkB,CAAC,CACxF,CAAC,CAAC,KACA,MAAM,QACJ,MAAM,SACJ,gBAAgB,GAChB,mBAAmB,GACnB,wBAAwB,GACxBC,eAA2B,CAC7B,CACF,GACA,MAAM,QAAQ,kBAAkB,CAAC,GACjC,MAAM,QAAQ,WAAW,GACzB,MAAM,KACR"}
1
+ {"version":3,"file":"index.js","names":["IdentityHub.Client","IdentityHub.ClientProvider"],"sources":["../src/Component.ts","../src/LocalDeployment.ts","../src/Providers.ts"],"sourcesContent":["import { toPath } from \"alchemy/FQN\";\nimport type { NamespaceNode } from \"alchemy/Namespace\";\nimport { Stack } from \"alchemy/Stack\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport type { Deployment } from \"./Deployment.ts\";\n\n/** A component's resources occupy this namespace in the deployment's Alchemy stack and stage. */\nexport interface ComponentBinding {\n readonly type: \"component\";\n readonly path: string;\n readonly namespace: readonly string[];\n}\n\n/**\n * Associate a native namespace with an installed component. `component` is the\n * installed name from the app's `convex.config.ts`; a nested install joins the\n * names with slashes, such as `\"workspace/mail\"`. An undefined namespace\n * associates the stack root. This records display metadata; it does not install\n * the component, set its environment, or change removal policies.\n */\nexport const bindComponent = (options: {\n deployment: Deployment;\n component: string;\n namespace: NamespaceNode | undefined;\n}) =>\n Effect.gen(function* () {\n if (options.component === \"\") {\n return yield* Effect.die(new Error(\"The component name is empty.\"));\n }\n const namespace = toPath(options.namespace);\n const sid = `convex.component:${JSON.stringify(namespace)}`;\n const stack = yield* Stack;\n const previous = stack.bindings[options.deployment.FQN]?.find((binding) => binding.sid === sid);\n // Alchemy keeps the last binding with a given sid. Reject conflicting owners before that happens.\n if (previous !== undefined) {\n const existing = Schema.decodeUnknownSync(Schema.Struct({ path: Schema.String }))(\n previous.data,\n );\n if (existing.path !== options.component) {\n return yield* Effect.die(\n new Error(\n `Alchemy namespace ${JSON.stringify(namespace)} is already bound to ${existing.path}.`,\n ),\n );\n }\n return;\n }\n yield* options.deployment.bind(sid, {\n type: \"component\",\n path: options.component,\n namespace,\n });\n });\n","// Convex.LocalDeployment: the logged-in local deployment of one folder, which\n// `npx convex deployment create <team>:<project>:local --select` makes and `npx convex dev` runs on\n// this machine. Each folder, such as each git worktree, has its own, with its own data.\n//\n// The resource writes its `env` and nothing else. The running `convex dev` owns the backend and\n// pushes the functions, so the development stage runs after `convex dev` has started, and the\n// first push of a new local deployment takes the variables that the project's default variables\n// for development gave it. The resource reads the deployment from\n// `.convex/local/default/config.json`, where the Convex CLI keeps its name, ports, and admin key,\n// and writes with that admin key through the same call as for a cloud deployment.\n//\n// A destroy changes nothing: the folder's deployment and its variables stay with the folder.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Provider from \"alchemy/Provider\";\nimport * as Effect from \"effect/Effect\";\nimport * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\nimport * as Schema from \"effect/Schema\";\nimport { readLocalDeployment } from \"./ManagementApi.ts\";\nimport type { Providers } from \"./Providers.ts\";\nimport { type EnvValue, push } from \"./Push.ts\";\n\n/** The folder has no logged-in local deployment. */\nexport class LocalDeploymentNotFound extends Schema.TaggedError<LocalDeploymentNotFound>()(\n \"LocalDeploymentNotFound\",\n { rootDir: Schema.String },\n) {\n override get message() {\n return `Convex.LocalDeployment: ${this.rootDir} has no logged-in local deployment. Run \\`npx convex deployment create <team>:<project>:local --select\\` there, then \\`npx convex dev\\`.`;\n }\n}\n\n/**\n * The folder's logged-in local deployment, read when the stack's program runs, so that a client\n * can take its `siteUrl`. Fails with `LocalDeploymentNotFound` when the folder has none.\n */\nconst of = (rootDir = \".\") => {\n const info = readLocalDeployment(rootDir);\n if (info === undefined) throw new LocalDeploymentNotFound({ rootDir });\n return { name: info.name, url: info.url, siteUrl: info.siteUrl };\n};\n\nexport interface LocalDeploymentProps {\n /** The folder of the Convex app, where `.convex/local/default` is. The working directory without it. */\n readonly rootDir?: string;\n /** The variables of the deployment. A name that leaves `env` is removed. */\n readonly env: Readonly<Record<string, EnvValue>>;\n}\n\nexport interface LocalDeploymentAttributes {\n readonly name: string;\n readonly url: string;\n readonly siteUrl: string;\n /** The names that this resource set, so a name that leaves `env` is removed. */\n readonly envNames: readonly string[];\n}\n\nexport type LocalDeployment = Resource<\n \"Convex.LocalDeployment\",\n LocalDeploymentProps,\n LocalDeploymentAttributes,\n never,\n Providers\n>;\nexport const LocalDeployment = Resource<LocalDeployment>(\"Convex.LocalDeployment\")({ of });\n\nexport const LocalDeploymentProvider = () =>\n Provider.effect(\n LocalDeployment,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return {\n // Always an update: the variables are read and only changed values are written.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n reconcile: Effect.fn(function* ({ news, output }) {\n const rootDir = news.rootDir ?? \".\";\n const info = readLocalDeployment(rootDir);\n if (info === undefined) return yield* new LocalDeploymentNotFound({ rootDir });\n // Without `source`, a push only sets the variables and removes the names that left `env`.\n yield* push(spawner, info.adminKey, {\n deployment: info.name,\n url: info.url,\n rootDir,\n source: undefined,\n env: news.env,\n previousEnvNames: output?.name === info.name ? output.envNames : [],\n adopt: true,\n previewName: undefined,\n });\n return {\n name: info.name,\n url: info.url,\n siteUrl: info.siteUrl,\n envNames: Object.keys(news.env).sort(),\n };\n }),\n\n delete: () => Effect.void,\n };\n }),\n );\n","// The provider collection users merge into a stack:\n// providers: Layer.mergeAll(Cloudflare.providers(), Convex.providers())\nimport * as Provider from \"alchemy/Provider\";\nimport { Random, RandomProvider } from \"alchemy/Random\";\nimport * as Layer from \"effect/Layer\";\nimport { type Credentials, fromConfig } from \"./Credentials.ts\";\nimport { DeploymentProvider, DeploymentResource } from \"./Deployment.ts\";\nimport * as IdentityHub from \"./IdentityHub.ts\";\nimport { LocalDeployment, LocalDeploymentProvider } from \"./LocalDeployment.ts\";\nimport { ManagementApiLive } from \"./ManagementApi.ts\";\nimport { Project, ProjectProvider } from \"./Project.ts\";\n\nexport class Providers extends Provider.ProviderCollection<Providers>()(\"Convex\") {}\n\n/**\n * The Convex resource providers. Pass a credentials layer to override the\n * default lookup (`CONVEX_ACCESS_TOKEN`, then the Convex CLI login, and\n * `CONVEX_DEPLOY_KEY`).\n */\nexport const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>\n Layer.effect(\n Providers,\n // Random's provider serves `IdentityHub.registrationKey` in a stack with no other collection\n // that holds one; with Cloudflare's too, the first found serves it, and both are the same.\n Provider.collection([Project, DeploymentResource, LocalDeployment, IdentityHub.Client, Random]),\n ).pipe(\n Layer.provide(\n Layer.mergeAll(\n ProjectProvider(),\n DeploymentProvider(),\n LocalDeploymentProvider(),\n IdentityHub.ClientProvider(),\n RandomProvider(),\n ),\n ),\n Layer.provide(ManagementApiLive()),\n Layer.provide(credentials),\n Layer.orDie,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,iBAAiB,YAK5B,OAAO,IAAI,aAAa;CACtB,IAAI,QAAQ,cAAc,IACxB,OAAO,OAAO,OAAO,oBAAI,IAAI,MAAM,8BAA8B,CAAC;CAEpE,MAAM,YAAY,OAAO,QAAQ,SAAS;CAC1C,MAAM,MAAM,oBAAoB,KAAK,UAAU,SAAS;CAExD,MAAM,YAAW,OADI,MAAA,CACE,SAAS,QAAQ,WAAW,IAAI,EAAE,MAAM,YAAY,QAAQ,QAAQ,GAAG;CAE9F,IAAI,aAAa,KAAA,GAAW;EAC1B,MAAM,WAAW,OAAO,kBAAkB,OAAO,OAAO,EAAE,MAAM,OAAO,OAA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V;IACA,QAAQ,KAAA;IACR,KAAK,KAAK;IACV,kBAAkB,QAAQ,SAAS,KAAK,OAAO,OAAO,WAAW,CAAC;IAClE,OAAO;IACP,aAAa,KAAA;GACf,CAAC;GACD,OAAO;IACL,MAAM,KAAK;IACX,KAAK,KAAK;IACV,SAAS,KAAK;IACd,UAAU,OAAO,KAAK,KAAK,GAAG,CAAC,CAAC,KAAK;GACvC;EACF,CAAC;EAED,cAAc,OAAO;CACvB;AACF,CAAC,CACH;;;AC5FF,IAAa,YAAb,cAA+B,SAAS,mBAA8B,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;;;;;;AAOnF,MAAa,aAAa,cAAwC,WAAW,MAC3E,MAAM,OACJ,WAGA,SAAS,WAAW;CAAC;CAAS;CAAoB;CAAiBA;CAAoB;AAAM,CAAC,CAChG,CAAC,CAAC,KACA,MAAM,QACJ,MAAM,SACJ,gBAAgB,GAChB,mBAAmB,GACnB,wBAAwB,GACxBC,eAA2B,GAC3B,eAAe,CACjB,CACF,GACA,MAAM,QAAQ,kBAAkB,CAAC,GACjC,MAAM,QAAQ,WAAW,GACzB,MAAM,KACR"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@samebase/alchemy-convex",
3
- "version": "0.41.0",
3
+ "version": "0.42.0",
4
4
  "description": "The Convex plane for Alchemy v2: projects, deployments, environment variables, and the push of the functions",
5
5
  "keywords": [
6
6
  "alchemy",
@@ -18,6 +18,12 @@
18
18
  // with `deploymentType: "development"` asks the hub with the token in place of the GitHub token
19
19
  // (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.
26
+ //
21
27
  // A client is enrolled in the connectors it signs in through, such as `google` and `github`, at
22
28
  // registration (RFC 137), and holds the return addresses its requests may name, one per handler of
23
29
  // the app, such as the sign-in callback and the connections callback. The hub records both sets on
@@ -42,11 +48,13 @@ import { Resource } from "alchemy";
42
48
  import { isResolved } from "alchemy/Diff";
43
49
  import * as Output from "alchemy/Output";
44
50
  import * as Provider from "alchemy/Provider";
51
+ import { Random } from "alchemy/Random";
45
52
  import { Stack } from "alchemy/Stack";
46
53
  import { State } from "alchemy/State";
47
54
  import * as Effect from "effect/Effect";
48
55
  import * as Option from "effect/Option";
49
56
  import * as Redacted from "effect/Redacted";
57
+ import * as Schedule from "effect/Schedule";
50
58
  import * as Schema from "effect/Schema";
51
59
  import type { Providers } from "./Providers.ts";
52
60
 
@@ -128,16 +136,30 @@ interface CommonProps {
128
136
  /**
129
137
  * A production or preview client asks with the GitHub OIDC token of the run. A development client
130
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.
131
141
  */
132
142
  export type ClientProps =
133
143
  | (CommonProps & {
134
144
  readonly deploymentType: "production" | "preview";
135
145
  readonly initialAccessToken?: never;
146
+ readonly key?: never;
136
147
  })
137
148
  | (CommonProps & {
138
149
  readonly deploymentType: "development";
139
150
  /** Empty before the first production registration: the client gets the off values. */
140
151
  readonly initialAccessToken: Redacted.Redacted<string>;
152
+ readonly key?: never;
153
+ })
154
+ | (CommonProps & {
155
+ readonly deploymentType: "production" | "preview" | "development";
156
+ /**
157
+ * 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
159
+ * whether this key may register a production client.
160
+ */
161
+ readonly key: Redacted.Redacted<string> | undefined;
162
+ readonly initialAccessToken?: never;
141
163
  });
142
164
 
143
165
  const DeploymentType = Schema.Literals(["production", "preview", "development"]);
@@ -211,9 +233,13 @@ const sameSet = (a: readonly string[], b: readonly string[]) =>
211
233
  const where = (client: { app: string; redirectUris: readonly string[] }) =>
212
234
  `${client.app} on ${client.redirectUris.join(", ")}`;
213
235
 
214
- /** What one registration sends, resolved from the props: the app's name and both sets. */
236
+ /**
237
+ * What one registration sends, resolved from the props: the app's name, the deployment's name (the
238
+ * stage), and both sets.
239
+ */
215
240
  interface Enrollment {
216
241
  readonly app: string;
242
+ readonly clientName: string;
217
243
  readonly connectors: readonly string[];
218
244
  readonly redirectUris: readonly string[];
219
245
  }
@@ -331,19 +357,37 @@ const refusalOf = (status: number, body: unknown): string => {
331
357
  }
332
358
  };
333
359
 
334
- const send = (who: string, url: string, token: string, init: { method: string; body?: string }) =>
335
- Effect.tryPromise({
336
- try: async () => {
337
- const response = await fetch(url, {
338
- ...init,
339
- headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
340
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
360
+ /**
361
+ * One request to `who` at `url`, with `token` as its Bearer. A token goes only to an https URL:
362
+ * to any other URL the request is not made.
363
+ */
364
+ const send = (
365
+ who: string,
366
+ url: string,
367
+ token: string | undefined,
368
+ init: { method: string; body?: string },
369
+ ) =>
370
+ token !== undefined && !(URL.canParse(url) && new URL(url).protocol === "https:")
371
+ ? Effect.fail(
372
+ new IdentityHubClientFailed({
373
+ reason: `${who} is not at an https URL, so no credential was sent to it`,
374
+ }),
375
+ )
376
+ : Effect.tryPromise({
377
+ try: async () => {
378
+ const response = await fetch(url, {
379
+ ...init,
380
+ headers: {
381
+ ...(token === undefined ? {} : { Authorization: `Bearer ${token}` }),
382
+ "Content-Type": "application/json",
383
+ },
384
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
385
+ });
386
+ const body: unknown = await response.json().catch(() => undefined);
387
+ return { status: response.status, body };
388
+ },
389
+ catch: () => new IdentityHubClientFailed({ reason: `${who} gave no answer` }),
341
390
  });
342
- const body: unknown = await response.json().catch(() => undefined);
343
- return { status: response.status, body };
344
- },
345
- catch: () => new IdentityHubClientFailed({ reason: `${who} gave no answer` }),
346
- });
347
391
 
348
392
  const decode =
349
393
  <S extends Schema.Codec<unknown, unknown>>(schema: S, who: string) =>
@@ -374,9 +418,10 @@ const readOidcToken = (requestUrl: string, requestToken: string, audience: strin
374
418
 
375
419
  /**
376
420
  * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial
377
- * access token: the GitHub OIDC token, or the app's own token. `software_id` is the app's name, and
378
- * `connectors` is the hub's own metadata field. Convex Auth posts the client's secret in the body
379
- * at the token endpoint, so the client registers that method.
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.
380
425
  */
381
426
  const requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: string) =>
382
427
  Effect.gen(function* () {
@@ -388,15 +433,21 @@ const requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: st
388
433
  redirect_uris: redirectUris,
389
434
  software_id: app,
390
435
  software_version: props.softwareVersion ?? "unknown",
436
+ client_name: enrollment.clientName,
437
+ deployment_type: props.deploymentType,
391
438
  connectors,
392
439
  token_endpoint_auth_method: "client_secret_post",
393
440
  }),
394
441
  });
395
442
  if (status !== 201) {
396
443
  const reason =
397
- status === 401 && props.deploymentType === "development"
398
- ? "the identity hub refused the initial access token"
399
- : refusalOf(status, body);
444
+ status !== 401
445
+ ? refusalOf(status, body)
446
+ : "key" in props
447
+ ? "the identity hub refused the registration key"
448
+ : props.deploymentType === "development"
449
+ ? "the identity hub refused the initial access token"
450
+ : refusalOf(status, body);
400
451
  return yield* new IdentityHubClientFailed({ reason: `${reason} (HTTP ${status})` });
401
452
  }
402
453
  const client = yield* decode(NewClient, "The identity hub")(body);
@@ -431,6 +482,37 @@ const requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: st
431
482
  };
432
483
  });
433
484
 
485
+ const Discovery = Schema.Struct({ issuer: Schema.String });
486
+
487
+ /**
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.
491
+ */
492
+ const DISCOVERY_RETRY = {
493
+ times: 15,
494
+ schedule: Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("15 seconds")]),
495
+ };
496
+
497
+ /**
498
+ * Succeeds when the hub's discovery document names the hub's issuer, after bounded retries; fails
499
+ * when it never does.
500
+ */
501
+ const hubAnswers = (hub: Hub) =>
502
+ send("The identity hub", `${hub.issuer}/.well-known/openid-configuration`, undefined, {
503
+ method: "GET",
504
+ }).pipe(
505
+ Effect.flatMap(({ body, status }) =>
506
+ status === 200 &&
507
+ Option.getOrUndefined(Schema.decodeUnknownOption(Discovery)(body))?.issuer === hub.issuer
508
+ ? Effect.void
509
+ : Effect.fail(
510
+ new IdentityHubClientFailed({ reason: "the identity hub does not answer discovery" }),
511
+ ),
512
+ ),
513
+ Effect.retry(DISCOVERY_RETRY),
514
+ );
515
+
434
516
  /** A new client, or the off values. */
435
517
  const newClient = (props: ClientProps, enrollment: Enrollment) => {
436
518
  const label = `IdentityHub.Client: ${where(enrollment)} deploys without the hub`;
@@ -445,6 +527,14 @@ const newClient = (props: ClientProps, enrollment: Enrollment) => {
445
527
  ),
446
528
  );
447
529
 
530
+ if ("key" in props) {
531
+ return props.key === undefined
532
+ ? Effect.logInfo(
533
+ `${label}: it has no registration key yet. Deploy the stage that makes the key first.`,
534
+ ).pipe(Effect.as(off))
535
+ : request(Effect.as(hubAnswers(props.hub), Redacted.value(props.key)));
536
+ }
537
+
448
538
  if (props.deploymentType === "development") {
449
539
  const token = Redacted.value(props.initialAccessToken);
450
540
  return token === ""
@@ -561,6 +651,50 @@ const read = (id: string, options: { readonly stage: string }) =>
561
651
  }),
562
652
  );
563
653
 
654
+ /** A saved row of an `Alchemy.Random`, whose `text` the store revives as `Redacted`. */
655
+ const SavedKey = Schema.Struct({
656
+ resourceType: Schema.Literal("Alchemy.Random"),
657
+ attr: Schema.Struct({ text: Schema.Redacted(Schema.String) }),
658
+ });
659
+
660
+ /**
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
664
+ * `Alchemy.Random` at the stack's root, made once and kept in state; the stack's providers need
665
+ * 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`).
668
+ */
669
+ export const registrationKey = (id: string, options: { readonly stage: string }) =>
670
+ Effect.gen(function* () {
671
+ const { stage } = yield* Stack;
672
+ if (stage === options.stage) {
673
+ const key: Output.Output<Redacted.Redacted<string> | undefined> = (yield* Random(id)).text;
674
+ return key;
675
+ }
676
+ return Output.fromEffect(
677
+ Effect.gen(function* () {
678
+ const stack = yield* Stack;
679
+ const state = yield* yield* State;
680
+ const row = yield* state
681
+ .get({ stack: stack.name, stage: options.stage, fqn: id })
682
+ .pipe(Effect.orDie);
683
+ if (row === undefined) return undefined;
684
+ const saved = yield* Schema.decodeUnknownEffect(SavedKey)(row).pipe(
685
+ Effect.catchCause(() =>
686
+ Effect.die(
687
+ new IdentityHubClientFailed({
688
+ reason: `the row ${id} of stage ${options.stage} is not an Alchemy.Random`,
689
+ }),
690
+ ),
691
+ ),
692
+ );
693
+ return saved.attr.text;
694
+ }),
695
+ );
696
+ });
697
+
564
698
  /**
565
699
  * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,
566
700
  * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when
@@ -622,6 +756,7 @@ export const ClientProvider = () =>
622
756
  }
623
757
  const enrollment: Enrollment = {
624
758
  app,
759
+ clientName: stack.stage,
625
760
  connectors: sortedSet(news.connectors),
626
761
  redirectUris: sortedSet(news.redirectUris),
627
762
  };
package/src/Providers.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // The provider collection users merge into a stack:
2
2
  // providers: Layer.mergeAll(Cloudflare.providers(), Convex.providers())
3
3
  import * as Provider from "alchemy/Provider";
4
+ import { Random, RandomProvider } from "alchemy/Random";
4
5
  import * as Layer from "effect/Layer";
5
6
  import { type Credentials, fromConfig } from "./Credentials.ts";
6
7
  import { DeploymentProvider, DeploymentResource } from "./Deployment.ts";
@@ -19,7 +20,9 @@ export class Providers extends Provider.ProviderCollection<Providers>()("Convex"
19
20
  export const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>
20
21
  Layer.effect(
21
22
  Providers,
22
- Provider.collection([Project, DeploymentResource, LocalDeployment, IdentityHub.Client]),
23
+ // Random's provider serves `IdentityHub.registrationKey` in a stack with no other collection
24
+ // that holds one; with Cloudflare's too, the first found serves it, and both are the same.
25
+ Provider.collection([Project, DeploymentResource, LocalDeployment, IdentityHub.Client, Random]),
23
26
  ).pipe(
24
27
  Layer.provide(
25
28
  Layer.mergeAll(
@@ -27,6 +30,7 @@ export const providers = (credentials: Layer.Layer<Credentials> = fromConfig())
27
30
  DeploymentProvider(),
28
31
  LocalDeploymentProvider(),
29
32
  IdentityHub.ClientProvider(),
33
+ RandomProvider(),
30
34
  ),
31
35
  ),
32
36
  Layer.provide(ManagementApiLive()),
@@ -1 +0,0 @@
1
- {"version":3,"file":"IdentityHub-lx5BPjOS.js","names":[],"sources":["../src/IdentityHub.ts"],"sourcesContent":["// IdentityHub.Client: one deployment of an app as a client of the identity hub that the stack\n// names, for an app that deploys in its own GitHub Actions run, on any host, and in development as a\n// stage of the same stack. Import it as\n// `import * as IdentityHub from \"@samebase/alchemy-convex/identity-hub\"`; `Convex.providers()`\n// registers its provider.\n//\n// A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs\n// no key and no Samebase account. The token names the repository. The hub reads\n// `/samebase-verification.json` at the origin of the return address, which must name the same\n// repository, and registers the client on that address. The answer holds the client's own\n// registration access token (RFC 7591), and each later deploy reads the client on the hub with that\n// token (RFC 7592). The hub keeps only hashes, so the state is the only record of the secret and the\n// token.\n//\n// The answer to a production registration also holds the app's initial access token (RFC 7591\n// section 1.2) and the repository id. The state of stage `prod` keeps them. A development checkout\n// runs the stack as a stage `dev-<name>`: it reads them with `IdentityHub.Client.read`, and a client\n// with `deploymentType: \"development\"` asks the hub with the token in place of the GitHub token\n// (RFC 133).\n//\n// A client is enrolled in the connectors it signs in through, such as `google` and `github`, at\n// registration (RFC 137), and holds the return addresses its requests may name, one per handler of\n// the app, such as the sign-in callback and the connections callback. The hub records both sets on\n// the client and never changes them: a stack with another set registers a new client.\n//\n// The app is the stack: its name on the hub defaults to the stack's path in the repository, as the\n// state store groups stacks (`owner/repo/<path>`), and `app` for a stack named after the repository.\n// `app` overrides it. The name groups the clients, their budgets, and the initial access token; it\n// plays no part in user ids, which the hub derives from the provider's own id.\n//\n// A push removes a variable that a deploy stops passing, so a failure here must not drop working\n// variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that\n// cannot work asks for a new one: it is gone, or it has another app name, return address set, type,\n// or connector set. If that request fails, the run gives the off values, so the app has guest\n// sign-in and not a broken button. The off values are the `no-hub` variables of a checkout without\n// a hub: Convex needs the variables, and the app hides the button for this client ID.\n//\n// No text in this file quotes an answer or a fetch error, so no log line can hold a secret. The one\n// exception is the connector names of an `invalid_connectors` refusal, each checked against the\n// grammar of a connector name before it is printed.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Output from \"alchemy/Output\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport type { Providers } from \"./Providers.ts\";\n\n/** A hung service must not hold a deploy: the time limit of one request. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** The variables of a deployment without a hub client, as the starter writes them. */\nconst OFF_VALUES = { issuer: \"http://127.0.0.1:1\", clientId: \"no-hub\", clientSecret: \"no-hub\" };\n\n/** The name of a connector on the hub. */\nconst CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;\n\n/** The return addresses of one client, as the hub caps them. */\nconst MAX_REDIRECT_URIS = 8;\n/** The app's name, as the hub caps it. A deeper stack path needs an explicit `app`. */\nconst MAX_APP_LENGTH = 64;\n\n/**\n * The app's default name: the stack's path below `owner/repo`, or `app` for a stack named after\n * the repository. Undefined for a stack whose name is not `owner/repo` or `owner/repo/<path>`.\n */\nexport const defaultApp = (stackName: string): string | undefined => {\n const segments = stackName.split(\"/\");\n if (segments.length < 2 || segments.some((segment) => segment === \"\")) {\n return undefined;\n }\n return segments.slice(2).join(\"/\") || \"app\";\n};\n\n/**\n * An identity hub of @samebase/identity-broker, such as Samebase's public hub:\n * `{ issuer: \"https://id.samebase.com\" }`.\n */\nexport interface Hub {\n /**\n * The hub's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/register`, with\n * a GitHub token whose audience is the issuer, so no other hub can use that token.\n */\n readonly issuer: string;\n}\n\ninterface CommonProps {\n /**\n * The app's name in its repository. Default: the stack's path in the repository, `apps/samebase`\n * for the stack `samebase/samebase/apps/samebase`, and `app` for a stack named after the\n * repository. A changed name registers a new client under the new name.\n */\n readonly app?: string;\n /** The hub to register at. A changed hub registers a new client there; the old one stays. */\n readonly hub: Hub;\n /**\n * The connectors the client signs in through, by their names on the hub, such as\n * `[\"google\", \"github\"]`: at least one, each of `[a-z0-9-]{1,64}`. The hub refuses a name it does\n * not offer, or does not allow this repository, and the log then names the allowed ones. The set\n * is recorded on the client for good: a changed set registers a new client.\n */\n readonly connectors: readonly string[];\n /**\n * The return addresses of this deployment, one to eight, such as\n * `[`${site.siteUrl}/auth/hub/callback`]`: each an https URL whose origin serves\n * `/samebase-verification.json` with the numeric GitHub id of this repository,\n * `{ \"repository\": \"123\" }`. They can come from a resource that this run creates. A development\n * client can also have http on a loopback host, which needs no file. Every request of the client\n * names one of them. The set is recorded on the client for good: a changed set registers a new\n * client.\n */\n readonly redirectUris: string[];\n /** Recorded on the hub's client, such as the commit. The hub records \"unknown\" without it. */\n readonly softwareVersion?: string;\n /**\n * The run fails unless the hub confirms the client in this run: it fails when the hub refuses or\n * does not answer a registration or a renewal, and when it suspended the client. Without it, such\n * a run gives the off values or keeps the saved client, so the app deploys anyway. Set it where\n * sign-in is the product. A failed run saves nothing, so the next run asks the hub again.\n */\n readonly required?: boolean;\n}\n\n/**\n * A production or preview client asks with the GitHub OIDC token of the run. A development client\n * asks with the app's initial access token, which `IdentityHub.Client.read` gives from stage `prod`.\n */\nexport type ClientProps =\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\";\n readonly initialAccessToken?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"development\";\n /** Empty before the first production registration: the client gets the off values. */\n readonly initialAccessToken: Redacted.Redacted<string>;\n });\n\nconst DeploymentType = Schema.Literals([\"production\", \"preview\", \"development\"]);\n\nconst Attributes = Schema.Struct({\n /** `off`: no client, and the values below are the off values. */\n status: Schema.Literals([\"on\", \"off\", \"suspended\"]),\n /** The issuer of the hub, which the deployment names to sign in. */\n issuer: Schema.String,\n clientId: Schema.String,\n /** Returned only at registration. */\n clientSecret: Schema.Redacted(Schema.String),\n /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */\n registrationAccessToken: Schema.Redacted(Schema.String),\n registrationClientUri: Schema.String,\n deploymentType: DeploymentType,\n /** The app's name on the hub, as sent. Empty for the off values. */\n app: Schema.String,\n /** The return addresses the client serves, sorted, each once. Empty for the off values. */\n redirectUris: Schema.Array(Schema.String),\n /** The connectors the client is enrolled in, sorted, each once. Empty for the off values. */\n connectors: Schema.Array(Schema.String),\n /**\n * Returned only at a production registration (RFC 7591 section 1.2). It registers development\n * clients of this app. Empty for a preview, for a development client, and for the off values.\n */\n initialAccessToken: Schema.Redacted(Schema.String),\n /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */\n repository: Schema.String,\n});\n\n/**\n * The attributes keep the real values of a suspended client, so that an unblock needs no new client.\n * `IdentityHub.Client.variables` gives the values that the app gets.\n */\nexport interface ClientAttributes extends Schema.Schema.Type<typeof Attributes> {}\n\n/**\n * The attributes of a saved row. A row that does not have this version's shape, or any other\n * failure of the decoder, stops the run with `reason`. The text of a schema issue can quote a value\n * of the row, so it is never kept.\n */\nconst savedAttributes = (value: unknown, reason: string) =>\n Schema.decodeUnknownEffect(Attributes)(value).pipe(\n Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason }))),\n );\n\n/** The attributes of no client. */\nconst offAttributes = (deploymentType: ClientAttributes[\"deploymentType\"]): ClientAttributes => ({\n status: \"off\",\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n registrationAccessToken: Redacted.make(\"\"),\n registrationClientUri: \"\",\n deploymentType,\n app: \"\",\n redirectUris: [],\n connectors: [],\n initialAccessToken: Redacted.make(\"\"),\n repository: \"\",\n});\n\n/** The set of `values`: sorted, each once. */\nconst sortedSet = (values: readonly string[]) => [...new Set(values)].sort();\n\nconst sameSet = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && a.every((name, index) => name === b[index]);\n\n/** The app and its return addresses, as every log line names a client: no secret, no answer. */\nconst where = (client: { app: string; redirectUris: readonly string[] }) =>\n `${client.app} on ${client.redirectUris.join(\", \")}`;\n\n/** What one registration sends, resolved from the props: the app's name and both sets. */\ninterface Enrollment {\n readonly app: string;\n readonly connectors: readonly string[];\n readonly redirectUris: readonly string[];\n}\n\n/** One request gave no usable answer. The reason holds no secret. */\nclass IdentityHubClientFailed extends Schema.TaggedError<IdentityHubClientFailed>()(\n \"IdentityHubClientFailed\",\n { reason: Schema.String },\n) {\n override get message() {\n return `IdentityHub.Client: ${this.reason}.`;\n }\n}\n\nconst OidcToken = Schema.Struct({ value: Schema.NonEmptyString });\n\n/**\n * The 201 answer of `POST /register` (RFC 7591 section 3.2.1), in the members that this file reads.\n * The decoder ignores the other members, such as `software_id`, whose full form the hub writes.\n */\nconst NewClient = Schema.Struct({\n issuer: Schema.NonEmptyString,\n client_id: Schema.NonEmptyString,\n client_secret: Schema.NonEmptyString,\n registration_access_token: Schema.NonEmptyString,\n registration_client_uri: Schema.NonEmptyString,\n /** The sets the hub recorded, which must be the sets the request sent. */\n redirect_uris: Schema.Array(Schema.String),\n connectors: Schema.Array(Schema.String),\n /** Only in the answer to a production registration with the GitHub token. */\n initial_access_token: Schema.optionalKey(Schema.NonEmptyString),\n repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\\d+$/))),\n});\n\n/** The other answers of `POST /register`, by status. A 401 can have no body (RFC 6750). */\nconst REFUSALS: Readonly<Record<number, string>> = {\n 400: \"the identity hub refused the client metadata, such as the app name\",\n 401: \"the identity hub refused the GitHub OIDC token\",\n 403: \"the identity hub does not allow this repository\",\n 404: \"the identity hub has no /register: it runs an identity-broker before 0.33.0\",\n 429: \"the identity hub limits new clients\",\n 502: \"GitHub's keys are not available to the identity hub\",\n 503: \"the identity hub could not apply its policy\",\n};\n\n/** The text of an `invalid_redirect_uri` 400 without a known reason. */\nconst BAD_REDIRECT_URIS =\n \"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\";\n\n/**\n * The reasons of a 400 or a 403 that a log line shows. Any other text of the answer is never\n * logged.\n */\nconst REASONS = new Map([\n [\"paused\", \"this app is paused on the identity hub\"],\n [\"run_not_allowed\", \"the identity hub gives clients only to runs of main and of pull requests\"],\n [\"blocked\", \"Samebase blocked this repository or its owner\"],\n [\"suspended\", \"the identity hub suspended this repository\"],\n [\"too_many_apps\", \"the repository has as many apps on the identity hub as it may\"],\n [\"too_many_clients\", \"the app has as many clients on the identity hub as it may\"],\n [\"app_taken\", \"the app's name belongs to another app on the identity hub\"],\n [\"host_unreachable\", \"the identity hub could not reach the host of the return address\"],\n [\n \"verification_file_missing\",\n \"the host of the return address does not serve /samebase-verification.json\",\n ],\n [\"verification_file_invalid\", \"/samebase-verification.json on the host holds no repository id\"],\n [\"repository_mismatch\", \"/samebase-verification.json on the host names another repository\"],\n [\"app_mismatch\", \"the initial access token belongs to another app on the identity hub\"],\n [\"stale_proof\", \"the identity hub took a newer GitHub OIDC token of this repository\"],\n]);\n\n/** The windows of a 429, by the name that the answer gives. */\nconst RATE_LIMITED = new Map([\n [\"repository\", \"the identity hub gives one repository at most 30 new clients an hour\"],\n [\"owner\", \"the identity hub gives one owner at most 100 new clients an hour\"],\n [\"new_owners\", \"the identity hub takes at most 50 new owners an hour\"],\n]);\n\nconst Refusal = Schema.Struct({ reason: Schema.String });\nconst InvalidRedirectUri = Schema.Struct({ error: Schema.Literal(\"invalid_redirect_uri\") });\nconst RateLimited = Schema.Struct({ window: Schema.String });\n/** A 400 for a connector the hub does not offer or allow, with the names it allows. */\nconst InvalidConnectors = Schema.Struct({\n reason: Schema.Literal(\"invalid_connectors\"),\n allowed: Schema.Array(Schema.String),\n});\n\n/**\n * The text of a refusal: a known reason of a 400 or a 403, or window of a 429, the allowed\n * connectors of an `invalid_connectors` 400 (only names of the connector grammar, so no other text\n * of the answer is printed), the text of an `invalid_redirect_uri` 400, else the text of its\n * status. `body` is undefined for an answer without JSON, such as a bare 401.\n */\nconst refusalOf = (status: number, body: unknown): string => {\n const decoded = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>\n Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));\n const ofStatus = () => REFUSALS[status] ?? \"the identity hub refused the request\";\n switch (status) {\n case 400: {\n const allowed = decoded(InvalidConnectors)?.allowed.filter((name) =>\n CONNECTOR_NAME.test(name),\n );\n return allowed === undefined\n ? (REASONS.get(decoded(Refusal)?.reason ?? \"\") ??\n (decoded(InvalidRedirectUri) === undefined ? ofStatus() : BAD_REDIRECT_URIS))\n : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? \"none for this app\" : allowed.join(\", \")}`;\n }\n case 403:\n return REASONS.get(decoded(Refusal)?.reason ?? \"\") ?? ofStatus();\n case 429:\n return RATE_LIMITED.get(decoded(RateLimited)?.window ?? \"\") ?? ofStatus();\n default:\n return ofStatus();\n }\n};\n\nconst send = (who: string, url: string, token: string, init: { method: string; body?: string }) =>\n Effect.tryPromise({\n try: async () => {\n const response = await fetch(url, {\n ...init,\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n const body: unknown = await response.json().catch(() => undefined);\n return { status: response.status, body };\n },\n catch: () => new IdentityHubClientFailed({ reason: `${who} gave no answer` }),\n });\n\nconst decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, who: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => new IdentityHubClientFailed({ reason: `${who} gave a bad answer` })),\n );\n\n/**\n * The OIDC token of this run for `audience`, read right before the call, because it lives for\n * minutes only.\n */\nconst readOidcToken = (requestUrl: string, requestToken: string, audience: string) =>\n Effect.gen(function* () {\n const { body, status } = yield* send(\n \"GitHub\",\n `${requestUrl}&audience=${encodeURIComponent(audience)}`,\n requestToken,\n { method: \"GET\" },\n );\n if (status !== 200) {\n return yield* new IdentityHubClientFailed({\n reason: `GitHub gave no OIDC token (HTTP ${status})`,\n });\n }\n return (yield* decode(OidcToken, \"GitHub\")(body)).value;\n });\n\n/**\n * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial\n * access token: the GitHub OIDC token, or the app's own token. `software_id` is the app's name, and\n * `connectors` is the hub's own metadata field. Convex Auth posts the client's secret in the body\n * at the token endpoint, so the client registers that method.\n */\nconst requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: string) =>\n Effect.gen(function* () {\n const { hub } = props;\n const { app, connectors, redirectUris } = enrollment;\n const { body, status } = yield* send(\"The identity hub\", `${hub.issuer}/register`, bearer, {\n method: \"POST\",\n body: JSON.stringify({\n redirect_uris: redirectUris,\n software_id: app,\n software_version: props.softwareVersion ?? \"unknown\",\n connectors,\n token_endpoint_auth_method: \"client_secret_post\",\n }),\n });\n if (status !== 201) {\n const reason =\n status === 401 && props.deploymentType === \"development\"\n ? \"the identity hub refused the initial access token\"\n : refusalOf(status, body);\n return yield* new IdentityHubClientFailed({ reason: `${reason} (HTTP ${status})` });\n }\n const client = yield* decode(NewClient, \"The identity hub\")(body);\n // The hub registers the addresses and the connectors that the request sent, under its own\n // issuer. The log and the state hold the stack's values, so no value that the answer chose is\n // printed or kept.\n if (\n client.issuer !== hub.issuer ||\n !sameSet(sortedSet(client.redirect_uris), redirectUris) ||\n !sameSet(client.connectors, connectors)\n ) {\n return yield* new IdentityHubClientFailed({ reason: \"The identity hub gave a bad answer\" });\n }\n yield* Effect.logInfo(\n `IdentityHub.Client: ${where(enrollment)} has a new client of the identity hub ${hub.issuer}.`,\n );\n // Only a production registration gives the app's token (RFC 7591); any other answer's is dropped.\n const production = props.deploymentType === \"production\";\n return {\n status: \"on\" as const,\n issuer: hub.issuer,\n clientId: client.client_id,\n clientSecret: Redacted.make(client.client_secret),\n registrationAccessToken: Redacted.make(client.registration_access_token),\n registrationClientUri: client.registration_client_uri,\n deploymentType: props.deploymentType,\n app,\n redirectUris,\n connectors,\n initialAccessToken: Redacted.make(production ? (client.initial_access_token ?? \"\") : \"\"),\n repository: production ? (client.repository ?? \"\") : \"\",\n };\n });\n\n/** A new client, or the off values. */\nconst newClient = (props: ClientProps, enrollment: Enrollment) => {\n const label = `IdentityHub.Client: ${where(enrollment)} deploys without the hub`;\n const off = offAttributes(props.deploymentType);\n const request = (bearer: Effect.Effect<string, IdentityHubClientFailed>) =>\n bearer.pipe(\n Effect.flatMap((token) => requestNewClient(props, enrollment, token)),\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(\n Effect.as(off),\n ),\n ),\n );\n\n if (props.deploymentType === \"development\") {\n const token = Redacted.value(props.initialAccessToken);\n return token === \"\"\n ? Effect.logInfo(\n \"IdentityHub.Client: deploy to main once for hub sign-in in development.\",\n ).pipe(Effect.as(off))\n : request(Effect.succeed(token));\n }\n\n const requestUrl = process.env[\"ACTIONS_ID_TOKEN_REQUEST_URL\"];\n const requestToken = process.env[\"ACTIONS_ID_TOKEN_REQUEST_TOKEN\"];\n // A development machine, or another CI. In a workflow, `id-token: write` gives both, so a\n // workflow without them is a mistake to show, not a normal run.\n if (!requestUrl || !requestToken) {\n return (\n process.env[\"GITHUB_ACTIONS\"] === \"true\"\n ? Effect.logWarning(`${label}: this workflow needs the permission id-token: write.`)\n : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)\n ).pipe(Effect.as(off));\n }\n return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));\n};\n\n/**\n * The client after a read on the hub, or undefined when the hub says that the client is gone. A\n * read with no usable answer keeps the saved client, except for a required one: a required client\n * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,\n * and did not save because that run failed, cannot pass a run that the hub does not answer.\n */\nconst renew = (saved: ClientAttributes, required: boolean) =>\n Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n saved.registrationClientUri,\n Redacted.value(saved.registrationAccessToken),\n { method: \"GET\" },\n );\n switch (status) {\n case 200:\n return { ...saved, status: \"on\" as const };\n case 401:\n return undefined;\n case 403:\n yield* Effect.logWarning(\n `IdentityHub.Client: the hub suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`,\n );\n return { ...saved, status: \"suspended\" as const };\n default:\n return yield* new IdentityHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n required\n ? Effect.fail(\n new IdentityHubClientFailed({\n reason: `${where(saved)} is required, and the hub did not confirm its client: ${error.reason}`,\n }),\n )\n : Effect.logWarning(\n `IdentityHub.Client: ${where(saved)} keeps the saved client: ${error.reason}.`,\n ).pipe(Effect.as(saved)),\n ),\n );\n\n/**\n * The type of this resource before 0.37.0. Alchemy finds this provider for a row of that type, and\n * the next write of the row gives it the new type, with the same client. Remove it, here and in\n * `SavedRow`, once no saved row has the old type.\n */\nconst OLD_TYPE = \"IdentityHub.SharedClient\";\n\n/** A saved row of this resource, whose `attr` `savedAttributes` reads. */\nconst SavedRow = Schema.Struct({\n resourceType: Schema.Literals([\"IdentityHub.Client\", OLD_TYPE]),\n attr: Schema.Unknown,\n});\n\n/**\n * The attributes of the client `id` in another stage of this stack, such as\n * `read(\"HubClient\", { stage: \"prod\" })` in a development stage, as Outputs: the\n * `initialAccessToken` and the `repository` of the production client. Without that row, the off\n * attributes, with `deploymentType: \"production\"`.\n *\n * `IdentityHub.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the\n * row is missing, and a development stage before the first deploy to main has none. This read runs\n * when the plan resolves it, with the State service of the running stack and its `get`, so it never\n * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every\n * read.\n */\nconst read = (id: string, options: { readonly stage: string }) =>\n Output.fromEffect(\n Effect.gen(function* () {\n const stack = yield* Stack;\n const state = yield* yield* State;\n const row = yield* state\n .get({ stack: stack.name, stage: options.stage, fqn: id })\n .pipe(Effect.orDie);\n if (row === undefined) return offAttributes(\"production\");\n const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(\n Effect.catchCause(() =>\n Effect.die(\n new IdentityHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not an IdentityHub.Client`,\n }),\n ),\n ),\n );\n return yield* savedAttributes(\n attr,\n `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`,\n );\n }),\n );\n\n/**\n * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,\n * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when\n * `status` is `on`, else the off values, so that a suspended client gives guest sign-in and keeps\n * its values in state.\n */\nconst variables = (client: Client) =>\n Output.map(Output.of(client), (attributes) =>\n attributes.status === \"on\"\n ? {\n issuer: attributes.issuer,\n clientId: attributes.clientId,\n clientSecret: attributes.clientSecret,\n }\n : {\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n },\n );\n\nexport type Client = Resource<\n \"IdentityHub.Client\",\n ClientProps,\n ClientAttributes,\n never,\n Providers\n>;\nexport const Client = Resource<Client>(\"IdentityHub.Client\", { aliases: [OLD_TYPE] })({\n read,\n variables,\n});\n\nexport const ClientProvider = () =>\n Provider.succeed(Client, {\n // Always an update, so that each deploy reaches the hub. No attribute is stable, so a push\n // reads the values that this run ended with. The same values cause no other push.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n // Only a client of the same hub (its issuer), app name, return address set, type, and\n // connector set is renewed. A saved row without this version's shape stops the run with a\n // fixed message.\n reconcile: Effect.fn(function* ({ news, output }) {\n // A bad prop is a mistake of the stack, not of the hub: the run fails, with no request.\n const stack = yield* Stack;\n const app = news.app ?? defaultApp(stack.name);\n if (app === undefined) {\n return yield* new IdentityHubClientFailed({\n reason: `the stack ${stack.name} is not named owner/repo or owner/repo/<path>, so set app`,\n });\n }\n if (app.length > MAX_APP_LENGTH) {\n return yield* new IdentityHubClientFailed({\n reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the hub's limit, so set a shorter app`,\n });\n }\n const enrollment: Enrollment = {\n app,\n connectors: sortedSet(news.connectors),\n redirectUris: sortedSet(news.redirectUris),\n };\n if (\n enrollment.connectors.length === 0 ||\n !enrollment.connectors.every((name) => CONNECTOR_NAME.test(name))\n ) {\n return yield* new IdentityHubClientFailed({\n reason: `${where(enrollment)} needs connectors: one or more names of [a-z0-9-]{1,64}`,\n });\n }\n if (\n enrollment.redirectUris.length === 0 ||\n enrollment.redirectUris.length > MAX_REDIRECT_URIS ||\n !enrollment.redirectUris.every((uri) => URL.canParse(uri))\n ) {\n return yield* new IdentityHubClientFailed({\n reason: `${app} needs redirectUris: one to ${MAX_REDIRECT_URIS} absolute URLs`,\n });\n }\n const saved =\n output === undefined || output.status === \"off\"\n ? undefined\n : yield* savedAttributes(\n output,\n `the saved attributes of ${where(enrollment)} cannot be read by this version`,\n );\n const renewed =\n saved?.issuer === news.hub.issuer &&\n saved.app === app &&\n sameSet(saved.redirectUris, enrollment.redirectUris) &&\n saved.deploymentType === news.deploymentType &&\n sameSet(saved.connectors, enrollment.connectors)\n ? yield* renew(saved, news.required === true)\n : undefined;\n const client = renewed ?? (yield* newClient(news, enrollment));\n if (news.required === true && client.status !== \"on\") {\n return yield* new IdentityHubClientFailed({\n reason: `${where(enrollment)} is required and has no working client (${client.status}). The warning above names the reason`,\n });\n }\n return client;\n }),\n\n // A failed delete does not stop a destroy: the removal date of a preview or development client\n // cleans it up. A destroy can leave a production deployment running, so its client stays.\n delete: ({ output }) =>\n output.deploymentType === \"production\" || output.status === \"off\"\n ? Effect.void\n : Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n output.registrationClientUri,\n Redacted.value(output.registrationAccessToken),\n { method: \"DELETE\" },\n );\n // 401: the client is gone already.\n if (status !== 204 && status !== 401) {\n return yield* new IdentityHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n // The row can be of an earlier version's shape, so the line names only the client id.\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n Effect.logWarning(\n `IdentityHub.Client: the client ${output.clientId} stays on the hub until its removal date: ${error.reason}.`,\n ),\n ),\n ),\n });\n"],"mappings":";;;;;;;;;;;;AAqDA,MAAM,qBAAqB;;AAG3B,MAAM,aAAa;CAAE,QAAQ;CAAsB,UAAU;CAAU,cAAc;AAAS;;AAG9F,MAAM,iBAAiB;;AAGvB,MA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