@samebase/alchemy-convex 0.35.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -24
- package/lib/IdentityHub-CvtrHlaK.js +324 -0
- package/lib/IdentityHub-CvtrHlaK.js.map +1 -0
- package/lib/IdentityHub.d.ts +122 -0
- package/lib/IdentityHub.d.ts.map +1 -0
- package/lib/IdentityHub.js +1 -0
- package/lib/Providers-Bq-4JsdP.d.ts +58 -0
- package/lib/Providers-Bq-4JsdP.d.ts.map +1 -0
- package/lib/{State-ceE-WFI3.js → State-CfIbfbVv.js} +21 -7
- package/lib/State-CfIbfbVv.js.map +1 -0
- package/lib/cli.js +3 -2
- package/lib/cli.js.map +1 -1
- package/lib/index.d.ts +2 -163
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +5 -316
- package/lib/index.js.map +1 -1
- package/lib/{sealedSecret-Bf8AeIp_.js → sealedSecret-B7HlvIg2.js} +2 -10
- package/lib/sealedSecret-B7HlvIg2.js.map +1 -0
- package/lib/sealedSecret.d.ts +0 -2
- package/lib/sealedSecret.d.ts.map +1 -1
- package/lib/sealedSecret.js +1 -1
- package/package.json +5 -1
- package/src/Deployment.ts +2 -1
- package/src/{SharedHubClient.ts → IdentityHub.ts} +73 -87
- package/src/Providers.ts +3 -3
- package/src/Push.ts +34 -7
- package/src/StackComment.ts +4 -1
- package/src/index.ts +0 -6
- package/src/store/sealedSecret.ts +0 -6
- package/lib/State-ceE-WFI3.js.map +0 -1
- package/lib/sealedSecret-Bf8AeIp_.js.map +0 -1
package/lib/index.js
CHANGED
|
@@ -1,17 +1,14 @@
|
|
|
1
|
-
import { A as ManagementApi, C as ConvexCliNotFound, D as parseDeployOutput, E as VariablesOwnedBySomeoneElse, F as CredentialsError, I as DEPLOY_KEY_ENV, L as fromConfig, M as readLocalDeployment, N as ACCESS_TOKEN_ENV, O as push, P as Credentials, R as fromValues, S as ConvexAppNotFound, T as PushTargetMismatch, _ as DeploymentIdentityChange, a as runRecord, b as ProductionDeploymentNotFound, c as CreatedProjectNotFound, d as ProjectNotFound, f as ProjectProvider, g as Deployment, h as AmbiguousDeployment, i as RunRecordError, j as ManagementApiLive, k as ConvexApiError, l as Project, m as AbsoluteRootDir, n as state, o as withRunRecord, p as ProjectTeamChange, r as RUN_RECORD_KEY, s as AmbiguousProject, t as STORE_PROJECT_NAME, u as ProjectDeploymentChange, v as DeploymentProvider, w as EnvironmentNeedsDeployKey, x as CodePushFailed, y as DeploymentResource } from "./State-
|
|
1
|
+
import { A as ManagementApi, C as ConvexCliNotFound, D as parseDeployOutput, E as VariablesOwnedBySomeoneElse, F as CredentialsError, I as DEPLOY_KEY_ENV, L as fromConfig, M as readLocalDeployment, N as ACCESS_TOKEN_ENV, O as push, P as Credentials, R as fromValues, S as ConvexAppNotFound, T as PushTargetMismatch, _ as DeploymentIdentityChange, a as runRecord, b as ProductionDeploymentNotFound, c as CreatedProjectNotFound, d as ProjectNotFound, f as ProjectProvider, g as Deployment, h as AmbiguousDeployment, i as RunRecordError, j as ManagementApiLive, k as ConvexApiError, l as Project, m as AbsoluteRootDir, n as state, o as withRunRecord, p as ProjectTeamChange, r as RUN_RECORD_KEY, s as AmbiguousProject, t as STORE_PROJECT_NAME, u as ProjectDeploymentChange, v as DeploymentProvider, w as EnvironmentNeedsDeployKey, x as CodePushFailed, y as DeploymentResource } from "./State-CfIbfbVv.js";
|
|
2
|
+
import { n as ClientProvider, t as Client } from "./IdentityHub-CvtrHlaK.js";
|
|
2
3
|
import { toPath } from "alchemy/FQN";
|
|
3
4
|
import { Stack } from "alchemy/Stack";
|
|
4
5
|
import * as Effect from "effect/Effect";
|
|
5
6
|
import * as Schema from "effect/Schema";
|
|
6
7
|
import * as Layer from "effect/Layer";
|
|
7
|
-
import * as Option from "effect/Option";
|
|
8
|
-
import * as Redacted from "effect/Redacted";
|
|
9
8
|
import { Resource } from "alchemy";
|
|
10
9
|
import { isResolved } from "alchemy/Diff";
|
|
11
10
|
import * as Provider from "alchemy/Provider";
|
|
12
11
|
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
|
13
|
-
import * as Output from "alchemy/Output";
|
|
14
|
-
import { State } from "alchemy/State";
|
|
15
12
|
//#region src/Component.ts
|
|
16
13
|
/**
|
|
17
14
|
* Associate a native namespace with an installed component. `component` is the
|
|
@@ -88,314 +85,6 @@ const LocalDeploymentProvider = () => Provider.effect(LocalDeployment, Effect.ge
|
|
|
88
85
|
};
|
|
89
86
|
}));
|
|
90
87
|
//#endregion
|
|
91
|
-
//#region src/SharedHubClient.ts
|
|
92
|
-
/** A hung service must not hold a deploy: the time limit of one request. */
|
|
93
|
-
const REQUEST_TIMEOUT_MS = 3e4;
|
|
94
|
-
/** The variables of a deployment without a hub client, as the starter writes them. */
|
|
95
|
-
const OFF_VALUES = {
|
|
96
|
-
issuer: "http://127.0.0.1:1",
|
|
97
|
-
clientId: "no-hub",
|
|
98
|
-
clientSecret: "no-hub"
|
|
99
|
-
};
|
|
100
|
-
/** The name of a connector on the hub. */
|
|
101
|
-
const CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;
|
|
102
|
-
const DeploymentType = Schema.Literals([
|
|
103
|
-
"production",
|
|
104
|
-
"preview",
|
|
105
|
-
"development"
|
|
106
|
-
]);
|
|
107
|
-
const Attributes = Schema.Struct({
|
|
108
|
-
/** `off`: no client, and the values below are the off values. */
|
|
109
|
-
status: Schema.Literals([
|
|
110
|
-
"on",
|
|
111
|
-
"off",
|
|
112
|
-
"suspended"
|
|
113
|
-
]),
|
|
114
|
-
/** The issuer of the hub, which the deployment names to sign in. */
|
|
115
|
-
issuer: Schema.String,
|
|
116
|
-
clientId: Schema.String,
|
|
117
|
-
/** Returned only at registration. */
|
|
118
|
-
clientSecret: Schema.Redacted(Schema.String),
|
|
119
|
-
/** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */
|
|
120
|
-
registrationAccessToken: Schema.Redacted(Schema.String),
|
|
121
|
-
registrationClientUri: Schema.String,
|
|
122
|
-
deploymentType: DeploymentType,
|
|
123
|
-
/** The return address that the client serves. Empty for the off values. */
|
|
124
|
-
redirectUri: Schema.String,
|
|
125
|
-
/** The connectors the client is enrolled in, sorted, each once. Empty for the off values. */
|
|
126
|
-
connectors: Schema.Array(Schema.String),
|
|
127
|
-
/**
|
|
128
|
-
* Returned only at a production registration (RFC 7591 section 1.2). It registers development
|
|
129
|
-
* clients of this app. Empty for a preview, for a development client, and for the off values.
|
|
130
|
-
*/
|
|
131
|
-
initialAccessToken: Schema.Redacted(Schema.String),
|
|
132
|
-
/** The numeric GitHub id of the repository, with the initial access token. Empty without it. */
|
|
133
|
-
repository: Schema.String
|
|
134
|
-
});
|
|
135
|
-
/**
|
|
136
|
-
* The attributes of a saved row, or undefined when the row does not have this version's shape, such
|
|
137
|
-
* as a row that 0.26 or earlier saved without the token fields. Only a schema issue gives undefined;
|
|
138
|
-
* any other failure of the decoder stops the run with a fixed message. The text of a schema issue
|
|
139
|
-
* can quote a value of the row, so it is never kept.
|
|
140
|
-
*/
|
|
141
|
-
const savedAttributes = (value) => Schema.decodeUnknownEffect(Attributes)(value).pipe(Effect.map((attributes) => attributes), Effect.catch(() => Effect.succeed(void 0)), Effect.catchDefect(() => Effect.die(new SharedHubClientFailed({ reason: "the state holds attributes of Convex.SharedHubClient that it cannot read" }))));
|
|
142
|
-
/** The attributes of no client. */
|
|
143
|
-
const offAttributes = (deploymentType) => ({
|
|
144
|
-
status: "off",
|
|
145
|
-
issuer: OFF_VALUES.issuer,
|
|
146
|
-
clientId: OFF_VALUES.clientId,
|
|
147
|
-
clientSecret: Redacted.make(OFF_VALUES.clientSecret),
|
|
148
|
-
registrationAccessToken: Redacted.make(""),
|
|
149
|
-
registrationClientUri: "",
|
|
150
|
-
deploymentType,
|
|
151
|
-
redirectUri: "",
|
|
152
|
-
connectors: [],
|
|
153
|
-
initialAccessToken: Redacted.make(""),
|
|
154
|
-
repository: ""
|
|
155
|
-
});
|
|
156
|
-
/** The set of `names`: sorted, each once. */
|
|
157
|
-
const connectorSet = (names) => [...new Set(names)].sort();
|
|
158
|
-
const sameSet = (a, b) => a.length === b.length && a.every((name, index) => name === b[index]);
|
|
159
|
-
/** One request gave no usable answer. The reason holds no secret. */
|
|
160
|
-
var SharedHubClientFailed = class extends Schema.TaggedError()("SharedHubClientFailed", { reason: Schema.String }) {
|
|
161
|
-
get message() {
|
|
162
|
-
return `Convex.SharedHubClient: ${this.reason}.`;
|
|
163
|
-
}
|
|
164
|
-
};
|
|
165
|
-
const OidcToken = Schema.Struct({ value: Schema.NonEmptyString });
|
|
166
|
-
/** The 201 answer of `POST /hub-clients`. */
|
|
167
|
-
const NewClient = Schema.Struct({
|
|
168
|
-
issuer: Schema.NonEmptyString,
|
|
169
|
-
client_id: Schema.NonEmptyString,
|
|
170
|
-
client_secret: Schema.NonEmptyString,
|
|
171
|
-
registration_access_token: Schema.NonEmptyString,
|
|
172
|
-
registration_client_uri: Schema.NonEmptyString,
|
|
173
|
-
redirect_uri: Schema.NonEmptyString,
|
|
174
|
-
/** The set the hub recorded, which must be the set the request sent. */
|
|
175
|
-
connectors: Schema.Array(Schema.String),
|
|
176
|
-
/** The terms of the hub's sign-in service, which must be the `terms` of the stack's `hub`. */
|
|
177
|
-
terms: Schema.String,
|
|
178
|
-
/** Only in the answer to a production registration with the GitHub token. */
|
|
179
|
-
initial_access_token: Schema.optionalKey(Schema.NonEmptyString),
|
|
180
|
-
repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\d+$/)))
|
|
181
|
-
});
|
|
182
|
-
/** The other answers of `POST /hub-clients`, by status. */
|
|
183
|
-
const REFUSALS = {
|
|
184
|
-
400: "the identity hub refused the request: the return address must be https on a DNS name, and the app name at most 64 characters",
|
|
185
|
-
401: "the identity hub refused the GitHub OIDC token",
|
|
186
|
-
403: "the identity hub does not allow this repository or return address",
|
|
187
|
-
404: "the identity hub has no /hub-clients",
|
|
188
|
-
429: "the identity hub limits new clients",
|
|
189
|
-
502: "GitHub's keys are not available to the identity hub"
|
|
190
|
-
};
|
|
191
|
-
/** The reasons of a 403 that a log line shows. Any other text of the answer is never logged. */
|
|
192
|
-
const NOT_ALLOWED = /* @__PURE__ */ new Map([
|
|
193
|
-
["paused", "this app is paused on the identity hub"],
|
|
194
|
-
["run_not_allowed", "the identity hub gives clients only to runs of main and of pull requests"],
|
|
195
|
-
["blocked", "Samebase blocked this repository or its owner"],
|
|
196
|
-
["suspended", "the identity hub suspended this repository"],
|
|
197
|
-
["too_many_apps", "the repository has as many apps on the identity hub as it may"],
|
|
198
|
-
["too_many_clients", "the app has as many clients on the identity hub as it may"],
|
|
199
|
-
["app_taken", "the app's name belongs to another app on the identity hub"],
|
|
200
|
-
["host_unreachable", "the identity hub could not reach the host of the return address"],
|
|
201
|
-
["verification_file_missing", "the host of the return address does not serve /samebase-verification.json"],
|
|
202
|
-
["verification_file_invalid", "/samebase-verification.json on the host holds no repository id"],
|
|
203
|
-
["repository_mismatch", "/samebase-verification.json on the host names another repository"],
|
|
204
|
-
["app_mismatch", "the initial access token belongs to another app on the identity hub"]
|
|
205
|
-
]);
|
|
206
|
-
/** The windows of a 429, by the name that the answer gives. */
|
|
207
|
-
const RATE_LIMITED = /* @__PURE__ */ new Map([
|
|
208
|
-
["repository", "the identity hub gives one repository at most 30 new clients an hour"],
|
|
209
|
-
["owner", "the identity hub gives one owner at most 100 new clients an hour"],
|
|
210
|
-
["new_owners", "the identity hub takes at most 50 new owners an hour"]
|
|
211
|
-
]);
|
|
212
|
-
const Refusal = Schema.Struct({ reason: Schema.String });
|
|
213
|
-
const RateLimited = Schema.Struct({ window: Schema.String });
|
|
214
|
-
/** A 400 for a connector the hub does not offer or allow, with the names it allows. */
|
|
215
|
-
const InvalidConnectors = Schema.Struct({
|
|
216
|
-
error: Schema.Literal("invalid_connectors"),
|
|
217
|
-
allowed: Schema.Array(Schema.String)
|
|
218
|
-
});
|
|
219
|
-
/**
|
|
220
|
-
* The text of a refusal: a known reason of a 403 or window of a 429, the allowed connectors of an
|
|
221
|
-
* `invalid_connectors` 400 (only names of the connector grammar, so no other text of the answer is
|
|
222
|
-
* printed), else the text of its status.
|
|
223
|
-
*/
|
|
224
|
-
const refusalOf = (status, body) => {
|
|
225
|
-
const decoded = (schema) => Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));
|
|
226
|
-
const ofStatus = () => REFUSALS[status] ?? "the identity hub refused the request";
|
|
227
|
-
switch (status) {
|
|
228
|
-
case 400: {
|
|
229
|
-
const allowed = decoded(InvalidConnectors)?.allowed.filter((name) => CONNECTOR_NAME.test(name));
|
|
230
|
-
return allowed === void 0 ? ofStatus() : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
|
|
231
|
-
}
|
|
232
|
-
case 403: return NOT_ALLOWED.get(decoded(Refusal)?.reason ?? "") ?? ofStatus();
|
|
233
|
-
case 429: return RATE_LIMITED.get(decoded(RateLimited)?.window ?? "") ?? ofStatus();
|
|
234
|
-
default: return ofStatus();
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
const send = (who, url, token, init) => Effect.tryPromise({
|
|
238
|
-
try: async () => {
|
|
239
|
-
const response = await fetch(url, {
|
|
240
|
-
...init,
|
|
241
|
-
headers: {
|
|
242
|
-
Authorization: `Bearer ${token}`,
|
|
243
|
-
"Content-Type": "application/json"
|
|
244
|
-
},
|
|
245
|
-
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
246
|
-
});
|
|
247
|
-
const body = await response.json().catch(() => void 0);
|
|
248
|
-
return {
|
|
249
|
-
status: response.status,
|
|
250
|
-
body
|
|
251
|
-
};
|
|
252
|
-
},
|
|
253
|
-
catch: () => new SharedHubClientFailed({ reason: `${who} gave no answer` })
|
|
254
|
-
});
|
|
255
|
-
const decode = (schema, who) => (value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => new SharedHubClientFailed({ reason: `${who} gave a bad answer` })));
|
|
256
|
-
/**
|
|
257
|
-
* The OIDC token of this run for `audience`, read right before the call, because it lives for
|
|
258
|
-
* minutes only.
|
|
259
|
-
*/
|
|
260
|
-
const readOidcToken = (requestUrl, requestToken, audience) => Effect.gen(function* () {
|
|
261
|
-
const { body, status } = yield* send("GitHub", `${requestUrl}&audience=${encodeURIComponent(audience)}`, requestToken, { method: "GET" });
|
|
262
|
-
if (status !== 200) return yield* new SharedHubClientFailed({ reason: `GitHub gave no OIDC token (HTTP ${status})` });
|
|
263
|
-
return (yield* decode(OidcToken, "GitHub")(body)).value;
|
|
264
|
-
});
|
|
265
|
-
/** `POST /hub-clients` with `bearer`: the GitHub OIDC token, or the app's initial access token. */
|
|
266
|
-
const requestNewClient = (props, connectors, bearer) => Effect.gen(function* () {
|
|
267
|
-
const { hub } = props;
|
|
268
|
-
const { body, status } = yield* send("The identity hub", `${hub.issuer}/hub-clients`, bearer, {
|
|
269
|
-
method: "POST",
|
|
270
|
-
body: JSON.stringify({
|
|
271
|
-
app: props.app,
|
|
272
|
-
redirectUri: props.redirectUri,
|
|
273
|
-
softwareVersion: props.softwareVersion ?? "unknown",
|
|
274
|
-
connectors
|
|
275
|
-
})
|
|
276
|
-
});
|
|
277
|
-
if (status !== 201) return yield* new SharedHubClientFailed({ reason: `${status === 401 && props.deploymentType === "development" ? "the identity hub refused the initial access token" : refusalOf(status, body)} (HTTP ${status})` });
|
|
278
|
-
const client = yield* decode(NewClient, "The identity hub")(body);
|
|
279
|
-
if (client.issuer !== hub.issuer || client.redirect_uri !== props.redirectUri || !sameSet(client.connectors, connectors) || client.terms !== hub.terms) return yield* new SharedHubClientFailed({ reason: "The identity hub gave a bad answer" });
|
|
280
|
-
yield* Effect.logInfo(`Convex.SharedHubClient: ${props.app} on ${props.redirectUri} has a new client of the identity hub. Its use is under ${hub.terms}.`);
|
|
281
|
-
const production = props.deploymentType === "production";
|
|
282
|
-
return {
|
|
283
|
-
status: "on",
|
|
284
|
-
issuer: hub.issuer,
|
|
285
|
-
clientId: client.client_id,
|
|
286
|
-
clientSecret: Redacted.make(client.client_secret),
|
|
287
|
-
registrationAccessToken: Redacted.make(client.registration_access_token),
|
|
288
|
-
registrationClientUri: client.registration_client_uri,
|
|
289
|
-
deploymentType: props.deploymentType,
|
|
290
|
-
redirectUri: props.redirectUri,
|
|
291
|
-
connectors,
|
|
292
|
-
initialAccessToken: Redacted.make(production ? client.initial_access_token ?? "" : ""),
|
|
293
|
-
repository: production ? client.repository ?? "" : ""
|
|
294
|
-
};
|
|
295
|
-
});
|
|
296
|
-
/** A new client, or the off values. */
|
|
297
|
-
const newClient = (props, connectors) => {
|
|
298
|
-
const label = `Convex.SharedHubClient: ${props.app} on ${props.redirectUri} deploys without the hub`;
|
|
299
|
-
const off = offAttributes(props.deploymentType);
|
|
300
|
-
const request = (bearer) => bearer.pipe(Effect.flatMap((token) => requestNewClient(props, connectors, token)), Effect.catchTag("SharedHubClientFailed", (error) => Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(Effect.as(off))));
|
|
301
|
-
if (props.deploymentType === "development") {
|
|
302
|
-
const token = Redacted.value(props.initialAccessToken);
|
|
303
|
-
return token === "" ? Effect.logInfo("Convex.SharedHubClient: deploy to main once for hub sign-in in development.").pipe(Effect.as(off)) : request(Effect.succeed(token));
|
|
304
|
-
}
|
|
305
|
-
const requestUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];
|
|
306
|
-
const requestToken = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];
|
|
307
|
-
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));
|
|
308
|
-
return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));
|
|
309
|
-
};
|
|
310
|
-
/**
|
|
311
|
-
* The client after a read on the hub, or undefined when the hub says that the client is gone. A
|
|
312
|
-
* read with no usable answer keeps the saved client, except for a required one: a required client
|
|
313
|
-
* passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,
|
|
314
|
-
* and did not save because that run failed, cannot pass a run that the hub does not answer.
|
|
315
|
-
*/
|
|
316
|
-
const renew = (saved, required) => Effect.gen(function* () {
|
|
317
|
-
const { status } = yield* send("The identity hub", saved.registrationClientUri, Redacted.value(saved.registrationAccessToken), { method: "GET" });
|
|
318
|
-
switch (status) {
|
|
319
|
-
case 200: return {
|
|
320
|
-
...saved,
|
|
321
|
-
status: "on"
|
|
322
|
-
};
|
|
323
|
-
case 401: return;
|
|
324
|
-
case 403:
|
|
325
|
-
yield* Effect.logWarning(`Convex.SharedHubClient: the hub suspended the client of ${saved.redirectUri}. It keeps its values, and nobody can sign in with it.`);
|
|
326
|
-
return {
|
|
327
|
-
...saved,
|
|
328
|
-
status: "suspended"
|
|
329
|
-
};
|
|
330
|
-
default: return yield* new SharedHubClientFailed({ reason: `The identity hub answered HTTP ${status}` });
|
|
331
|
-
}
|
|
332
|
-
}).pipe(Effect.catchTag("SharedHubClientFailed", (error) => required ? Effect.fail(new SharedHubClientFailed({ reason: `${saved.redirectUri} is required, and the hub did not confirm its client: ${error.reason}` })) : Effect.logWarning(`Convex.SharedHubClient: ${saved.redirectUri} keeps the saved client: ${error.reason}.`).pipe(Effect.as(saved))));
|
|
333
|
-
/** A saved row of this resource, whose `attr` `savedAttributes` reads. */
|
|
334
|
-
const SavedRow = Schema.Struct({
|
|
335
|
-
resourceType: Schema.Literal("IdentityHub.SharedClient"),
|
|
336
|
-
attr: Schema.Unknown
|
|
337
|
-
});
|
|
338
|
-
/**
|
|
339
|
-
* The attributes of the client `id` in another stage of this stack, such as
|
|
340
|
-
* `read("HubClient", { stage: "prod" })` in a development stage, as Outputs: the
|
|
341
|
-
* `initialAccessToken` and the `repository` of the production client. Without that row, the off
|
|
342
|
-
* attributes, with `deploymentType: "production"`.
|
|
343
|
-
*
|
|
344
|
-
* `SharedHubClient.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the
|
|
345
|
-
* row is missing, and a development stage before the first deploy to main has none. This read runs
|
|
346
|
-
* when the plan resolves it, with the State service of the running stack and its `get`, so it never
|
|
347
|
-
* creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every
|
|
348
|
-
* read.
|
|
349
|
-
*/
|
|
350
|
-
const read = (id, options) => Output.fromEffect(Effect.gen(function* () {
|
|
351
|
-
const stack = yield* Stack;
|
|
352
|
-
const row = yield* (yield* yield* State).get({
|
|
353
|
-
stack: stack.name,
|
|
354
|
-
stage: options.stage,
|
|
355
|
-
fqn: id
|
|
356
|
-
}).pipe(Effect.orDie);
|
|
357
|
-
if (row === void 0) return offAttributes("production");
|
|
358
|
-
const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(Effect.catchCause(() => Effect.die(new SharedHubClientFailed({ reason: `the row ${id} of stage ${options.stage} is not a Convex.SharedHubClient` }))));
|
|
359
|
-
const saved = yield* savedAttributes(attr);
|
|
360
|
-
if (saved === void 0) return yield* Effect.die(new SharedHubClientFailed({ reason: `the row ${id} of stage ${options.stage} holds attributes that this version cannot read` }));
|
|
361
|
-
return saved;
|
|
362
|
-
}));
|
|
363
|
-
/**
|
|
364
|
-
* The three values that the app's deployment gets, such as `HUB_ISSUER`, `HUB_CLIENT_ID`, and
|
|
365
|
-
* `HUB_CLIENT_SECRET`, as Outputs: the client's values when `status` is `on`, else the off values,
|
|
366
|
-
* so that a suspended client gives guest sign-in and keeps its values in state.
|
|
367
|
-
*/
|
|
368
|
-
const variables = (client) => Output.map(Output.of(client), (attributes) => attributes.status === "on" ? {
|
|
369
|
-
issuer: attributes.issuer,
|
|
370
|
-
clientId: attributes.clientId,
|
|
371
|
-
clientSecret: attributes.clientSecret
|
|
372
|
-
} : {
|
|
373
|
-
issuer: OFF_VALUES.issuer,
|
|
374
|
-
clientId: OFF_VALUES.clientId,
|
|
375
|
-
clientSecret: Redacted.make(OFF_VALUES.clientSecret)
|
|
376
|
-
});
|
|
377
|
-
const SharedHubClient = Resource("IdentityHub.SharedClient")({
|
|
378
|
-
read,
|
|
379
|
-
variables
|
|
380
|
-
});
|
|
381
|
-
const SharedHubClientProvider = () => Provider.succeed(SharedHubClient, {
|
|
382
|
-
diff: ({ news }) => Effect.succeed(isResolved(news) ? { action: "update" } : void 0),
|
|
383
|
-
read: ({ output }) => Effect.succeed(output),
|
|
384
|
-
reconcile: Effect.fn(function* ({ news, output }) {
|
|
385
|
-
if (news.connectors.length === 0 || !news.connectors.every((name) => CONNECTOR_NAME.test(name))) return yield* new SharedHubClientFailed({ reason: `${news.app} on ${news.redirectUri} needs connectors: one or more names of [a-z0-9-]{1,64}` });
|
|
386
|
-
const connectors = connectorSet(news.connectors);
|
|
387
|
-
const saved = output === void 0 || output.status === "off" ? void 0 : yield* savedAttributes(output);
|
|
388
|
-
if (output !== void 0 && output.status !== "off" && saved === void 0) yield* Effect.logWarning(`Convex.SharedHubClient: the saved attributes of ${news.app} on ${news.redirectUri} cannot be read by this version, so this run registers a new client, which replaces the saved one.`);
|
|
389
|
-
const client = (saved?.issuer === news.hub.issuer && saved.redirectUri === news.redirectUri && saved.deploymentType === news.deploymentType && sameSet(saved.connectors, connectors) ? yield* renew(saved, news.required === true) : void 0) ?? (yield* newClient(news, connectors));
|
|
390
|
-
if (news.required === true && client.status !== "on") return yield* new SharedHubClientFailed({ reason: `${news.app} on ${news.redirectUri} is required and has no working client (${client.status}). The warning above names the reason` });
|
|
391
|
-
return client;
|
|
392
|
-
}),
|
|
393
|
-
delete: ({ output }) => output.deploymentType === "production" || output.status === "off" ? Effect.void : Effect.gen(function* () {
|
|
394
|
-
const { status } = yield* send("The identity hub", output.registrationClientUri, Redacted.value(output.registrationAccessToken), { method: "DELETE" });
|
|
395
|
-
if (status !== 204 && status !== 401) return yield* new SharedHubClientFailed({ reason: `The identity hub answered HTTP ${status}` });
|
|
396
|
-
}).pipe(Effect.catchTag("SharedHubClientFailed", (error) => Effect.logWarning(`Convex.SharedHubClient: the client of ${output.redirectUri} stays on the hub until its removal date: ${error.reason}.`)))
|
|
397
|
-
});
|
|
398
|
-
//#endregion
|
|
399
88
|
//#region src/Providers.ts
|
|
400
89
|
var Providers = class extends Provider.ProviderCollection()("Convex") {};
|
|
401
90
|
/**
|
|
@@ -407,9 +96,9 @@ const providers = (credentials = fromConfig()) => Layer.effect(Providers, Provid
|
|
|
407
96
|
Project,
|
|
408
97
|
DeploymentResource,
|
|
409
98
|
LocalDeployment,
|
|
410
|
-
|
|
411
|
-
])).pipe(Layer.provide(Layer.mergeAll(ProjectProvider(), DeploymentProvider(), LocalDeploymentProvider(),
|
|
99
|
+
Client
|
|
100
|
+
])).pipe(Layer.provide(Layer.mergeAll(ProjectProvider(), DeploymentProvider(), LocalDeploymentProvider(), ClientProvider())), Layer.provide(ManagementApiLive()), Layer.provide(credentials), Layer.orDie);
|
|
412
101
|
//#endregion
|
|
413
|
-
export { ACCESS_TOKEN_ENV, AbsoluteRootDir, AmbiguousDeployment, AmbiguousProject, CodePushFailed, ConvexApiError, ConvexAppNotFound, ConvexCliNotFound, CreatedProjectNotFound, Credentials, CredentialsError, DEPLOY_KEY_ENV, Deployment, DeploymentIdentityChange, EnvironmentNeedsDeployKey, LocalDeployment, LocalDeploymentNotFound, ManagementApi, ProductionDeploymentNotFound, Project, ProjectDeploymentChange, ProjectNotFound, ProjectTeamChange, Providers, PushTargetMismatch, RUN_RECORD_KEY, RunRecordError, STORE_PROJECT_NAME,
|
|
102
|
+
export { ACCESS_TOKEN_ENV, AbsoluteRootDir, AmbiguousDeployment, AmbiguousProject, CodePushFailed, ConvexApiError, ConvexAppNotFound, ConvexCliNotFound, CreatedProjectNotFound, Credentials, CredentialsError, DEPLOY_KEY_ENV, Deployment, DeploymentIdentityChange, EnvironmentNeedsDeployKey, LocalDeployment, LocalDeploymentNotFound, ManagementApi, ProductionDeploymentNotFound, Project, ProjectDeploymentChange, ProjectNotFound, ProjectTeamChange, Providers, PushTargetMismatch, RUN_RECORD_KEY, RunRecordError, STORE_PROJECT_NAME, VariablesOwnedBySomeoneElse, bindComponent, fromConfig, fromValues, parseDeployOutput, providers, runRecord, state, withRunRecord };
|
|
414
103
|
|
|
415
104
|
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/Component.ts","../src/LocalDeployment.ts","../src/SharedHubClient.ts","../src/Providers.ts"],"sourcesContent":["import { toPath } from \"alchemy/FQN\";\nimport type { NamespaceNode } from \"alchemy/Namespace\";\nimport { Stack } from \"alchemy/Stack\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport type { Deployment } from \"./Deployment.ts\";\n\n/** A component's resources occupy this namespace in the deployment's Alchemy stack and stage. */\nexport interface ComponentBinding {\n readonly type: \"component\";\n readonly path: string;\n readonly namespace: readonly string[];\n}\n\n/**\n * Associate a native namespace with an installed component. `component` is the\n * installed name from the app's `convex.config.ts`; a nested install joins the\n * names with slashes, such as `\"workspace/mail\"`. An undefined namespace\n * associates the stack root. This records display metadata; it does not install\n * the component, set its environment, or change removal policies.\n */\nexport const bindComponent = (options: {\n deployment: Deployment;\n component: string;\n namespace: NamespaceNode | undefined;\n}) =>\n Effect.gen(function* () {\n if (options.component === \"\") {\n return yield* Effect.die(new Error(\"The component name is empty.\"));\n }\n const namespace = toPath(options.namespace);\n const sid = `convex.component:${JSON.stringify(namespace)}`;\n const stack = yield* Stack;\n const previous = stack.bindings[options.deployment.FQN]?.find((binding) => binding.sid === sid);\n // Alchemy keeps the last binding with a given sid. Reject conflicting owners before that happens.\n if (previous !== undefined) {\n const existing = Schema.decodeUnknownSync(Schema.Struct({ path: Schema.String }))(\n previous.data,\n );\n if (existing.path !== options.component) {\n return yield* Effect.die(\n new Error(\n `Alchemy namespace ${JSON.stringify(namespace)} is already bound to ${existing.path}.`,\n ),\n );\n }\n return;\n }\n yield* options.deployment.bind(sid, {\n type: \"component\",\n path: options.component,\n namespace,\n });\n });\n","// Convex.LocalDeployment: the logged-in local deployment of one folder, which\n// `npx convex deployment create <team>:<project>:local --select` makes and `npx convex dev` runs on\n// this machine. Each folder, such as each git worktree, has its own, with its own data.\n//\n// The resource writes its `env` and nothing else. The running `convex dev` owns the backend and\n// pushes the functions, so the development stage runs after `convex dev` has started, and the\n// first push of a new local deployment takes the variables that the project's default variables\n// for development gave it. The resource reads the deployment from\n// `.convex/local/default/config.json`, where the Convex CLI keeps its name, ports, and admin key,\n// and writes with that admin key through the same call as for a cloud deployment.\n//\n// A destroy changes nothing: the folder's deployment and its variables stay with the folder.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Provider from \"alchemy/Provider\";\nimport * as Effect from \"effect/Effect\";\nimport * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\nimport * as Schema from \"effect/Schema\";\nimport { readLocalDeployment } from \"./ManagementApi.ts\";\nimport type { Providers } from \"./Providers.ts\";\nimport { type EnvValue, push } from \"./Push.ts\";\n\n/** The folder has no logged-in local deployment. */\nexport class LocalDeploymentNotFound extends Schema.TaggedError<LocalDeploymentNotFound>()(\n \"LocalDeploymentNotFound\",\n { rootDir: Schema.String },\n) {\n override get message() {\n return `Convex.LocalDeployment: ${this.rootDir} has no logged-in local deployment. Run \\`npx convex deployment create <team>:<project>:local --select\\` there, then \\`npx convex dev\\`.`;\n }\n}\n\n/**\n * The folder's logged-in local deployment, read when the stack's program runs, so that a client\n * can take its `siteUrl`. Fails with `LocalDeploymentNotFound` when the folder has none.\n */\nconst of = (rootDir = \".\") => {\n const info = readLocalDeployment(rootDir);\n if (info === undefined) throw new LocalDeploymentNotFound({ rootDir });\n return { name: info.name, url: info.url, siteUrl: info.siteUrl };\n};\n\nexport interface LocalDeploymentProps {\n /** The folder of the Convex app, where `.convex/local/default` is. The working directory without it. */\n readonly rootDir?: string;\n /** The variables of the deployment. A name that leaves `env` is removed. */\n readonly env: Readonly<Record<string, EnvValue>>;\n}\n\nexport interface LocalDeploymentAttributes {\n readonly name: string;\n readonly url: string;\n readonly siteUrl: string;\n /** The names that this resource set, so a name that leaves `env` is removed. */\n readonly envNames: readonly string[];\n}\n\nexport type LocalDeployment = Resource<\n \"Convex.LocalDeployment\",\n LocalDeploymentProps,\n LocalDeploymentAttributes,\n never,\n Providers\n>;\nexport const LocalDeployment = Resource<LocalDeployment>(\"Convex.LocalDeployment\")({ of });\n\nexport const LocalDeploymentProvider = () =>\n Provider.effect(\n LocalDeployment,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return {\n // Always an update: the variables are read and only changed values are written.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n reconcile: Effect.fn(function* ({ news, output }) {\n const rootDir = news.rootDir ?? \".\";\n const info = readLocalDeployment(rootDir);\n if (info === undefined) return yield* new LocalDeploymentNotFound({ rootDir });\n // Without `source`, a push only sets the variables and removes the names that left `env`.\n yield* push(spawner, info.adminKey, {\n deployment: info.name,\n url: info.url,\n rootDir,\n source: undefined,\n env: news.env,\n previousEnvNames: output?.name === info.name ? output.envNames : [],\n adopt: true,\n previewName: undefined,\n });\n return {\n name: info.name,\n url: info.url,\n siteUrl: info.siteUrl,\n envNames: Object.keys(news.env).sort(),\n };\n }),\n\n delete: () => Effect.void,\n };\n }),\n );\n","// Convex.SharedHubClient: one deployment of an app as a client of the identity hub that the stack\n// names, for an app that deploys in its own GitHub Actions run, on any host, and in development as a\n// stage of the same stack.\n//\n// A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs\n// no key and no Samebase account. The token names the repository. The hub reads\n// `/samebase-verification.json` at the origin of the return address, which must name the same\n// repository, and registers the client on that address. The answer holds the client's own\n// registration access token (RFC 7591), and each later deploy reads the client on the hub with that\n// token (RFC 7592). The hub keeps only hashes, so the state is the only record of the secret and the\n// token.\n//\n// The answer to a production registration also holds the app's initial access token (RFC 7591\n// section 1.2) and the repository id. The state of stage `prod` keeps them. A development checkout\n// runs the stack as a stage `dev-<name>`: it reads them with `SharedHubClient.read`, and a client\n// with `deploymentType: \"development\"` asks the hub with the token in place of the GitHub token\n// (RFC 133).\n//\n// A client is enrolled in the connectors it signs in through, such as `google` and `github`, at\n// registration (RFC 137). The hub records the set on the client and never changes it: a stack with\n// another set registers a new client.\n//\n// A push removes a variable that a deploy stops passing, so a failure here must not drop working\n// variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that\n// cannot work asks for a new one: it is gone, or it has another return address, type, or connector\n// set. If that request fails, the run gives the off values, so the app has guest sign-in and not a\n// broken button. The off values are the `no-hub` variables of a checkout without a hub: Convex\n// needs the variables, and the app hides the button for this client ID.\n//\n// No text in this file quotes an answer or a fetch error, so no log line can hold a secret. The one\n// exception is the connector names of an `invalid_connectors` refusal, each checked against the\n// grammar of a connector name before it is printed.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Output from \"alchemy/Output\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport type { Providers } from \"./Providers.ts\";\n\n/** A hung service must not hold a deploy: the time limit of one request. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** The variables of a deployment without a hub client, as the starter writes them. */\nconst OFF_VALUES = { issuer: \"http://127.0.0.1:1\", clientId: \"no-hub\", clientSecret: \"no-hub\" };\n\n/** The name of a connector on the hub. */\nconst CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;\n\n/**\n * An identity hub of @samebase/identity-broker, such as Samebase's:\n * `{ issuer: \"https://auth.samebase.com\", terms: \"https://samebase.com/terms\" }`.\n */\nexport interface Hub {\n /**\n * The hub's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/hub-clients`,\n * with a GitHub token whose audience is the issuer, so no other hub can use that token.\n */\n readonly issuer: string;\n /**\n * The terms of the hub's sign-in service, which its answer must name. The log prints them for a\n * new client, so no value that the answer chose reaches the log.\n */\n readonly terms: string;\n}\n\ninterface CommonProps {\n /** The stable name of the app, set once in the stack. */\n readonly app: string;\n /** The hub to register at. A changed hub registers a new client there; the old one stays. */\n readonly hub: Hub;\n /**\n * The connectors the client signs in through, by their names on the hub, such as\n * `[\"google\", \"github\"]`: at least one, each of `[a-z0-9-]{1,64}`. The hub refuses a name it does\n * not offer, or does not allow this repository, and the log then names the allowed ones. The set\n * is recorded on the client for good: a changed set registers a new client.\n */\n readonly connectors: readonly string[];\n /**\n * The return address of the hub's sign-ins, such as `${site.siteUrl}/auth/hub/callback`: an https\n * URL whose origin serves `/samebase-verification.json` with the numeric GitHub id of this\n * repository, `{ \"repository\": \"123\" }`. It can come from a resource that this run creates. A\n * development client can also have http on a loopback host, which needs no file.\n */\n readonly redirectUri: string;\n /** Recorded on the hub's client, such as the commit. The hub records \"unknown\" without it. */\n readonly softwareVersion?: string;\n /**\n * The run fails unless the hub confirms the client in this run: it fails when the hub refuses or\n * does not answer a registration or a renewal, and when it suspended the client. Without it, such\n * a run gives the off values or keeps the saved client, so the app deploys anyway. Set it where\n * sign-in is the product. A failed run saves nothing, so the next run asks the hub again.\n */\n readonly required?: boolean;\n}\n\n/**\n * A production or preview client asks with the GitHub OIDC token of the run. A development client\n * asks with the app's initial access token, which `SharedHubClient.read` gives from stage `prod`.\n */\nexport type SharedHubClientProps =\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\";\n readonly initialAccessToken?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"development\";\n /** Empty before the first production registration: the client gets the off values. */\n readonly initialAccessToken: Redacted.Redacted<string>;\n });\n\nconst DeploymentType = Schema.Literals([\"production\", \"preview\", \"development\"]);\n\nconst Attributes = Schema.Struct({\n /** `off`: no client, and the values below are the off values. */\n status: Schema.Literals([\"on\", \"off\", \"suspended\"]),\n /** The issuer of the hub, which the deployment names to sign in. */\n issuer: Schema.String,\n clientId: Schema.String,\n /** Returned only at registration. */\n clientSecret: Schema.Redacted(Schema.String),\n /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */\n registrationAccessToken: Schema.Redacted(Schema.String),\n registrationClientUri: Schema.String,\n deploymentType: DeploymentType,\n /** The return address that the client serves. Empty for the off values. */\n redirectUri: Schema.String,\n /** The connectors the client is enrolled in, sorted, each once. Empty for the off values. */\n connectors: Schema.Array(Schema.String),\n /**\n * Returned only at a production registration (RFC 7591 section 1.2). It registers development\n * clients of this app. Empty for a preview, for a development client, and for the off values.\n */\n initialAccessToken: Schema.Redacted(Schema.String),\n /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */\n repository: Schema.String,\n});\n\n/**\n * The attributes keep the real values of a suspended client, so that an unblock needs no new client.\n * `SharedHubClient.variables` gives the values that the app gets.\n */\nexport interface SharedHubClientAttributes extends Schema.Schema.Type<typeof Attributes> {}\n\n/**\n * The attributes of a saved row, or undefined when the row does not have this version's shape, such\n * as a row that 0.26 or earlier saved without the token fields. Only a schema issue gives undefined;\n * any other failure of the decoder stops the run with a fixed message. The text of a schema issue\n * can quote a value of the row, so it is never kept.\n */\nconst savedAttributes = (value: unknown) =>\n Schema.decodeUnknownEffect(Attributes)(value).pipe(\n Effect.map((attributes): SharedHubClientAttributes | undefined => attributes),\n Effect.catch(() => Effect.succeed(undefined)),\n Effect.catchDefect(() =>\n Effect.die(\n new SharedHubClientFailed({\n reason: \"the state holds attributes of Convex.SharedHubClient that it cannot read\",\n }),\n ),\n ),\n );\n\n/** The attributes of no client. */\nconst offAttributes = (\n deploymentType: SharedHubClientAttributes[\"deploymentType\"],\n): SharedHubClientAttributes => ({\n status: \"off\",\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n registrationAccessToken: Redacted.make(\"\"),\n registrationClientUri: \"\",\n deploymentType,\n redirectUri: \"\",\n connectors: [],\n initialAccessToken: Redacted.make(\"\"),\n repository: \"\",\n});\n\n/** The set of `names`: sorted, each once. */\nconst connectorSet = (names: readonly string[]) => [...new Set(names)].sort();\n\nconst sameSet = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && a.every((name, index) => name === b[index]);\n\n/** One request gave no usable answer. The reason holds no secret. */\nclass SharedHubClientFailed extends Schema.TaggedError<SharedHubClientFailed>()(\n \"SharedHubClientFailed\",\n { reason: Schema.String },\n) {\n override get message() {\n return `Convex.SharedHubClient: ${this.reason}.`;\n }\n}\n\nconst OidcToken = Schema.Struct({ value: Schema.NonEmptyString });\n\n/** The 201 answer of `POST /hub-clients`. */\nconst NewClient = Schema.Struct({\n issuer: Schema.NonEmptyString,\n client_id: Schema.NonEmptyString,\n client_secret: Schema.NonEmptyString,\n registration_access_token: Schema.NonEmptyString,\n registration_client_uri: Schema.NonEmptyString,\n redirect_uri: Schema.NonEmptyString,\n /** The set the hub recorded, which must be the set the request sent. */\n connectors: Schema.Array(Schema.String),\n /** The terms of the hub's sign-in service, which must be the `terms` of the stack's `hub`. */\n terms: Schema.String,\n /** Only in the answer to a production registration with the GitHub token. */\n initial_access_token: Schema.optionalKey(Schema.NonEmptyString),\n repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\\d+$/))),\n});\n\n/** The other answers of `POST /hub-clients`, by status. */\nconst REFUSALS: Readonly<Record<number, string>> = {\n 400: \"the identity hub refused the request: the return address must be https on a DNS name, and the app name at most 64 characters\",\n 401: \"the identity hub refused the GitHub OIDC token\",\n 403: \"the identity hub does not allow this repository or return address\",\n 404: \"the identity hub has no /hub-clients\",\n 429: \"the identity hub limits new clients\",\n 502: \"GitHub's keys are not available to the identity hub\",\n};\n\n/** The reasons of a 403 that a log line shows. Any other text of the answer is never logged. */\nconst NOT_ALLOWED = new Map([\n [\"paused\", \"this app is paused on the identity hub\"],\n [\"run_not_allowed\", \"the identity hub gives clients only to runs of main and of pull requests\"],\n [\"blocked\", \"Samebase blocked this repository or its owner\"],\n [\"suspended\", \"the identity hub suspended this repository\"],\n [\"too_many_apps\", \"the repository has as many apps on the identity hub as it may\"],\n [\"too_many_clients\", \"the app has as many clients on the identity hub as it may\"],\n [\"app_taken\", \"the app's name belongs to another app on the identity hub\"],\n [\"host_unreachable\", \"the identity hub could not reach the host of the return address\"],\n [\n \"verification_file_missing\",\n \"the host of the return address does not serve /samebase-verification.json\",\n ],\n [\"verification_file_invalid\", \"/samebase-verification.json on the host holds no repository id\"],\n [\"repository_mismatch\", \"/samebase-verification.json on the host names another repository\"],\n [\"app_mismatch\", \"the initial access token belongs to another app on the identity hub\"],\n]);\n\n/** The windows of a 429, by the name that the answer gives. */\nconst RATE_LIMITED = new Map([\n [\"repository\", \"the identity hub gives one repository at most 30 new clients an hour\"],\n [\"owner\", \"the identity hub gives one owner at most 100 new clients an hour\"],\n [\"new_owners\", \"the identity hub takes at most 50 new owners an hour\"],\n]);\n\nconst Refusal = Schema.Struct({ reason: Schema.String });\nconst RateLimited = Schema.Struct({ window: Schema.String });\n/** A 400 for a connector the hub does not offer or allow, with the names it allows. */\nconst InvalidConnectors = Schema.Struct({\n error: Schema.Literal(\"invalid_connectors\"),\n allowed: Schema.Array(Schema.String),\n});\n\n/**\n * The text of a refusal: a known reason of a 403 or window of a 429, the allowed connectors of an\n * `invalid_connectors` 400 (only names of the connector grammar, so no other text of the answer is\n * printed), else the text of its status.\n */\nconst refusalOf = (status: number, body: unknown): string => {\n const decoded = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>\n Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));\n const ofStatus = () => REFUSALS[status] ?? \"the identity hub refused the request\";\n switch (status) {\n case 400: {\n const allowed = decoded(InvalidConnectors)?.allowed.filter((name) =>\n CONNECTOR_NAME.test(name),\n );\n return allowed === undefined\n ? ofStatus()\n : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? \"none for this app\" : allowed.join(\", \")}`;\n }\n case 403:\n return NOT_ALLOWED.get(decoded(Refusal)?.reason ?? \"\") ?? ofStatus();\n case 429:\n return RATE_LIMITED.get(decoded(RateLimited)?.window ?? \"\") ?? ofStatus();\n default:\n return ofStatus();\n }\n};\n\nconst send = (who: string, url: string, token: string, init: { method: string; body?: string }) =>\n Effect.tryPromise({\n try: async () => {\n const response = await fetch(url, {\n ...init,\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n const body: unknown = await response.json().catch(() => undefined);\n return { status: response.status, body };\n },\n catch: () => new SharedHubClientFailed({ 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 SharedHubClientFailed({ 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 SharedHubClientFailed({\n reason: `GitHub gave no OIDC token (HTTP ${status})`,\n });\n }\n return (yield* decode(OidcToken, \"GitHub\")(body)).value;\n });\n\n/** `POST /hub-clients` with `bearer`: the GitHub OIDC token, or the app's initial access token. */\nconst requestNewClient = (\n props: SharedHubClientProps,\n connectors: readonly string[],\n bearer: string,\n) =>\n Effect.gen(function* () {\n const { hub } = props;\n const { body, status } = yield* send(\"The identity hub\", `${hub.issuer}/hub-clients`, bearer, {\n method: \"POST\",\n body: JSON.stringify({\n app: props.app,\n redirectUri: props.redirectUri,\n softwareVersion: props.softwareVersion ?? \"unknown\",\n connectors,\n }),\n });\n if (status !== 201) {\n const reason =\n status === 401 && props.deploymentType === \"development\"\n ? \"the identity hub refused the initial access token\"\n : refusalOf(status, body);\n return yield* new SharedHubClientFailed({ reason: `${reason} (HTTP ${status})` });\n }\n const client = yield* decode(NewClient, \"The identity hub\")(body);\n // The hub registers the address and the connectors that the request sent, under its own issuer\n // and the terms that the stack names. The log and the state hold the stack's, so no value that\n // the answer chose is printed or kept.\n if (\n client.issuer !== hub.issuer ||\n client.redirect_uri !== props.redirectUri ||\n !sameSet(client.connectors, connectors) ||\n client.terms !== hub.terms\n ) {\n return yield* new SharedHubClientFailed({ reason: \"The identity hub gave a bad answer\" });\n }\n yield* Effect.logInfo(\n `Convex.SharedHubClient: ${props.app} on ${props.redirectUri} has a new client of the identity hub. Its use is under ${hub.terms}.`,\n );\n // Only a production registration gives the app's token (RFC 7591); any other answer's is dropped.\n const production = props.deploymentType === \"production\";\n return {\n status: \"on\" as const,\n issuer: hub.issuer,\n clientId: client.client_id,\n clientSecret: Redacted.make(client.client_secret),\n registrationAccessToken: Redacted.make(client.registration_access_token),\n registrationClientUri: client.registration_client_uri,\n deploymentType: props.deploymentType,\n redirectUri: props.redirectUri,\n connectors,\n initialAccessToken: Redacted.make(production ? (client.initial_access_token ?? \"\") : \"\"),\n repository: production ? (client.repository ?? \"\") : \"\",\n };\n });\n\n/** A new client, or the off values. */\nconst newClient = (props: SharedHubClientProps, connectors: readonly string[]) => {\n const label = `Convex.SharedHubClient: ${props.app} on ${props.redirectUri} deploys without the hub`;\n const off = offAttributes(props.deploymentType);\n const request = (bearer: Effect.Effect<string, SharedHubClientFailed>) =>\n bearer.pipe(\n Effect.flatMap((token) => requestNewClient(props, connectors, token)),\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(\n Effect.as(off),\n ),\n ),\n );\n\n if (props.deploymentType === \"development\") {\n const token = Redacted.value(props.initialAccessToken);\n return token === \"\"\n ? Effect.logInfo(\n \"Convex.SharedHubClient: deploy to main once for hub sign-in in development.\",\n ).pipe(Effect.as(off))\n : request(Effect.succeed(token));\n }\n\n const requestUrl = process.env[\"ACTIONS_ID_TOKEN_REQUEST_URL\"];\n const requestToken = process.env[\"ACTIONS_ID_TOKEN_REQUEST_TOKEN\"];\n // A development machine, or another CI. In a workflow, `id-token: write` gives both, so a\n // workflow without them is a mistake to show, not a normal run.\n if (!requestUrl || !requestToken) {\n return (\n process.env[\"GITHUB_ACTIONS\"] === \"true\"\n ? Effect.logWarning(`${label}: this workflow needs the permission id-token: write.`)\n : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)\n ).pipe(Effect.as(off));\n }\n return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));\n};\n\n/**\n * The client after a read on the hub, or undefined when the hub says that the client is gone. A\n * read with no usable answer keeps the saved client, except for a required one: a required client\n * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,\n * and did not save because that run failed, cannot pass a run that the hub does not answer.\n */\nconst renew = (saved: SharedHubClientAttributes, required: boolean) =>\n Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n saved.registrationClientUri,\n Redacted.value(saved.registrationAccessToken),\n { method: \"GET\" },\n );\n switch (status) {\n case 200:\n return { ...saved, status: \"on\" as const };\n case 401:\n return undefined;\n case 403:\n yield* Effect.logWarning(\n `Convex.SharedHubClient: the hub suspended the client of ${saved.redirectUri}. It keeps its values, and nobody can sign in with it.`,\n );\n return { ...saved, status: \"suspended\" as const };\n default:\n return yield* new SharedHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n required\n ? Effect.fail(\n new SharedHubClientFailed({\n reason: `${saved.redirectUri} is required, and the hub did not confirm its client: ${error.reason}`,\n }),\n )\n : Effect.logWarning(\n `Convex.SharedHubClient: ${saved.redirectUri} keeps the saved client: ${error.reason}.`,\n ).pipe(Effect.as(saved)),\n ),\n );\n\n/** A saved row of this resource, whose `attr` `savedAttributes` reads. */\nconst SavedRow = Schema.Struct({\n resourceType: Schema.Literal(\"IdentityHub.SharedClient\"),\n attr: Schema.Unknown,\n});\n\n/**\n * The attributes of the client `id` in another stage of this stack, such as\n * `read(\"HubClient\", { stage: \"prod\" })` in a development stage, as Outputs: the\n * `initialAccessToken` and the `repository` of the production client. Without that row, the off\n * attributes, with `deploymentType: \"production\"`.\n *\n * `SharedHubClient.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the\n * row is missing, and a development stage before the first deploy to main has none. This read runs\n * when the plan resolves it, with the State service of the running stack and its `get`, so it never\n * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every\n * read.\n */\nconst read = (id: string, options: { readonly stage: string }) =>\n Output.fromEffect(\n Effect.gen(function* () {\n const stack = yield* Stack;\n const state = yield* yield* State;\n const row = yield* state\n .get({ stack: stack.name, stage: options.stage, fqn: id })\n .pipe(Effect.orDie);\n if (row === undefined) return offAttributes(\"production\");\n const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(\n Effect.catchCause(() =>\n Effect.die(\n new SharedHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not a Convex.SharedHubClient`,\n }),\n ),\n ),\n );\n const saved = yield* savedAttributes(attr);\n if (saved === undefined) {\n return yield* Effect.die(\n new SharedHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`,\n }),\n );\n }\n return saved;\n }),\n );\n\n/**\n * The three values that the app's deployment gets, such as `HUB_ISSUER`, `HUB_CLIENT_ID`, and\n * `HUB_CLIENT_SECRET`, as Outputs: the client's values when `status` is `on`, else the off values,\n * so that a suspended client gives guest sign-in and keeps its values in state.\n */\nconst variables = (client: SharedHubClient) =>\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 SharedHubClient = Resource<\n \"IdentityHub.SharedClient\",\n SharedHubClientProps,\n SharedHubClientAttributes,\n never,\n Providers\n>;\nexport const SharedHubClient = Resource<SharedHubClient>(\"IdentityHub.SharedClient\")({\n read,\n variables,\n});\n\nexport const SharedHubClientProvider = () =>\n Provider.succeed(SharedHubClient, {\n // Always an update, so that each deploy reaches the hub. No attribute is stable, so a push\n // reads the values that this run ended with. The same values cause no other push.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n // Only a client of the same hub (its issuer), return address, type, and connector set is\n // renewed. A saved row without this version's shape, such as one that 0.32 or earlier saved, is\n // no client: the run asks for a new one, which replaces the saved client, and for a production\n // client also replaces the app's initial access token.\n reconcile: Effect.fn(function* ({ news, output }) {\n // A bad prop is a mistake of the stack, not of the hub: the run fails, with no request.\n if (\n news.connectors.length === 0 ||\n !news.connectors.every((name) => CONNECTOR_NAME.test(name))\n ) {\n return yield* new SharedHubClientFailed({\n reason: `${news.app} on ${news.redirectUri} needs connectors: one or more names of [a-z0-9-]{1,64}`,\n });\n }\n const connectors = connectorSet(news.connectors);\n const saved =\n output === undefined || output.status === \"off\"\n ? undefined\n : yield* savedAttributes(output);\n if (output !== undefined && output.status !== \"off\" && saved === undefined) {\n yield* Effect.logWarning(\n `Convex.SharedHubClient: the saved attributes of ${news.app} on ${news.redirectUri} cannot be read by this version, so this run registers a new client, which replaces the saved one.`,\n );\n }\n const renewed =\n saved?.issuer === news.hub.issuer &&\n saved.redirectUri === news.redirectUri &&\n saved.deploymentType === news.deploymentType &&\n sameSet(saved.connectors, connectors)\n ? yield* renew(saved, news.required === true)\n : undefined;\n const client = renewed ?? (yield* newClient(news, connectors));\n if (news.required === true && client.status !== \"on\") {\n return yield* new SharedHubClientFailed({\n reason: `${news.app} on ${news.redirectUri} is required and has no working client (${client.status}). The warning above names the reason`,\n });\n }\n return client;\n }),\n\n // A failed delete does not stop a destroy: the removal date of a preview or development client\n // cleans it up. A destroy can leave a production deployment running, so its client stays.\n delete: ({ output }) =>\n output.deploymentType === \"production\" || output.status === \"off\"\n ? Effect.void\n : Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n output.registrationClientUri,\n Redacted.value(output.registrationAccessToken),\n { method: \"DELETE\" },\n );\n // 401: the client is gone already.\n if (status !== 204 && status !== 401) {\n return yield* new SharedHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n Effect.logWarning(\n `Convex.SharedHubClient: the client of ${output.redirectUri} stays on the hub until its removal date: ${error.reason}.`,\n ),\n ),\n ),\n });\n","// The provider collection users merge into a stack:\n// providers: Layer.mergeAll(Cloudflare.providers(), Convex.providers())\nimport * as Provider from \"alchemy/Provider\";\nimport * as Layer from \"effect/Layer\";\nimport { type Credentials, fromConfig } from \"./Credentials.ts\";\nimport { DeploymentProvider, DeploymentResource } from \"./Deployment.ts\";\nimport { LocalDeployment, LocalDeploymentProvider } from \"./LocalDeployment.ts\";\nimport { ManagementApiLive } from \"./ManagementApi.ts\";\nimport { Project, ProjectProvider } from \"./Project.ts\";\nimport { SharedHubClient, SharedHubClientProvider } from \"./SharedHubClient.ts\";\n\nexport class Providers extends Provider.ProviderCollection<Providers>()(\"Convex\") {}\n\n/**\n * The Convex resource providers. Pass a credentials layer to override the\n * default lookup (`CONVEX_ACCESS_TOKEN`, then the Convex CLI login, and\n * `CONVEX_DEPLOY_KEY`).\n */\nexport const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>\n Layer.effect(\n Providers,\n Provider.collection([Project, DeploymentResource, LocalDeployment, SharedHubClient]),\n ).pipe(\n Layer.provide(\n Layer.mergeAll(\n ProjectProvider(),\n DeploymentProvider(),\n LocalDeploymentProvider(),\n SharedHubClientProvider(),\n ),\n ),\n Layer.provide(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B,OAAO,WAAW,QACxD,OAAO,OACP,OAAO,IAAI,aAAa;EACtB,MAAM,EAAE,WAAW,OAAO,KACxB,oBACA,OAAO,uBACP,SAAS,MAAM,OAAO,uBAAuB,GAC7C,EAAE,QAAQ,SAAS,CACrB;EAEA,IAAI,WAAW,OAAO,WAAW,KAC/B,OAAO,OAAO,IAAI,sBAAsB,EACtC,QAAQ,kCAAkC,SAC5C,CAAC;CAEL,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,0BAA0B,UACxC,OAAO,WACL,yCAAyC,OAAO,YAAY,4CAA4C,MAAM,OAAO,EACvH,CACF,CACF;AACR,CAAC;;;AClmBH,IAAa,YAAb,cAA+B,SAAS,mBAA8B,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;;;;;;AAOnF,MAAa,aAAa,cAAwC,WAAW,MAC3E,MAAM,OACJ,WACA,SAAS,WAAW;CAAC;CAAS;CAAoB;CAAiB;AAAe,CAAC,CACrF,CAAC,CAAC,KACA,MAAM,QACJ,MAAM,SACJ,gBAAgB,GAChB,mBAAmB,GACnB,wBAAwB,GACxB,wBAAwB,CAC1B,CACF,GACA,MAAM,QAAQ,kBAAkB,CAAC,GACjC,MAAM,QAAQ,WAAW,GACzB,MAAM,KACR"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["IdentityHub.Client","IdentityHub.ClientProvider"],"sources":["../src/Component.ts","../src/LocalDeployment.ts","../src/Providers.ts"],"sourcesContent":["import { toPath } from \"alchemy/FQN\";\nimport type { NamespaceNode } from \"alchemy/Namespace\";\nimport { Stack } from \"alchemy/Stack\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport type { Deployment } from \"./Deployment.ts\";\n\n/** A component's resources occupy this namespace in the deployment's Alchemy stack and stage. */\nexport interface ComponentBinding {\n readonly type: \"component\";\n readonly path: string;\n readonly namespace: readonly string[];\n}\n\n/**\n * Associate a native namespace with an installed component. `component` is the\n * installed name from the app's `convex.config.ts`; a nested install joins the\n * names with slashes, such as `\"workspace/mail\"`. An undefined namespace\n * associates the stack root. This records display metadata; it does not install\n * the component, set its environment, or change removal policies.\n */\nexport const bindComponent = (options: {\n deployment: Deployment;\n component: string;\n namespace: NamespaceNode | undefined;\n}) =>\n Effect.gen(function* () {\n if (options.component === \"\") {\n return yield* Effect.die(new Error(\"The component name is empty.\"));\n }\n const namespace = toPath(options.namespace);\n const sid = `convex.component:${JSON.stringify(namespace)}`;\n const stack = yield* Stack;\n const previous = stack.bindings[options.deployment.FQN]?.find((binding) => binding.sid === sid);\n // Alchemy keeps the last binding with a given sid. Reject conflicting owners before that happens.\n if (previous !== undefined) {\n const existing = Schema.decodeUnknownSync(Schema.Struct({ path: Schema.String }))(\n previous.data,\n );\n if (existing.path !== options.component) {\n return yield* Effect.die(\n new Error(\n `Alchemy namespace ${JSON.stringify(namespace)} is already bound to ${existing.path}.`,\n ),\n );\n }\n return;\n }\n yield* options.deployment.bind(sid, {\n type: \"component\",\n path: options.component,\n namespace,\n });\n });\n","// Convex.LocalDeployment: the logged-in local deployment of one folder, which\n// `npx convex deployment create <team>:<project>:local --select` makes and `npx convex dev` runs on\n// this machine. Each folder, such as each git worktree, has its own, with its own data.\n//\n// The resource writes its `env` and nothing else. The running `convex dev` owns the backend and\n// pushes the functions, so the development stage runs after `convex dev` has started, and the\n// first push of a new local deployment takes the variables that the project's default variables\n// for development gave it. The resource reads the deployment from\n// `.convex/local/default/config.json`, where the Convex CLI keeps its name, ports, and admin key,\n// and writes with that admin key through the same call as for a cloud deployment.\n//\n// A destroy changes nothing: the folder's deployment and its variables stay with the folder.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Provider from \"alchemy/Provider\";\nimport * as Effect from \"effect/Effect\";\nimport * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\nimport * as Schema from \"effect/Schema\";\nimport { readLocalDeployment } from \"./ManagementApi.ts\";\nimport type { Providers } from \"./Providers.ts\";\nimport { type EnvValue, push } from \"./Push.ts\";\n\n/** The folder has no logged-in local deployment. */\nexport class LocalDeploymentNotFound extends Schema.TaggedError<LocalDeploymentNotFound>()(\n \"LocalDeploymentNotFound\",\n { rootDir: Schema.String },\n) {\n override get message() {\n return `Convex.LocalDeployment: ${this.rootDir} has no logged-in local deployment. Run \\`npx convex deployment create <team>:<project>:local --select\\` there, then \\`npx convex dev\\`.`;\n }\n}\n\n/**\n * The folder's logged-in local deployment, read when the stack's program runs, so that a client\n * can take its `siteUrl`. Fails with `LocalDeploymentNotFound` when the folder has none.\n */\nconst of = (rootDir = \".\") => {\n const info = readLocalDeployment(rootDir);\n if (info === undefined) throw new LocalDeploymentNotFound({ rootDir });\n return { name: info.name, url: info.url, siteUrl: info.siteUrl };\n};\n\nexport interface LocalDeploymentProps {\n /** The folder of the Convex app, where `.convex/local/default` is. The working directory without it. */\n readonly rootDir?: string;\n /** The variables of the deployment. A name that leaves `env` is removed. */\n readonly env: Readonly<Record<string, EnvValue>>;\n}\n\nexport interface LocalDeploymentAttributes {\n readonly name: string;\n readonly url: string;\n readonly siteUrl: string;\n /** The names that this resource set, so a name that leaves `env` is removed. */\n readonly envNames: readonly string[];\n}\n\nexport type LocalDeployment = Resource<\n \"Convex.LocalDeployment\",\n LocalDeploymentProps,\n LocalDeploymentAttributes,\n never,\n Providers\n>;\nexport const LocalDeployment = Resource<LocalDeployment>(\"Convex.LocalDeployment\")({ of });\n\nexport const LocalDeploymentProvider = () =>\n Provider.effect(\n LocalDeployment,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return {\n // Always an update: the variables are read and only changed values are written.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n reconcile: Effect.fn(function* ({ news, output }) {\n const rootDir = news.rootDir ?? \".\";\n const info = readLocalDeployment(rootDir);\n if (info === undefined) return yield* new LocalDeploymentNotFound({ rootDir });\n // Without `source`, a push only sets the variables and removes the names that left `env`.\n yield* push(spawner, info.adminKey, {\n deployment: info.name,\n url: info.url,\n rootDir,\n source: undefined,\n env: news.env,\n previousEnvNames: output?.name === info.name ? output.envNames : [],\n adopt: true,\n previewName: undefined,\n });\n return {\n name: info.name,\n url: info.url,\n siteUrl: info.siteUrl,\n envNames: Object.keys(news.env).sort(),\n };\n }),\n\n delete: () => Effect.void,\n };\n }),\n );\n","// The provider collection users merge into a stack:\n// providers: Layer.mergeAll(Cloudflare.providers(), Convex.providers())\nimport * as Provider from \"alchemy/Provider\";\nimport * as Layer from \"effect/Layer\";\nimport { type Credentials, fromConfig } from \"./Credentials.ts\";\nimport { DeploymentProvider, DeploymentResource } from \"./Deployment.ts\";\nimport * as IdentityHub from \"./IdentityHub.ts\";\nimport { LocalDeployment, LocalDeploymentProvider } from \"./LocalDeployment.ts\";\nimport { ManagementApiLive } from \"./ManagementApi.ts\";\nimport { Project, ProjectProvider } from \"./Project.ts\";\n\nexport class Providers extends Provider.ProviderCollection<Providers>()(\"Convex\") {}\n\n/**\n * The Convex resource providers. Pass a credentials layer to override the\n * default lookup (`CONVEX_ACCESS_TOKEN`, then the Convex CLI login, and\n * `CONVEX_DEPLOY_KEY`).\n */\nexport const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>\n Layer.effect(\n Providers,\n Provider.collection([Project, DeploymentResource, LocalDeployment, IdentityHub.Client]),\n ).pipe(\n Layer.provide(\n Layer.mergeAll(\n ProjectProvider(),\n DeploymentProvider(),\n LocalDeploymentProvider(),\n IdentityHub.ClientProvider(),\n ),\n ),\n Layer.provide(ManagementApiLive()),\n Layer.provide(credentials),\n Layer.orDie,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,MAAa,iBAAiB,YAK5B,OAAO,IAAI,aAAa;CACtB,IAAI,QAAQ,cAAc,IACxB,OAAO,OAAO,OAAO,oBAAI,IAAI,MAAM,8BAA8B,CAAC;CAEpE,MAAM,YAAY,OAAO,QAAQ,SAAS;C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G,WAAW,EAAE,MAAM,UAAU;GAChD,MAAM,UAAU,KAAK,WAAW;GAChC,MAAM,OAAO,oBAAoB,OAAO;GACxC,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,IAAI,wBAAwB,EAAE,QAAQ,CAAC;GAE7E,OAAO,KAAK,SAAS,KAAK,UAAU;IAClC,YAAY,KAAK;IACjB,KAAK,KAAK;IACV;IACA,QAAQ,KAAA;IACR,KAAK,KAAK;IACV,kBAAkB,QAAQ,SAAS,KAAK,OAAO,OAAO,WAAW,CAAC;IAClE,OAAO;IACP,aAAa,KAAA;GACf,CAAC;GACD,OAAO;IACL,MAAM,KAAK;IACX,KAAK,KAAK;IACV,SAAS,KAAK;IACd,UAAU,OAAO,KAAK,KAAK,GAAG,CAAC,CAAC,KAAK;GACvC;EACF,CAAC;EAED,cAAc,OAAO;CACvB;AACF,CAAC,CACH;;;AC7FF,IAAa,YAAb,cAA+B,SAAS,mBAA8B,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;;;;;;AAOnF,MAAa,aAAa,cAAwC,WAAW,MAC3E,MAAM,OACJ,WACA,SAAS,WAAW;CAAC;CAAS;CAAoB;CAAiBA;AAAkB,CAAC,CACxF,CAAC,CAAC,KACA,MAAM,QACJ,MAAM,SACJ,gBAAgB,GAChB,mBAAmB,GACnB,wBAAwB,GACxBC,eAA2B,CAC7B,CACF,GACA,MAAM,QAAQ,kBAAkB,CAAC,GACjC,MAAM,QAAQ,WAAW,GACzB,MAAM,KACR"}
|
|
@@ -41,14 +41,6 @@ const parseKeyRing = (name, text) => {
|
|
|
41
41
|
const newKeyId = () => Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6)), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
42
42
|
/** A random key of 32 bytes in base64. It needs real randomness, like `sealSecret`. */
|
|
43
43
|
const newKey = () => toBase64(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
|
|
44
|
-
/** The text of a new key ring with one random key. */
|
|
45
|
-
const newKeyRing = () => {
|
|
46
|
-
const keyId = newKeyId();
|
|
47
|
-
return JSON.stringify({
|
|
48
|
-
current: keyId,
|
|
49
|
-
keys: { [keyId]: newKey() }
|
|
50
|
-
});
|
|
51
|
-
};
|
|
52
44
|
const importKey = (ring, keyId) => {
|
|
53
45
|
const bytes = ring.keys.get(keyId);
|
|
54
46
|
if (bytes === void 0) throw new Error(`The key ring has no key "${keyId}".`);
|
|
@@ -81,6 +73,6 @@ const openSecret = async (ring, args) => {
|
|
|
81
73
|
return new TextDecoder().decode(plaintext);
|
|
82
74
|
};
|
|
83
75
|
//#endregion
|
|
84
|
-
export {
|
|
76
|
+
export { sealSecret as a, parseKeyRing as i, newKeyId as n, openSecret as r, newKey as t };
|
|
85
77
|
|
|
86
|
-
//# sourceMappingURL=sealedSecret-
|
|
78
|
+
//# sourceMappingURL=sealedSecret-B7HlvIg2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sealedSecret-B7HlvIg2.js","names":[],"sources":["../src/store/sealedSecret.ts"],"sourcesContent":["// AES-256-GCM sealing under a key ring, with Web Crypto only, so that it runs in Convex and in Node.\n//\n// A key ring is the JSON text `{\"current\":\"<keyId>\",\"keys\":{\"<keyId>\":\"<base64 of 32 bytes>\"}}`,\n// which a deployment keeps in one environment variable. `sealSecret` seals with the `current` key.\n// `openSecret` opens with the key that the sealed object names, so an old key stays in the ring\n// until a reseal moves its values to the current key.\n//\n// Seal only where randomness is real: in a Convex action, or outside Convex. In a Convex query or\n// mutation `crypto.getRandomValues` is a seeded deterministic generator, and a repeated IV under one\n// key breaks AES-GCM. Opening draws no randomness, so a query can open.\n\n/** A value sealed with AES-256-GCM under the key `keyId` of a key ring. */\nexport interface SealedSecret {\n readonly keyId: string;\n /** 12 random bytes, base64url. */\n readonly iv: string;\n /** The AES-GCM output with its 16-byte tag, base64url. */\n readonly ciphertext: string;\n}\n\nexport interface KeyRing {\n readonly current: string;\n readonly keys: ReadonlyMap<string, Uint8Array<ArrayBuffer>>;\n}\n\nconst toBase64 = (bytes: Uint8Array) =>\n btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(\"\"));\n\nconst toBase64Url = (bytes: Uint8Array) =>\n toBase64(bytes).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/, \"\");\n\n/** The bytes of base64 or base64url text. */\nconst fromBase64 = (text: string) => {\n const standard = text.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n const padded = standard.padEnd(standard.length + ((4 - (standard.length % 4)) % 4), \"=\");\n return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));\n};\n\n/** A key of 32 bytes in base64 is 43 characters and one `=`. */\nconst KEY_TEXT = /^[A-Za-z0-9+/]{43}=$/;\n\n/**\n * The key ring in the text of the variable `name`. It fails closed when the text is missing or\n * malformed, or when the current key id has no key. An error never quotes the text, which holds\n * the keys.\n */\nexport const parseKeyRing = (name: string, text: string | undefined): KeyRing => {\n let value: unknown;\n try {\n value = JSON.parse(text ?? \"\");\n } catch {\n throw new Error(`${name} is missing or is not JSON.`);\n }\n const malformed = new Error(\n `${name} must be {\"current\":\"<keyId>\",\"keys\":{\"<keyId>\":\"<base64 of 32 bytes>\"}}.`,\n );\n if (typeof value !== \"object\" || value === null) throw malformed;\n if (!(\"current\" in value) || !(\"keys\" in value)) throw malformed;\n const { current, keys: keyTexts } = value;\n if (typeof current !== \"string\" || typeof keyTexts !== \"object\" || keyTexts === null) {\n throw malformed;\n }\n const keys = new Map<string, Uint8Array<ArrayBuffer>>();\n for (const [keyId, key] of Object.entries(keyTexts)) {\n if (typeof key !== \"string\" || !KEY_TEXT.test(key)) throw malformed;\n keys.set(keyId, fromBase64(key));\n }\n if (!keys.has(current)) throw new Error(`${name} has no key for its current key id.`);\n return { current, keys };\n};\n\n/** A random key id of 12 hexadecimal characters, which is also safe in a variable name. */\nexport const newKeyId = (): string =>\n Array.from(crypto.getRandomValues(new Uint8Array(6)), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n\n/** A random key of 32 bytes in base64. It needs real randomness, like `sealSecret`. */\nexport const newKey = (): string => toBase64(crypto.getRandomValues(new Uint8Array(32)));\n\nconst importKey = (ring: KeyRing, keyId: string) => {\n const bytes = ring.keys.get(keyId);\n if (bytes === undefined) throw new Error(`The key ring has no key \"${keyId}\".`);\n return crypto.subtle.importKey(\"raw\", bytes, \"AES-GCM\", false, [\"encrypt\", \"decrypt\"]);\n};\n\n/** Seals `plaintext` with the current key. `aad` names the owner, so the value opens only there. */\nexport const sealSecret = async (\n ring: KeyRing,\n args: { readonly plaintext: string; readonly aad: string },\n): Promise<SealedSecret> => {\n const key = await importKey(ring, ring.current);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ciphertext = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: new TextEncoder().encode(args.aad) },\n key,\n new TextEncoder().encode(args.plaintext),\n );\n return {\n keyId: ring.current,\n iv: toBase64Url(iv),\n ciphertext: toBase64Url(new Uint8Array(ciphertext)),\n };\n};\n\n/** Opens a sealed value with the key it names. A different `aad` or a changed value fails. */\nexport const openSecret = async (\n ring: KeyRing,\n args: { readonly sealed: SealedSecret; readonly aad: string },\n): Promise<string> => {\n const { sealed } = args;\n const key = await importKey(ring, sealed.keyId);\n const plaintext = await crypto.subtle.decrypt(\n {\n name: \"AES-GCM\",\n iv: fromBase64(sealed.iv),\n additionalData: new TextEncoder().encode(args.aad),\n },\n key,\n fromBase64(sealed.ciphertext),\n );\n return new TextDecoder().decode(plaintext);\n};\n"],"mappings":";AAyBA,MAAM,YAAY,UAChB,KAAK,MAAM,KAAK,QAAQ,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;AAEtE,MAAM,eAAe,UACnB,SAAS,KAAK,CAAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;;AA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AW,EAAE,CAAC,CAAC;AAEvF,MAAM,aAAa,MAAe,UAAkB;CAClD,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK;CACjC,IAAI,UAAU,KAAA,GAAW,MAAM,IAAI,MAAM,4BAA4B,MAAM,GAAG;CAC9E,OAAO,OAAO,OAAO,UAAU,OAAO,OAAO,WAAW,OAAO,CAAC,WAAW,SAAS,CAAC;AACvF;;AAGA,MAAa,aAAa,OACxB,MACA,SAC0B;CAC1B,MAAM,MAAM,MAAM,UAAU,MAAM,KAAK,OAAO;CAC9C,MAAM,KAAK,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC;CACpD,MAAM,aAAa,MAAM,OAAO,OAAO,QACrC;EAAE,MAAM;EAAW;EAAI,gBAAgB,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,GAAG;CAAE,GAC1E,KACA,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,SAAS,CACzC;CACA,OAAO;EACL,OAAO,KAAK;EACZ,IAAI,YAAY,EAAE;EAClB,YAAY,YAAY,IAAI,WAAW,UAAU,CAAC;CACpD;AACF;;AAGA,MAAa,aAAa,OACxB,MACA,SACoB;CACpB,MAAM,EAAE,WAAW;CACnB,MAAM,MAAM,MAAM,UAAU,MAAM,OAAO,KAAK;CAC9C,MAAM,YAAY,MAAM,OAAO,OAAO,QACpC;EACE,MAAM;EACN,IAAI,WAAW,OAAO,EAAE;EACxB,gBAAgB,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,GAAG;CACnD,GACA,KACA,WAAW,OAAO,UAAU,CAC9B;CACA,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,SAAS;AAC3C"}
|
package/lib/sealedSecret.d.ts
CHANGED
|
@@ -21,8 +21,6 @@ export declare const parseKeyRing: (name: string, text: string | undefined) => K
|
|
|
21
21
|
export declare const newKeyId: () => string;
|
|
22
22
|
/** A random key of 32 bytes in base64. It needs real randomness, like `sealSecret`. */
|
|
23
23
|
export declare const newKey: () => string;
|
|
24
|
-
/** The text of a new key ring with one random key. */
|
|
25
|
-
export declare const newKeyRing: () => string;
|
|
26
24
|
/** Seals `plaintext` with the current key. `aad` names the owner, so the value opens only there. */
|
|
27
25
|
export declare const sealSecret: (ring: KeyRing, args: {
|
|
28
26
|
readonly plaintext: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sealedSecret.d.ts","names":[],"sources":["../src/store/sealedSecret.ts"],"mappings":";;iBAYiB;WACN;;WAEA;;WAEA;;iBAGM;WACN;WACA,MAAM,oBAAoB,WAAW;;;;;;;qBAwBnC,eAAgB,cAAc,6BAA2B;;qBA0BzD;;qBAMA;;
|
|
1
|
+
{"version":3,"file":"sealedSecret.d.ts","names":[],"sources":["../src/store/sealedSecret.ts"],"mappings":";;iBAYiB;WACN;;WAEA;;WAEA;;iBAGM;WACN;WACA,MAAM,oBAAoB,WAAW;;;;;;;qBAwBnC,eAAgB,cAAc,6BAA2B;;qBA0BzD;;qBAMA;;qBASA,aACX,MAAM,SACN;WAAiB;WAA4B;MAC5C,QAAQ;;qBAgBE,aACX,MAAM,SACN;WAAiB,QAAQ;WAAuB;MAC/C"}
|
package/lib/sealedSecret.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as newKey, n as newKeyId, r as
|
|
1
|
+
export { t as newKey, n as newKeyId, r as openSecret, i as parseKeyRing, a as sealSecret } from "./sealedSecret-B7HlvIg2.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@samebase/alchemy-convex",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.37.0",
|
|
4
4
|
"description": "The Convex plane for Alchemy v2: projects, deployments, environment variables, and the push of the functions",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"alchemy",
|
|
@@ -36,6 +36,10 @@
|
|
|
36
36
|
"types": "./lib/index.d.ts",
|
|
37
37
|
"import": "./lib/index.js"
|
|
38
38
|
},
|
|
39
|
+
"./identity-hub": {
|
|
40
|
+
"types": "./lib/IdentityHub.d.ts",
|
|
41
|
+
"import": "./lib/IdentityHub.js"
|
|
42
|
+
},
|
|
39
43
|
"./sealed-secret": {
|
|
40
44
|
"types": "./lib/sealedSecret.d.ts",
|
|
41
45
|
"import": "./lib/sealedSecret.js"
|
package/src/Deployment.ts
CHANGED
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
// `source.command` replaces `convex deploy`, such as `convex-hosting
|
|
18
18
|
// deploy`, and `source.include` adds the files that it reads to the hash.
|
|
19
19
|
// - `env` is set on the deployment before the push. A name that leaves `env`
|
|
20
|
-
// is removed
|
|
20
|
+
// is removed after a successful push, because the code that runs until then
|
|
21
|
+
// can require it; without `source`, with the new values. A variable that exists with another value and that this
|
|
21
22
|
// resource did not set is someone else's: it is overwritten only with
|
|
22
23
|
// --adopt. Delete leaves the variables: they go with the deployment.
|
|
23
24
|
// - Credentials by scope (see Access below): a deploy key of the deployment,
|