@samebase/alchemy-convex 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,830 +0,0 @@
1
- // IdentityHub.Client: one deployment of an app as a client of the identity hub that the stack
2
- // names, for an app that deploys in its own GitHub Actions run, on any host, and in development as a
3
- // stage of the same stack. Import it as
4
- // `import * as IdentityHub from "@samebase/alchemy-convex/identity-hub"`; `Convex.providers()`
5
- // registers its provider.
6
- //
7
- // A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs
8
- // no key and no Samebase account. The token names the repository. The hub reads
9
- // `/samebase-verification.json` at the origin of the return address, which must name the same
10
- // repository, and registers the client on that address. The answer holds the client's own
11
- // registration access token (RFC 7591), and each later deploy reads the client on the hub with that
12
- // token (RFC 7592). The hub keeps only hashes, so the state is the only record of the secret and the
13
- // token.
14
- //
15
- // The answer to a production registration also holds the app's initial access token (RFC 7591
16
- // section 1.2) and the repository id. The state of stage `prod` keeps them. A development checkout
17
- // runs the stack as a stage `dev-<name>`: it reads them with `IdentityHub.Client.read`, and a client
18
- // with `deploymentType: "development"` asks the hub with the token in place of the GitHub token
19
- // (RFC 133).
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
- //
27
- // A client is enrolled in the connectors it signs in through, such as `google` and `github`, at
28
- // registration (RFC 137), and holds the return addresses its requests may name, one per handler of
29
- // the app, such as the sign-in callback and the connections callback. The hub records both sets on
30
- // the client and never changes them: a stack with another set registers a new client.
31
- //
32
- // The app is the stack: its name on the hub defaults to the stack's path in the repository, as the
33
- // state store groups stacks (`owner/repo/<path>`), and `app` for a stack named after the repository.
34
- // `app` overrides it. The name groups the clients, their budgets, and the initial access token; it
35
- // plays no part in user ids, which the hub derives from the provider's own id.
36
- //
37
- // A push removes a variable that a deploy stops passing, so a failure here must not drop working
38
- // variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that
39
- // cannot work asks for a new one: it is gone, or it has another app name, return address set, type,
40
- // or connector set. If that request fails, the run gives the off values, so the app has guest
41
- // sign-in and not a broken button. The off values are the `no-hub` variables of a checkout without
42
- // a hub: Convex needs the variables, and the app hides the button for this client ID.
43
- //
44
- // No text in this file quotes an answer or a fetch error, so no log line can hold a secret. The one
45
- // exception is the connector names of an `invalid_connectors` refusal, each checked against the
46
- // grammar of a connector name before it is printed.
47
- import { Resource } from "alchemy";
48
- import { isResolved } from "alchemy/Diff";
49
- import * as Output from "alchemy/Output";
50
- import * as Provider from "alchemy/Provider";
51
- import { Random } from "alchemy/Random";
52
- import { Stack } from "alchemy/Stack";
53
- import { State } from "alchemy/State";
54
- import * as Effect from "effect/Effect";
55
- import * as Option from "effect/Option";
56
- import * as Redacted from "effect/Redacted";
57
- import * as Schedule from "effect/Schedule";
58
- import * as Schema from "effect/Schema";
59
- import type { Providers } from "./Providers.ts";
60
-
61
- /** A hung service must not hold a deploy: the time limit of one request. */
62
- const REQUEST_TIMEOUT_MS = 30_000;
63
-
64
- /** The variables of a deployment without a hub client, as the starter writes them. */
65
- const OFF_VALUES = { issuer: "http://127.0.0.1:1", clientId: "no-hub", clientSecret: "no-hub" };
66
-
67
- /** The name of a connector on the hub. */
68
- const CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;
69
-
70
- /** The return addresses of one client, as the hub caps them. */
71
- const MAX_REDIRECT_URIS = 8;
72
- /** The app's name, as the hub caps it. A deeper stack path needs an explicit `app`. */
73
- const MAX_APP_LENGTH = 64;
74
-
75
- /**
76
- * The app's default name: the stack's path below `owner/repo`, or `app` for a stack named after
77
- * the repository. Undefined for a stack whose name is not `owner/repo` or `owner/repo/<path>`.
78
- */
79
- export const defaultApp = (stackName: string): string | undefined => {
80
- const segments = stackName.split("/");
81
- if (segments.length < 2 || segments.some((segment) => segment === "")) {
82
- return undefined;
83
- }
84
- return segments.slice(2).join("/") || "app";
85
- };
86
-
87
- /**
88
- * An identity hub of @samebase/identity-broker, such as Samebase's public hub:
89
- * `{ issuer: "https://id.samebase.com" }`.
90
- */
91
- export interface Hub {
92
- /**
93
- * The hub's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/register`, with
94
- * a GitHub token whose audience is the issuer, so no other hub can use that token.
95
- */
96
- readonly issuer: string;
97
- }
98
-
99
- interface CommonProps {
100
- /**
101
- * The app's name in its repository. Default: the stack's path in the repository, `apps/samebase`
102
- * for the stack `samebase/samebase/apps/samebase`, and `app` for a stack named after the
103
- * repository. A changed name registers a new client under the new name.
104
- */
105
- readonly app?: string;
106
- /** The hub to register at. A changed hub registers a new client there; the old one stays. */
107
- readonly hub: Hub;
108
- /**
109
- * The connectors the client signs in through, by their names on the hub, such as
110
- * `["google", "github"]`: at least one, each of `[a-z0-9-]{1,64}`. The hub refuses a name it does
111
- * not offer, or does not allow this repository, and the log then names the allowed ones. The set
112
- * is recorded on the client for good: a changed set registers a new client.
113
- */
114
- readonly connectors: readonly string[];
115
- /**
116
- * The return addresses of this deployment, one to eight, such as
117
- * `[`${site.siteUrl}/auth/hub/callback`]`: each an https URL whose origin serves
118
- * `/samebase-verification.json` with the numeric GitHub id of this repository,
119
- * `{ "repository": "123" }`. They can come from a resource that this run creates. A development
120
- * client can also have http on a loopback host, which needs no file. Every request of the client
121
- * names one of them. The set is recorded on the client for good: a changed set registers a new
122
- * client.
123
- */
124
- readonly redirectUris: string[];
125
- /** Recorded on the hub's client, such as the commit. The hub records "unknown" without it. */
126
- readonly softwareVersion?: string;
127
- /**
128
- * The run fails unless the hub confirms the client in this run: it fails when the hub refuses or
129
- * does not answer a registration or a renewal, and when it suspended the client. Without it, such
130
- * a run gives the off values or keeps the saved client, so the app deploys anyway. Set it where
131
- * sign-in is the product. A failed run saves nothing, so the next run asks the hub again.
132
- */
133
- readonly required?: boolean;
134
- }
135
-
136
- /**
137
- * A production or preview client asks with the GitHub OIDC token of the run. A development client
138
- * asks with the app's initial access token, which `IdentityHub.Client.read` gives from stage `prod`.
139
- * A client of any type with `key` asks with that key, a key of a hub on the stack layer, such as
140
- * `IdentityHub.registrationKey` gives.
141
- */
142
- export type ClientProps =
143
- | (CommonProps & {
144
- readonly deploymentType: "production" | "preview";
145
- readonly initialAccessToken?: never;
146
- readonly key?: never;
147
- })
148
- | (CommonProps & {
149
- readonly deploymentType: "development";
150
- /** Empty before the first production registration: the client gets the off values. */
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;
163
- });
164
-
165
- const DeploymentType = Schema.Literals(["production", "preview", "development"]);
166
-
167
- const Attributes = Schema.Struct({
168
- /** `off`: no client, and the values below are the off values. */
169
- status: Schema.Literals(["on", "off", "suspended"]),
170
- /** The issuer of the hub, which the deployment names to sign in. */
171
- issuer: Schema.String,
172
- clientId: Schema.String,
173
- /** Returned only at registration. */
174
- clientSecret: Schema.Redacted(Schema.String),
175
- /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */
176
- registrationAccessToken: Schema.Redacted(Schema.String),
177
- registrationClientUri: Schema.String,
178
- deploymentType: DeploymentType,
179
- /** The app's name on the hub, as sent. Empty for the off values. */
180
- app: Schema.String,
181
- /** The return addresses the client serves, sorted, each once. Empty for the off values. */
182
- redirectUris: Schema.Array(Schema.String),
183
- /** The connectors the client is enrolled in, sorted, each once. Empty for the off values. */
184
- connectors: Schema.Array(Schema.String),
185
- /**
186
- * Returned only at a production registration (RFC 7591 section 1.2). It registers development
187
- * clients of this app. Empty for a preview, for a development client, and for the off values.
188
- */
189
- initialAccessToken: Schema.Redacted(Schema.String),
190
- /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */
191
- repository: Schema.String,
192
- });
193
-
194
- /**
195
- * The attributes keep the real values of a suspended client, so that an unblock needs no new client.
196
- * `IdentityHub.Client.variables` gives the values that the app gets.
197
- */
198
- export interface ClientAttributes extends Schema.Schema.Type<typeof Attributes> {}
199
-
200
- /**
201
- * The attributes of a saved row. A row that does not have this version's shape, or any other
202
- * failure of the decoder, stops the run with `reason`. The text of a schema issue can quote a value
203
- * of the row, so it is never kept.
204
- */
205
- const savedAttributes = (value: unknown, reason: string) =>
206
- Schema.decodeUnknownEffect(Attributes)(value).pipe(
207
- Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason }))),
208
- );
209
-
210
- /** The attributes of no client. */
211
- const offAttributes = (deploymentType: ClientAttributes["deploymentType"]): ClientAttributes => ({
212
- status: "off",
213
- issuer: OFF_VALUES.issuer,
214
- clientId: OFF_VALUES.clientId,
215
- clientSecret: Redacted.make(OFF_VALUES.clientSecret),
216
- registrationAccessToken: Redacted.make(""),
217
- registrationClientUri: "",
218
- deploymentType,
219
- app: "",
220
- redirectUris: [],
221
- connectors: [],
222
- initialAccessToken: Redacted.make(""),
223
- repository: "",
224
- });
225
-
226
- /** The set of `values`: sorted, each once. */
227
- const sortedSet = (values: readonly string[]) => [...new Set(values)].sort();
228
-
229
- const sameSet = (a: readonly string[], b: readonly string[]) =>
230
- a.length === b.length && a.every((name, index) => name === b[index]);
231
-
232
- /** The app and its return addresses, as every log line names a client: no secret, no answer. */
233
- const where = (client: { app: string; redirectUris: readonly string[] }) =>
234
- `${client.app} on ${client.redirectUris.join(", ")}`;
235
-
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
- */
240
- interface Enrollment {
241
- readonly app: string;
242
- readonly clientName: string;
243
- readonly connectors: readonly string[];
244
- readonly redirectUris: readonly string[];
245
- }
246
-
247
- /** One request gave no usable answer. The reason holds no secret. */
248
- class IdentityHubClientFailed extends Schema.TaggedError<IdentityHubClientFailed>()(
249
- "IdentityHubClientFailed",
250
- { reason: Schema.String },
251
- ) {
252
- override get message() {
253
- return `IdentityHub.Client: ${this.reason}.`;
254
- }
255
- }
256
-
257
- const OidcToken = Schema.Struct({ value: Schema.NonEmptyString });
258
-
259
- /**
260
- * The 201 answer of `POST /register` (RFC 7591 section 3.2.1), in the members that this file reads.
261
- * The decoder ignores the other members, such as `software_id`, whose full form the hub writes.
262
- */
263
- const NewClient = Schema.Struct({
264
- issuer: Schema.NonEmptyString,
265
- client_id: Schema.NonEmptyString,
266
- client_secret: Schema.NonEmptyString,
267
- registration_access_token: Schema.NonEmptyString,
268
- registration_client_uri: Schema.NonEmptyString,
269
- /** The sets the hub recorded, which must be the sets the request sent. */
270
- redirect_uris: Schema.Array(Schema.String),
271
- connectors: Schema.Array(Schema.String),
272
- /** Only in the answer to a production registration with the GitHub token. */
273
- initial_access_token: Schema.optionalKey(Schema.NonEmptyString),
274
- repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\d+$/))),
275
- });
276
-
277
- /** The other answers of `POST /register`, by status. A 401 can have no body (RFC 6750). */
278
- const REFUSALS: Readonly<Record<number, string>> = {
279
- 400: "the identity hub refused the client metadata, such as the app name",
280
- 401: "the identity hub refused the GitHub OIDC token",
281
- 403: "the identity hub does not allow this repository",
282
- 404: "the identity hub has no /register: it runs an identity-broker before 0.33.0",
283
- 429: "the identity hub limits new clients",
284
- 502: "GitHub's keys are not available to the identity hub",
285
- 503: "the identity hub could not apply its policy",
286
- };
287
-
288
- /** The text of an `invalid_redirect_uri` 400 without a known reason. */
289
- const BAD_REDIRECT_URIS =
290
- "the identity hub refused the return addresses: one to eight, each https on a DNS name, or http on a loopback host for a development client";
291
-
292
- /**
293
- * The reasons of a 400 or a 403 that a log line shows. Any other text of the answer is never
294
- * logged.
295
- */
296
- const REASONS = new Map([
297
- ["paused", "this app is paused on the identity hub"],
298
- ["run_not_allowed", "the identity hub gives clients only to runs of main and of pull requests"],
299
- ["blocked", "Samebase blocked this repository or its owner"],
300
- ["suspended", "the identity hub suspended this repository"],
301
- ["too_many_apps", "the repository has as many apps on the identity hub as it may"],
302
- ["too_many_clients", "the app has as many clients on the identity hub as it may"],
303
- ["app_taken", "the app's name belongs to another app on the identity hub"],
304
- ["host_unreachable", "the identity hub could not reach the host of the return address"],
305
- [
306
- "verification_file_missing",
307
- "the host of the return address does not serve /samebase-verification.json",
308
- ],
309
- ["verification_file_invalid", "/samebase-verification.json on the host holds no repository id"],
310
- ["repository_mismatch", "/samebase-verification.json on the host names another repository"],
311
- ["app_mismatch", "the initial access token belongs to another app on the identity hub"],
312
- ["stale_proof", "the identity hub took a newer GitHub OIDC token of this repository"],
313
- ]);
314
-
315
- /** The windows of a 429, by the name that the answer gives. */
316
- const RATE_LIMITED = new Map([
317
- ["repository", "the identity hub gives one repository at most 30 new clients an hour"],
318
- ["owner", "the identity hub gives one owner at most 100 new clients an hour"],
319
- ["new_owners", "the identity hub takes at most 50 new owners an hour"],
320
- ]);
321
-
322
- const Refusal = Schema.Struct({ reason: Schema.String });
323
- const InvalidRedirectUri = Schema.Struct({ error: Schema.Literal("invalid_redirect_uri") });
324
- const RateLimited = Schema.Struct({ window: Schema.String });
325
- /** A 400 for a connector the hub does not offer or allow, with the names it allows. */
326
- const InvalidConnectors = Schema.Struct({
327
- reason: Schema.Literal("invalid_connectors"),
328
- allowed: Schema.Array(Schema.String),
329
- });
330
-
331
- /**
332
- * The text of a refusal: a known reason of a 400 or a 403, or window of a 429, the allowed
333
- * connectors of an `invalid_connectors` 400 (only names of the connector grammar, so no other text
334
- * of the answer is printed), the text of an `invalid_redirect_uri` 400, else the text of its
335
- * status. `body` is undefined for an answer without JSON, such as a bare 401.
336
- */
337
- const refusalOf = (status: number, body: unknown): string => {
338
- const decoded = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>
339
- Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));
340
- const ofStatus = () => REFUSALS[status] ?? "the identity hub refused the request";
341
- switch (status) {
342
- case 400: {
343
- const allowed = decoded(InvalidConnectors)?.allowed.filter((name) =>
344
- CONNECTOR_NAME.test(name),
345
- );
346
- return allowed === undefined
347
- ? (REASONS.get(decoded(Refusal)?.reason ?? "") ??
348
- (decoded(InvalidRedirectUri) === undefined ? ofStatus() : BAD_REDIRECT_URIS))
349
- : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
350
- }
351
- case 403:
352
- return REASONS.get(decoded(Refusal)?.reason ?? "") ?? ofStatus();
353
- case 429:
354
- return RATE_LIMITED.get(decoded(RateLimited)?.window ?? "") ?? ofStatus();
355
- default:
356
- return ofStatus();
357
- }
358
- };
359
-
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` }),
390
- });
391
-
392
- const decode =
393
- <S extends Schema.Codec<unknown, unknown>>(schema: S, who: string) =>
394
- (value: unknown) =>
395
- Schema.decodeUnknownEffect(schema)(value).pipe(
396
- Effect.mapError(() => new IdentityHubClientFailed({ reason: `${who} gave a bad answer` })),
397
- );
398
-
399
- /**
400
- * The OIDC token of this run for `audience`, read right before the call, because it lives for
401
- * minutes only.
402
- */
403
- const readOidcToken = (requestUrl: string, requestToken: string, audience: string) =>
404
- Effect.gen(function* () {
405
- const { body, status } = yield* send(
406
- "GitHub",
407
- `${requestUrl}&audience=${encodeURIComponent(audience)}`,
408
- requestToken,
409
- { method: "GET" },
410
- );
411
- if (status !== 200) {
412
- return yield* new IdentityHubClientFailed({
413
- reason: `GitHub gave no OIDC token (HTTP ${status})`,
414
- });
415
- }
416
- return (yield* decode(OidcToken, "GitHub")(body)).value;
417
- });
418
-
419
- /**
420
- * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial
421
- * access token: the GitHub OIDC token, the app's own token, or a key of the hub. `software_id` is
422
- * the app's name, `client_name` the stage, and `connectors` and `deployment_type` are the hub's own
423
- * metadata fields. Convex Auth posts the client's secret in the body at the token endpoint, so the
424
- * client registers that method.
425
- */
426
- const requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: string) =>
427
- Effect.gen(function* () {
428
- const { hub } = props;
429
- const { app, connectors, redirectUris } = enrollment;
430
- const { body, status } = yield* send("The identity hub", `${hub.issuer}/register`, bearer, {
431
- method: "POST",
432
- body: JSON.stringify({
433
- redirect_uris: redirectUris,
434
- software_id: app,
435
- software_version: props.softwareVersion ?? "unknown",
436
- client_name: enrollment.clientName,
437
- deployment_type: props.deploymentType,
438
- connectors,
439
- token_endpoint_auth_method: "client_secret_post",
440
- }),
441
- });
442
- if (status !== 201) {
443
- const reason =
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);
451
- return yield* new IdentityHubClientFailed({ reason: `${reason} (HTTP ${status})` });
452
- }
453
- const client = yield* decode(NewClient, "The identity hub")(body);
454
- // The hub registers the addresses and the connectors that the request sent, under its own
455
- // issuer. The log and the state hold the stack's values, so no value that the answer chose is
456
- // printed or kept.
457
- if (
458
- client.issuer !== hub.issuer ||
459
- !sameSet(sortedSet(client.redirect_uris), redirectUris) ||
460
- !sameSet(client.connectors, connectors)
461
- ) {
462
- return yield* new IdentityHubClientFailed({ reason: "The identity hub gave a bad answer" });
463
- }
464
- yield* Effect.logInfo(
465
- `IdentityHub.Client: ${where(enrollment)} has a new client of the identity hub ${hub.issuer}.`,
466
- );
467
- // Only a production registration gives the app's token (RFC 7591); any other answer's is dropped.
468
- const production = props.deploymentType === "production";
469
- return {
470
- status: "on" as const,
471
- issuer: hub.issuer,
472
- clientId: client.client_id,
473
- clientSecret: Redacted.make(client.client_secret),
474
- registrationAccessToken: Redacted.make(client.registration_access_token),
475
- registrationClientUri: client.registration_client_uri,
476
- deploymentType: props.deploymentType,
477
- app,
478
- redirectUris,
479
- connectors,
480
- initialAccessToken: Redacted.make(production ? (client.initial_access_token ?? "") : ""),
481
- repository: production ? (client.repository ?? "") : "",
482
- };
483
- });
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
-
516
- /** A new client, or the off values. */
517
- const newClient = (props: ClientProps, enrollment: Enrollment) => {
518
- const label = `IdentityHub.Client: ${where(enrollment)} deploys without the hub`;
519
- const off = offAttributes(props.deploymentType);
520
- const request = (bearer: Effect.Effect<string, IdentityHubClientFailed>) =>
521
- bearer.pipe(
522
- Effect.flatMap((token) => requestNewClient(props, enrollment, token)),
523
- Effect.catchTag("IdentityHubClientFailed", (error) =>
524
- Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(
525
- Effect.as(off),
526
- ),
527
- ),
528
- );
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
-
538
- if (props.deploymentType === "development") {
539
- const token = Redacted.value(props.initialAccessToken);
540
- return token === ""
541
- ? Effect.logInfo(
542
- "IdentityHub.Client: deploy to main once for hub sign-in in development.",
543
- ).pipe(Effect.as(off))
544
- : request(Effect.succeed(token));
545
- }
546
-
547
- const requestUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];
548
- const requestToken = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];
549
- // A development machine, or another CI. In a workflow, `id-token: write` gives both, so a
550
- // workflow without them is a mistake to show, not a normal run.
551
- if (!requestUrl || !requestToken) {
552
- return (
553
- process.env["GITHUB_ACTIONS"] === "true"
554
- ? Effect.logWarning(`${label}: this workflow needs the permission id-token: write.`)
555
- : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)
556
- ).pipe(Effect.as(off));
557
- }
558
- return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));
559
- };
560
-
561
- /**
562
- * The client after a read on the hub, or undefined when the hub says that the client is gone. A
563
- * read with no usable answer keeps the saved client, except for a required one: a required client
564
- * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,
565
- * and did not save because that run failed, cannot pass a run that the hub does not answer.
566
- */
567
- const renew = (saved: ClientAttributes, required: boolean) =>
568
- Effect.gen(function* () {
569
- const { status } = yield* send(
570
- "The identity hub",
571
- saved.registrationClientUri,
572
- Redacted.value(saved.registrationAccessToken),
573
- { method: "GET" },
574
- );
575
- switch (status) {
576
- case 200:
577
- return { ...saved, status: "on" as const };
578
- case 401:
579
- return undefined;
580
- case 403:
581
- yield* Effect.logWarning(
582
- `IdentityHub.Client: the hub suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`,
583
- );
584
- return { ...saved, status: "suspended" as const };
585
- default:
586
- return yield* new IdentityHubClientFailed({
587
- reason: `The identity hub answered HTTP ${status}`,
588
- });
589
- }
590
- }).pipe(
591
- Effect.catchTag("IdentityHubClientFailed", (error) =>
592
- required
593
- ? Effect.fail(
594
- new IdentityHubClientFailed({
595
- reason: `${where(saved)} is required, and the hub did not confirm its client: ${error.reason}`,
596
- }),
597
- )
598
- : Effect.logWarning(
599
- `IdentityHub.Client: ${where(saved)} keeps the saved client: ${error.reason}.`,
600
- ).pipe(Effect.as(saved)),
601
- ),
602
- );
603
-
604
- /**
605
- * The type of this resource before 0.37.0. Alchemy finds this provider for a row of that type, and
606
- * the next write of the row gives it the new type, with the same client. Remove it, here and in
607
- * `SavedRow`, once no saved row has the old type.
608
- */
609
- const OLD_TYPE = "IdentityHub.SharedClient";
610
-
611
- /** A saved row of this resource, whose `attr` `savedAttributes` reads. */
612
- const SavedRow = Schema.Struct({
613
- resourceType: Schema.Literals(["IdentityHub.Client", OLD_TYPE]),
614
- attr: Schema.Unknown,
615
- });
616
-
617
- /**
618
- * The attributes of the client `id` in another stage of this stack, such as
619
- * `read("HubClient", { stage: "prod" })` in a development stage, as Outputs: the
620
- * `initialAccessToken` and the `repository` of the production client. Without that row, the off
621
- * attributes, with `deploymentType: "production"`.
622
- *
623
- * `IdentityHub.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the
624
- * row is missing, and a development stage before the first deploy to main has none. This read runs
625
- * when the plan resolves it, with the State service of the running stack and its `get`, so it never
626
- * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every
627
- * read.
628
- */
629
- const read = (id: string, options: { readonly stage: string }) =>
630
- Output.fromEffect(
631
- Effect.gen(function* () {
632
- const stack = yield* Stack;
633
- const state = yield* yield* State;
634
- const row = yield* state
635
- .get({ stack: stack.name, stage: options.stage, fqn: id })
636
- .pipe(Effect.orDie);
637
- if (row === undefined) return offAttributes("production");
638
- const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(
639
- Effect.catchCause(() =>
640
- Effect.die(
641
- new IdentityHubClientFailed({
642
- reason: `the row ${id} of stage ${options.stage} is not an IdentityHub.Client`,
643
- }),
644
- ),
645
- ),
646
- );
647
- return yield* savedAttributes(
648
- attr,
649
- `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`,
650
- );
651
- }),
652
- );
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
-
698
- /**
699
- * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,
700
- * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when
701
- * `status` is `on`, else the off values, so that a suspended client gives guest sign-in and keeps
702
- * its values in state.
703
- */
704
- const variables = (client: Client) =>
705
- Output.map(Output.of(client), (attributes) =>
706
- attributes.status === "on"
707
- ? {
708
- issuer: attributes.issuer,
709
- clientId: attributes.clientId,
710
- clientSecret: attributes.clientSecret,
711
- }
712
- : {
713
- issuer: OFF_VALUES.issuer,
714
- clientId: OFF_VALUES.clientId,
715
- clientSecret: Redacted.make(OFF_VALUES.clientSecret),
716
- },
717
- );
718
-
719
- export type Client = Resource<
720
- "IdentityHub.Client",
721
- ClientProps,
722
- ClientAttributes,
723
- never,
724
- Providers
725
- >;
726
- export const Client = Resource<Client>("IdentityHub.Client", { aliases: [OLD_TYPE] })({
727
- read,
728
- variables,
729
- });
730
-
731
- export const ClientProvider = () =>
732
- Provider.succeed(Client, {
733
- // Always an update, so that each deploy reaches the hub. No attribute is stable, so a push
734
- // reads the values that this run ended with. The same values cause no other push.
735
- diff: ({ news }) =>
736
- Effect.succeed(isResolved(news) ? ({ action: "update" } as const) : undefined),
737
-
738
- read: ({ output }) => Effect.succeed(output),
739
-
740
- // Only a client of the same hub (its issuer), app name, return address set, type, and
741
- // connector set is renewed. A saved row without this version's shape stops the run with a
742
- // fixed message.
743
- reconcile: Effect.fn(function* ({ news, output }) {
744
- // A bad prop is a mistake of the stack, not of the hub: the run fails, with no request.
745
- const stack = yield* Stack;
746
- const app = news.app ?? defaultApp(stack.name);
747
- if (app === undefined) {
748
- return yield* new IdentityHubClientFailed({
749
- reason: `the stack ${stack.name} is not named owner/repo or owner/repo/<path>, so set app`,
750
- });
751
- }
752
- if (app.length > MAX_APP_LENGTH) {
753
- return yield* new IdentityHubClientFailed({
754
- reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the hub's limit, so set a shorter app`,
755
- });
756
- }
757
- const enrollment: Enrollment = {
758
- app,
759
- clientName: stack.stage,
760
- connectors: sortedSet(news.connectors),
761
- redirectUris: sortedSet(news.redirectUris),
762
- };
763
- if (
764
- enrollment.connectors.length === 0 ||
765
- !enrollment.connectors.every((name) => CONNECTOR_NAME.test(name))
766
- ) {
767
- return yield* new IdentityHubClientFailed({
768
- reason: `${where(enrollment)} needs connectors: one or more names of [a-z0-9-]{1,64}`,
769
- });
770
- }
771
- if (
772
- enrollment.redirectUris.length === 0 ||
773
- enrollment.redirectUris.length > MAX_REDIRECT_URIS ||
774
- !enrollment.redirectUris.every((uri) => URL.canParse(uri))
775
- ) {
776
- return yield* new IdentityHubClientFailed({
777
- reason: `${app} needs redirectUris: one to ${MAX_REDIRECT_URIS} absolute URLs`,
778
- });
779
- }
780
- const saved =
781
- output === undefined || output.status === "off"
782
- ? undefined
783
- : yield* savedAttributes(
784
- output,
785
- `the saved attributes of ${where(enrollment)} cannot be read by this version`,
786
- );
787
- const renewed =
788
- saved?.issuer === news.hub.issuer &&
789
- saved.app === app &&
790
- sameSet(saved.redirectUris, enrollment.redirectUris) &&
791
- saved.deploymentType === news.deploymentType &&
792
- sameSet(saved.connectors, enrollment.connectors)
793
- ? yield* renew(saved, news.required === true)
794
- : undefined;
795
- const client = renewed ?? (yield* newClient(news, enrollment));
796
- if (news.required === true && client.status !== "on") {
797
- return yield* new IdentityHubClientFailed({
798
- reason: `${where(enrollment)} is required and has no working client (${client.status}). The warning above names the reason`,
799
- });
800
- }
801
- return client;
802
- }),
803
-
804
- // A failed delete does not stop a destroy: the removal date of a preview or development client
805
- // cleans it up. A destroy can leave a production deployment running, so its client stays.
806
- delete: ({ output }) =>
807
- output.deploymentType === "production" || output.status === "off"
808
- ? Effect.void
809
- : Effect.gen(function* () {
810
- const { status } = yield* send(
811
- "The identity hub",
812
- output.registrationClientUri,
813
- Redacted.value(output.registrationAccessToken),
814
- { method: "DELETE" },
815
- );
816
- // 401: the client is gone already.
817
- if (status !== 204 && status !== 401) {
818
- return yield* new IdentityHubClientFailed({
819
- reason: `The identity hub answered HTTP ${status}`,
820
- });
821
- }
822
- }).pipe(
823
- // The row can be of an earlier version's shape, so the line names only the client id.
824
- Effect.catchTag("IdentityHubClientFailed", (error) =>
825
- Effect.logWarning(
826
- `IdentityHub.Client: the client ${output.clientId} stays on the hub until its removal date: ${error.reason}.`,
827
- ),
828
- ),
829
- ),
830
- });