@midsummer-ai/sdk 0.1.0-next.901 → 0.1.0-staging.3100

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.
Files changed (40) hide show
  1. package/auth-1W-SzpD3.mjs +441 -0
  2. package/build-DQo-JrlN.d.mts +120 -0
  3. package/bytes-C2pcyl9u.mjs +280 -0
  4. package/{connection-CDk7H1FL.mjs → connection-Cu2GSOaR.mjs} +171 -31
  5. package/database/build.d.mts +2 -2
  6. package/database/build.mjs +1404 -117
  7. package/database/client.d.mts +85 -9
  8. package/database/client.mjs +550 -32
  9. package/database/contract.d.mts +92 -2
  10. package/database/contract.mjs +2179 -3
  11. package/database/errors.d.mts +1 -22
  12. package/database/react.d.mts +133 -0
  13. package/database/react.mjs +488 -0
  14. package/database/server.d.mts +2 -3
  15. package/database/server.mjs +3 -320
  16. package/database/stand-in.d.mts +95 -9
  17. package/database/stand-in.mjs +1436 -116
  18. package/errors-x2vXKi0u.d.mts +25 -0
  19. package/index-DNNXNny7.d.mts +410 -0
  20. package/key-BrRdFY-n.mjs +11 -0
  21. package/package.json +114 -1
  22. package/schema-CTHQMRsW.mjs +217 -0
  23. package/server-B5HK2Ou9.d.mts +574 -0
  24. package/server-EDRbF2u-.mjs +1893 -0
  25. package/{store-BzI9at5x.mjs → store-lIZ5GxVv.mjs} +1 -1
  26. package/{tabs-D-P8_ci_.mjs → tabs-zCh8kceo.mjs} +1 -1
  27. package/vector/contract.d.mts +1 -1
  28. package/vector/contract.mjs +773 -1
  29. package/vector/index.d.mts +2 -2
  30. package/vector/index.mjs +71 -3
  31. package/vector/stand-in.d.mts +1 -1
  32. package/vector/stand-in.mjs +326 -23
  33. package/vector/wire.d.mts +11 -2
  34. package/vector/wire.mjs +179 -14
  35. package/build-SQ44jwSa.d.mts +0 -41
  36. package/index-DdoK0y7D.d.mts +0 -192
  37. package/schema-BF-Y1EVu.mjs +0 -142
  38. package/schema-DS8x1Dn8.mjs +0 -115
  39. package/schema-f7E9uzUn.d.mts +0 -74
  40. package/server-C7O7CICU.d.mts +0 -182
