@samebase/alchemy-convex 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,20 +10,22 @@ import * as Schedule from "effect/Schedule";
10
10
  import { Random } from "alchemy/Random";
11
11
  import * as Output from "alchemy/Output";
12
12
  import { State } from "alchemy/State";
13
- //#region src/IdentityHub.ts
13
+ //#region src/IdentityBroker.ts
14
14
  /** A hung service must not hold a deploy: the time limit of one request. */
15
15
  const REQUEST_TIMEOUT_MS = 3e4;
16
- /** The variables of a deployment without a hub client, as the starter writes them. */
16
+ /** The client ID and the client secret of a deployment without a broker client. */
17
+ const DISABLED = "broker-disabled";
18
+ /** The variables of a deployment without a broker client. */
17
19
  const OFF_VALUES = {
18
20
  issuer: "http://127.0.0.1:1",
19
- clientId: "no-hub",
20
- clientSecret: "no-hub"
21
+ clientId: DISABLED,
22
+ clientSecret: DISABLED
21
23
  };
22
- /** The name of a connector on the hub. */
24
+ /** The name of a connector on the broker. */
23
25
  const CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;
24
- /** The return addresses of one client, as the hub caps them. */
26
+ /** The return addresses of one client, as the broker caps them. */
25
27
  const MAX_REDIRECT_URIS = 8;
26
- /** The app's name, as the hub caps it. A deeper stack path needs an explicit `app`. */
28
+ /** The app's name, as the broker caps it. A deeper stack path needs an explicit `app`. */
27
29
  const MAX_APP_LENGTH = 64;
28
30
  /**
29
31
  * The app's default name: the stack's path below `owner/repo`, or `app` for a stack named after
@@ -46,16 +48,16 @@ const Attributes = Schema.Struct({
46
48
  "off",
47
49
  "suspended"
48
50
  ]),
49
- /** The issuer of the hub, which the deployment names to sign in. */
51
+ /** The issuer of the broker, which the deployment names to sign in. */
50
52
  issuer: Schema.String,
51
53
  clientId: Schema.String,
52
54
  /** Returned only at registration. */
53
55
  clientSecret: Schema.Redacted(Schema.String),
54
- /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */
56
+ /** Returned only at registration. It reads and deletes this client on the broker, and nothing else. */
55
57
  registrationAccessToken: Schema.Redacted(Schema.String),
56
58
  registrationClientUri: Schema.String,
57
59
  deploymentType: DeploymentType,
58
- /** The app's name on the hub, as sent. Empty for the off values. */
60
+ /** The app's name on the broker, as sent. Empty for the off values. */
59
61
  app: Schema.String,
60
62
  /** The return addresses the client serves, sorted, each once. Empty for the off values. */
61
63
  redirectUris: Schema.Array(Schema.String),
@@ -74,7 +76,7 @@ const Attributes = Schema.Struct({
74
76
  * failure of the decoder, stops the run with `reason`. The text of a schema issue can quote a value
75
77
  * of the row, so it is never kept.
76
78
  */
77
- const savedAttributes = (value, reason) => Schema.decodeUnknownEffect(Attributes)(value).pipe(Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason }))));
79
+ const savedAttributes = (value, reason) => Schema.decodeUnknownEffect(Attributes)(value).pipe(Effect.catchCause(() => Effect.die(new IdentityBrokerClientFailed({ reason }))));
78
80
  /** The attributes of no client. */
