zitejs 0.10.0-start.28 → 0.10.0-start.29

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 (36) hide show
  1. package/dist/cjs/check/start/sourceRules.js +7 -0
  2. package/dist/cjs/start/airtable/cache.d.ts +17 -0
  3. package/dist/cjs/start/airtable/cache.js +76 -0
  4. package/dist/cjs/start/types.d.ts +37 -7
  5. package/dist/esm/check/start/sourceRules.js +7 -0
  6. package/dist/esm/signin/keys.d.ts +10 -13
  7. package/dist/esm/signin/keys.js +87 -52
  8. package/dist/esm/signin/signin.js +1 -3
  9. package/dist/esm/signin/verify.d.ts +2 -2
  10. package/dist/esm/signin/verify.js +29 -35
  11. package/dist/esm/start/airtable/cache.d.ts +17 -0
  12. package/dist/esm/start/airtable/cache.js +72 -0
  13. package/dist/esm/start/airtable/dispatch.d.ts +3 -0
  14. package/dist/esm/start/airtable/dispatch.js +14 -12
  15. package/dist/esm/start/airtable/index.js +8 -0
  16. package/dist/esm/start/data/baseRunner.d.ts +5 -0
  17. package/dist/esm/start/data/baseRunner.js +10 -0
  18. package/dist/esm/start/data/dispatch.d.ts +1 -0
  19. package/dist/esm/start/data/dispatch.js +13 -1
  20. package/dist/esm/start/demo.d.ts +11 -0
  21. package/dist/esm/start/demo.js +21 -0
  22. package/dist/esm/start/direct.js +7 -3
  23. package/dist/esm/start/fetch.js +3 -1
  24. package/dist/esm/start/outbound.js +1 -0
  25. package/dist/esm/start/requestEnv.d.ts +8 -0
  26. package/dist/esm/start/requestEnv.js +115 -0
  27. package/dist/esm/start/server.d.ts +2 -1
  28. package/dist/esm/start/server.js +23 -27
  29. package/dist/esm/start/steps.d.ts +15 -15
  30. package/dist/esm/start/steps.js +56 -81
  31. package/dist/esm/start/types.d.ts +37 -7
  32. package/dist/esm/start/version.d.ts +1 -1
  33. package/dist/esm/start/version.js +1 -1
  34. package/dist/esm/start/workflowRun.d.ts +30 -5
  35. package/dist/esm/start/workflowRun.js +28 -20
  36. package/package.json +2 -1
