@samebase/alchemy-convex 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/HubClient.ts DELETED
@@ -1,310 +0,0 @@
1
- // Convex.HubClient: one deployment of an app as a client of the identity hub
2
- // of its team.
3
- //
4
- // The hub is the production deployment of the project `identity-hub` of the team.
5
- // It has the internal functions of `@samebase/identity-broker` in its module
6
- // `identityBroker`. This resource finds the project by name and runs those
7
- // functions with a short-lived key, so a stack that has the Convex credential
8
- // of the team needs no other credential and no hub address. The hub answers
9
- // with its issuer and the client.
10
- //
11
- // The hub keeps only the hash of the secret, so the state is the only record
12
- // of it. A client belongs to one redirect URI: another URI is a new client. A
13
- // change of `app` updates the stored props and does not move the client: the
14
- // app is the identity of the users of the app, and it does not change. The
15
- // team does not change either: the state of a stack is in its team.
16
- //
17
- // Each deploy renews the client on the hub, so a preview or development client
18
- // is deleted 14 days after its last deploy or use. A client that the hub no
19
- // longer has gets a new one in the same run. A production client never
20
- // expires, and a destroy leaves it: the production deployment can stay.
21
- import { Resource } from "alchemy";
22
- import { isResolved } from "alchemy/Diff";
23
- import * as Provider from "alchemy/Provider";
24
- import * as Effect from "effect/Effect";
25
- import * as Redacted from "effect/Redacted";
26
- import * as Schema from "effect/Schema";
27
- import { ManagementApi, type ManagementApiService } from "./ManagementApi.ts";
28
- import { findProjectByName, prodDeploymentOf } from "./Project.ts";
29
- import type { Providers } from "./Providers.ts";
30
- import { withPushKey } from "./Push.ts";
31
- import { type FunctionApi, makeFunctionApi, RUN_KEY_ACTIONS } from "./State.ts";
32
-
33
- /** The name of the project of the hub in each team. */
34
- export const HUB_PROJECT_NAME = "identity-hub";
35
-
36
- export type HubDeploymentType = "production" | "development" | "preview";
37
-
38
- export interface HubClientProps {
39
- /** The Convex team, a slug or an id, whose project `identity-hub` holds the hub. */
40
- readonly team: string | number;
41
- /** The app on the hub, such as `scout`. The first client of an app creates it, as a first-party app. */
42
- readonly app: string;
43
- /** The deployment's callback URL, such as `<deployment site URL>/auth/hub/callback`. */
44
- readonly redirectUri: string;
45
- readonly deploymentType: HubDeploymentType;
46
- /** The name the hub records for the client. */
47
- readonly clientName: string;
48
- /** Recorded on the hub's client, such as the commit. The hub records "unknown" without it. */
49
- readonly softwareVersion?: string;
50
- }
51
-
52
- export interface HubClientAttributes {
53
- /** The issuer of the hub, which the deployment names to sign in. */
54
- readonly issuer: string;
55
- readonly redirectUri: string;
56
- readonly deploymentType: HubDeploymentType;
57
- /** The name the client was registered with. */
58
- readonly clientName: string;
59
- readonly clientId: string;
60
- /** Returned by the hub only at registration. */
61
- readonly clientSecret: Redacted.Redacted<string>;
62
- }
63
-
64
- export type HubClient = Resource<
65
- "IdentityHub.Client",
66
- HubClientProps,
67
- HubClientAttributes,
68
- never,
69
- Providers
70
- >;
71
- export const HubClient = Resource<HubClient>("IdentityHub.Client");
72
-
73
- /** The hub of the team could not do the call. The reason is the Convex message: it holds no secret. */
74
- export class HubClientFailed extends Schema.TaggedError<HubClientFailed>()("HubClientFailed", {
75
- team: Schema.Union([Schema.String, Schema.Number]),
76
- reason: Schema.String,
77
- }) {
78
- override get message() {
79
- return `Convex.HubClient: the hub of team ${this.team}: ${this.reason}.`;
80
- }
81
- }
82
-
83
- /** The reply of `identityBroker:registerClient`. */
84
- const Registered = Schema.Struct({
85
- issuer: Schema.NonEmptyString,
86
- clientId: Schema.NonEmptyString,
87
- clientSecret: Schema.NonEmptyString,
88
- });
89
-
90
- /** The reply of `identityBroker:renewClient`: false when the hub no longer has the client. */
91
- const Renewed = Schema.Boolean;
92
-
93
- /** Runs `use` with the function API of the hub of `team`, with a key of this call only. */
94
- const withHub = <A, E, R>(
95
- api: ManagementApiService,
96
- team: string | number,
97
- use: (functions: FunctionApi) => Effect.Effect<A, E, R>,
98
- ) =>
99
- Effect.gen(function* () {
100
- const teamId = yield* api.resolveTeamId(team);
101
- const project = yield* findProjectByName(api, teamId, HUB_PROJECT_NAME);
102
- if (project === undefined) {
103
- return yield* new HubClientFailed({
104
- team,
105
- reason: `no project ${HUB_PROJECT_NAME}, which holds the hub`,
106
- });
107
- }
108
- const deployment = yield* prodDeploymentOf(api, project.id);
109
- if (deployment === undefined) {
110
- return yield* new HubClientFailed({
111
- team,
112
- reason: `project ${HUB_PROJECT_NAME} has no production deployment`,
113
- });
114
- }
115
- return yield* withPushKey(api, deployment.name, RUN_KEY_ACTIONS, (key) =>
116
- use(makeFunctionApi(deployment.deploymentUrl, key)),
117
- );
118
- });
119
-
120
- /** One internal function of the hub: its value, or the Convex message as an error. */
121
- const runHub = (
122
- functions: FunctionApi,
123
- team: string | number,
124
- name: string,
125
- args: Record<string, string | boolean>,
126
- ) =>
127
- functions.call(`identityBroker:${name}`, args).pipe(
128
- Effect.mapError((error) => new HubClientFailed({ team, reason: error.message })),
129
- Effect.flatMap((reply) =>
130
- reply.status === "success"
131
- ? Effect.succeed(reply.value)
132
- : Effect.fail(new HubClientFailed({ team, reason: reply.errorMessage.trim() })),
133
- ),
134
- );
135
-
136
- /**
137
- * Registers one client, which expires unless it is a production client. An
138
- * attempt that a lost reply repeats leaves one spare client on the hub, which
139
- * signs nobody in, and which the hub deletes after 14 days.
140
- */
141
- export const registerHubClient = (api: ManagementApiService, props: HubClientProps) =>
142
- withHub(api, props.team, (functions) =>
143
- runHub(functions, props.team, "registerClient", {
144
- appId: props.app,
145
- redirectUri: props.redirectUri,
146
- deploymentType: props.deploymentType,
147
- clientName: props.clientName,
148
- softwareVersion: props.softwareVersion ?? "unknown",
149
- // Convex Auth's generic OAuth method posts the client credentials in the body.
150
- tokenEndpointAuthMethod: "client_secret_post",
151
- expires: true,
152
- }),
153
- ).pipe(
154
- Effect.flatMap((value) =>
155
- Schema.decodeUnknownEffect(Registered)(value).pipe(
156
- Effect.mapError(
157
- () => new HubClientFailed({ team: props.team, reason: "registerClient gave no client" }),
158
- ),
159
- ),
160
- ),
161
- Effect.map(({ issuer, clientId, clientSecret }) => ({
162
- issuer,
163
- clientId,
164
- clientSecret: Redacted.make(clientSecret),
165
- })),
166
- );
167
-
168
- /**
169
- * Renews one client: true while the hub has it. A preview or development client
170
- * then expires 14 days after this call.
171
- */
172
- const renewHubClient = (api: ManagementApiService, team: string | number, clientId: string) =>
173
- withHub(api, team, (functions) =>
174
- runHub(functions, team, "renewClient", { clientId, expires: true }),
175
- ).pipe(
176
- Effect.flatMap((value) =>
177
- Schema.decodeUnknownEffect(Renewed)(value).pipe(
178
- Effect.mapError(() => new HubClientFailed({ team, reason: "renewClient gave no answer" })),
179
- ),
180
- ),
181
- );
182
-
183
- /**
184
- * Renews a client whose values the caller holds: false only when the hub answers that the client is
185
- * gone. Any other failure, such as a hub or a Convex API that cannot answer, keeps the client and
186
- * warns, so an outage never stops a deploy or a dev start; the next one renews it.
187
- */
188
- const renewOrKeep = (api: ManagementApiService, team: string | number, clientId: string) =>
189
- renewHubClient(api, team, clientId).pipe(
190
- Effect.catch((error) =>
191
- Effect.logWarning(
192
- `Convex.HubClient: ${clientId} keeps its saved values, because the hub could not renew it: ${error.message}`,
193
- ).pipe(Effect.as(true)),
194
- ),
195
- );
196
-
197
- const unregister = (api: ManagementApiService, team: string | number, clientId: string) =>
198
- withHub(api, team, (functions) => runHub(functions, team, "deleteClient", { clientId }));
199
-
200
- /** True when the client in state serves the redirect URI and deployment type of `props`. */
201
- const registeredFor = (output: HubClientAttributes, props: HubClientProps) =>
202
- output.redirectUri === props.redirectUri && output.deploymentType === props.deploymentType;
203
-
204
- export const HubClientProvider = () =>
205
- Provider.effect(
206
- HubClient,
207
- Effect.gen(function* () {
208
- const api = yield* ManagementApi;
209
- return {
210
- // Always an update, so that each deploy reaches the hub and renews the client. No attribute
211
- // is stable, so a push reads the values that this run ended with. The same values cause no
212
- // other push.
213
- diff: ({ news }) =>
214
- Effect.succeed(isResolved(news) ? ({ action: "update" } as const) : undefined),
215
-
216
- read: ({ output }) => Effect.succeed(output),
217
-
218
- reconcile: Effect.fn(function* ({ news, output }) {
219
- const saved = output !== undefined && registeredFor(output, news) ? output : undefined;
220
- if (saved !== undefined && (yield* renewOrKeep(api, news.team, saved.clientId))) {
221
- return saved;
222
- }
223
- // A new client: the hub no longer has the saved one, or the redirect URI or the
224
- // deployment type changed. In the second case the old client goes, and the new client is
225
- // returned whatever happens to the old one.
226
- const client = yield* registerHubClient(api, news);
227
- if (output !== undefined && saved === undefined) {
228
- yield* unregister(api, news.team, output.clientId).pipe(
229
- Effect.catchTag("HubClientFailed", (error) =>
230
- Effect.logWarning(
231
- `Client ${output.clientId} stays on the hub: ${error.message} Delete it with \`npx convex run --prod identityBroker:deleteClient\`.`,
232
- ),
233
- ),
234
- );
235
- }
236
- return {
237
- ...client,
238
- redirectUri: news.redirectUri,
239
- deploymentType: news.deploymentType,
240
- clientName: news.clientName,
241
- };
242
- }),
243
-
244
- // A destroy can leave a production deployment running, so its client stays.
245
- delete: ({ olds, output }) =>
246
- output.deploymentType === "production"
247
- ? Effect.void
248
- : unregister(api, olds.team, output.clientId).pipe(Effect.asVoid),
249
- };
250
- }),
251
- );
252
-
253
- export interface DevelopmentClientOptions {
254
- readonly team: string | number;
255
- readonly app: string;
256
- /** The path of the hub's callback after the site URL of the deployment. */
257
- readonly callbackPath: string;
258
- /** Prefix of the three deployment variables. A second callback needs its own client. */
259
- readonly envPrefix?: string;
260
- /** Runs the Convex CLI on the deployment of this directory, and answers its output. */
261
- readonly convex: (args: readonly string[], input?: string) => string;
262
- }
263
-
264
- /**
265
- * `alchemy-convex hub-client`: a stack deploys production and previews, and this covers the
266
- * development deployment, which no stack deploys. Run it at each dev start: it renews the client
267
- * that the three variables name, so the client expires 14 days after the last dev start or use. A
268
- * deployment without all three variables, or whose client the hub no longer has, such as one with
269
- * the `no-hub` values, gets a new client. Answers the callback URL of a new client, or undefined
270
- * for a renewal. The secret reaches the Convex CLI on standard input, never in its arguments.
271
- */
272
- export const registerDevelopmentClient = (options: DevelopmentClientOptions) =>
273
- Effect.gen(function* () {
274
- const { convex } = options;
275
- const api = yield* ManagementApi;
276
- const envPrefix = options.envPrefix ?? "HUB";
277
- const variables = [
278
- `${envPrefix}_ISSUER`,
279
- `${envPrefix}_CLIENT_ID`,
280
- `${envPrefix}_CLIENT_SECRET`,
281
- ];
282
- const names = convex(["env", "list", "--names-only"]).split("\n");
283
- if (variables.every((name) => names.includes(name))) {
284
- const clientId = convex(["env", "get", `${envPrefix}_CLIENT_ID`]);
285
- if (yield* renewOrKeep(api, options.team, clientId)) return undefined;
286
- }
287
- const siteUrl = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String))(
288
- convex(["run", "--inline-query", "process.env.CONVEX_SITE_URL"]),
289
- ).pipe(
290
- Effect.mapError(
291
- () => new HubClientFailed({ team: options.team, reason: "no CONVEX_SITE_URL to register" }),
292
- ),
293
- );
294
- const callbackUrl = `${siteUrl.replace(/\/$/, "")}${options.callbackPath}`;
295
- const client = yield* registerHubClient(api, {
296
- team: options.team,
297
- app: options.app,
298
- redirectUri: callbackUrl,
299
- deploymentType: "development",
300
- clientName: "development",
301
- softwareVersion: new URL(siteUrl).host,
302
- });
303
- // One request, so that an interrupted run cannot leave half a client. `--force` replaces the
304
- // values of an earlier one.
305
- convex(
306
- ["env", "set", "--force"],
307
- `${envPrefix}_ISSUER='${client.issuer}'\n${envPrefix}_CLIENT_ID='${client.clientId}'\n${envPrefix}_CLIENT_SECRET='${Redacted.value(client.clientSecret)}'\n`,
308
- );
309
- return callbackUrl;
310
- });