@samebase/alchemy-convex 0.36.0 → 0.38.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
@@ -298,7 +298,10 @@ resources and output, from the store function `state:readStack({ stack })` in on
298
298
  `env`, then pushes. A failed push sets the changed variables back, and deletes a dev or preview
299
299
  deployment that the same run created.
300
300
  - `env` values are strings or secrets such as `Config.Redacted("AUTH_SECRET")`. A name that leaves
301
- `env` is removed from the deployment.
301
+ `env` is removed from the deployment after a successful push, because the code that runs until
302
+ then can require it, and Convex refuses to remove a variable that the running code requires. A
303
+ failed push keeps it, and the next run removes it. Without `source`, the update removes it with
304
+ the new values.
302
305
  - `source: { path, command?, include? }` replaces `convex deploy` with `command`, run in `rootDir`
303
306
  with the push key in `CONVEX_DEPLOY_KEY`, such as
304
307
  `["node_modules/.bin/convex-hosting", "deploy", "--build", "node_modules/.bin/vp build", "--dist", "dist/client"]`.
@@ -307,9 +310,9 @@ resources and output, from the store function `state:readStack({ stack })` in on
307
310
  as the build inputs `["src/**", "public/**", "vite.config.ts"]`. A minted key for a command has
308
311
  every action, because the command can do more than a push.
309
312
 
310
- - `Convex.SharedHubClient`:
311
- `{ app, redirectUri, deploymentType, connectors, initialAccessToken?, softwareVersion? }` gets a
312
- client of the central identity hub, for an app that deploys in its own GitHub Actions run, on any
313
+ - `IdentityHub.Client`, from `import * as IdentityHub from "@samebase/alchemy-convex/identity-hub"`:
314
+ `{ app, hub, redirectUri, deploymentType, connectors, initialAccessToken?, softwareVersion? }`
315
+ gets a client of an identity hub, for an app that deploys in its own GitHub Actions run, on any
313
316
  host, and for development as a stage of the same stack. `deploymentType` is `production`,
314
317
  `preview`, or `development`. A production or preview client needs `permissions: id-token: write`
315
318
  in the workflow, and no key and no Samebase account. `app` is at most 64 characters. The origin of
@@ -336,9 +339,9 @@ resources and output, from the store function `state:readStack({ stack })` in on
336
339
  `connectors` too. A replaced production client stays valid on the hub until its administrator
337
340
  deletes it. A saved row whose attributes this version cannot read stops the run with a fixed
338
341
  message, which holds no value of the row.
339
- - A new client logs the link to the terms of the shared sign-in service. A refusal logs its
340
- reason, such as a host that does not serve the file, a block, a token of another app, a
341
- connector the hub does not offer or allow, or the hourly limit it reached.
342
+ - A new client logs the hub's issuer. A refusal logs its reason, such as a host that does not
343
+ serve the file, a block, a token of another app, a connector the hub does not offer or allow, or
344
+ the hourly limit it reached.
342
345
  - No failure of the hub stops a deploy or a destroy. A failed renewal keeps the saved values.
343
346
  Without saved values, `status` is `off`, and `issuer`, `clientId`, and `clientSecret` are the
344
347
  `no-hub` values of a checkout without a hub. A production or preview run without a GitHub OIDC
@@ -349,20 +352,23 @@ resources and output, from the store function `state:readStack({ stack })` in on
349
352
  stopped, with a green run. A failed run saves nothing, and the next run asks the hub again.
350
353
  - `status` is `suspended` when the hub suspended the client. The state keeps the client and its
351
354
  values, so the client works again when the hub lifts the suspension.
352
- - `Convex.SharedHubClient.variables(client)` gives `issuer`, `clientId`, and `clientSecret` for
353
- the app's deployment: the client's values when `status` is `on`, and the `no-hub` values when it
354
- is `off` or `suspended`. Give these to the deployment, not the outputs of the client.
355
- - `Convex.SharedHubClient.read(id, { stage })` gives the attributes of the client `id` in another
355
+ - `IdentityHub.Client.variables(client)` gives `issuer`, `clientId`, and `clientSecret` for the
356
+ app's deployment: the client's values when `status` is `on`, and the `no-hub` values when it is
357
+ `off` or `suspended`. Give these to the deployment, not the outputs of the client.
358
+ - `IdentityHub.Client.read(id, { stage })` gives the attributes of the client `id` in another
356
359
  stage of the same stack, from the state store of the stack. When that stage has no row, it gives