@@ -0,0 +1,441 @@
1
+ import { DatabaseError } from "./database/errors.mjs";
2
+ //#region src/database/auth.ts
3
+ /**
4
+ * Signing a Database's users in with the sign-in provider the app already has: Auth0, Clerk or any
5
+ * OIDC issuer. The Project declares whom its Database trusts in `db/auth.config.ts`, deployed with its
6
+ * functions, so a rollback rolls it back too:
7
+ *
8
+ * export default {
9
+ * providers: [
10
+ * // An OIDC issuer: its keys are found through its discovery document.
11
+ * { domain: "https://acme.us.auth0.com/", applicationID: "yourClientId" },
12
+ * // Any issuer of JWTs, with its key set's address (or a `data:` URI of it) and its algorithm.
13
+ * { type: "customJwt", issuer: "https://auth.acme.dev", jwks: "https://auth.acme.dev/jwks.json", algorithm: "ES256", applicationID: "acme" },
14
+ * ],
15
+ * // Left out, callers with no token run every public function, and `ctx.auth.getUserIdentity()` gives them null.
16
+ * anonymous: false,
17
+ * }
18
+ *
19
+ * As in Convex: a Database with this file admits callers with no token unless `anonymous` is false, an OIDC
20
+ * provider's tokens must name its `applicationID` in their `aud`, and a `customJwt` provider's must when it names
21
+ * one. A value may be `process.env.NAME`, read where the Database runs, and is never shown in a refusal or a log.
22
+ * At most 8 providers; every address is https, and never a private one.
23
+ *
24
+ * `verifier(trusted)` checks a token as a Database does, and nothing about it is believed before it passes:
25
+ * an RS256 (RSA of at least 2048 bits) or ES256 (P-256) signature, by a key the issuer publishes; its `iss`
26
+ * exactly one the Database trusts; its `aud` naming that provider's audience; `exp`, and `nbf` and `iat` where
27
+ * given, with 60 s for the two clocks; and a `sub` of 1 to 256 characters. Key sets are kept 10 minutes, and
28
+ * kept past a failed fetch for a day; a provider that failed is asked again at most every 5 s; a token signed
29
+ * by a key the set doesn't have (`kid`) fetches it again, at most every 30 s. A discovery document or key set
30
+ * comes only from a public address, at most 64 KiB, cut off as it arrives.
31
+ */
32
+ const MAX_PROVIDERS = 8;
33
+ const MAX_VALUE = 256;
34
+ const MAX_DATA_JWKS = 16384;
35
+ const TOKEN_CHARS = 8192;
36
+ const FRESH_MS = 6e5;
37
+ const REFETCH_MS = 3e4;
38
+ const STALE_MS = 864e5;
39
+ /** How long a failed fetch is remembered before it is tried again, so a provider that is down is not asked once a token. */
40
+ const FAILED_MS = 5e3;
41
+ const FETCH_MS = 5e3;
42
+ const BODY_BYTES = 65536;
43
+ const B64URL = /^[A-Za-z0-9_-]+$/u;
44
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
45
+ /** Whether an IP address is one a sign-in provider's keys may come from: not loopback, private, link-local, shared or reserved. */
46
+ function publicAddress(address) {
47
+ const v4 = /^(?:::ffff:)?(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/iu.exec(address);
48
+ if (v4) {
49
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
50
+ return !(a === 0 || a === 10 || a === 127 || a >= 224 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 192 && b === 0 && Number(v4[3]) === 0 || a === 198 && (b === 18 || b === 19));
51
+ }
52
+ const v6 = address.toLowerCase().replace(/^\[|\]$/gu, "");
53
+ if (!v6.includes(":")) return false;
54
+ return !(v6 === "::" || v6 === "::1" || /^f[cd]/u.test(v6) || /^fe[89ab]/u.test(v6) || /^ff/u.test(v6) || v6.startsWith("::ffff:") || v6.startsWith("64:ff9b:"));
55
+ }
56
+ /** A host no address check is needed to refuse: a literal private address, or a name kept for local or internal use. */
57
+ const privateHost = (host) => {
58
+ const name = host.toLowerCase().replace(/^\[|\]$/gu, "").replace(/\.$/u, "");
59
+ if (/^[\d.]+$/u.test(name) || name.includes(":")) return !publicAddress(name);
60
+ return name === "localhost" || /\.(?:localhost|local|internal|home\.arpa)$/u.test(name);
61
+ };
62
+ /**
63
+ * Why a value of a provider is wrong, or null. `shown`: the value may be quoted, as it is written in the
64
+ * source; a value read from the environment never is.
65
+ */
66
+ function urlError(value, what, { data = false, shown = true } = {}) {
67
+ const quoted = shown ? `: ${JSON.stringify(value)}` : "";
68
+ if (data && value.startsWith("data:")) return value.length > MAX_DATA_JWKS ? `${what} is a data: URI of more than ${MAX_DATA_JWKS} characters` : /^data:application\/(?:jwk-set\+)?json(?:;base64)?,/u.test(value) ? null : `${what} is a data: URI of application/json`;
69
+ if (value.length > MAX_VALUE) return `${what} is longer than ${MAX_VALUE} characters`;
70
+ let url;
71
+ try {
72
+ url = new URL(value);
73
+ } catch {
74
+ return `${what} is not an address${quoted}`;
75
+ }
76
+ if (url.protocol !== "https:") return `${what} is an https address${quoted}`;
77
+ if (url.username || url.password || url.hash) return `${what} carries no credentials or fragment${shown ? `: ${url.origin}` : ""}`;
78
+ if (privateHost(url.hostname)) return `${what} is a public address, not a private or local one${shown ? `: ${url.hostname}` : ""}`;
79
+ return null;
80
+ }
81
+ /**
82
+ * `db/auth.config.ts`'s default export, checked. A value may be `{ env: NAME }` (`process.env.NAME` as written),
83
+ * checked once it is read. Throws an Error saying what is wrong.
84
+ */
85
+ function authConfigOf(value) {
86
+ if (!isObject(value)) throw new Error("auth.config is `export default { providers: [...] }`");
87
+ for (const key of Object.keys(value)) if (key !== "providers" && key !== "anonymous") throw new Error(`auth.config has no setting ${JSON.stringify(key)}: it takes providers and anonymous`);
88
+ const { providers = [], anonymous = true } = value;
89
+ if (typeof anonymous !== "boolean") throw new Error("auth.config's anonymous is true or false");
90
+ if (!Array.isArray(providers) || providers.length > MAX_PROVIDERS) throw new Error(`auth.config's providers is a list of at most ${MAX_PROVIDERS}`);
91
+ const configured = (provider, key, check) => {
92
+ const given = provider[key];
93
+ if (isObject(given) && typeof given.env === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(given.env) && Object.keys(given).length === 1) return { env: given.env };
94
+ if (typeof given !== "string") throw new Error(`a provider's ${key} is a string or process.env.NAME`);
95
+ const why = check(given);
96
+ if (why) throw new Error(why);
97
+ return given;
98
+ };
99
+ const audience = (text) => text.length >= 1 && text.length <= MAX_VALUE ? null : `applicationID is 1 to ${MAX_VALUE} characters`;
100
+ return Object.freeze({
101
+ anonymous,
102
+ providers: Object.freeze(providers.map((provider) => {
103
+ if (!isObject(provider)) throw new Error("a provider is { domain, applicationID } or { type: \"customJwt\", issuer, jwks, algorithm, applicationID }");
104
+ if (provider.type === "customJwt") {
105
+ for (const key of Object.keys(provider)) if (![
106
+ "type",
107
+ "issuer",
108
+ "jwks",
109
+ "algorithm",
110
+ "applicationID"
111
+ ].includes(key)) throw new Error(`a customJwt provider has no ${JSON.stringify(key)}: it takes issuer, jwks, algorithm and applicationID`);
112
+ if (provider.algorithm !== "RS256" && provider.algorithm !== "ES256") throw new Error("a customJwt provider's algorithm is \"RS256\" or \"ES256\"");
113
+ return Object.freeze({
114
+ type: "customJwt",
115
+ issuer: configured(provider, "issuer", (text) => urlError(text, "issuer")),
116
+ jwks: configured(provider, "jwks", (text) => urlError(text, "jwks", { data: true })),
117
+ algorithm: provider.algorithm,
118
+ ...provider.applicationID === void 0 ? {} : { applicationID: configured(provider, "applicationID", audience) }
119
+ });
120
+ }
121
+ if (provider.type !== void 0) throw new Error(`a provider's type is "customJwt", or left out for an OIDC issuer: ${JSON.stringify(provider.type)}`);
122
+ for (const key of Object.keys(provider)) if (key !== "domain" && key !== "applicationID") throw new Error(`an OIDC provider has no ${JSON.stringify(key)}: it takes domain and applicationID`);
123
+ return Object.freeze({
124
+ domain: configured(provider, "domain", (text) => urlError(text, "domain")),
125
+ applicationID: configured(provider, "applicationID", audience)
126
+ });
127
+ }))
128
+ });
129
+ }
130
+ /**
131
+ * The providers with their values read from `env`. Throws an Error naming the setting and the variable that is
132
+ * unset or wrong, never its value.
133
+ */
134
+ function trustedOf(config, env) {
135
+ const read = (value, key, check) => {
136
+ if (typeof value === "string") return value;
137
+ const text = env(value.env);
138
+ if (text === void 0 || text === "") throw new Error(`auth.config reads ${key} from ${value.env}, which is not set`);
139
+ const why = check(text, false);
140
+ if (why) throw new Error(`auth.config reads ${key} from ${value.env}, whose value is wrong: ${why}`);
141
+ return text;
142
+ };
143
+ const audience = (text) => text.length <= MAX_VALUE ? null : `applicationID is at most ${MAX_VALUE} characters`;
144
+ const trusted = config.providers.map((provider) => "type" in provider ? {
145
+ issuer: read(provider.issuer, "issuer", (text, shown) => urlError(text, "issuer", { shown })),
146
+ audience: provider.applicationID === void 0 ? null : read(provider.applicationID, "applicationID", audience),
147
+ algorithms: [provider.algorithm],
148
+ jwks: read(provider.jwks, "jwks", (text, shown) => urlError(text, "jwks", {
149
+ data: true,
150
+ shown
151
+ }))
152
+ } : {
153
+ issuer: read(provider.domain, "domain", (text, shown) => urlError(text, "domain", { shown })),
154
+ audience: read(provider.applicationID, "applicationID", audience),
155
+ algorithms: ["RS256", "ES256"],
156
+ jwks: null
157
+ });
158
+ const seen = /* @__PURE__ */ new Set();
159
+ for (const one of trusted) {
160
+ const key = `${one.issuer}\n${one.audience ?? ""}`;
161
+ if (seen.has(key)) throw new Error("auth.config trusts one issuer for one audience twice");
162
+ seen.add(key);
163
+ }
164
+ return Object.freeze(trusted.map((one) => Object.freeze(one)));
165
+ }
166
+ const refuse = (why) => new DatabaseError("unauthenticated", why);
167
+ const bytesOf = (part) => Uint8Array.from(atob(part.replace(/-/gu, "+").replace(/_/gu, "/")), (character) => character.charCodeAt(0));
168
+ /** `bytesOf`, or null for text that is not base64url. */
169
+ const bytesOrNull = (part) => {
170
+ try {
171
+ return bytesOf(part);
172
+ } catch {
173
+ return null;
174
+ }
175
+ };
176
+ function jsonOf(part) {
177
+ let value;
178
+ try {
179
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytesOf(part)));
180
+ } catch {
181
+ throw refuse("the token is not a JWT: a part is not base64url JSON");
182
+ }
183
+ if (!isObject(value)) throw refuse("the token is not a JWT: its header and claims are JSON objects");
184
+ return value;
185
+ }
186
+ function deepFreeze(value) {
187
+ if (typeof value === "object" && value !== null) {
188
+ for (const child of Object.values(value)) deepFreeze(child);
189
+ Object.freeze(value);
190
+ }
191
+ return value;
192
+ }
193
+ /** Where a fetch went, for a message: its origin, never its path or query, which may carry a key. */
194
+ const where = (url) => {
195
+ try {
196
+ return new URL(url).origin;
197
+ } catch {
198
+ return "an address that does not parse";
199
+ }
200
+ };
201
+ /** A key of a key set fit to check `alg`: its own kind and curve, for signing, of a size worth trusting. */
202
+ function fits(key, alg) {
203
+ if (key.use !== void 0 && key.use !== "sig") return false;
204
+ if (key.alg !== void 0 && key.alg !== alg) return false;
205
+ if (key.key_ops !== void 0 && !(Array.isArray(key.key_ops) && key.key_ops.includes("verify"))) return false;
206
+ if (alg === "RS256") return key.kty === "RSA" && typeof key.n === "string" && typeof key.e === "string" && B64URL.test(key.n) && B64URL.test(key.e) && (bytesOrNull(key.n)?.length ?? 0) >= 256;
207
+ return key.kty === "EC" && key.crv === "P-256" && typeof key.x === "string" && typeof key.y === "string" && B64URL.test(key.x) && B64URL.test(key.y);
208
+ }
209
+ const PARAMS = {
210
+ RS256: {
211
+ key: {
212
+ name: "RSASSA-PKCS1-v1_5",
213
+ hash: "SHA-256"
214
+ },
215
+ verify: { name: "RSASSA-PKCS1-v1_5" }
216
+ },
217
+ ES256: {
218
+ key: {
219
+ name: "ECDSA",
220
+ namedCurve: "P-256"
221
+ },
222
+ verify: {
223
+ name: "ECDSA",
224
+ hash: "SHA-256"
225
+ }
226
+ }
227
+ };
228
+ /** A fetch's failure in words this file wrote, safe to tell a caller. */
229
+ var Unfetched = class extends Error {};
230
+ /** The addresses a host name resolves to, by this machine's resolver. */
231
+ async function resolved(host) {
232
+ const { lookup } = await import("node:dns/promises");
233
+ return (await lookup(host, {
234
+ all: true,
235
+ verbatim: true
236
+ })).map((entry) => entry.address);
237
+ }
238
+ /**
239
+ * A check of tokens for the providers `trusted`: the token's `Verified` caller, or a `DatabaseError` whose code
240
+ * is `unauthenticated` saying why it was refused, or `unavailable` when its issuer's keys could not be fetched.
241
+ * One verifier keeps its key sets, so keep one for as long as its providers are trusted.
242
+ */
243
+ function verifier(trusted, options = {}) {
244
+ const clock = options.now ?? Date.now;
245
+ const get = options.fetch ?? ((url, init) => fetch(url, init));
246
+ const resolve = options.resolve ?? resolved;
247
+ const entries = /* @__PURE__ */ new Map();
248
+ const imported = /* @__PURE__ */ new WeakMap();
249
+ /**
250
+ * A JSON document from a public https address, read a chunk at a time and cut off past BODY_BYTES. The host's
251
+ * addresses are checked before the fetch; the fetch resolves the name again, so a name that changes its
252
+ * address between the two is the engine's to stop, by connecting to the address it checked.
253
+ */
254
+ async function fetched(url) {
255
+ const at = new URL(url);
256
+ if (at.protocol !== "https:" || privateHost(at.hostname)) throw new Unfetched("it is not a public https address");
257
+ const deadline = AbortSignal.timeout(FETCH_MS);
258
+ const addresses = await Promise.race([resolve(at.hostname), new Promise((_, fail) => deadline.addEventListener("abort", () => fail(new Unfetched("its host's address took too long to find")), { once: true }))]);
259
+ if (!addresses.length || !addresses.every(publicAddress)) throw new Unfetched("its host has a private address");
260
+ const response = await get(url, {
261
+ redirect: "error",
262
+ signal: deadline,
263
+ headers: { accept: "application/json" }
264
+ });
265
+ if (!response.ok) {
266
+ await response.body?.cancel();
267
+ throw new Unfetched(`it returned ${response.status}`);
268
+ }
269
+ if (Number(response.headers.get("content-length") ?? 0) > BODY_BYTES) {
270
+ await response.body?.cancel();
271
+ throw new Unfetched(`it is over ${BODY_BYTES} bytes`);
272
+ }
273
+ const chunks = [];
274
+ let size = 0;
275
+ const reader = response.body?.getReader();
276
+ for (;;) {
277
+ const read = reader ? await reader.read() : {
278
+ done: true,
279
+ value: void 0
280
+ };
281
+ if (read.done) break;
282
+ size += read.value.byteLength;
283
+ if (size > BODY_BYTES) {
284
+ await reader?.cancel();
285
+ throw new Unfetched(`it is over ${BODY_BYTES} bytes`);
286
+ }
287
+ chunks.push(read.value);
288
+ }
289
+ const body = new Uint8Array(size);
290
+ let offset = 0;
291
+ for (const chunk of chunks) {
292
+ body.set(chunk, offset);
293
+ offset += chunk.byteLength;
294
+ }
295
+ try {
296
+ return JSON.parse(new TextDecoder().decode(body));
297
+ } catch {
298
+ throw new Unfetched("it is not JSON");
299
+ }
300
+ }
301
+ /**
302
+ * A document at `url`, kept FRESH_MS; `again` asks for it anew unless it was asked for within REFETCH_MS. A
303
+ * failed fetch is not tried again for FAILED_MS, whether or not a copy from before is kept.
304
+ */
305
+ async function document(url, again) {
306
+ if (url.startsWith("data:")) {
307
+ const entry = entries.get(url);
308
+ if (entry) return entry.value;
309
+ const [head, body = ""] = url.split(",", 2);
310
+ let value;
311
+ try {
312
+ value = JSON.parse(head.endsWith(";base64") ? new TextDecoder().decode(bytesOf(body.replace(/=+$/u, ""))) : decodeURIComponent(body));
313
+ } catch {
314
+ throw refuse("the trusted key set, a data: URI, is not JSON");
315
+ }
316
+ entries.set(url, {
317
+ value,
318
+ at: 0,
319
+ tried: 0
320
+ });
321
+ return value;
322
+ }
323
+ const entry = entries.get(url) ?? {
324
+ at: 0,
325
+ tried: 0
326
+ };
327
+ entries.set(url, entry);
328
+ const now = clock();
329
+ const resting = entry.failed !== void 0 && now - entry.tried < FAILED_MS;
330
+ const kept = entry.value !== void 0 && now - entry.at < STALE_MS;
331
+ const due = entry.value === void 0 || now - entry.at > FRESH_MS && !resting || again && !resting && now - entry.tried > REFETCH_MS;
332
+ if (resting && !kept) throw entry.failed;
333
+ if (!due) return entry.value;
334
+ entry.asking ??= (async () => {
335
+ entry.tried = clock();
336
+ try {
337
+ const value = await fetched(url);
338
+ entry.value = value;
339
+ entry.at = clock();
340
+ entry.failed = void 0;
341
+ return value;
342
+ } finally {
343
+ entry.asking = void 0;
344
+ }
345
+ })();
346
+ try {
347
+ return await entry.asking;
348
+ } catch (error) {
349
+ entry.failed = new DatabaseError("unavailable", `the sign-in provider's keys could not be fetched from ${where(url)}: ${error instanceof Unfetched ? error.message : "the request failed"}`);
350
+ if (entry.value !== void 0 && clock() - entry.at < STALE_MS) return entry.value;
351
+ throw entry.failed;
352
+ }
353
+ }
354
+ /** The address of a provider's key set: given, or from its issuer's discovery document, which must name exactly that issuer. */
355
+ async function keysAt(provider) {
356
+ if (provider.jwks) return provider.jwks;
357
+ const found = await document(`${provider.issuer.replace(/\/$/u, "")}/.well-known/openid-configuration`, false);
358
+ const issuer = isObject(found) ? found.issuer : void 0, jwks = isObject(found) ? found.jwks_uri : void 0;
359
+ if (issuer !== provider.issuer) throw new DatabaseError("unavailable", `the discovery document at ${where(provider.issuer)} is for another issuer`);
360
+ if (typeof jwks !== "string" || urlError(jwks, "jwks_uri", { shown: false })) throw new DatabaseError("unavailable", `the discovery document at ${where(provider.issuer)} names no public https jwks_uri`);
361
+ return jwks;
362
+ }
363
+ function key(jwk, alg) {
364
+ let got = imported.get(jwk);
365
+ if (!got) {
366
+ const pub = alg === "RS256" ? {
367
+ kty: "RSA",
368
+ n: jwk.n,
369
+ e: jwk.e
370
+ } : {
371
+ kty: "EC",
372
+ crv: "P-256",
373
+ x: jwk.x,
374
+ y: jwk.y
375
+ };
376
+ got = crypto.subtle.importKey("jwk", pub, PARAMS[alg].key, false, ["verify"]);
377
+ imported.set(jwk, got);
378
+ }
379
+ return got;
380
+ }
381
+ /** Whether a key the provider publishes signed `signed`; a `kid` the set lacks (or no fitting key) fetches it again once. */
382
+ async function signedBy(provider, alg, kid, signed, signature) {
383
+ for (const again of [false, true]) {
384
+ const set = await document(await keysAt(provider), again);
385
+ const keys = (isObject(set) && Array.isArray(set.keys) ? set.keys : []).filter((k) => isObject(k) && (kid === void 0 || k.kid === kid) && fits(k, alg));
386
+ if (!keys.length) continue;
387
+ for (const jwk of keys.slice(0, 8)) {
388
+ let ok = false;
389
+ try {
390
+ ok = await crypto.subtle.verify(PARAMS[alg].verify, await key(jwk, alg), signature, signed);
391
+ } catch {}
392
+ if (ok) return true;
393
+ }
394
+ return false;
395
+ }
396
+ return false;
397
+ }
398
+ return async function verify(token) {
399
+ if (typeof token !== "string" || token.length > TOKEN_CHARS) throw refuse(`the token is not a JWT of at most ${TOKEN_CHARS} characters`);
400
+ const parts = token.split(".");
401
+ if (parts.length !== 3 || !parts.every((part) => B64URL.test(part))) throw refuse("the token is not a signed JWT");
402
+ const header = jsonOf(parts[0]), claims = jsonOf(parts[1]);
403
+ const alg = header.alg;
404
+ if (alg !== "RS256" && alg !== "ES256") throw refuse(`the token is signed with ${JSON.stringify(alg)}: a database takes RS256 or ES256`);
405
+ if (header.crit !== void 0) throw refuse("the token has critical header parameters, which a database does not take");
406
+ if (header.kid !== void 0 && typeof header.kid !== "string") throw refuse("the token's kid is not a string");
407
+ const iss = claims.iss;
408
+ if (typeof iss !== "string") throw refuse("the token names no issuer");
409
+ const ofIssuer = trusted.filter((one) => one.issuer === iss);
410
+ if (!ofIssuer.length) throw refuse(`the token's issuer, ${iss.slice(0, MAX_VALUE)}, is not one this database trusts`);
411
+ const audiences = typeof claims.aud === "string" ? [claims.aud] : Array.isArray(claims.aud) ? claims.aud.filter((one) => typeof one === "string") : [];
412
+ const provider = ofIssuer.find((one) => one.audience !== null && audiences.includes(one.audience)) ?? ofIssuer.find((one) => one.audience === null);
413
+ if (!provider) throw refuse(`the token's audience is not one this database trusts for ${iss}`);
414
+ if (!provider.algorithms.includes(alg)) throw refuse(`this database takes ${iss}'s tokens signed with ${provider.algorithms.join(" or ")}, not ${alg}`);
415
+ const signature = bytesOrNull(parts[2]);
416
+ if (!signature || alg === "ES256" && signature.length !== 64) throw refuse("the token's signature does not match any key its issuer publishes");
417
+ if (!await signedBy(provider, alg, header.kid, new TextEncoder().encode(`${parts[0]}.${parts[1]}`), signature)) throw refuse("the token's signature does not match any key its issuer publishes");
418
+ const now = Math.floor(clock() / 1e3);
419
+ const time = (name) => {
420
+ const value = claims[name];
421
+ if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value))) throw refuse(`the token's ${name} is not a time`);
422
+ return value;
423
+ };
424
+ const exp = time("exp"), nbf = time("nbf"), iat = time("iat");
425
+ if (exp === void 0) throw refuse("the token has no expiry (exp)");
426
+ if (now > exp + 60) throw refuse(`the token expired at ${(/* @__PURE__ */ new Date(exp * 1e3)).toISOString()}`);
427
+ if (nbf !== void 0 && now < nbf - 60) throw refuse(`the token is not valid until ${(/* @__PURE__ */ new Date(nbf * 1e3)).toISOString()}`);
428
+ if (iat !== void 0 && iat > now + 60) throw refuse("the token was issued in the future");
429
+ const sub = claims.sub;
430
+ if (typeof sub !== "string" || sub.length < 1 || sub.length > MAX_VALUE) throw refuse(`the token's subject (sub) is not 1 to ${MAX_VALUE} characters`);
431
+ return Object.freeze({
432
+ subject: sub,
433
+ issuer: iss,
434
+ claims: deepFreeze(structuredClone(claims))
435
+ });
436
+ };
437
+ }
438
+ /** When a provider's verified token stops admitting its session's calls: its `exp`, with the clocks' 60 s. */
439
+ const sessionEnd = (claims) => typeof claims?.exp === "number" ? (claims.exp + 60) * 1e3 : Number.POSITIVE_INFINITY;
440
+ //#endregion
441
+ export { verifier as i, sessionEnd as n, trustedOf as r, authConfigOf as t };
@@ -0,0 +1,120 @@
1
+ import { $ as VectorIndex, J as IndexDeclaration, X as SearchIndex, Z as Shape, n as CronJob } from "./server-B5HK2Ou9.mjs";
2
+ import { Node } from "acorn";
3
+ //#region src/database/auth.d.ts
4
+ /** A value as `db/auth.config.ts` writes it: a string, or an environment variable read where the Database runs. */
5
+ type Configured = string | {
6
+ readonly env: string;
7
+ };
8
+ type Algorithm = "RS256" | "ES256";
9
+ /** An OIDC issuer, found by discovery: `domain` is its `iss`, `applicationID` the audience its tokens name. */
10
+ interface OidcProvider {
11
+ readonly domain: Configured;
12
+ readonly applicationID: Configured;
13
+ }
14
+ /** An issuer of JWTs that publishes no discovery document: its key set is `jwks`, an https address or a `data:` URI. */
15
+ interface JwtProvider {
16
+ readonly type: "customJwt";
17
+ readonly issuer: Configured;
18
+ readonly jwks: Configured;
19
+ readonly algorithm: Algorithm;
20
+ readonly applicationID?: Configured;
21
+ }
22
+ type AuthProvider = OidcProvider | JwtProvider;
23
+ /** `db/auth.config.ts`, as the build reads it. */
24
+ interface AuthConfig {
25
+ readonly providers: ReadonlyArray<AuthProvider>;
26
+ readonly anonymous: boolean;
27
+ }
28
+ //#endregion
29
+ //#region src/database/build.d.ts
30
+ /** A file the Database would refuse; the message gives the file, and the line when there is one. */
31
+ declare class Refused extends Error {
32
+ constructor(message: string);
33
+ }
34
+ interface BuiltFunction {
35
+ readonly name: string;
36
+ readonly kind: "query" | "mutation" | "action" | "internalQuery" | "internalMutation" | "internalAction";
37
+ /** The built file it is in, and the export that holds it. */
38
+ readonly file: string;
39
+ readonly export: string;
40
+ /** Its `args` fields and `returns` shape as written, for its types: null where they are not literals. */
41
+ readonly args: Readonly<Record<string, Shape | null>> | null;
42
+ readonly returns: Shape | null;
43
+ }
44
+ interface Built {
45
+ /** The folder's modules as JavaScript, by `<name>.mjs`, each import of the folder naming its built file. */
46
+ readonly files: Readonly<Record<string, string>>;
47
+ /** Which author file each built one came from. */
48
+ readonly from: Readonly<Record<string, string>>;
49
+ /** The files outside the folder the build read, by path: the packages' and the project's. A change to one changes the build. */
50
+ readonly inputs: ReadonlyArray<string>;
51
+ readonly functions: ReadonlyArray<BuiltFunction>;
52
+ /** The schema's tables by field, and their indexes; null without `schema.ts`. */
53
+ readonly tables: Readonly<Record<string, Readonly<Record<string, Shape>>>> | null;
54
+ readonly indexes: Readonly<Record<string, Readonly<Record<string, IndexDeclaration>>>> | null;
55
+ /** Each table's search and vector indexes by name; null without `schema.ts`. */
56
+ readonly search: Readonly<Record<string, Readonly<Record<string, SearchIndex>>>> | null;
57
+ readonly vector: Readonly<Record<string, Readonly<Record<string, VectorIndex>>>> | null;
58
+ /** The built file whose default export is the HTTP router, `http.mjs`; null without `http.ts`. */
59
+ readonly http: string | null;
60
+ /** Whom the Database trusts to sign its users in, from `auth.config.ts`; null without one, when it takes only its own tokens. */
61
+ readonly auth: AuthConfig | null;
62
+ /** `crons.ts`'s scheduled runs, as Convex's `cronJobs()` writes them; none without it. */
63
+ readonly crons: ReadonlyArray<CronJob>;
64
+ /** The files of `db/_generated/`. */
65
+ readonly generated: {
66
+ readonly "api.mjs": string;
67
+ readonly "api.d.ts": string;
68
+ readonly "dataModel.d.ts": string;
69
+ readonly "server.d.ts": string;
70
+ };
71
+ }
72
+ /** How a build reads the installed packages: the folder's own path, a file's text (null when there is none) and a path with its links followed. Paths use `/`. */
73
+ interface Packages {
74
+ readonly root: string;
75
+ read(path: string): string | null;
76
+ real(path: string): string;
77
+ }
78
+ /** The most one built file may be, as a deploy admits it. */
79
+ declare const MODULE_BYTES: number;
80
+ /** The most a whole build may be: the folder's modules and every package file they reach. */
81
+ declare const BUILD_BYTES: number;
82
+ /** The most files a build may have, as a deploy admits it. */
83
+ declare const BUILD_FILES = 4000;
84
+ /**
85
+ * Whether a file of `db/`, by its path in it, is a source: types (`.d.ts`), dotfiles, `_generated/`, `node_modules/` and
86
+ * a dotted name directly in the folder other than `auth.config` are none.
87
+ */
88
+ declare const isSource: (name: string) => boolean;
89
+ type Any = Node & Record<string, any>;
90
+ /**
91
+ * TypeScript with the enum that starts at `line` and `column` written as the object TypeScript
92
+ * makes of it: `enum Status { New, Done }` is `const Status = { "New": 0, "0": "New", "Done": 1,
93
+ * "1": "Done" }`. Lines stay where they were. Null when a member's value is anything but a number
94
+ * or a string.
95
+ */
96
+ declare function enumAsObject(ts: string, line: number, column: number): string | null;
97
+ /** The names statements declare in their own block: variables, functions, classes and imports. */
98
+ declare function blockNames(statements: ReadonlyArray<Any>, out: Set<string>): void;
99
+ /** Every call of `name` where no scope around it binds `name`: the global's, which a module may not call. */
100
+ declare function unboundCalls(tree: Any, name: string): Any[];
101
+ /**
102
+ * The file a package's `exports` gives `sub` ("." or "./<path>"), with `*` patterns; null when it
103
+ * gives none. Of the patterns that match, the longest part before `*` wins, then the longest key, as Node orders them.
104
+ */
105
+ declare function exported(exports: unknown, sub: string, conditions?: ReadonlySet<string>): string | null;
106
+ /**
107
+ * Builds a `db/` folder's sources: `{ <path>: text }`, every source at any depth, by its path in the
108
+ * folder. Without `packages` an import of a package or of a file outside the folder is refused.
109
+ *
110
+ * A build's own `files` build again to the same files: what a deploy uploads, and what the Database
111
+ * checks, is the build. Throws `Refused`.
112
+ */
113
+ declare function buildDatabase(sources: Readonly<Record<string, string>>, strip: (ts: string) => string, options?: {
114
+ readonly packages?: Packages;
115
+ readonly ahead?: boolean;
116
+ }): Built;
117
+ /** A shape as a TypeScript type. */
118
+ declare function typeOf(shape: Shape | null | undefined): string;
119
+ //#endregion
120
+ export { MODULE_BYTES as a, blockNames as c, exported as d, isSource as f, AuthConfig as h, BuiltFunction as i, buildDatabase as l, unboundCalls as m, BUILD_FILES as n, Packages as o, typeOf as p, Built as r, Refused as s, BUILD_BYTES as t, enumAsObject as u };