@@ -441,11 +441,15 @@ const ROOT_LAYOUTS = new Set(["src/routes/__root.tsx", "src/routes/_app.tsx", "s
441
441
  const CLASSIC_IMPORTS = {
442
442
  "zitejs/backend": "server code is a signedInFn/publicFn server function from zitejs/start",
443
443
  "zitejs/api": "pages call server functions directly, from a loader or an event handler",
444
+ "zitejs/caller": "pages call server functions directly, from a loader or an event handler",
444
445
  "react-router-dom": "routing is file routes, with Link and useNavigate from @tanstack/react-router",
445
446
  "react-router": "routing is file routes, with Link and useNavigate from @tanstack/react-router",
446
447
  };
447
448
  // A Start app reads its user from the router; zitejs/auth's actions work in both runtimes.
448
449
  const CLASSIC_AUTH_READS = new Set(["useAuth", "useSession"]);
450
+ // Classic's caller POSTs to `/api/<name>`, which a Start app doesn't serve; zitejs/runtime's other exports are the
451
+ // generated clients' own.
452
+ const RUNTIME_CALLER = "createCaller";
449
453
  const importsModule = (source, module) => source === module || source.startsWith(`${module}/`);
450
454
  const containsTypeofWindow = (node) => {
451
455
  let found = false;
@@ -963,6 +967,9 @@ function sourceProblems(sources, { internal = false, kind } = {}) {
963
967
  report("classic-construct", "error", path, statement, `${name} is classic's; in a Start app, read the user from the router: context.user in beforeLoad and loaders, Route.useRouteContext() in a page, useRouteContext({ from: '__root__' }) in shared components`);
964
968
  }
965
969
  }
970
+ if (source === "zitejs/runtime" && values !== "all" && values.includes(RUNTIME_CALLER)) {
971
+ report("classic-construct", "error", path, statement, `${RUNTIME_CALLER} is classic's; in a Start app, ${CLASSIC_IMPORTS["zitejs/api"]}`);
972
+ }
966
973
  if (source === "cloudflare:workers") {
967
974
  report("cloudflare-env", "error", path, statement, "read the app's environment from process.env, not cloudflare:workers");
968
975
  }
@@ -0,0 +1,17 @@
1
+ /** How long a read is served from the cache, as classic's. */
2
+ export declare const AIRTABLE_READ_TTL_MS = 10000;
3
+ export type AirtableCache = {
4
+ /** A read kept across requests; a write to `table` makes it stale. */
5
+ read<T>(table: string, key: string, load: () => Promise<T>): Promise<T>;
6
+ /** A write to `table`, which makes its reads stale in every isolate the cache reaches, this request's at once. */
7
+ wrote(table: string): Promise<void>;
8
+ };
9
+ /**
10
+ * One request's view of the cache for one connection. Entries are keyed by its token's hash, so only a caller holding
11
+ * the same token reads them, whoever shares the cache.
12
+ */
13
+ export declare const createAirtableCache: ({ token, waitUntil, now, }: {
14
+ token: string;
15
+ waitUntil?: (promise: Promise<unknown>) => void;
16
+ now?: () => number;
17
+ }) => Promise<AirtableCache | undefined>;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ // Classic keeps an Airtable read for 10 s across runs, in KV, and a write makes the table's reads stale wherever the
3
+ // version it bumps reaches (restly's apps/cloudflare-lambda/src/integrationCache.ts). A Start app keeps them in its
4
+ // Worker's own Cache API cache, per colo, on the same terms. Off Workers there is none, and each read goes to Airtable.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createAirtableCache = exports.AIRTABLE_READ_TTL_MS = void 0;
7
+ const CACHE_NAME = "zite-airtable";
8
+ const ORIGIN = "https://airtable-cache.zite.invalid";
9
+ /** How long a read is served from the cache, as classic's. */
10
+ exports.AIRTABLE_READ_TTL_MS = 10_000;
11
+ // What the cache may keep an entry for, past which it's gone whether read or not; classic's KV minimum.
12
+ const HARD_TTL_S = 60;
13
+ const VERSION_TTL_S = 24 * 60 * 60;
14
+ // Classic's cap, KV's largest value.
15
+ const MAX_ENTRY_CHARS = 25 * 1024 * 1024;
16
+ const openCache = async () => {
17
+ const storage = globalThis.caches;
18
+ if (!storage?.open)
19
+ return undefined;
20
+ try {
21
+ return await storage.open(CACHE_NAME);
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ };
27
+ const sha256 = async (text) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))].map((b) => b.toString(16).padStart(2, "0")).join("");
28
+ /**
29
+ * One request's view of the cache for one connection. Entries are keyed by its token's hash, so only a caller holding
30
+ * the same token reads them, whoever shares the cache.
31
+ */
32
+ const createAirtableCache = async ({ token, waitUntil, now = () => Date.now(), }) => {
33
+ const cache = await openCache();
34
+ if (!cache)
35
+ return undefined;
36
+ const scope = (await sha256(token)).slice(0, 32);
37
+ // This request's writes, added to what the cache says, so a read after a write misses even before the bump lands.
38
+ const bumps = new Map();
39
+ const at = (...parts) => new Request(`${ORIGIN}/${parts.map(encodeURIComponent).join("/")}`);
40
+ const stored = async (table) => {
41
+ const held = await cache.match(at("v", scope, table)).catch(() => undefined);
42
+ return Number.parseInt((await held?.text().catch(() => "")) ?? "", 10) || 0;
43
+ };
44
+ const kept = (put) => {
45
+ const quiet = put.catch((error) => console.warn("[zite] Airtable cache write failed", error));
46
+ waitUntil?.(quiet);
47
+ return quiet;
48
+ };
49
+ return {
50
+ async read(table, key, load) {
51
+ let entry;
52
+ try {
53
+ entry = at("r", scope, table, String((await stored(table)) + (bumps.get(table) ?? 0)), await sha256(key));
54
+ const held = await cache.match(entry);
55
+ const found = held ? (await held.json()) : undefined;
56
+ if (found && typeof found.at === "number" && now() - found.at < exports.AIRTABLE_READ_TTL_MS)
57
+ return found.value;
58
+ }
59
+ catch (error) {
60
+ console.warn("[zite] Airtable cache read failed", error);
61
+ }
62
+ const value = await load();
63
+ const body = entry ? JSON.stringify({ at: now(), value }) : undefined;
64
+ if (entry && body && body.length <= MAX_ENTRY_CHARS) {
65
+ void kept(cache.put(entry, new Response(body, { headers: { "content-type": "application/json", "cache-control": `max-age=${HARD_TTL_S}` } })));
66
+ }
67
+ return value;
68
+ },
69
+ async wrote(table) {
70
+ bumps.set(table, (bumps.get(table) ?? 0) + 1);
71
+ const next = String((await stored(table)) + 1);
72
+ await kept(cache.put(at("v", scope, table), new Response(next, { headers: { "cache-control": `max-age=${VERSION_TTL_S}` } })));
73
+ },
74
+ };
75
+ };
76
+ exports.createAirtableCache = createAirtableCache;
@@ -1,4 +1,6 @@
1
+ import type { StepEventStatus, StepSuspension } from "../steps/index.js";
1
2
  import type { AiUsageRecord } from "./aiUsage.js";