357
- the off attributes and does not fail. `Convex.SharedHubClient.ref` fails when the row is
358
- missing, and a development stage before the first deploy to main has no `prod` row.
360
+ the off attributes and does not fail. `IdentityHub.Client.ref` fails when the row is missing,
361
+ and a development stage before the first deploy to main has no `prod` row.
362
+ - The resource type is `IdentityHub.Client`. A row that an earlier version saved as
363
+ `IdentityHub.SharedClient` is the same client: the next deploy updates it in place and saves it
364
+ with the new type.
359
365
  - A destroy deletes a preview or development client. It does nothing to a production client,
360
366
  because the production deployment can stay.
361
- - `hub` is the identity hub to register at, required: `{ issuer, terms }`, such as
362
- `{ issuer: "https://auth.samebase.com", terms: "https://samebase.com/terms" }`. The run asks at
363
- `<issuer>/hub-clients` with a GitHub token whose audience is the issuer, and the answer must
364
- name that issuer and `terms`. A client is renewed only at the hub that issued it: a changed hub
365
- registers a new client there, and the old one stays at the old hub.
367
+ - `hub` is the identity hub to register at, required: `{ issuer }`, such as
368
+ `{ issuer: "https://id.samebase.com" }`. The run asks at `<issuer>/hub-clients` with a GitHub
369
+ token whose audience is the issuer, and the answer must name that issuer. A client is renewed
370
+ only at the hub that issued it: a changed hub registers a new client there, and the old one
371
+ stays at the old hub.
366
372
 
367
373
  - `Convex.LocalDeployment`: `{ rootDir?, env }` writes the `env` of the logged-in local deployment
368
374
  of the folder `rootDir` (the working directory without it), which
@@ -389,7 +395,7 @@ taken over by its Convex name:
389
395
  ```ts
390
396
  // `selected` is the name in CONVEX_DEPLOYMENT of .env.local, such as happy-animal-123, and
391
397
  // `project` is the project of stage `prod`.
392
- const prod = Convex.SharedHubClient.read("HubClient", { stage: "prod" });
398
+ const prod = IdentityHub.Client.read("HubClient", { stage: "prod" });
393
399
  const site =
394
400
  yield *
395
401
  Convex.Deployment("Verification", {
@@ -400,28 +406,29 @@ const site =
400
406
  }).pipe(adopt(true));
401
407
  const hub =
402
408
  yield *
403
- Convex.SharedHubClient("HubClient", {
409
+ IdentityHub.Client("HubClient", {
404
410
  app: "scout",
405
411
  redirectUri: Output.interpolate`${site.siteUrl}/auth/hub/callback`,
406
412
  deploymentType: "development",
407
413
  connectors: ["google", "github"],
408
414
  initialAccessToken: prod.initialAccessToken,
409
415
  });
410
- const variables = Convex.SharedHubClient.variables(hub);
416
+ const variables = IdentityHub.Client.variables(hub);
411
417
  yield *
412
418
  Convex.Deployment("Site", {
413
419
  project,
414
420
  type: "dev",
415
421
  name: selected,
416
422
  env: {
417
- HUB_ISSUER: variables.issuer,
418
- HUB_CLIENT_ID: variables.clientId,
419
- HUB_CLIENT_SECRET: variables.clientSecret,
423
+ IDENTITY_HUB_ISSUER: variables.issuer,
424
+ IDENTITY_HUB_CLIENT_ID: variables.clientId,
425
+ IDENTITY_HUB_CLIENT_SECRET: variables.clientSecret,
420
426
  },
421
427
  }).pipe(adopt(true));
422
428
  ```
423
429
 
424
- The imports are `alchemy/AdoptPolicy` for `adopt` and `alchemy/Output` for `Output`.
430
+ The imports are `alchemy/AdoptPolicy` for `adopt`, `alchemy/Output` for `Output`, and
431
+ `@samebase/alchemy-convex/identity-hub` for `IdentityHub`.
425
432
 
426
433
  1. `read` gives the initial access token and the repository id from the `HubClient` row of stage
427
434
  `prod`.