79
81
  const offAttributes = (deploymentType) => ({
80
82
  status: "off",
@@ -96,15 +98,15 @@ const sameSet = (a, b) => a.length === b.length && a.every((name, index) => name
96
98
  /** The app and its return addresses, as every log line names a client: no secret, no answer. */
97
99
  const where = (client) => `${client.app} on ${client.redirectUris.join(", ")}`;
98
100
  /** One request gave no usable answer. The reason holds no secret. */
99
- var IdentityHubClientFailed = class extends Schema.TaggedError()("IdentityHubClientFailed", { reason: Schema.String }) {
101
+ var IdentityBrokerClientFailed = class extends Schema.TaggedError()("IdentityBrokerClientFailed", { reason: Schema.String }) {
100
102
  get message() {
101
- return `IdentityHub.Client: ${this.reason}.`;
103
+ return `IdentityBroker.Client: ${this.reason}.`;
102
104
  }
103
105
  };
104
106
  const OidcToken = Schema.Struct({ value: Schema.NonEmptyString });
105
107
  /**
106
108
  * The 201 answer of `POST /register` (RFC 7591 section 3.2.1), in the members that this file reads.
107
- * The decoder ignores the other members, such as `software_id`, whose full form the hub writes.
109
+ * The decoder ignores the other members, such as `software_id`, whose full form the broker writes.
108
110
  */
109
111
  const NewClient = Schema.Struct({
110
112
  issuer: Schema.NonEmptyString,
@@ -112,7 +114,7 @@ const NewClient = Schema.Struct({
112
114
  client_secret: Schema.NonEmptyString,
113
115
  registration_access_token: Schema.NonEmptyString,
114
116
  registration_client_uri: Schema.NonEmptyString,
115
- /** The sets the hub recorded, which must be the sets the request sent. */
117
+ /** The sets the broker recorded, which must be the sets the request sent. */
116
118
  redirect_uris: Schema.Array(Schema.String),
117
119
  connectors: Schema.Array(Schema.String),
118
120
  /** Only in the answer to a production registration with the GitHub token. */
@@ -121,45 +123,45 @@ const NewClient = Schema.Struct({
121
123
  });
122
124
  /** The other answers of `POST /register`, by status. A 401 can have no body (RFC 6750). */
123
125
  const REFUSALS = {
124
- 400: "the identity hub refused the client metadata, such as the app name",
125
- 401: "the identity hub refused the GitHub OIDC token",
126
- 403: "the identity hub does not allow this repository",
127
- 404: "the identity hub has no /register: it runs an identity-broker before 0.33.0",
128
- 429: "the identity hub limits new clients",
129
- 502: "GitHub's keys are not available to the identity hub",
130
- 503: "the identity hub could not apply its policy"
126
+ 400: "the identity broker refused the client metadata, such as the app name",
127
+ 401: "the identity broker refused the GitHub OIDC token",
128
+ 403: "the identity broker does not allow this repository",
129
+ 404: "the identity broker has no /register: it runs an identity-broker before 0.33.0",
130
+ 429: "the identity broker limits new clients",
131
+ 502: "GitHub's keys are not available to the identity broker",
132
+ 503: "the identity broker could not apply its policy"
131
133
  };
132
134
  /** The text of an `invalid_redirect_uri` 400 without a known reason. */
133
- const BAD_REDIRECT_URIS = "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";
135
+ const BAD_REDIRECT_URIS = "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";
134
136
  /**
135
137
  * The reasons of a 400 or a 403 that a log line shows. Any other text of the answer is never
136
138
  * logged.
137
139
  */
138
140
  const REASONS = /* @__PURE__ */ new Map([
139
- ["paused", "this app is paused on the identity hub"],
140
- ["run_not_allowed", "the identity hub gives clients only to runs of main and of pull requests"],
141
+ ["paused", "this app is paused on the identity broker"],
142
+ ["run_not_allowed", "the identity broker gives clients only to runs of main and of pull requests"],
141
143
  ["blocked", "Samebase blocked this repository or its owner"],
142
- ["suspended", "the identity hub suspended this repository"],
143
- ["too_many_apps", "the repository has as many apps on the identity hub as it may"],
144
- ["too_many_clients", "the app has as many clients on the identity hub as it may"],
145
- ["app_taken", "the app's name belongs to another app on the identity hub"],
146
- ["host_unreachable", "the identity hub could not reach the host of the return address"],
144
+ ["suspended", "the identity broker suspended this repository"],
145
+ ["too_many_apps", "the repository has as many apps on the identity broker as it may"],
146
+ ["too_many_clients", "the app has as many clients on the identity broker as it may"],
147
+ ["app_taken", "the app's name belongs to another app on the identity broker"],
148
+ ["host_unreachable", "the identity broker could not reach the host of the return address"],
147
149
  ["verification_file_missing", "the host of the return address does not serve /samebase-verification.json"],
148
150
  ["verification_file_invalid", "/samebase-verification.json on the host holds no repository id"],
149
151
  ["repository_mismatch", "/samebase-verification.json on the host names another repository"],
150
- ["app_mismatch", "the initial access token belongs to another app on the identity hub"],
151
- ["stale_proof", "the identity hub took a newer GitHub OIDC token of this repository"]
152
+ ["app_mismatch", "the initial access token belongs to another app on the identity broker"],
153
+ ["stale_proof", "the identity broker took a newer GitHub OIDC token of this repository"]
152
154
  ]);
153
155
  /** The windows of a 429, by the name that the answer gives. */
154
156
  const RATE_LIMITED = /* @__PURE__ */ new Map([
155
- ["repository", "the identity hub gives one repository at most 30 new clients an hour"],
156
- ["owner", "the identity hub gives one owner at most 100 new clients an hour"],
157
- ["new_owners", "the identity hub takes at most 50 new owners an hour"]
157
+ ["repository", "the identity broker gives one repository at most 30 new clients an hour"],
158
+ ["owner", "the identity broker gives one owner at most 100 new clients an hour"],
159
+ ["new_owners", "the identity broker takes at most 50 new owners an hour"]
158
160
  ]);
159
161
  const Refusal = Schema.Struct({ reason: Schema.String });
160
162
  const InvalidRedirectUri = Schema.Struct({ error: Schema.Literal("invalid_redirect_uri") });
161
163
  const RateLimited = Schema.Struct({ window: Schema.String });
162
- /** A 400 for a connector the hub does not offer or allow, with the names it allows. */
164
+ /** A 400 for a connector the broker does not offer or allow, with the names it allows. */
163
165
  const InvalidConnectors = Schema.Struct({
164
166
  reason: Schema.Literal("invalid_connectors"),
165
167
  allowed: Schema.Array(Schema.String)
@@ -172,11 +174,11 @@ const InvalidConnectors = Schema.Struct({
172
174
  */
173
175
  const refusalOf = (status, body) => {
174
176
  const decoded = (schema) => Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));
175
- const ofStatus = () => REFUSALS[status] ?? "the identity hub refused the request";
177
+ const ofStatus = () => REFUSALS[status] ?? "the identity broker refused the request";
176
178
  switch (status) {
177
179
  case 400: {
178
180
  const allowed = decoded(InvalidConnectors)?.allowed.filter((name) => CONNECTOR_NAME.test(name));
179
- return allowed === void 0 ? REASONS.get(decoded(Refusal)?.reason ?? "") ?? (decoded(InvalidRedirectUri) === void 0 ? ofStatus() : BAD_REDIRECT_URIS) : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
181
+ return allowed === void 0 ? REASONS.get(decoded(Refusal)?.reason ?? "") ?? (decoded(InvalidRedirectUri) === void 0 ? ofStatus() : BAD_REDIRECT_URIS) : `the identity broker does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
180
182
  }
181
183
  case 403: return REASONS.get(decoded(Refusal)?.reason ?? "") ?? ofStatus();
182
184
  case 429: return RATE_LIMITED.get(decoded(RateLimited)?.window ?? "") ?? ofStatus();
@@ -187,7 +189,7 @@ const refusalOf = (status, body) => {
187
189
  * One request to `who` at `url`, with `token` as its Bearer. A token goes only to an https URL:
188
190
  * to any other URL the request is not made.
189
191
  */
190
- const send = (who, url, token, init) => token !== void 0 && !(URL.canParse(url) && new URL(url).protocol === "https:") ? Effect.fail(new IdentityHubClientFailed({ reason: `${who} is not at an https URL, so no credential was sent to it` })) : Effect.tryPromise({
192
+ const send = (who, url, token, init) => token !== void 0 && !(URL.canParse(url) && new URL(url).protocol === "https:") ? Effect.fail(new IdentityBrokerClientFailed({ reason: `${who} is not at an https URL, so no credential was sent to it` })) : Effect.tryPromise({
191
193
  try: async () => {
192
194
  const response = await fetch(url, {
193
195
  ...init,
@@ -203,29 +205,29 @@ const send = (who, url, token, init) => token !== void 0 && !(URL.canParse(url)
203
205
  body
204
206
  };
205
207
  },
206
- catch: () => new IdentityHubClientFailed({ reason: `${who} gave no answer` })
208
+ catch: () => new IdentityBrokerClientFailed({ reason: `${who} gave no answer` })
207
209
  });
208
- const decode = (schema, who) => (value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => new IdentityHubClientFailed({ reason: `${who} gave a bad answer` })));
210
+ const decode = (schema, who) => (value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => new IdentityBrokerClientFailed({ reason: `${who} gave a bad answer` })));
209
211
  /**
210
212
  * The OIDC token of this run for `audience`, read right before the call, because it lives for
211
213
  * minutes only.
212
214
  */
213
215
  const readOidcToken = (requestUrl, requestToken, audience) => Effect.gen(function* () {
214
216
  const { body, status } = yield* send("GitHub", `${requestUrl}&audience=${encodeURIComponent(audience)}`, requestToken, { method: "GET" });
215
- if (status !== 200) return yield* new IdentityHubClientFailed({ reason: `GitHub gave no OIDC token (HTTP ${status})` });
217
+ if (status !== 200) return yield* new IdentityBrokerClientFailed({ reason: `GitHub gave no OIDC token (HTTP ${status})` });
216
218
  return (yield* decode(OidcToken, "GitHub")(body)).value;
217
219
  });
218
220
  /**
219
221
  * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial
220
- * access token: the GitHub OIDC token, the app's own token, or a key of the hub. `software_id` is
221
- * the app's name, `client_name` the stage, and `connectors` and `deployment_type` are the hub's own
222
- * metadata fields. Convex Auth posts the client's secret in the body at the token endpoint, so the
223
- * client registers that method.
222
+ * access token: the GitHub OIDC token, the app's own token, or a key of the broker. `software_id` is
223
+ * the app's name, `client_name` the stage, and `connectors` and `deployment_type` are the broker's
224
+ * own metadata fields. Convex Auth posts the client's secret in the body at the token endpoint, so
225
+ * the client registers that method.
224
226
  */
225
227
  const requestNewClient = (props, enrollment, bearer) => Effect.gen(function* () {
226
- const { hub } = props;
228
+ const { broker } = props;
227
229
  const { app, connectors, redirectUris } = enrollment;
228
- const { body, status } = yield* send("The identity hub", `${hub.issuer}/register`, bearer, {
230
+ const { body, status } = yield* send("The identity broker", `${broker.issuer}/register`, bearer, {
229
231
  method: "POST",
230
232
  body: JSON.stringify({
231
233
  redirect_uris: redirectUris,
@@ -237,14 +239,14 @@ const requestNewClient = (props, enrollment, bearer) => Effect.gen(function* ()
237
239
  token_endpoint_auth_method: "client_secret_post"
238
240
  })
239
241
  });
240
- if (status !== 201) return yield* new IdentityHubClientFailed({ reason: `${status !== 401 ? refusalOf(status, body) : "key" in props ? "the identity hub refused the registration key" : props.deploymentType === "development" ? "the identity hub refused the initial access token" : refusalOf(status, body)} (HTTP ${status})` });
241
- const client = yield* decode(NewClient, "The identity hub")(body);
242
- if (client.issuer !== hub.issuer || !sameSet(sortedSet(client.redirect_uris), redirectUris) || !sameSet(client.connectors, connectors)) return yield* new IdentityHubClientFailed({ reason: "The identity hub gave a bad answer" });
243
- yield* Effect.logInfo(`IdentityHub.Client: ${where(enrollment)} has a new client of the identity hub ${hub.issuer}.`);
242
+ if (status !== 201) return yield* new IdentityBrokerClientFailed({ reason: `${status !== 401 ? refusalOf(status, body) : "key" in props ? "the identity broker refused the registration key" : props.deploymentType === "development" ? "the identity broker refused the initial access token" : refusalOf(status, body)} (HTTP ${status})` });
243
+ const client = yield* decode(NewClient, "The identity broker")(body);
244
+ if (client.issuer !== broker.issuer || !sameSet(sortedSet(client.redirect_uris), redirectUris) || !sameSet(client.connectors, connectors)) return yield* new IdentityBrokerClientFailed({ reason: "The identity broker gave a bad answer" });
245
+ yield* Effect.logInfo(`IdentityBroker.Client: ${where(enrollment)} has a new client of the identity broker ${broker.issuer}.`);
244
246
  const production = props.deploymentType === "production";
245
247
  return {
246
248
  status: "on",
247
- issuer: hub.issuer,
249
+ issuer: broker.issuer,
248
250
  clientId: client.client_id,
249
251
  clientSecret: Redacted.make(client.client_secret),
250
252
  registrationAccessToken: Redacted.make(client.registration_access_token),
@@ -259,42 +261,42 @@ const requestNewClient = (props, enrollment, bearer) => Effect.gen(function* ()
259
261
  });
260
262
  const Discovery = Schema.Struct({ issuer: Schema.String });
261
263
  /**
262
- * The time a hub has to answer discovery before a registration with a key: the stage that deploys
263
- * the hub registers its own client in the same run, and a new workers.dev route answers after
264
- * about a minute. Delays of 1, 2, 4, 8 and then 15 seconds, about three minutes in all.
264
+ * The time a broker has to answer discovery before a registration with a key: the stage that
265
+ * deploys the broker registers its own client in the same run, and a new workers.dev route answers
266
+ * after about a minute. Delays of 1, 2, 4, 8 and then 15 seconds, about three minutes in all.
265
267
  */
266
268
  const DISCOVERY_RETRY = {
267
269
  times: 15,
268
270
  schedule: Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("15 seconds")])
269
271
  };
270
272
  /**
271
- * Succeeds when the hub's discovery document names the hub's issuer, after bounded retries; fails
272
- * when it never does.
273
+ * Succeeds when the broker's discovery document names the broker's issuer, after bounded retries;
274
+ * fails when it never does.
273
275
  */
274
- const hubAnswers = (hub) => send("The identity hub", `${hub.issuer}/.well-known/openid-configuration`, void 0, { method: "GET" }).pipe(Effect.flatMap(({ body, status }) => status === 200 && Option.getOrUndefined(Schema.decodeUnknownOption(Discovery)(body))?.issuer === hub.issuer ? Effect.void : Effect.fail(new IdentityHubClientFailed({ reason: "the identity hub does not answer discovery" }))), Effect.retry(DISCOVERY_RETRY));
276
+ const brokerAnswers = (broker) => send("The identity broker", `${broker.issuer}/.well-known/openid-configuration`, void 0, { method: "GET" }).pipe(Effect.flatMap(({ body, status }) => status === 200 && Option.getOrUndefined(Schema.decodeUnknownOption(Discovery)(body))?.issuer === broker.issuer ? Effect.void : Effect.fail(new IdentityBrokerClientFailed({ reason: "the identity broker does not answer discovery" }))), Effect.retry(DISCOVERY_RETRY));
275
277
  /** A new client, or the off values. */
276
278
  const newClient = (props, enrollment) => {
277
- const label = `IdentityHub.Client: ${where(enrollment)} deploys without the hub`;
279
+ const label = `IdentityBroker.Client: ${where(enrollment)} deploys without the broker`;
278
280
  const off = offAttributes(props.deploymentType);
279
- const request = (bearer) => bearer.pipe(Effect.flatMap((token) => requestNewClient(props, enrollment, token)), Effect.catchTag("IdentityHubClientFailed", (error) => Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(Effect.as(off))));
280
- if ("key" in props) return props.key === void 0 ? Effect.logInfo(`${label}: it has no registration key yet. Deploy the stage that makes the key first.`).pipe(Effect.as(off)) : request(Effect.as(hubAnswers(props.hub), Redacted.value(props.key)));
281
+ const request = (bearer) => bearer.pipe(Effect.flatMap((token) => requestNewClient(props, enrollment, token)), Effect.catchTag("IdentityBrokerClientFailed", (error) => Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(Effect.as(off))));
282
+ if ("key" in props) return props.key === void 0 ? Effect.logInfo(`${label}: it has no registration key yet. Deploy the stage that makes the key first.`).pipe(Effect.as(off)) : request(Effect.as(brokerAnswers(props.broker), Redacted.value(props.key)));
281
283
  if (props.deploymentType === "development") {
282
284
  const token = Redacted.value(props.initialAccessToken);
283
- return token === "" ? Effect.logInfo("IdentityHub.Client: deploy to main once for hub sign-in in development.").pipe(Effect.as(off)) : request(Effect.succeed(token));
285
+ return token === "" ? Effect.logInfo("IdentityBroker.Client: deploy to main once for broker sign-in in development.").pipe(Effect.as(off)) : request(Effect.succeed(token));
284
286
  }
285
287
  const requestUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];
286
288
  const requestToken = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];
287
289
  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));
288
- return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));
290
+ return request(readOidcToken(requestUrl, requestToken, props.broker.issuer));
289
291
  };
290
292
  /**
291
- * The client after a read on the hub, or undefined when the hub says that the client is gone. A
292
- * read with no usable answer keeps the saved client, except for a required one: a required client
293
- * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,
294
- * and did not save because that run failed, cannot pass a run that the hub does not answer.
293
+ * The client after a read on the broker, or undefined when the broker says that the client is gone.
294
+ * A read with no usable answer keeps the saved client, except for a required one: a required client
295
+ * passes a run only when the broker confirms it in that run, so a suspension that an earlier run
296
+ * saw, and did not save because that run failed, cannot pass a run that the broker does not answer.
295
297
  */
296
298
  const renew = (saved, required) => Effect.gen(function* () {
297
- const { status } = yield* send("The identity hub", saved.registrationClientUri, Redacted.value(saved.registrationAccessToken), { method: "GET" });
299
+ const { status } = yield* send("The identity broker", saved.registrationClientUri, Redacted.value(saved.registrationAccessToken), { method: "GET" });
298
300
  switch (status) {
299
301
  case 200: return {
300
302
  ...saved,
@@ -302,36 +304,41 @@ const renew = (saved, required) => Effect.gen(function* () {
302
304
  };
303
305
  case 401: return;
304
306
  case 403:
305
- yield* Effect.logWarning(`IdentityHub.Client: the hub suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`);
307
+ yield* Effect.logWarning(`IdentityBroker.Client: the broker suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`);
306
308
  return {
307
309
  ...saved,
308
310
  status: "suspended"
309
311
  };
310
- default: return yield* new IdentityHubClientFailed({ reason: `The identity hub answered HTTP ${status}` });
312
+ default: return yield* new IdentityBrokerClientFailed({ reason: `The identity broker answered HTTP ${status}` });
311
313
  }
312
- }).pipe(Effect.catchTag("IdentityHubClientFailed", (error) => required ? Effect.fail(new IdentityHubClientFailed({ reason: `${where(saved)} is required, and the hub did not confirm its client: ${error.reason}` })) : Effect.logWarning(`IdentityHub.Client: ${where(saved)} keeps the saved client: ${error.reason}.`).pipe(Effect.as(saved))));
314
+ }).pipe(Effect.catchTag("IdentityBrokerClientFailed", (error) => required ? Effect.fail(new IdentityBrokerClientFailed({ reason: `${where(saved)} is required, and the broker did not confirm its client: ${error.reason}` })) : Effect.logWarning(`IdentityBroker.Client: ${where(saved)} keeps the saved client: ${error.reason}.`).pipe(Effect.as(saved))));
313
315
  /**
314
- * The type of this resource before 0.37.0. Alchemy finds this provider for a row of that type, and
315
- * the next write of the row gives it the new type, with the same client. Remove it, here and in
316
- * `SavedRow`, once no saved row has the old type.
316
+ * The types of this resource before 0.46.0. A deploy updates a row of such a type in place and
317
+ * gives it the new type, with the same client; a destroy or an orphan delete finds this provider
318
+ * for it by these aliases. Remove them, here and in `SavedRow`, once no saved row has an old type.
317
319
  */
318
- const OLD_TYPE = "IdentityHub.SharedClient";
320
+ const OLD_TYPE = "IdentityHub.Client";
321
+ const OLDER_TYPE = "IdentityHub.SharedClient";
319
322
  /** A saved row of this resource, whose `attr` `savedAttributes` reads. */
320
323
  const SavedRow = Schema.Struct({
321
- resourceType: Schema.Literals(["IdentityHub.Client", OLD_TYPE]),
324
+ resourceType: Schema.Literals([
325
+ "IdentityBroker.Client",
326
+ OLD_TYPE,
327
+ OLDER_TYPE
328
+ ]),
322
329
  attr: Schema.Unknown
323
330
  });
324
331
  /**
325
332
  * The attributes of the client `id` in another stage of this stack, such as
326
- * `read("HubClient", { stage: "prod" })` in a development stage, as Outputs: the
333
+ * `read("BrokerClient", { stage: "prod" })` in a development stage, as Outputs: the
327
334
  * `initialAccessToken` and the `repository` of the production client. Without that row, the off
328
335
  * attributes, with `deploymentType: "production"`.
329
336
  *
330
- * `IdentityHub.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the
331
- * row is missing, and a development stage before the first deploy to main has none. This read runs
332
- * when the plan resolves it, with the State service of the running stack and its `get`, so it never
333
- * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every
334
- * read.
337
+ * `IdentityBroker.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when
338
+ * the row is missing, and a development stage before the first deploy to main has none. This read
339
+ * runs when the plan resolves it, with the State service of the running stack and its `get`, so it
340
+ * never creates or upgrades a store. The store revives each secret as `Redacted`, as it does for
341
+ * every read.
335
342
  */
336
343
  const read = (id, options) => Output.fromEffect(Effect.gen(function* () {
337
344
  const stack = yield* Stack;
@@ -341,7 +348,7 @@ const read = (id, options) => Output.fromEffect(Effect.gen(function* () {
341
348
  fqn: id
342
349
  }).pipe(Effect.orDie);
343
350
  if (row === void 0) return offAttributes("production");
344
- const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason: `the row ${id} of stage ${options.stage} is not an IdentityHub.Client` }))));
351
+ const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(Effect.catchCause(() => Effect.die(new IdentityBrokerClientFailed({ reason: `the row ${id} of stage ${options.stage} is not an IdentityBroker.Client` }))));
345
352
  return yield* savedAttributes(attr, `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`);
346
353
  }));
347
354
  /** A saved row of an `Alchemy.Random`, whose `text` the store revives as `Redacted`. */
@@ -350,13 +357,13 @@ const SavedKey = Schema.Struct({
350
357
  attr: Schema.Struct({ text: Schema.Redacted(Schema.String) })
351
358
  });
352
359
  /**
353
- * A key of a hub on the stack layer, as a redacted Output, for the hub's secret binding and for
354
- * `IdentityHub.Client`'s `key`. `id` is the key's resource id, the author's name for it, so a stack
355
- * can make several. In `options.stage`, the stage that deploys the hub, the key is an
360
+ * A key of a broker on the stack layer, as a redacted Output, for the broker's secret binding and
361
+ * for `IdentityBroker.Client`'s `key`. `id` is the key's resource id, the author's name for it, so a
362
+ * stack can make several. In `options.stage`, the stage that deploys the broker, the key is an
356
363
  * `Alchemy.Random` at the stack's root, made once and kept in state; the stack's providers need
357
364
  * Random's provider (`Convex.providers()` and `Cloudflare.providers()` hold one). Every other stage
358
- * reads that row from the state store, as `IdentityHub.Client.read` does, so it never creates the
359
- * key; before the hub's stage ran, there is no row and no key (`undefined`).
365
+ * reads that row from the state store, as `IdentityBroker.Client.read` does, so it never creates the
366
+ * key; before the broker's stage ran, there is no row and no key (`undefined`).
360
367
  */
361
368
  const registrationKey = (id, options) => Effect.gen(function* () {
362
369
  const { stage } = yield* Stack;
@@ -369,14 +376,14 @@ const registrationKey = (id, options) => Effect.gen(function* () {
369
376
  fqn: id
370
377
  }).pipe(Effect.orDie);
371
378
  if (row === void 0) return void 0;
372
- return (yield* Schema.decodeUnknownEffect(SavedKey)(row).pipe(Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason: `the row ${id} of stage ${options.stage} is not an Alchemy.Random` }))))).attr.text;
379
+ return (yield* Schema.decodeUnknownEffect(SavedKey)(row).pipe(Effect.catchCause(() => Effect.die(new IdentityBrokerClientFailed({ reason: `the row ${id} of stage ${options.stage} is not an Alchemy.Random` }))))).attr.text;
373
380
  }));
374
381
  });
375
382
  /**
376
- * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,
377
- * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when
378
- * `status` is `on`, else the off values, so that a suspended client gives guest sign-in and keeps
379
- * its values in state.
383
+ * The three values that the app's deployment gets, such as `IDENTITY_BROKER_ISSUER`,
384
+ * `IDENTITY_BROKER_CLIENT_ID`, and `IDENTITY_BROKER_CLIENT_SECRET`, as Outputs: the client's values
385
+ * when `status` is `on`, else the off values, so that a suspended client gives guest sign-in and
386
+ * keeps its values in state.
380
387
  */
381
388
  const variables = (client) => Output.map(Output.of(client), (attributes) => attributes.status === "on" ? {
382
389
  issuer: attributes.issuer,
@@ -387,7 +394,7 @@ const variables = (client) => Output.map(Output.of(client), (attributes) => attr
387
394
  clientId: OFF_VALUES.clientId,
388
395
  clientSecret: Redacted.make(OFF_VALUES.clientSecret)
389
396
  });
390
- const Client = Resource("IdentityHub.Client", { aliases: [OLD_TYPE] })({
397
+ const Client = Resource("IdentityBroker.Client", { aliases: [OLD_TYPE, OLDER_TYPE] })({
391
398
  read,
392
399
  variables
393
400
  });
@@ -397,27 +404,27 @@ const ClientProvider = () => Provider.succeed(Client, {
397
404
  reconcile: Effect.fn(function* ({ news, output }) {
398
405
  const stack = yield* Stack;
399
406
  const app = news.app ?? defaultApp(stack.name);
400
- if (app === void 0) return yield* new IdentityHubClientFailed({ reason: `the stack ${stack.name} is not named owner/repo or owner/repo/<path>, so set app` });
401
- if (app.length > MAX_APP_LENGTH) return yield* new IdentityHubClientFailed({ reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the hub's limit, so set a shorter app` });
407
+ if (app === void 0) return yield* new IdentityBrokerClientFailed({ reason: `the stack ${stack.name} is not named owner/repo or owner/repo/<path>, so set app` });
408
+ if (app.length > MAX_APP_LENGTH) return yield* new IdentityBrokerClientFailed({ reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the broker's limit, so set a shorter app` });
402
409
  const enrollment = {
403
410
  app,
404
411
  clientName: stack.stage,
405
412
  connectors: sortedSet(news.connectors),
406
413
  redirectUris: sortedSet(news.redirectUris)
407
414
  };
408
- if (enrollment.connectors.length === 0 || !enrollment.connectors.every((name) => CONNECTOR_NAME.test(name))) return yield* new IdentityHubClientFailed({ reason: `${where(enrollment)} needs connectors: one or more names of [a-z0-9-]{1,64}` });
409
- if (enrollment.redirectUris.length === 0 || enrollment.redirectUris.length > MAX_REDIRECT_URIS || !enrollment.redirectUris.every((uri) => URL.canParse(uri))) return yield* new IdentityHubClientFailed({ reason: `${app} needs redirectUris: one to ${MAX_REDIRECT_URIS} absolute URLs` });
415
+ if (enrollment.connectors.length === 0 || !enrollment.connectors.every((name) => CONNECTOR_NAME.test(name))) return yield* new IdentityBrokerClientFailed({ reason: `${where(enrollment)} needs connectors: one or more names of [a-z0-9-]{1,64}` });
416
+ if (enrollment.redirectUris.length === 0 || enrollment.redirectUris.length > MAX_REDIRECT_URIS || !enrollment.redirectUris.every((uri) => URL.canParse(uri))) return yield* new IdentityBrokerClientFailed({ reason: `${app} needs redirectUris: one to ${MAX_REDIRECT_URIS} absolute URLs` });
410
417
  const saved = output === void 0 || output.status === "off" ? void 0 : yield* savedAttributes(output, `the saved attributes of ${where(enrollment)} cannot be read by this version`);
411
- const client = (saved?.issuer === news.hub.issuer && saved.app === app && sameSet(saved.redirectUris, enrollment.redirectUris) && saved.deploymentType === news.deploymentType && sameSet(saved.connectors, enrollment.connectors) ? yield* renew(saved, news.required === true) : void 0) ?? (yield* newClient(news, enrollment));
412
- if (news.required === true && client.status !== "on") return yield* new IdentityHubClientFailed({ reason: `${where(enrollment)} is required and has no working client (${client.status}). The warning above names the reason` });
418
+ const client = (saved?.issuer === news.broker.issuer && saved.app === app && sameSet(saved.redirectUris, enrollment.redirectUris) && saved.deploymentType === news.deploymentType && sameSet(saved.connectors, enrollment.connectors) ? yield* renew(saved, news.required === true) : void 0) ?? (yield* newClient(news, enrollment));
419
+ if (news.required === true && client.status !== "on") return yield* new IdentityBrokerClientFailed({ reason: `${where(enrollment)} is required and has no working client (${client.status}). The warning above names the reason` });
413
420
  return client;
414
421
  }),
415
422
  delete: ({ output }) => output.deploymentType === "production" || output.status === "off" ? Effect.void : Effect.gen(function* () {
416
- const { status } = yield* send("The identity hub", output.registrationClientUri, Redacted.value(output.registrationAccessToken), { method: "DELETE" });
417
- if (status !== 204 && status !== 401) return yield* new IdentityHubClientFailed({ reason: `The identity hub answered HTTP ${status}` });
418
- }).pipe(Effect.catchTag("IdentityHubClientFailed", (error) => Effect.logWarning(`IdentityHub.Client: the client ${output.clientId} stays on the hub until its removal date: ${error.reason}.`)))
423
+ const { status } = yield* send("The identity broker", output.registrationClientUri, Redacted.value(output.registrationAccessToken), { method: "DELETE" });
424
+ if (status !== 204 && status !== 401) return yield* new IdentityBrokerClientFailed({ reason: `The identity broker answered HTTP ${status}` });
425
+ }).pipe(Effect.catchTag("IdentityBrokerClientFailed", (error) => Effect.logWarning(`IdentityBroker.Client: the client ${output.clientId} stays on the broker until its removal date: ${error.reason}.`)))
419
426
  });
420
427
  //#endregion
421
- export { registrationKey as i, ClientProvider as n, defaultApp as r, Client as t };
428
+ export { registrationKey as a, defaultApp as i, ClientProvider as n, DISABLED as r, Client as t };
422
429
 
423
- //# sourceMappingURL=IdentityHub-CDG7GXm6.js.map
430
+ //# sourceMappingURL=IdentityBroker-BqA_2V3_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IdentityBroker-BqA_2V3_.js","names":[],"sources":["../src/IdentityBroker.ts"],"sourcesContent":["// IdentityBroker.Client: one deployment of an app as a client of the identity broker 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 IdentityBroker from \"@samebase/alchemy-convex/identity-broker\"`; `Convex.providers()`\n// registers its provider.\n//\n// A run in GitHub Actions asks the broker for a new client with a GitHub OIDC token, so the stack\n// needs no key and no Samebase account. The token names the repository. The broker 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 broker with\n// that token (RFC 7592). The broker keeps only hashes, so the state is the only record of the secret\n// and the 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 `IdentityBroker.Client.read`, and a\n// client with `deploymentType: \"development\"` asks the broker with the token in place of the GitHub\n// token (RFC 133).\n//\n// A broker on the stack layer, which the app's own stack deploys, takes a key in place of a proof:\n// a client with `key` asks with it, from any run, and the broker reads no verification file.\n// `IdentityBroker.registrationKey` makes each key in the stage that deploys the broker and reads it\n// in every other stage. That stage's client waits until the broker answers discovery, so one run\n// deploys the broker and registers its client.\n//\n// A client is enrolled in the connectors it signs in through, such as `google` and `github`, at\n// registration (RFC 137), and holds the return addresses its requests may name, one per handler of\n// the app, such as the sign-in callback and the connections callback. The broker records both sets\n// on the client and never changes them: a stack with another set registers a new client.\n//\n// The app is the stack: its name on the broker defaults to the stack's path in the repository, as\n// the state store groups stacks (`owner/repo/<path>`), and `app` for a stack named after the\n// repository. `app` overrides it. The name groups the clients, their budgets, and the initial access\n// token; it plays no part in user ids, which the broker derives from the provider's own id.\n//\n// A push removes a variable that a deploy stops passing, so a failure here must not drop working\n// variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that\n// cannot work asks for a new one: it is gone, or it has another app name, return address set, type,\n// or connector set. If that request fails, the run gives the off values, so the app has guest\n// sign-in and not a broken button. The off values are the `DISABLED` variables of a checkout\n// without a broker: Convex needs the variables, and the app hides the button for this client ID.\n//\n// No text in this file quotes an answer or a fetch error, so no log line can hold a secret. The one\n// exception is the connector names of an `invalid_connectors` refusal, each checked against the\n// grammar of a connector name before it is printed.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Output from \"alchemy/Output\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Random } from \"alchemy/Random\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Schema from \"effect/Schema\";\nimport type { Providers } from \"./Providers.ts\";\n\n/** A hung service must not hold a deploy: the time limit of one request. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** The client ID and the client secret of a deployment without a broker client. */\nexport const DISABLED = \"broker-disabled\";\n\n/** The variables of a deployment without a broker client. */\nconst OFF_VALUES = { issuer: \"http://127.0.0.1:1\", clientId: DISABLED, clientSecret: DISABLED };\n\n/** The name of a connector on the broker. */\nconst CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;\n\n/** The return addresses of one client, as the broker caps them. */\nconst MAX_REDIRECT_URIS = 8;\n/** The app's name, as the broker caps it. A deeper stack path needs an explicit `app`. */\nconst MAX_APP_LENGTH = 64;\n\n/**\n * The app's default name: the stack's path below `owner/repo`, or `app` for a stack named after\n * the repository. Undefined for a stack whose name is not `owner/repo` or `owner/repo/<path>`.\n */\nexport const defaultApp = (stackName: string): string | undefined => {\n const segments = stackName.split(\"/\");\n if (segments.length < 2 || segments.some((segment) => segment === \"\")) {\n return undefined;\n }\n return segments.slice(2).join(\"/\") || \"app\";\n};\n\n/**\n * An identity broker of @samebase/identity-broker, such as Samebase's public broker:\n * `{ issuer: \"https://id.samebase.com\" }`.\n */\nexport interface BrokerEndpoint {\n /**\n * The broker's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/register`,\n * with a GitHub token whose audience is the issuer, so no other broker can use that token.\n */\n readonly issuer: string;\n}\n\ninterface CommonProps {\n /**\n * The app's name in its repository. Default: the stack's path in the repository, `apps/samebase`\n * for the stack `samebase/samebase/apps/samebase`, and `app` for a stack named after the\n * repository. A changed name registers a new client under the new name.\n */\n readonly app?: string;\n /** The broker to register at. A changed broker registers a new client there; the old one stays. */\n readonly broker: BrokerEndpoint;\n /**\n * The connectors the client signs in through, by their names on the broker, such as\n * `[\"google\", \"github\"]`: at least one, each of `[a-z0-9-]{1,64}`. The broker refuses a name it\n * does not offer, or does not allow this repository, and the log then names the allowed ones. The\n * set is recorded on the client for good: a changed set registers a new client.\n */\n readonly connectors: readonly string[];\n /**\n * The return addresses of this deployment, one to eight, such as\n * `[`${site.siteUrl}/auth/broker/callback`]`: each an https URL whose origin serves\n * `/samebase-verification.json` with the numeric GitHub id of this repository,\n * `{ \"repository\": \"123\" }`. They can come from a resource that this run creates. A development\n * client can also have http on a loopback host, which needs no file. Every request of the client\n * names one of them. The set is recorded on the client for good: a changed set registers a new\n * client.\n */\n readonly redirectUris: string[];\n /** Recorded on the broker's client, such as the commit. The broker records \"unknown\" without it. */\n readonly softwareVersion?: string;\n /**\n * The run fails unless the broker confirms the client in this run: it fails when the broker\n * refuses or does not answer a registration or a renewal, and when it suspended the client.\n * Without it, such a run gives the off values or keeps the saved client, so the app deploys\n * anyway. Set it where sign-in is the product. A failed run saves nothing, so the next run asks\n * the broker 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 `IdentityBroker.Client.read` gives from stage\n * `prod`. A client of any type with `key` asks with that key, a key of a broker on the stack layer,\n * such as `IdentityBroker.registrationKey` gives.\n */\nexport type ClientProps =\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\";\n readonly initialAccessToken?: never;\n readonly key?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"development\";\n /** Empty before the first production registration: the client gets the off values. */\n readonly initialAccessToken: Redacted.Redacted<string>;\n readonly key?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\" | \"development\";\n /**\n * The Bearer of `POST /register`. Undefined, as before the stage that makes the key ever\n * ran: the client gets the off values, or the run fails when `required`. The broker decides\n * whether this key may register a production client.\n */\n readonly key: Redacted.Redacted<string> | undefined;\n readonly initialAccessToken?: never;\n });\n\nconst DeploymentType = Schema.Literals([\"production\", \"preview\", \"development\"]);\n\nconst Attributes = Schema.Struct({\n /** `off`: no client, and the values below are the off values. */\n status: Schema.Literals([\"on\", \"off\", \"suspended\"]),\n /** The issuer of the broker, 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 broker, and nothing else. */\n registrationAccessToken: Schema.Redacted(Schema.String),\n registrationClientUri: Schema.String,\n deploymentType: DeploymentType,\n /** The app's name on the broker, as sent. Empty for the off values. */\n app: Schema.String,\n /** The return addresses the client serves, sorted, each once. Empty for the off values. */\n redirectUris: Schema.Array(Schema.String),\n /** The connectors the client is enrolled in, sorted, each once. Empty for the off values. */\n connectors: Schema.Array(Schema.String),\n /**\n * Returned only at a production registration (RFC 7591 section 1.2). It registers development\n * clients of this app. Empty for a preview, for a development client, and for the off values.\n */\n initialAccessToken: Schema.Redacted(Schema.String),\n /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */\n repository: Schema.String,\n});\n\n/**\n * The attributes keep the real values of a suspended client, so that an unblock needs no new client.\n * `IdentityBroker.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 IdentityBrokerClientFailed({ reason }))),\n );\n\n/** The attributes of no client. */\nconst offAttributes = (deploymentType: ClientAttributes[\"deploymentType\"]): ClientAttributes => ({\n status: \"off\",\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n registrationAccessToken: Redacted.make(\"\"),\n registrationClientUri: \"\",\n deploymentType,\n app: \"\",\n redirectUris: [],\n connectors: [],\n initialAccessToken: Redacted.make(\"\"),\n repository: \"\",\n});\n\n/** The set of `values`: sorted, each once. */\nconst sortedSet = (values: readonly string[]) => [...new Set(values)].sort();\n\nconst sameSet = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && a.every((name, index) => name === b[index]);\n\n/** The app and its return addresses, as every log line names a client: no secret, no answer. */\nconst where = (client: { app: string; redirectUris: readonly string[] }) =>\n `${client.app} on ${client.redirectUris.join(\", \")}`;\n\n/**\n * What one registration sends, resolved from the props: the app's name, the deployment's name (the\n * stage), and both sets.\n */\ninterface Enrollment {\n readonly app: string;\n readonly clientName: string;\n readonly connectors: readonly string[];\n readonly redirectUris: readonly string[];\n}\n\n/** One request gave no usable answer. The reason holds no secret. */\nclass IdentityBrokerClientFailed extends Schema.TaggedError<IdentityBrokerClientFailed>()(\n \"IdentityBrokerClientFailed\",\n { reason: Schema.String },\n) {\n override get message() {\n return `IdentityBroker.Client: ${this.reason}.`;\n }\n}\n\nconst OidcToken = Schema.Struct({ value: Schema.NonEmptyString });\n\n/**\n * The 201 answer of `POST /register` (RFC 7591 section 3.2.1), in the members that this file reads.\n * The decoder ignores the other members, such as `software_id`, whose full form the broker writes.\n */\nconst NewClient = Schema.Struct({\n issuer: Schema.NonEmptyString,\n client_id: Schema.NonEmptyString,\n client_secret: Schema.NonEmptyString,\n registration_access_token: Schema.NonEmptyString,\n registration_client_uri: Schema.NonEmptyString,\n /** The sets the broker recorded, which must be the sets the request sent. */\n redirect_uris: Schema.Array(Schema.String),\n connectors: Schema.Array(Schema.String),\n /** Only in the answer to a production registration with the GitHub token. */\n initial_access_token: Schema.optionalKey(Schema.NonEmptyString),\n repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\\d+$/))),\n});\n\n/** The other answers of `POST /register`, by status. A 401 can have no body (RFC 6750). */\nconst REFUSALS: Readonly<Record<number, string>> = {\n 400: \"the identity broker refused the client metadata, such as the app name\",\n 401: \"the identity broker refused the GitHub OIDC token\",\n 403: \"the identity broker does not allow this repository\",\n 404: \"the identity broker has no /register: it runs an identity-broker before 0.33.0\",\n 429: \"the identity broker limits new clients\",\n 502: \"GitHub's keys are not available to the identity broker\",\n 503: \"the identity broker could not apply its policy\",\n};\n\n/** The text of an `invalid_redirect_uri` 400 without a known reason. */\nconst BAD_REDIRECT_URIS =\n \"the identity broker refused the return addresses: one to eight, each https on a DNS name, or http on a loopback host for a development client\";\n\n/**\n * The reasons of a 400 or a 403 that a log line shows. Any other text of the answer is never\n * logged.\n */\nconst REASONS = new Map([\n [\"paused\", \"this app is paused on the identity broker\"],\n [\n \"run_not_allowed\",\n \"the identity broker gives clients only to runs of main and of pull requests\",\n ],\n [\"blocked\", \"Samebase blocked this repository or its owner\"],\n [\"suspended\", \"the identity broker suspended this repository\"],\n [\"too_many_apps\", \"the repository has as many apps on the identity broker as it may\"],\n [\"too_many_clients\", \"the app has as many clients on the identity broker as it may\"],\n [\"app_taken\", \"the app's name belongs to another app on the identity broker\"],\n [\"host_unreachable\", \"the identity broker 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 broker\"],\n [\"stale_proof\", \"the identity broker took a newer GitHub OIDC token of this repository\"],\n]);\n\n/** The windows of a 429, by the name that the answer gives. */\nconst RATE_LIMITED = new Map([\n [\"repository\", \"the identity broker gives one repository at most 30 new clients an hour\"],\n [\"owner\", \"the identity broker gives one owner at most 100 new clients an hour\"],\n [\"new_owners\", \"the identity broker takes at most 50 new owners an hour\"],\n]);\n\nconst Refusal = Schema.Struct({ reason: Schema.String });\nconst InvalidRedirectUri = Schema.Struct({ error: Schema.Literal(\"invalid_redirect_uri\") });\nconst RateLimited = Schema.Struct({ window: Schema.String });\n/** A 400 for a connector the broker does not offer or allow, with the names it allows. */\nconst InvalidConnectors = Schema.Struct({\n reason: Schema.Literal(\"invalid_connectors\"),\n allowed: Schema.Array(Schema.String),\n});\n\n/**\n * The text of a refusal: a known reason of a 400 or a 403, or window of a 429, the allowed\n * connectors of an `invalid_connectors` 400 (only names of the connector grammar, so no other text\n * of the answer is printed), the text of an `invalid_redirect_uri` 400, else the text of its\n * status. `body` is undefined for an answer without JSON, such as a bare 401.\n */\nconst refusalOf = (status: number, body: unknown): string => {\n const decoded = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>\n Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));\n const ofStatus = () => REFUSALS[status] ?? \"the identity broker refused the request\";\n switch (status) {\n case 400: {\n const allowed = decoded(InvalidConnectors)?.allowed.filter((name) =>\n CONNECTOR_NAME.test(name),\n );\n return allowed === undefined\n ? (REASONS.get(decoded(Refusal)?.reason ?? \"\") ??\n (decoded(InvalidRedirectUri) === undefined ? ofStatus() : BAD_REDIRECT_URIS))\n : `the identity broker does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? \"none for this app\" : allowed.join(\", \")}`;\n }\n case 403:\n return REASONS.get(decoded(Refusal)?.reason ?? \"\") ?? ofStatus();\n case 429:\n return RATE_LIMITED.get(decoded(RateLimited)?.window ?? \"\") ?? ofStatus();\n default:\n return ofStatus();\n }\n};\n\n/**\n * One request to `who` at `url`, with `token` as its Bearer. A token goes only to an https URL:\n * to any other URL the request is not made.\n */\nconst send = (\n who: string,\n url: string,\n token: string | undefined,\n init: { method: string; body?: string },\n) =>\n token !== undefined && !(URL.canParse(url) && new URL(url).protocol === \"https:\")\n ? Effect.fail(\n new IdentityBrokerClientFailed({\n reason: `${who} is not at an https URL, so no credential was sent to it`,\n }),\n )\n : Effect.tryPromise({\n try: async () => {\n const response = await fetch(url, {\n ...init,\n headers: {\n ...(token === undefined ? {} : { Authorization: `Bearer ${token}` }),\n \"Content-Type\": \"application/json\",\n },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n const body: unknown = await response.json().catch(() => undefined);\n return { status: response.status, body };\n },\n catch: () => new IdentityBrokerClientFailed({ 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 IdentityBrokerClientFailed({ 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 IdentityBrokerClientFailed({\n reason: `GitHub gave no OIDC token (HTTP ${status})`,\n });\n }\n return (yield* decode(OidcToken, \"GitHub\")(body)).value;\n });\n\n/**\n * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial\n * access token: the GitHub OIDC token, the app's own token, or a key of the broker. `software_id` is\n * the app's name, `client_name` the stage, and `connectors` and `deployment_type` are the broker's\n * own metadata fields. Convex Auth posts the client's secret in the body at the token endpoint, so\n * the client registers that method.\n */\nconst requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: string) =>\n Effect.gen(function* () {\n const { broker } = props;\n const { app, connectors, redirectUris } = enrollment;\n const { body, status } = yield* send(\n \"The identity broker\",\n `${broker.issuer}/register`,\n bearer,\n {\n method: \"POST\",\n body: JSON.stringify({\n redirect_uris: redirectUris,\n software_id: app,\n software_version: props.softwareVersion ?? \"unknown\",\n client_name: enrollment.clientName,\n deployment_type: props.deploymentType,\n connectors,\n token_endpoint_auth_method: \"client_secret_post\",\n }),\n },\n );\n if (status !== 201) {\n const reason =\n status !== 401\n ? refusalOf(status, body)\n : \"key\" in props\n ? \"the identity broker refused the registration key\"\n : props.deploymentType === \"development\"\n ? \"the identity broker refused the initial access token\"\n : refusalOf(status, body);\n return yield* new IdentityBrokerClientFailed({ reason: `${reason} (HTTP ${status})` });\n }\n const client = yield* decode(NewClient, \"The identity broker\")(body);\n // The broker registers the addresses and the connectors that the request sent, under its own\n // issuer. The log and the state hold the stack's values, so no value that the answer chose is\n // printed or kept.\n if (\n client.issuer !== broker.issuer ||\n !sameSet(sortedSet(client.redirect_uris), redirectUris) ||\n !sameSet(client.connectors, connectors)\n ) {\n return yield* new IdentityBrokerClientFailed({\n reason: \"The identity broker gave a bad answer\",\n });\n }\n yield* Effect.logInfo(\n `IdentityBroker.Client: ${where(enrollment)} has a new client of the identity broker ${broker.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: broker.issuer,\n clientId: client.client_id,\n clientSecret: Redacted.make(client.client_secret),\n registrationAccessToken: Redacted.make(client.registration_access_token),\n registrationClientUri: client.registration_client_uri,\n deploymentType: props.deploymentType,\n app,\n redirectUris,\n connectors,\n initialAccessToken: Redacted.make(production ? (client.initial_access_token ?? \"\") : \"\"),\n repository: production ? (client.repository ?? \"\") : \"\",\n };\n });\n\nconst Discovery = Schema.Struct({ issuer: Schema.String });\n\n/**\n * The time a broker has to answer discovery before a registration with a key: the stage that\n * deploys the broker registers its own client in the same run, and a new workers.dev route answers\n * after about a minute. Delays of 1, 2, 4, 8 and then 15 seconds, about three minutes in all.\n */\nconst DISCOVERY_RETRY = {\n times: 15,\n schedule: Schedule.min([Schedule.exponential(\"1 second\"), Schedule.spaced(\"15 seconds\")]),\n};\n\n/**\n * Succeeds when the broker's discovery document names the broker's issuer, after bounded retries;\n * fails when it never does.\n */\nconst brokerAnswers = (broker: BrokerEndpoint) =>\n send(\"The identity broker\", `${broker.issuer}/.well-known/openid-configuration`, undefined, {\n method: \"GET\",\n }).pipe(\n Effect.flatMap(({ body, status }) =>\n status === 200 &&\n Option.getOrUndefined(Schema.decodeUnknownOption(Discovery)(body))?.issuer === broker.issuer\n ? Effect.void\n : Effect.fail(\n new IdentityBrokerClientFailed({\n reason: \"the identity broker does not answer discovery\",\n }),\n ),\n ),\n Effect.retry(DISCOVERY_RETRY),\n );\n\n/** A new client, or the off values. */\nconst newClient = (props: ClientProps, enrollment: Enrollment) => {\n const label = `IdentityBroker.Client: ${where(enrollment)} deploys without the broker`;\n const off = offAttributes(props.deploymentType);\n const request = (bearer: Effect.Effect<string, IdentityBrokerClientFailed>) =>\n bearer.pipe(\n Effect.flatMap((token) => requestNewClient(props, enrollment, token)),\n Effect.catchTag(\"IdentityBrokerClientFailed\", (error) =>\n Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(\n Effect.as(off),\n ),\n ),\n );\n\n if (\"key\" in props) {\n return props.key === undefined\n ? Effect.logInfo(\n `${label}: it has no registration key yet. Deploy the stage that makes the key first.`,\n ).pipe(Effect.as(off))\n : request(Effect.as(brokerAnswers(props.broker), Redacted.value(props.key)));\n }\n\n if (props.deploymentType === \"development\") {\n const token = Redacted.value(props.initialAccessToken);\n return token === \"\"\n ? Effect.logInfo(\n \"IdentityBroker.Client: deploy to main once for broker 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.broker.issuer));\n};\n\n/**\n * The client after a read on the broker, or undefined when the broker says that the client is gone.\n * A read with no usable answer keeps the saved client, except for a required one: a required client\n * passes a run only when the broker confirms it in that run, so a suspension that an earlier run\n * saw, and did not save because that run failed, cannot pass a run that the broker does not answer.\n */\nconst renew = (saved: ClientAttributes, required: boolean) =>\n Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity broker\",\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 `IdentityBroker.Client: the broker suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`,\n );\n return { ...saved, status: \"suspended\" as const };\n default:\n return yield* new IdentityBrokerClientFailed({\n reason: `The identity broker answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"IdentityBrokerClientFailed\", (error) =>\n required\n ? Effect.fail(\n new IdentityBrokerClientFailed({\n reason: `${where(saved)} is required, and the broker did not confirm its client: ${error.reason}`,\n }),\n )\n : Effect.logWarning(\n `IdentityBroker.Client: ${where(saved)} keeps the saved client: ${error.reason}.`,\n ).pipe(Effect.as(saved)),\n ),\n );\n\n/**\n * The types of this resource before 0.46.0. A deploy updates a row of such a type in place and\n * gives it the new type, with the same client; a destroy or an orphan delete finds this provider\n * for it by these aliases. Remove them, here and in `SavedRow`, once no saved row has an old type.\n */\nconst OLD_TYPE = \"IdentityHub.Client\";\nconst OLDER_TYPE = \"IdentityHub.SharedClient\";\n\n/** A saved row of this resource, whose `attr` `savedAttributes` reads. */\nconst SavedRow = Schema.Struct({\n resourceType: Schema.Literals([\"IdentityBroker.Client\", OLD_TYPE, OLDER_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(\"BrokerClient\", { 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 * `IdentityBroker.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when\n * the row is missing, and a development stage before the first deploy to main has none. This read\n * runs when the plan resolves it, with the State service of the running stack and its `get`, so it\n * never creates or upgrades a store. The store revives each secret as `Redacted`, as it does for\n * every 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 IdentityBrokerClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not an IdentityBroker.Client`,\n }),\n ),\n ),\n );\n return yield* savedAttributes(\n attr,\n `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`,\n );\n }),\n );\n\n/** A saved row of an `Alchemy.Random`, whose `text` the store revives as `Redacted`. */\nconst SavedKey = Schema.Struct({\n resourceType: Schema.Literal(\"Alchemy.Random\"),\n attr: Schema.Struct({ text: Schema.Redacted(Schema.String) }),\n});\n\n/**\n * A key of a broker on the stack layer, as a redacted Output, for the broker's secret binding and\n * for `IdentityBroker.Client`'s `key`. `id` is the key's resource id, the author's name for it, so a\n * stack can make several. In `options.stage`, the stage that deploys the broker, the key is an\n * `Alchemy.Random` at the stack's root, made once and kept in state; the stack's providers need\n * Random's provider (`Convex.providers()` and `Cloudflare.providers()` hold one). Every other stage\n * reads that row from the state store, as `IdentityBroker.Client.read` does, so it never creates the\n * key; before the broker's stage ran, there is no row and no key (`undefined`).\n */\nexport const registrationKey = (id: string, options: { readonly stage: string }) =>\n Effect.gen(function* () {\n const { stage } = yield* Stack;\n if (stage === options.stage) {\n const key: Output.Output<Redacted.Redacted<string> | undefined> = (yield* Random(id)).text;\n return key;\n }\n return Output.fromEffect(\n Effect.gen(function* () {\n const stack = yield* Stack;\n const state = yield* yield* State;\n const row = yield* state\n .get({ stack: stack.name, stage: options.stage, fqn: id })\n .pipe(Effect.orDie);\n if (row === undefined) return undefined;\n const saved = yield* Schema.decodeUnknownEffect(SavedKey)(row).pipe(\n Effect.catchCause(() =>\n Effect.die(\n new IdentityBrokerClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not an Alchemy.Random`,\n }),\n ),\n ),\n );\n return saved.attr.text;\n }),\n );\n });\n\n/**\n * The three values that the app's deployment gets, such as `IDENTITY_BROKER_ISSUER`,\n * `IDENTITY_BROKER_CLIENT_ID`, and `IDENTITY_BROKER_CLIENT_SECRET`, as Outputs: the client's values\n * when `status` is `on`, else the off values, so that a suspended client gives guest sign-in and\n * keeps 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 \"IdentityBroker.Client\",\n ClientProps,\n ClientAttributes,\n never,\n Providers\n>;\nexport const Client = Resource<Client>(\"IdentityBroker.Client\", {\n aliases: [OLD_TYPE, OLDER_TYPE],\n})({\n read,\n variables,\n});\n\nexport const ClientProvider = () =>\n Provider.succeed(Client, {\n // Always an update, so that each deploy reaches the broker. 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 broker (its issuer), app name, return address set, type, and\n // connector set is renewed. A saved row without this version's shape stops the run with a\n // fixed message.\n reconcile: Effect.fn(function* ({ news, output }) {\n // A bad prop is a mistake of the stack, not of the broker: the run fails, with no request.\n const stack = yield* Stack;\n const app = news.app ?? defaultApp(stack.name);\n if (app === undefined) {\n return yield* new IdentityBrokerClientFailed({\n reason: `the stack ${stack.name} is not named owner/repo or owner/repo/<path>, so set app`,\n });\n }\n if (app.length > MAX_APP_LENGTH) {\n return yield* new IdentityBrokerClientFailed({\n reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the broker's limit, so set a shorter app`,\n });\n }\n const enrollment: Enrollment = {\n app,\n clientName: stack.stage,\n connectors: sortedSet(news.connectors),\n redirectUris: sortedSet(news.redirectUris),\n };\n if (\n enrollment.connectors.length === 0 ||\n !enrollment.connectors.every((name) => CONNECTOR_NAME.test(name))\n ) {\n return yield* new IdentityBrokerClientFailed({\n reason: `${where(enrollment)} needs connectors: one or more names of [a-z0-9-]{1,64}`,\n });\n }\n if (\n enrollment.redirectUris.length === 0 ||\n enrollment.redirectUris.length > MAX_REDIRECT_URIS ||\n !enrollment.redirectUris.every((uri) => URL.canParse(uri))\n ) {\n return yield* new IdentityBrokerClientFailed({\n reason: `${app} needs redirectUris: one to ${MAX_REDIRECT_URIS} absolute URLs`,\n });\n }\n const saved =\n output === undefined || output.status === \"off\"\n ? undefined\n : yield* savedAttributes(\n output,\n `the saved attributes of ${where(enrollment)} cannot be read by this version`,\n );\n const renewed =\n saved?.issuer === news.broker.issuer &&\n saved.app === app &&\n sameSet(saved.redirectUris, enrollment.redirectUris) &&\n saved.deploymentType === news.deploymentType &&\n sameSet(saved.connectors, enrollment.connectors)\n ? yield* renew(saved, news.required === true)\n : undefined;\n const client = renewed ?? (yield* newClient(news, enrollment));\n if (news.required === true && client.status !== \"on\") {\n return yield* new IdentityBrokerClientFailed({\n reason: `${where(enrollment)} is required and has no working client (${client.status}). The warning above names the reason`,\n });\n }\n return client;\n }),\n\n // A failed delete does not stop a destroy: the removal date of a preview or development client\n // cleans it up. A destroy can leave a production deployment running, so its client stays.\n delete: ({ output }) =>\n output.deploymentType === \"production\" || output.status === \"off\"\n ? Effect.void\n : Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity broker\",\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 IdentityBrokerClientFailed({\n reason: `The identity broker answered HTTP ${status}`,\n });\n }\n }).pipe(\n // The row can be of an earlier version's shape, so the line names only the client id.\n Effect.catchTag(\"IdentityBrokerClientFailed\", (error) =>\n Effect.logWarning(\n `IdentityBroker.Client: the client ${output.clientId} stays on the broker until its removal date: ${error.reason}.`,\n ),\n ),\n ),\n });\n"],"mappings":";;;;;;;;;;;;;;AA6DA,MAAM,qBAAqB;;AAG3B,MAAa,WAAW;;AAGxB,MAAM,aAAa;CAAE,QAAQ;CAAsB,UAAU;CAAU,cAAc;AAAS;;AAG9F,MAAM,iBAAiB;;AAGvB,MAAM,oBAAoB;;AAE1B,MAAM,iBAAiB;;;;;AAMvB,MAAa,cAAc,cAA0C;CACnE,MAAM,WAAW,UAAU,MAAM,GAAG;CACpC,IAAI,SAAS,SAAS,KAAK,SAAS,MAAM,YAA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