3
+ import type { AirtableCache } from "./airtable/cache.js";
2
4
  export type Role = {
3
5
  id: string;
4
6
  name: string;
@@ -31,14 +33,33 @@ export type RunRecord = {
31
33
  stack?: string;
32
34
  };
33
35
  /** A workflow's steps, as they ran, replayed or failed. */
34
- steps?: {
35
- name: string;
36
- status: "ran" | "memoized" | "failed";
37
- durationMs?: number;
38
- at: number;
39
- }[];
36
+ steps?: StepRecord[];
40
37
  /** The step a failed workflow stopped in, where a resume picks up. */
41
38
  failedStep?: string;
39
+ /** A durable call that stopped short of the end, which the run's next call carries on from. */
40
+ suspended?: StepSuspension;
41
+ };
42
+ /** One step of a workflow call, as zitejs/steps reports it. `failed` marks a replayed final failure. */
43
+ export type StepRecord = {
44
+ name: string;
45
+ status: StepEventStatus;
46
+ durationMs?: number;
47
+ at: number;
48
+ failed?: true;
49
+ wakeAt?: string;
50
+ };
51
+ /**
52
+ * A workflow call the host's run loop calls again, as classic's durable automation calls are: a step that throws with
53
+ * tries left stops the call for a later one instead of reaching the code, and past its budget the call starts no new
54
+ * step. The host sends it on a call it will carry on; without it a run is one call.
55
+ */
56
+ export type DurableCall = {
57
+ /** 1, the default, for the run's first call. A later call throws a step's saved final failure again rather than run it. */
58
+ invocation?: number;
59
+ /** Which try each step that failed in an earlier call is on, from that call's `retry.attempts`; others are on their first. */
60
+ attempts?: Record<string, number>;
61
+ /** How long the call starts new steps for; 60 seconds by default. */
62
+ budgetMs?: number;
42
63
  };
43
64
  export type AccessKind = "signedIn" | "anyone" | "webhook" | "workflow";
44
65
  /** One data, integration or email call. Who is calling is the platform's to know, never the app's to say. */
@@ -155,7 +176,7 @@ export type AppContext = {
155
176
  orgSettingsVersion: number | null;
156
177
  /** Whether the org's plan shows Zite's badge. */
157
178
  showZiteBadge: boolean;
158
- /** The app's live URL, demo included: `process.env.ZITE_APP_URL`. Null when the platform has none to give. */
179
+ /** The app's URL, a demo's its own as on classic: `process.env.ZITE_APP_URL`. Null when the platform has none to give. */
159
180
  appUrl: string | null;
160
181
  };
161
182
  /**
@@ -268,6 +289,8 @@ export type HostProps = AppContext & {
268
289
  connectionServices?: Record<string, string>;
269
290
  /** A resumed run's first attempt, whose saved steps it replays. */
270
291
  runRoot?: string;
292
+ /** A workflow call the host's run loop carries on; absent, the run is this one call. */
293
+ durable?: DurableCall;
271
294
  /** This request's app token, sent only to `urls`. */
272
295
  appToken?: string;
273
296
  /** When `appToken` expires, in milliseconds since the epoch; absent without one. */
