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