@@ -442,8 +449,7 @@ deletes the development client and keeps the deployment.
442
449
  `alchemy-convex stack-comment` keeps one comment on a pull request. The comment has a card for each
443
450
  stack of the repository at the stage `pr-<number>`: the folder, the address, the last run, the
444
451
  Convex deployments, Workers, and R2 buckets, and the sign-in status and connectors of a
445
- `Convex.SharedHubClient`. A stack sees only itself, so a comment that a stack declares cannot show
446
- this.
452
+ `IdentityHub.Client`. A stack sees only itself, so a comment that a stack declares cannot show this.
447
453
 
448
454
  Run it after every deploy of the workflow. The run record gives the repository and the pull request,
449
455
  so the command needs no argument with a team access token:
@@ -0,0 +1,322 @@
1
+ import { Stack } from "alchemy/Stack";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Schema from "effect/Schema";
4
+ import * as Option from "effect/Option";
5
+ import * as Redacted from "effect/Redacted";
6
+ import { Resource } from "alchemy";
7
+ import { isResolved } from "alchemy/Diff";
8
+ import * as Provider from "alchemy/Provider";
9
+ import * as Output from "alchemy/Output";
10
+ import { State } from "alchemy/State";
11
+ //#region src/IdentityHub.ts
12
+ /** A hung service must not hold a deploy: the time limit of one request. */
13
+ const REQUEST_TIMEOUT_MS = 3e4;
14
+ /** The variables of a deployment without a hub client, as the starter writes them. */
15
+ const OFF_VALUES = {
16
+ issuer: "http://127.0.0.1:1",
17
+ clientId: "no-hub",
18
+ clientSecret: "no-hub"
19
+ };
20
+ /** The name of a connector on the hub. */
21
+ const CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;
22
+ const DeploymentType = Schema.Literals([
23
+ "production",
24
+ "preview",
25
+ "development"
26
+ ]);
27
+ const Attributes = Schema.Struct({
28
+ /** `off`: no client, and the values below are the off values. */
29
+ status: Schema.Literals([
30
+ "on",
31
+ "off",
32
+ "suspended"
33
+ ]),
34
+ /** The issuer of the hub, which the deployment names to sign in. */
35
+ issuer: Schema.String,
36
+ clientId: Schema.String,
37
+ /** Returned only at registration. */
38
+ clientSecret: Schema.Redacted(Schema.String),
39
+ /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */
40
+ registrationAccessToken: Schema.Redacted(Schema.String),
41
+ registrationClientUri: Schema.String,
42
+ deploymentType: DeploymentType,
43
+ /** The return address that the client serves. Empty for the off values. */
44
+ redirectUri: Schema.String,
45
+ /** The connectors the client is enrolled in, sorted, each once. Empty for the off values. */
46
+ connectors: Schema.Array(Schema.String),
47
+ /**
48
+ * Returned only at a production registration (RFC 7591 section 1.2). It registers development
49
+ * clients of this app. Empty for a preview, for a development client, and for the off values.
50
+ */
51
+ initialAccessToken: Schema.Redacted(Schema.String),
52
+ /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */
53
+ repository: Schema.String
54
+ });
55
+ /**
56
+ * The attributes of a saved row. A row that does not have this version's shape, or any other
57
+ * failure of the decoder, stops the run with `reason`. The text of a schema issue can quote a value
58
+ * of the row, so it is never kept.
59
+ */
60
+ const savedAttributes = (value, reason) => Schema.decodeUnknownEffect(Attributes)(value).pipe(Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason }))));
61
+ /** The attributes of no client. */
62
+ const offAttributes = (deploymentType) => ({
63
+ status: "off",
64
+ issuer: OFF_VALUES.issuer,
65
+ clientId: OFF_VALUES.clientId,
66
+ clientSecret: Redacted.make(OFF_VALUES.clientSecret),
67
+ registrationAccessToken: Redacted.make(""),
68
+ registrationClientUri: "",
69
+ deploymentType,
70
+ redirectUri: "",
71
+ connectors: [],
72
+ initialAccessToken: Redacted.make(""),
73
+ repository: ""
74
+ });
75
+ /** The set of `names`: sorted, each once. */
76
+ const connectorSet = (names) => [...new Set(names)].sort();
77
+ const sameSet = (a, b) => a.length === b.length && a.every((name, index) => name === b[index]);
78
+ /** One request gave no usable answer. The reason holds no secret. */
79
+ var IdentityHubClientFailed = class extends Schema.TaggedError()("IdentityHubClientFailed", { reason: Schema.String }) {
80
+ get message() {
81
+ return `IdentityHub.Client: ${this.reason}.`;
82
+ }
83
+ };
84
+ const OidcToken = Schema.Struct({ value: Schema.NonEmptyString });
85
+ /** The 201 answer of `POST /hub-clients`. */
86
+ const NewClient = Schema.Struct({
87
+ issuer: Schema.NonEmptyString,
88
+ client_id: Schema.NonEmptyString,
89
+ client_secret: Schema.NonEmptyString,
90
+ registration_access_token: Schema.NonEmptyString,
91
+ registration_client_uri: Schema.NonEmptyString,
92
+ redirect_uri: Schema.NonEmptyString,
93
+ /** The set the hub recorded, which must be the set the request sent. */
94
+ connectors: Schema.Array(Schema.String),
95
+ /** Only in the answer to a production registration with the GitHub token. */
96
+ initial_access_token: Schema.optionalKey(Schema.NonEmptyString),
97
+ repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\d+$/)))
98
+ });
99
+ /** The other answers of `POST /hub-clients`, by status. */
100
+ const REFUSALS = {
101
+ 400: "the identity hub refused the request: the return address must be https on a DNS name, and the app name at most 64 characters",
102
+ 401: "the identity hub refused the GitHub OIDC token",
103
+ 403: "the identity hub does not allow this repository or return address",
104
+ 404: "the identity hub has no /hub-clients",
105
+ 429: "the identity hub limits new clients",
106
+ 502: "GitHub's keys are not available to the identity hub"
107
+ };
108
+ /** The reasons of a 403 that a log line shows. Any other text of the answer is never logged. */
109
+ const NOT_ALLOWED = /* @__PURE__ */ new Map([
110
+ ["paused", "this app is paused on the identity hub"],
111
+ ["run_not_allowed", "the identity hub gives clients only to runs of main and of pull requests"],
112
+ ["blocked", "Samebase blocked this repository or its owner"],
113
+ ["suspended", "the identity hub suspended this repository"],
114
+ ["too_many_apps", "the repository has as many apps on the identity hub as it may"],
115
+ ["too_many_clients", "the app has as many clients on the identity hub as it may"],
116
+ ["app_taken", "the app's name belongs to another app on the identity hub"],
117
+ ["host_unreachable", "the identity hub could not reach the host of the return address"],
118
+ ["verification_file_missing", "the host of the return address does not serve /samebase-verification.json"],
119
+ ["verification_file_invalid", "/samebase-verification.json on the host holds no repository id"],
120
+ ["repository_mismatch", "/samebase-verification.json on the host names another repository"],
121
+ ["app_mismatch", "the initial access token belongs to another app on the identity hub"]
122
+ ]);
123
+ /** The windows of a 429, by the name that the answer gives. */
124
+ const RATE_LIMITED = /* @__PURE__ */ new Map([
125
+ ["repository", "the identity hub gives one repository at most 30 new clients an hour"],
126
+ ["owner", "the identity hub gives one owner at most 100 new clients an hour"],
127
+ ["new_owners", "the identity hub takes at most 50 new owners an hour"]
128
+ ]);
129
+ const Refusal = Schema.Struct({ reason: Schema.String });
130
+ const RateLimited = Schema.Struct({ window: Schema.String });
131
+ /** A 400 for a connector the hub does not offer or allow, with the names it allows. */
132
+ const InvalidConnectors = Schema.Struct({
133
+ error: Schema.Literal("invalid_connectors"),
134
+ allowed: Schema.Array(Schema.String)
135
+ });
136
+ /**
137
+ * The text of a refusal: a known reason of a 403 or window of a 429, the allowed connectors of an
138
+ * `invalid_connectors` 400 (only names of the connector grammar, so no other text of the answer is
139
+ * printed), else the text of its status.
140
+ */
141
+ const refusalOf = (status, body) => {
142
+ const decoded = (schema) => Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));
143
+ const ofStatus = () => REFUSALS[status] ?? "the identity hub refused the request";
144
+ switch (status) {
145
+ case 400: {
146
+ const allowed = decoded(InvalidConnectors)?.allowed.filter((name) => CONNECTOR_NAME.test(name));
147
+ return allowed === void 0 ? ofStatus() : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
148
+ }
149
+ case 403: return NOT_ALLOWED.get(decoded(Refusal)?.reason ?? "") ?? ofStatus();
150
+ case 429: return RATE_LIMITED.get(decoded(RateLimited)?.window ?? "") ?? ofStatus();
151
+ default: return ofStatus();
152
+ }
153
+ };
154
+ const send = (who, url, token, init) => Effect.tryPromise({
155
+ try: async () => {
156
+ const response = await fetch(url, {
157
+ ...init,
158
+ headers: {
159
+ Authorization: `Bearer ${token}`,
160
+ "Content-Type": "application/json"
161
+ },
162
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
163
+ });
164
+ const body = await response.json().catch(() => void 0);
165
+ return {
166
+ status: response.status,
167
+ body
168
+ };
169
+ },
170
+ catch: () => new IdentityHubClientFailed({ reason: `${who} gave no answer` })
171
+ });
172
+ const decode = (schema, who) => (value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => new IdentityHubClientFailed({ reason: `${who} gave a bad answer` })));
173
+ /**
174
+ * The OIDC token of this run for `audience`, read right before the call, because it lives for
175
+ * minutes only.
176
+ */
177
+ const readOidcToken = (requestUrl, requestToken, audience) => Effect.gen(function* () {
178
+ const { body, status } = yield* send("GitHub", `${requestUrl}&audience=${encodeURIComponent(audience)}`, requestToken, { method: "GET" });
179
+ if (status !== 200) return yield* new IdentityHubClientFailed({ reason: `GitHub gave no OIDC token (HTTP ${status})` });
180
+ return (yield* decode(OidcToken, "GitHub")(body)).value;
181
+ });
182
+ /** `POST /hub-clients` with `bearer`: the GitHub OIDC token, or the app's initial access token. */
183
+ const requestNewClient = (props, connectors, bearer) => Effect.gen(function* () {
184
+ const { hub } = props;
185
+ const { body, status } = yield* send("The identity hub", `${hub.issuer}/hub-clients`, bearer, {
186
+ method: "POST",
187
+ body: JSON.stringify({
188
+ app: props.app,
189
+ redirectUri: props.redirectUri,
190
+ softwareVersion: props.softwareVersion ?? "unknown",
191
+ connectors
192
+ })
193
+ });
194
+ 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})` });
195
+ const client = yield* decode(NewClient, "The identity hub")(body);
196
+ if (client.issuer !== hub.issuer || client.redirect_uri !== props.redirectUri || !sameSet(client.connectors, connectors)) return yield* new IdentityHubClientFailed({ reason: "The identity hub gave a bad answer" });
197
+ yield* Effect.logInfo(`IdentityHub.Client: ${props.app} on ${props.redirectUri} has a new client of the identity hub ${hub.issuer}.`);
198
+ const production = props.deploymentType === "production";
199
+ return {
200
+ status: "on",
201
+ issuer: hub.issuer,
202
+ clientId: client.client_id,
203
+ clientSecret: Redacted.make(client.client_secret),
204
+ registrationAccessToken: Redacted.make(client.registration_access_token),
205
+ registrationClientUri: client.registration_client_uri,
206
+ deploymentType: props.deploymentType,
207
+ redirectUri: props.redirectUri,
208
+ connectors,
209
+ initialAccessToken: Redacted.make(production ? client.initial_access_token ?? "" : ""),
210
+ repository: production ? client.repository ?? "" : ""
211
+ };
212
+ });
213
+ /** A new client, or the off values. */
214
+ const newClient = (props, connectors) => {
215
+ const label = `IdentityHub.Client: ${props.app} on ${props.redirectUri} deploys without the hub`;
216
+ const off = offAttributes(props.deploymentType);
217
+ const request = (bearer) => bearer.pipe(Effect.flatMap((token) => requestNewClient(props, connectors, token)), Effect.catchTag("IdentityHubClientFailed", (error) => Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(Effect.as(off))));
218
+ if (props.deploymentType === "development") {
219
+ const token = Redacted.value(props.initialAccessToken);
220
+ return token === "" ? Effect.logInfo("IdentityHub.Client: deploy to main once for hub sign-in in development.").pipe(Effect.as(off)) : request(Effect.succeed(token));
221
+ }
222
+ const requestUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];
223
+ const requestToken = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];
224
+ if (!requestUrl || !requestToken) return (process.env["GITHUB_ACTIONS"] === "true" ? Effect.logWarning(`${label}: this workflow needs the permission id-token: write.`) : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)).pipe(Effect.as(off));
225
+ return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));
226
+ };
227
+ /**
228
+ * The client after a read on the hub, or undefined when the hub says that the client is gone. A
229
+ * read with no usable answer keeps the saved client, except for a required one: a required client
230
+ * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,
231
+ * and did not save because that run failed, cannot pass a run that the hub does not answer.
232
+ */
233
+ const renew = (saved, required) => Effect.gen(function* () {
234
+ const { status } = yield* send("The identity hub", saved.registrationClientUri, Redacted.value(saved.registrationAccessToken), { method: "GET" });
235
+ switch (status) {
236
+ case 200: return {
237
+ ...saved,
238
+ status: "on"
239
+ };
240
+ case 401: return;
241
+ case 403:
242
+ yield* Effect.logWarning(`IdentityHub.Client: the hub suspended the client of ${saved.redirectUri}. It keeps its values, and nobody can sign in with it.`);
243
+ return {
244
+ ...saved,
245
+ status: "suspended"
246
+ };
247
+ default: return yield* new IdentityHubClientFailed({ reason: `The identity hub answered HTTP ${status}` });
248
+ }
249
+ }).pipe(Effect.catchTag("IdentityHubClientFailed", (error) => required ? Effect.fail(new IdentityHubClientFailed({ reason: `${saved.redirectUri} is required, and the hub did not confirm its client: ${error.reason}` })) : Effect.logWarning(`IdentityHub.Client: ${saved.redirectUri} keeps the saved client: ${error.reason}.`).pipe(Effect.as(saved))));
250
+ /**
251
+ * The type of this resource before 0.37.0. Alchemy finds this provider for a row of that type, and
252
+ * the next write of the row gives it the new type, with the same client. Remove it, here and in
253
+ * `SavedRow`, once no saved row has the old type.
254
+ */
255
+ const OLD_TYPE = "IdentityHub.SharedClient";
256
+ /** A saved row of this resource, whose `attr` `savedAttributes` reads. */
257
+ const SavedRow = Schema.Struct({
258
+ resourceType: Schema.Literals(["IdentityHub.Client", OLD_TYPE]),
259
+ attr: Schema.Unknown
260
+ });
261
+ /**
262
+ * The attributes of the client `id` in another stage of this stack, such as
263
+ * `read("HubClient", { stage: "prod" })` in a development stage, as Outputs: the
264
+ * `initialAccessToken` and the `repository` of the production client. Without that row, the off
265
+ * attributes, with `deploymentType: "production"`.
266
+ *
267
+ * `IdentityHub.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the
268
+ * row is missing, and a development stage before the first deploy to main has none. This read runs
269
+ * when the plan resolves it, with the State service of the running stack and its `get`, so it never
270
+ * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every
271
+ * read.
272
+ */
273
+ const read = (id, options) => Output.fromEffect(Effect.gen(function* () {
274
+ const stack = yield* Stack;
275
+ const row = yield* (yield* yield* State).get({
276
+ stack: stack.name,
277
+ stage: options.stage,
278
+ fqn: id
279
+ }).pipe(Effect.orDie);
280
+ if (row === void 0) return offAttributes("production");
281
+ 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` }))));
282
+ return yield* savedAttributes(attr, `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`);
283
+ }));
284
+ /**
285
+ * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,
286
+ * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when
287
+ * `status` is `on`, else the off values, so that a suspended client gives guest sign-in and keeps
288
+ * its values in state.
289
+ */
290
+ const variables = (client) => Output.map(Output.of(client), (attributes) => attributes.status === "on" ? {
291
+ issuer: attributes.issuer,
292
+ clientId: attributes.clientId,
293
+ clientSecret: attributes.clientSecret
294
+ } : {
295
+ issuer: OFF_VALUES.issuer,
296
+ clientId: OFF_VALUES.clientId,
297
+ clientSecret: Redacted.make(OFF_VALUES.clientSecret)
298
+ });
299
+ const Client = Resource("IdentityHub.Client", { aliases: [OLD_TYPE] })({
300
+ read,
301
+ variables
302
+ });
303
+ const ClientProvider = () => Provider.succeed(Client, {
304
+ diff: ({ news }) => Effect.succeed(isResolved(news) ? { action: "update" } : void 0),
305
+ read: ({ output }) => Effect.succeed(output),
306
+ reconcile: Effect.fn(function* ({ news, output }) {
307
+ if (news.connectors.length === 0 || !news.connectors.every((name) => CONNECTOR_NAME.test(name))) return yield* new IdentityHubClientFailed({ reason: `${news.app} on ${news.redirectUri} needs connectors: one or more names of [a-z0-9-]{1,64}` });
308
+ const connectors = connectorSet(news.connectors);
309
+ const saved = output === void 0 || output.status === "off" ? void 0 : yield* savedAttributes(output, `the saved attributes of ${news.app} on ${news.redirectUri} cannot be read by this version`);
310
+ const client = (saved?.issuer === news.hub.issuer && saved.redirectUri === news.redirectUri && saved.deploymentType === news.deploymentType && sameSet(saved.connectors, connectors) ? yield* renew(saved, news.required === true) : void 0) ?? (yield* newClient(news, connectors));
311
+ if (news.required === true && client.status !== "on") return yield* new IdentityHubClientFailed({ reason: `${news.app} on ${news.redirectUri} is required and has no working client (${client.status}). The warning above names the reason` });
312
+ return client;
313
+ }),
314
+ delete: ({ output }) => output.deploymentType === "production" || output.status === "off" ? Effect.void : Effect.gen(function* () {
315
+ const { status } = yield* send("The identity hub", output.registrationClientUri, Redacted.value(output.registrationAccessToken), { method: "DELETE" });
316
+ if (status !== 204 && status !== 401) return yield* new IdentityHubClientFailed({ reason: `The identity hub answered HTTP ${status}` });
317
+ }).pipe(Effect.catchTag("IdentityHubClientFailed", (error) => Effect.logWarning(`IdentityHub.Client: the client of ${output.redirectUri} stays on the hub until its removal date: ${error.reason}.`)))
318
+ });
319
+ //#endregion
320
+ export { ClientProvider as n, Client as t };
321
+
322
+ //# sourceMappingURL=IdentityHub-XSCxmYoN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IdentityHub-XSCxmYoN.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). The hub records the set on the client and never changes it: a stack with\n// another set registers a new client.\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 return address, type, or connector\n// set. If that request fails, the run gives the off values, so the app has guest sign-in and not a\n// broken button. The off values are the `no-hub` variables of a checkout without a hub: Convex\n// 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/**\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>/hub-clients`,\n * with 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 /** The stable name of the app, set once in the stack. */\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 address of the hub's sign-ins, such as `${site.siteUrl}/auth/hub/callback`: an https\n * URL whose origin serves `/samebase-verification.json` with the numeric GitHub id of this\n * repository, `{ \"repository\": \"123\" }`. It can come from a resource that this run creates. A\n * development client can also have http on a loopback host, which needs no file.\n */\n readonly redirectUri: 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 return address that the client serves. Empty for the off values. */\n redirectUri: 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 redirectUri: \"\",\n connectors: [],\n initialAccessToken: Redacted.make(\"\"),\n repository: \"\",\n});\n\n/** The set of `names`: sorted, each once. */\nconst connectorSet = (names: readonly string[]) => [...new Set(names)].sort();\n\nconst sameSet = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && a.every((name, index) => name === b[index]);\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/** The 201 answer of `POST /hub-clients`. */\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 redirect_uri: Schema.NonEmptyString,\n /** The set the hub recorded, which must be the set the request sent. */\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 /hub-clients`, by status. */\nconst REFUSALS: Readonly<Record<number, string>> = {\n 400: \"the identity hub refused the request: the return address must be https on a DNS name, and the app name at most 64 characters\",\n 401: \"the identity hub refused the GitHub OIDC token\",\n 403: \"the identity hub does not allow this repository or return address\",\n 404: \"the identity hub has no /hub-clients\",\n 429: \"the identity hub limits new clients\",\n 502: \"GitHub's keys are not available to the identity hub\",\n};\n\n/** The reasons of a 403 that a log line shows. Any other text of the answer is never logged. */\nconst NOT_ALLOWED = 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]);\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 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 error: Schema.Literal(\"invalid_connectors\"),\n allowed: Schema.Array(Schema.String),\n});\n\n/**\n * The text of a refusal: a known reason of a 403 or window of a 429, the allowed connectors of an\n * `invalid_connectors` 400 (only names of the connector grammar, so no other text of the answer is\n * printed), else the text of its status.\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 ? ofStatus()\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 NOT_ALLOWED.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/** `POST /hub-clients` with `bearer`: the GitHub OIDC token, or the app's initial access token. */\nconst requestNewClient = (props: ClientProps, connectors: readonly string[], bearer: string) =>\n Effect.gen(function* () {\n const { hub } = props;\n const { body, status } = yield* send(\"The identity hub\", `${hub.issuer}/hub-clients`, bearer, {\n method: \"POST\",\n body: JSON.stringify({\n app: props.app,\n redirectUri: props.redirectUri,\n softwareVersion: props.softwareVersion ?? \"unknown\",\n connectors,\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 address and the connectors that the request sent, under its own issuer.\n // The log and the state hold the stack's values, so no value that the answer chose is printed\n // or kept.\n if (\n client.issuer !== hub.issuer ||\n client.redirect_uri !== props.redirectUri ||\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: ${props.app} on ${props.redirectUri} 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 redirectUri: props.redirectUri,\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, connectors: readonly string[]) => {\n const label = `IdentityHub.Client: ${props.app} on ${props.redirectUri} 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, connectors, 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 ${saved.redirectUri}. 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: `${saved.redirectUri} is required, and the hub did not confirm its client: ${error.reason}`,\n }),\n )\n : Effect.logWarning(\n `IdentityHub.Client: ${saved.redirectUri} 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), return address, type, and connector set is\n // renewed. A saved row without this version's shape stops the run with a 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 if (\n news.connectors.length === 0 ||\n !news.connectors.every((name) => CONNECTOR_NAME.test(name))\n ) {\n return yield* new IdentityHubClientFailed({\n reason: `${news.app} on ${news.redirectUri} needs connectors: one or more names of [a-z0-9-]{1,64}`,\n });\n }\n const connectors = connectorSet(news.connectors);\n const saved =\n output === undefined || output.status === \"off\"\n ? undefined\n : yield* savedAttributes(\n output,\n `the saved attributes of ${news.app} on ${news.redirectUri} cannot be read by this version`,\n );\n const renewed =\n saved?.issuer === news.hub.issuer &&\n saved.redirectUri === news.redirectUri &&\n saved.deploymentType === news.deploymentType &&\n sameSet(saved.connectors, connectors)\n ? yield* renew(saved, news.required === true)\n : undefined;\n const client = renewed ?? (yield* newClient(news, connectors));\n if (news.required === true && client.status !== \"on\") {\n return yield* new IdentityHubClientFailed({\n reason: `${news.app} on ${news.redirectUri} 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 Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n Effect.logWarning(\n `IdentityHub.Client: the client of ${output.redirectUri} stays on the hub until its removal date: ${error.reason}.`,\n ),\n ),\n ),\n });\n"],"mappings":";;;;;;;;;;;;AA+CA,MAAM,qBAAqB;;AAG3B,MAAM,aAAa;CAAE,QAAQ;CAAsB,UAAU;CAAU,cAAc;AAAS;;AAG9F,MAAM,iBAAiB;AA2DvB,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,aAAa,OAAO;;CAEpB,YAAY,OAAO,MAAM,OAAO,MAAM;;;;;CAKtC,oBAAoB,OAAO,SAAS,OAAO,MAAM;;CAEjD,YAAY,OAAO;AACrB,CAAC;;;;;;AAaD,MAAM,mBAAmB,OAAgB,WACvC,OAAO,oBAAoB,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,KAC5C,OAAO,iBAAiB,OAAO,IAAI,IAAI,wBAAwB,EAAE,OAAO,CAAC,CAAC,CAAC,CAC7E;;AAGF,MAAM,iBAAiB,oBAA0E;CAC/F,QAAQ;CACR,QAAQ,WAAW;CACnB,UAAU,WAAW;CACrB,cAAc,SAAS,KAAK,WAAW,YAAY;CACnD,yBAAyB,SAAS,KAAK,EAAE;CACzC,uBAAuB;CACvB;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