@@ -297,10 +320,15 @@ export type HostRequestState = {
297
320
  previewClaim?: string;
298
321
  /** Classic's connection env vars the host sent, set into `process.env` for the request. */
299
322
  env?: Record<string, string>;
323
+ /** A demo's own `process.env` vars, which it reads in place of any a request set in the isolate's. */
324
+ demoEnv?: Map<string, string | undefined>;
325
+ /** A platform call this demo made was refused. */
326
+ demoRefused?: boolean;
300
327
  envConnections?: Record<string, string>;
301
328
  connectionServices?: Record<string, string>;
302
329
  /** A resumed run's first attempt, whose saved steps it replays. */
303
330
  runRoot?: string;
331
+ durable?: DurableCall;
304
332
  /** The connection each token this request was handed belongs to. */
305
333
  connectionTokens?: Map<string, string>;
306
334
  /** `integrations.get`'s answers this request, by name. */
@@ -321,6 +349,8 @@ export type HostRequestState = {
321
349
  calls?: CallRecord[];
322
350
  /** This request's Airtable reads, so the same one twice goes out once. */
323
351
  airtableReads?: Map<string, Promise<unknown>>;
352
+ /** This request's view of the Airtable read cache, by connection token. */
353
+ airtableCaches?: Map<string, Promise<AirtableCache | undefined>>;
324
354
  /** Records still reading a copy of a body; the flush waits for them. */
325
355
  pending?: Promise<void>[];
326
356
  provider?: PlatformProvider;
@@ -438,11 +438,15 @@ const ROOT_LAYOUTS = new Set(["src/routes/__root.tsx", "src/routes/_app.tsx", "s
438
438
  const CLASSIC_IMPORTS = {
439
439
  "zitejs/backend": "server code is a signedInFn/publicFn server function from zitejs/start",
440
440
  "zitejs/api": "pages call server functions directly, from a loader or an event handler",
441
+ "zitejs/caller": "pages call server functions directly, from a loader or an event handler",
441
442
  "react-router-dom": "routing is file routes, with Link and useNavigate from @tanstack/react-router",
442
443
  "react-router": "routing is file routes, with Link and useNavigate from @tanstack/react-router",
443
444
  };
444
445
  // A Start app reads its user from the router; zitejs/auth's actions work in both runtimes.
445
446
  const CLASSIC_AUTH_READS = new Set(["useAuth", "useSession"]);
447
+ // Classic's caller POSTs to `/api/<name>`, which a Start app doesn't serve; zitejs/runtime's other exports are the
448
+ // generated clients' own.
449
+ const RUNTIME_CALLER = "createCaller";
446
450
  const importsModule = (source, module) => source === module || source.startsWith(`${module}/`);
447
451
  const containsTypeofWindow = (node) => {
448
452
  let found = false;
@@ -960,6 +964,9 @@ export function sourceProblems(sources, { internal = false, kind } = {}) {
960
964
  report("classic-construct", "error", path, statement, `${name} is classic's; in a Start app, read the user from the router: context.user in beforeLoad and loaders, Route.useRouteContext() in a page, useRouteContext({ from: '__root__' }) in shared components`);
961
965
  }
962
966
  }
967
+ if (source === "zitejs/runtime" && values !== "all" && values.includes(RUNTIME_CALLER)) {
968
+ report("classic-construct", "error", path, statement, `${RUNTIME_CALLER} is classic's; in a Start app, ${CLASSIC_IMPORTS["zitejs/api"]}`);
969
+ }
963
970
  if (source === "cloudflare:workers") {
964
971
  report("cloudflare-env", "error", path, statement, "read the app's environment from process.env, not cloudflare:workers");
965
972
  }
@@ -1,17 +1,17 @@
1
+ import { type CryptoKey, type JWSHeaderParameters } from "jose";
1
2
  /**
2
3
  * The identity issuer's public keys by `kid`, each its raw Ed25519 key (base64url), as read from the issuer's JWK Set
3
4
  * (RFC 7517): the dispatcher's `ZITE_IDENTITY_JWKS`, or the backend's `jwks_uri` off Zite.
4
5
  */
5
6
  export type IdentityKeys = Readonly<Record<string, string>>;
6
- /** Where a verifier finds keys: what it holds now, and a refetch for a `kid` it doesn't know. */
7
- export type IdentityKeySource = {
8
- /** The keys to verify with; a source that fetches them fetches again first once what it holds is stale. */
9
- current(): IdentityKeys | Promise<IdentityKeys>;
10
- /** The keys after a refetch, or undefined when none happened (none configured, or one ran under a minute ago). */
11
- refresh(): Promise<IdentityKeys | undefined>;
12
- };
7
+ /**
8
+ * Where a verifier finds the key a token's header names, as jose's `compactVerify` asks for it. It throws jose's
9
+ * `JWKSNoMatchingKey` for a `kid` it doesn't hold, and anything else when it has no keys to look in.
10
+ */
11
+ export type IdentityKeySource = (header: JWSHeaderParameters) => Promise<CryptoKey>;
13
12
  /** An Ed25519 key's JWS `alg`: RFC 9864's `Ed25519`, or the older `EdDSA`, which the identity server signs with. */
14
- export declare const ED25519_ALGS: ReadonlySet<unknown>;
13
+ export declare const ED25519_ALGS: string[];
14
+ export declare const isEd25519Alg: (alg: unknown) => boolean;
15
15
  /**
16
16
  * Parses the identity issuer's JWK Set by the rule every verifier of it follows, restly's included. A key of a kind
17
17
  * zitejs doesn't use (another `kty`, `crv` or `alg`, an RS256 key for other clients, say) is skipped and logged, as
@@ -27,14 +27,11 @@ export declare const maxAgeOf: (response: Response) => number;
27
27
  type Fetch = (request: Request) => Promise<Response>;
28
28
  type FetchOptions = {
29
29
  fetch?: Fetch;
30
- now?: () => number;
31
30
  };
32
31
  /** For tests: forget every fetched key set and discovery document. */
33
32
  export declare const resetFetchedIdentityKeys: () => void;
34
- /** Keys from the JWK Set at `url`, as {@link fetchedIdentityKeys} holds them. */
35
- export declare const remoteIdentityKeys: (url: string, options?: FetchOptions & {
36
- initial?: IdentityKeys;
37
- }) => IdentityKeySource;
33
+ /** Keys from the JWK Set at `url`, as {@link remoteKeySet} holds them. Make one per request. */
34
+ export declare const remoteIdentityKeys: (url: string, options?: FetchOptions) => IdentityKeySource;
38
35
  /** Keys from the JWK Set `issuer`'s discovery document names, as {@link remoteIdentityKeys} holds them. */
39
36
  export declare const discoveredIdentityKeys: (issuer: string, options?: FetchOptions) => IdentityKeySource;
40
37
  export {};
@@ -1,11 +1,13 @@
1
+ import { createRemoteJWKSet, customFetch, errors, importJWK, jwksCache, } from "jose";
1
2
  import { fromBase64Url, isRecord } from "./encoding.js";
2
3
  const KEY_SET_NAME = "the identity JWK Set";
3
4
  /** An Ed25519 key's JWS `alg`: RFC 9864's `Ed25519`, or the older `EdDSA`, which the identity server signs with. */
4
- export const ED25519_ALGS = new Set(["EdDSA", "Ed25519"]);
5
+ export const ED25519_ALGS = ["EdDSA", "Ed25519"];
6
+ export const isEd25519Alg = (alg) => ED25519_ALGS.some((known) => known === alg);
5
7
  // RFC 7518 §6's private members, of every key type.
6
8
  const PRIVATE_MEMBERS = ["d", "p", "q", "dp", "dq", "qi", "oth", "k"];
7
9
  // The kind of key the identity server signs with; a set may hold others, for other clients.
8
- const isEd25519Kind = (jwk) => jwk.kty === "OKP" && jwk.crv === "Ed25519" && (jwk.alg === undefined || ED25519_ALGS.has(jwk.alg));
10
+ const isEd25519Kind = (jwk) => jwk.kty === "OKP" && jwk.crv === "Ed25519" && (jwk.alg === undefined || isEd25519Alg(jwk.alg));
9
11
  /** An Ed25519 key's `kid` and `x`, or what's wrong with it: an operator's typo, which fails at once, never skipped. */
10
12
  const ed25519KeyOf = (jwk) => {
11
13
  if (jwk.use !== undefined && jwk.use !== "sig")
@@ -67,11 +69,22 @@ export const identityKeys = (json) => {
67
69
  throw new Error(`${KEY_SET_NAME} holds no Ed25519 key`);
68
70
  return keys;
69
71
  };
72
+ // Imported once per process; a CryptoKey holds no request's I/O.
73
+ const imported = new Map();
74
+ const publicKeyOf = async (x) => {
75
+ const held = imported.get(x);
76
+ if (held)
77
+ return held;
78
+ const key = await importJWK({ kty: "OKP", crv: "Ed25519", x }, "Ed25519");
79
+ imported.set(x, key);
80
+ return key;
81
+ };
70
82
  /** Keys that never change: the dispatcher's configured set. */
71
- export const staticIdentityKeys = (keys) => ({
72
- current: () => keys,
73
- refresh: async () => undefined,
74
- });
83
+ export const staticIdentityKeys = (keys) => async ({ kid }) => {
84
+ if (typeof kid !== "string" || !Object.hasOwn(keys, kid))
85
+ throw new errors.JWKSNoMatchingKey();
86
+ return publicKeyOf(keys[kid]);
87
+ };
75
88
  const REFETCH_EVERY_MS = 60_000;
76
89
  const FETCH_TIMEOUT_MS = 5_000;
77
90
  // What the backend sends, and how long a set is held when its response names no max-age.
@@ -88,9 +101,6 @@ export const maxAgeOf = (response) => {
88
101
  return maxAge === undefined ? DEFAULT_MAX_AGE_S : Number(maxAge);
89
102
  };
90
103
  const getJson = (url, fetch = globalThis.fetch) => fetch(new Request(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }));
91
- // Per process, only fetched keys, when they were fetched and for how long they hold, and when a fetch last started:
92
- // Workers ties a fetch to the request that made it, so a pending one is never shared across requests. Another request
93
- // inside the minute keeps the keys it has.
94
104
  const fetched = new Map();
95
105
  // Per process, each issuer's `jwks_uri`, once its discovery document named it.
96
106
  const discovered = new Map();
@@ -99,48 +109,56 @@ export const resetFetchedIdentityKeys = () => {
99
109
  fetched.clear();
100
110
  discovered.clear();
101
111
  };
112
+ const fetchedFor = (id) => {
113
+ let entry = fetched.get(id);
114
+ if (!entry)
115
+ fetched.set(id, (entry = { cache: {}, maxAgeMs: DEFAULT_MAX_AGE_S * 1000, retryAt: 0 }));
116
+ return entry;
117
+ };
102
118
  /**
103
- * Keys from the JWK Set at `jwksUri()`, held per process under `id`. They're fetched when none are held, once the set
104
- * is older than its response's `max-age` (five minutes without one), and on an unknown `kid`, at most once a minute
105
- * in all. A failed fetch keeps the keys held. Make one per request; concurrent fetches on it share one.
119
+ * jose's fetch of the set, with our rules on what comes back: jose gets only the Ed25519 keys, each without its `alg`,
120
+ * so it takes a token naming either. A fetch that fails, or a set the rules refuse, keeps what's held, which then holds
121
+ * for a minute before the next fetch.
106
122
  */
107
- const fetchedIdentityKeys = (id, jwksUri, options) => {
108
- const now = options.now ?? Date.now;
109
- let refreshing;
110
- const load = async () => {
111
- const held = fetched.get(id);
112
- const startedAt = now();
113
- if (held && startedAt - held.startedAt < REFETCH_EVERY_MS)
114
- return undefined;
115
- fetched.set(id, { ...held, startedAt });
116
- let url = id;
123
+ const checkedFetch = (entry, fetch = globalThis.fetch) => async (url, init) => {
124
+ if (Date.now() >= entry.retryAt) {
117
125
  try {
118
- url = await jwksUri();
119
- const response = await getJson(url, options.fetch);
126
+ const response = await fetch(new Request(url, init));
120
127
  if (!response.ok)
121
128
  throw new Error(`${response.status}`);
122
129
  const keys = identityKeys(await response.text());
123
- fetched.set(id, { keys, fetchedAt: now(), maxAgeMs: maxAgeOf(response) * 1000, startedAt });
124
- return keys;
130
+ entry.jwks = { keys: Object.entries(keys).map(([kid, x]) => ({ kty: "OKP", crv: "Ed25519", kid, x })) };
131
+ entry.maxAgeMs = Math.max(maxAgeOf(response) * 1000, REFETCH_EVERY_MS);
125
132
  }
126
133
  catch (error) {
127
134
  console.error(`[zite] couldn't fetch the identity keys from ${url}`, error);
128
- return undefined;
135
+ entry.retryAt = Date.now() + REFETCH_EVERY_MS;
136
+ entry.maxAgeMs = REFETCH_EVERY_MS;
129
137
  }
130
- };
131
- const refresh = () => (refreshing ??= load());
132
- const held = () => fetched.get(id)?.keys ?? options.initial ?? {};
133
- return {
134
- current: () => {
135
- const entry = fetched.get(id);
136
- const fresh = entry?.keys !== undefined && entry.fetchedAt !== undefined && now() - entry.fetchedAt < (entry.maxAgeMs ?? 0);
137
- return fresh ? held() : refresh().then((keys) => keys ?? held());
138
- },
139
- refresh,
140
- };
138
+ }
139
+ if (!entry.jwks)
140
+ throw new Error(`No identity keys from ${url}`);
141
+ return Response.json(entry.jwks);
142
+ };
143
+ /**
144
+ * jose's set over the keys at `url`, held per process under `id`: refetched once older than its response's `max-age`
145
+ * (five minutes without one, a minute at least), and on an unknown `kid` at most once a minute.
146
+ */
147
+ const remoteKeySet = (id, url, fetch) => {
148
+ const entry = fetchedFor(id);
149
+ return createRemoteJWKSet(new URL(url), {
150
+ timeoutDuration: FETCH_TIMEOUT_MS,
151
+ cacheMaxAge: entry.maxAgeMs,
152
+ cooldownDuration: REFETCH_EVERY_MS,
153
+ [jwksCache]: entry.cache,
154
+ [customFetch]: checkedFetch(entry, fetch),
155
+ });
156
+ };
157
+ /** Keys from the JWK Set at `url`, as {@link remoteKeySet} holds them. Make one per request. */
158
+ export const remoteIdentityKeys = (url, options = {}) => {
159
+ let keySet;
160
+ return async (header) => (keySet ??= remoteKeySet(url, url, options.fetch))(header);
141
161
  };
142
- /** Keys from the JWK Set at `url`, as {@link fetchedIdentityKeys} holds them. */
143
- export const remoteIdentityKeys = (url, options = {}) => fetchedIdentityKeys(url, async () => url, options);
144
162
  const isHttpUrl = (value) => {
145
163
  try {
146
164
  return typeof value === "string" && /^https?:$/.test(new URL(value).protocol);
@@ -151,21 +169,38 @@ const isHttpUrl = (value) => {
151
169
  };
152
170
  /**
153
171
  * The `jwks_uri` of `issuer`'s discovery document (OpenID Connect Discovery 1.0 §4), fetched once per process. It must
154
- * name this issuer (§4.3), and an http(s) URL.
172
+ * name this issuer (§4.3), and an http(s) URL. A failed fetch waits a minute, as the keys' does.
155
173
  */
156
- const jwksUriOf = async (issuer, fetch) => {
174
+ const jwksUriOf = async (issuer, entry, fetch) => {
157
175
  const held = discovered.get(issuer);
158
176
  if (held)
159
177
  return held;
160
- const response = await getJson(`${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`, fetch);
161
- if (!response.ok)
162
- throw new Error(`discovery answered ${response.status}`);
163
- const metadata = await response.json();
164
- const jwksUri = isRecord(metadata) && metadata.issuer === issuer ? metadata.jwks_uri : undefined;
165
- if (!isHttpUrl(jwksUri))
166
- throw new Error(`${issuer}'s discovery document names no jwks_uri for it`);
167
- discovered.set(issuer, jwksUri);
168
- return jwksUri;
178
+ const url = `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
179
+ if (Date.now() < entry.retryAt)
180
+ throw new Error(`No identity keys from ${url}`);
181
+ try {
182
+ const response = await getJson(url, fetch);
183
+ if (!response.ok)
184
+ throw new Error(`discovery answered ${response.status}`);
185
+ const metadata = await response.json();
186
+ const jwksUri = isRecord(metadata) && metadata.issuer === issuer ? metadata.jwks_uri : undefined;
187
+ if (!isHttpUrl(jwksUri))
188
+ throw new Error(`${issuer}'s discovery document names no jwks_uri for it`);
189
+ discovered.set(issuer, jwksUri);
190
+ return jwksUri;
191
+ }
192
+ catch (error) {
193
+ console.error(`[zite] couldn't fetch the identity keys from ${url}`, error);
194
+ entry.retryAt = Date.now() + REFETCH_EVERY_MS;
195
+ throw error;
196
+ }
169
197
  };
170
198
  /** Keys from the JWK Set `issuer`'s discovery document names, as {@link remoteIdentityKeys} holds them. */
171
- export const discoveredIdentityKeys = (issuer, options = {}) => fetchedIdentityKeys(`${issuer}/.well-known/openid-configuration`, () => jwksUriOf(issuer, options.fetch), options);
199
+ export const discoveredIdentityKeys = (issuer, options = {}) => {
200
+ const id = `${issuer}/.well-known/openid-configuration`;
201
+ let keySet;
202
+ return async (header) => {
203
+ keySet ??= jwksUriOf(issuer, fetchedFor(id), options.fetch).then((url) => remoteKeySet(id, url, options.fetch));
204
+ return (await keySet)(header);
205
+ };
206
+ };
@@ -103,9 +103,7 @@ export const createSignIn = (config) => {
103
103
  const context = config.cookies;
104
104
  // Never framed: off Zite only, and a refresh token stays first-party.
105
105
  const sessionContext = { secure: context.secure, framed: false };
106
- const keySource = "current" in config.keys && typeof config.keys.current === "function"
107
- ? config.keys
108
- : staticIdentityKeys(config.keys);
106
+ const keySource = typeof config.keys === "function" ? config.keys : staticIdentityKeys(config.keys);
109
107
  const verifier = createIdentityVerifier(keySource, { onRefusal: config.onRefusal });
110
108
  const scope = transport.longLived.kind === "refresh-token" ? "openid offline_access" : "openid";
111
109
  const longLivedNames = transport.longLived.kind === "session-cookie" ? transport.longLived.names : undefined;
@@ -69,8 +69,8 @@ export type RefusalReport = {
69
69
  };
70
70
  /**
71
71
  * Verifies identity tokens against `keys`, in §6.1's order, the header's `alg` `EdDSA` or RFC 9864's `Ed25519`. A
72
- * `kid` the keys don't know triggers one refetch. Each
73
- * refusal is reported to `onRefusal`, by default logged once per reason and key id.
72
+ * `kid` fetched keys don't know triggers a refetch, at most once a minute. Each refusal is reported to `onRefusal`, by
73
+ * default logged once per reason and key id.
74
74
  */
75
75
  export declare const createIdentityVerifier: (keys: IdentityKeySource, options?: {
76
76
  onRefusal?: (report: RefusalReport) => void;
@@ -1,7 +1,8 @@
1
1
  // The identity token's verifier (T5 design §6.1), the same rules as restly's `identityToken.ts` on the front and the
2
- // dispatcher. Web Crypto only.
3
- import { fromBase64Url, isRecord, jsonOf, utf8 } from "./encoding.js";
4
- import { ED25519_ALGS } from "./keys.js";
2
+ // dispatcher. jose checks the signature, on Web Crypto; the rules around it are ours.
3
+ import { compactVerify, errors } from "jose";
4
+ import { fromBase64Url, isRecord, jsonOf } from "./encoding.js";
5
+ import { ED25519_ALGS, isEd25519Alg } from "./keys.js";
5
6
  /** The `typ` every identity token carries in its header, and nothing else does. */
6
7
  export const IDENTITY_TOKEN_TYPE = "zite-id+jwt";
7
8
  export const DEFAULT_MAX_LIFETIME_S = 300;
@@ -57,24 +58,13 @@ const previewOk = (preview, mode, pinned) => {
57
58
  preview.editor.length > 0 &&
58
59
  (pinned === undefined || preview.build === pinned));
59
60
  };
60
- // Imported once per process; a CryptoKey holds no request's I/O.
61
- const imported = new Map();
62
- const publicKey = async (raw) => {
63
- const held = imported.get(raw);
64
- if (held)
65
- return held;
66
- const bytes = fromBase64Url(raw);
67
- if (!bytes)
68
- return undefined;
69
- try {
70
- const key = await crypto.subtle.importKey("raw", bytes, { name: "Ed25519" }, false, ["verify"]);
71
- imported.set(raw, key);
72
- return key;
73
- }
74
- catch {
75
- return undefined;
76
- }
77
- };
61
+ // What jose's refusal says of the token: a signature its key didn't make, a header jose won't take (an unknown
62
+ // `crit`), or no key to check it with.
63
+ const refusalOf = (error) => error instanceof errors.JWSSignatureVerificationFailed
64
+ ? "signature"
65
+ : error instanceof errors.JWSInvalid || error instanceof errors.JOSENotSupported
66
+ ? "malformed"
67
+ : "kid";
78
68
  // Reported once per reason and key id, and only so many: both come from the caller.
79
69
  const MAX_REPORTED = 64;
80
70
  const reported = new Set();
@@ -87,8 +77,8 @@ const reportOnce = (report) => {
87
77
  };
88
78
  /**
89
79
  * Verifies identity tokens against `keys`, in §6.1's order, the header's `alg` `EdDSA` or RFC 9864's `Ed25519`. A
90
- * `kid` the keys don't know triggers one refetch. Each
91
- * refusal is reported to `onRefusal`, by default logged once per reason and key id.
80
+ * `kid` fetched keys don't know triggers a refetch, at most once a minute. Each refusal is reported to `onRefusal`, by
81
+ * default logged once per reason and key id.
92
82
  */
93
83
  export const createIdentityVerifier = (keys, options = {}) => async (token, expect) => {
94
84
  const refuse = (reason, kid) => {
@@ -101,25 +91,29 @@ export const createIdentityVerifier = (keys, options = {}) => async (token, expe
101
91
  return refuse("malformed");
102
92
  const [headerPart, payloadPart, signaturePart] = parts;
103
93
  const header = jsonOf(fromBase64Url(headerPart));
104
- const payload = jsonOf(fromBase64Url(payloadPart));
105
- const signature = fromBase64Url(signaturePart);
106
- if (!isRecord(header) || !isRecord(payload) || !signature)
94
+ const claimed = jsonOf(fromBase64Url(payloadPart));
95
+ // One spelling of each segment: jose decodes base64url as loosely as atob, and would take a respelled or padded
96
+ // signature.
97
+ if (!isRecord(header) || !isRecord(claimed) || !fromBase64Url(signaturePart))
107
98
  return refuse("malformed");
108
- if (!ED25519_ALGS.has(header.alg))
99
+ if (!isEd25519Alg(header.alg))
109
100
  return refuse("alg");
110
101
  if (header.typ !== IDENTITY_TOKEN_TYPE)
111
102
  return refuse("typ");
112
103
  const kid = typeof header.kid === "string" ? header.kid : undefined;
113
104
  if (kid === undefined)
114
105
  return refuse("kid");
115
- const own = (map) => (map && Object.hasOwn(map, kid) ? map[kid] : undefined);
116
- const raw = own(await keys.current()) ?? own(await keys.refresh());
117
- if (!raw)
118
- return refuse("kid", kid);
119
- const key = await publicKey(raw);
120
- const genuine = !!key && (await crypto.subtle.verify({ name: "Ed25519" }, key, signature, utf8(`${headerPart}.${payloadPart}`)));
121
- if (!genuine)
122
- return refuse("signature", kid);
106
+ let signed;
107
+ try {
108
+ ({ payload: signed } = await compactVerify(token, keys, { algorithms: ED25519_ALGS }));
109
+ }
110
+ catch (error) {
111
+ return refuse(refusalOf(error), kid);
112
+ }
113
+ // Read from what jose verified, which under a `b64: false` header isn't the segment's decoding.
114
+ const payload = jsonOf(signed);
115
+ if (!isRecord(payload))
116
+ return refuse("malformed", kid);
123
117
  if (payload.iss !== expect.issuer)
124
118
  return refuse("iss", kid);
125
119
  if (typeof payload.aud !== "string" || payload.aud !== expect.clientId)
@@ -0,0 +1,17 @@
1
+ /** How long a read is served from the cache, as classic's. */
2
+ export declare const AIRTABLE_READ_TTL_MS = 10000;
3
+ export type AirtableCache = {
4
+ /** A read kept across requests; a write to `table` makes it stale. */
5
+ read<T>(table: string, key: string, load: () => Promise<T>): Promise<T>;
6
+ /** A write to `table`, which makes its reads stale in every isolate the cache reaches, this request's at once. */
7
+ wrote(table: string): Promise<void>;
8
+ };
9
+ /**
10
+ * One request's view of the cache for one connection. Entries are keyed by its token's hash, so only a caller holding
11
+ * the same token reads them, whoever shares the cache.
12
+ */
13
+ export declare const createAirtableCache: ({ token, waitUntil, now, }: {
14
+ token: string;
15
+ waitUntil?: (promise: Promise<unknown>) => void;
16
+ now?: () => number;
17
+ }) => Promise<AirtableCache | undefined>;