zitejs 0.10.0-start.27 → 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.
- package/dist/cjs/check/start/sourceRules.js +7 -0
- package/dist/cjs/start/airtable/cache.d.ts +17 -0
- package/dist/cjs/start/airtable/cache.js +76 -0
- package/dist/cjs/start/types.d.ts +37 -7
- package/dist/esm/check/start/sourceRules.js +7 -0
- package/dist/esm/signin/index.d.ts +1 -1
- package/dist/esm/signin/index.js +1 -1
- package/dist/esm/signin/keys.d.ts +26 -19
- package/dist/esm/signin/keys.js +167 -45
- package/dist/esm/signin/signin.js +1 -3
- package/dist/esm/signin/verify.d.ts +4 -3
- package/dist/esm/signin/verify.js +30 -34
- package/dist/esm/start/airtable/cache.d.ts +17 -0
- package/dist/esm/start/airtable/cache.js +72 -0
- package/dist/esm/start/airtable/dispatch.d.ts +3 -0
- package/dist/esm/start/airtable/dispatch.js +14 -12
- package/dist/esm/start/airtable/index.js +8 -0
- package/dist/esm/start/data/baseRunner.d.ts +5 -0
- package/dist/esm/start/data/baseRunner.js +10 -0
- package/dist/esm/start/data/dispatch.d.ts +1 -0
- package/dist/esm/start/data/dispatch.js +13 -1
- package/dist/esm/start/demo.d.ts +11 -0
- package/dist/esm/start/demo.js +21 -0
- package/dist/esm/start/direct.js +7 -3
- package/dist/esm/start/fetch.js +3 -1
- package/dist/esm/start/localSignIn.d.ts +2 -4
- package/dist/esm/start/localSignIn.js +4 -5
- package/dist/esm/start/outbound.js +1 -0
- package/dist/esm/start/requestEnv.d.ts +8 -0
- package/dist/esm/start/requestEnv.js +115 -0
- package/dist/esm/start/server.d.ts +2 -1
- package/dist/esm/start/server.js +24 -28
- package/dist/esm/start/steps.d.ts +15 -15
- package/dist/esm/start/steps.js +56 -81
- package/dist/esm/start/types.d.ts +37 -7
- package/dist/esm/start/version.d.ts +1 -1
- package/dist/esm/start/version.js +1 -1
- package/dist/esm/start/workflowRun.d.ts +30 -5
- package/dist/esm/start/workflowRun.js +28 -20
- 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
|
|
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,6 +1,6 @@
|
|
|
1
1
|
export { createSignIn, isSignInPath, PREVIEW_IDENTITY_HEADER, PREVIEW_IDENTITY_PARAM, type Resolution, type SignIn, type SignInConfig } from "./signin.js";
|
|
2
2
|
export { createIdentityVerifier, DEFAULT_MAX_LIFETIME_S, IDENTITY_TOKEN_TYPE, type IdentityClaims, type IdentityMode, type IdentityVerifier, type Refusal, type RefusalReport, type Verdict, type VerifyExpectations, } from "./verify.js";
|
|
3
|
-
export { identityKeys, remoteIdentityKeys, staticIdentityKeys, type IdentityKeys, type IdentityKeySource, } from "./keys.js";
|
|
3
|
+
export { discoveredIdentityKeys, identityKeys, remoteIdentityKeys, staticIdentityKeys, type IdentityKeys, type IdentityKeySource, } from "./keys.js";
|
|
4
4
|
export { clearCookie, cookieName, isModuleCookie, MODULE_COOKIES, type CookieContext, type ModuleCookie } from "./cookies.js";
|
|
5
5
|
export { aesGcmSealer, type Sealer } from "./seal.js";
|
|
6
6
|
export { httpTransport, type ClientAuth, type HttpTransportOptions } from "./http.js";
|
package/dist/esm/signin/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// bundle, in an app's Worker and on Node alike.
|
|
3
3
|
export { createSignIn, isSignInPath, PREVIEW_IDENTITY_HEADER, PREVIEW_IDENTITY_PARAM } from "./signin.js";
|
|
4
4
|
export { createIdentityVerifier, DEFAULT_MAX_LIFETIME_S, IDENTITY_TOKEN_TYPE, } from "./verify.js";
|
|
5
|
-
export { identityKeys, remoteIdentityKeys, staticIdentityKeys, } from "./keys.js";
|
|
5
|
+
export { discoveredIdentityKeys, identityKeys, remoteIdentityKeys, staticIdentityKeys, } from "./keys.js";
|
|
6
6
|
export { clearCookie, cookieName, isModuleCookie, MODULE_COOKIES } from "./cookies.js";
|
|
7
7
|
export { aesGcmSealer } from "./seal.js";
|
|
8
8
|
export { httpTransport } from "./http.js";
|
|
@@ -1,30 +1,37 @@
|
|
|
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
|
-
current(): IdentityKeys;
|
|
9
|
-
/** The keys after a refetch, or undefined when none happened (none configured, or one ran under a minute ago). */
|
|
10
|
-
refresh(): Promise<IdentityKeys | undefined>;
|
|
11
|
-
};
|
|
12
7
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
|
|
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>;
|
|
12
|
+
/** An Ed25519 key's JWS `alg`: RFC 9864's `Ed25519`, or the older `EdDSA`, which the identity server signs with. */
|
|
13
|
+
export declare const ED25519_ALGS: string[];
|
|
14
|
+
export declare const isEd25519Alg: (alg: unknown) => boolean;
|
|
15
|
+
/**
|
|
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
|
+
* zitejs doesn't use (another `kty`, `crv` or `alg`, an RS256 key for other clients, say) is skipped and logged, as
|
|
18
|
+
* RFC 7517 §5 has it, so a key type the issuer adds later doesn't break an older zitejs. Anything else throws, so a bad
|
|
19
|
+
* deploy fails at once: a document that isn't a set, an Ed25519 key with a bad `x`, `kid` or `use`, a private member in
|
|
20
|
+
* any key, a `kid` two keys share, or no Ed25519 key at all.
|
|
16
21
|
*/
|
|
17
22
|
export declare const identityKeys: (json: string) => IdentityKeys;
|
|
18
23
|
/** Keys that never change: the dispatcher's configured set. */
|
|
19
24
|
export declare const staticIdentityKeys: (keys: IdentityKeys) => IdentityKeySource;
|
|
20
|
-
/**
|
|
25
|
+
/** How long a response may be held, in seconds, by its `Cache-Control` (RFC 9111 §5.2.2): its `max-age`, or none. */
|
|
26
|
+
export declare const maxAgeOf: (response: Response) => number;
|
|
27
|
+
type Fetch = (request: Request) => Promise<Response>;
|
|
28
|
+
type FetchOptions = {
|
|
29
|
+
fetch?: Fetch;
|
|
30
|
+
};
|
|
31
|
+
/** For tests: forget every fetched key set and discovery document. */
|
|
21
32
|
export declare const resetFetchedIdentityKeys: () => void;
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
export
|
|
27
|
-
initial?: IdentityKeys;
|
|
28
|
-
fetch?: (request: Request) => Promise<Response>;
|
|
29
|
-
now?: () => number;
|
|
30
|
-
}) => 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;
|
|
35
|
+
/** Keys from the JWK Set `issuer`'s discovery document names, as {@link remoteIdentityKeys} holds them. */
|
|
36
|
+
export declare const discoveredIdentityKeys: (issuer: string, options?: FetchOptions) => IdentityKeySource;
|
|
37
|
+
export {};
|
package/dist/esm/signin/keys.js
CHANGED
|
@@ -1,20 +1,39 @@
|
|
|
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
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
4
|
+
/** An Ed25519 key's JWS `alg`: RFC 9864's `Ed25519`, or the older `EdDSA`, which the identity server signs with. */
|
|
5
|
+
export const ED25519_ALGS = ["EdDSA", "Ed25519"];
|
|
6
|
+
export const isEd25519Alg = (alg) => ED25519_ALGS.some((known) => known === alg);
|
|
7
|
+
// RFC 7518 §6's private members, of every key type.
|
|
8
|
+
const PRIVATE_MEMBERS = ["d", "p", "q", "dp", "dq", "qi", "oth", "k"];
|
|
9
|
+
// The kind of key the identity server signs with; a set may hold others, for other clients.
|
|
10
|
+
const isEd25519Kind = (jwk) => jwk.kty === "OKP" && jwk.crv === "Ed25519" && (jwk.alg === undefined || isEd25519Alg(jwk.alg));
|
|
11
|
+
/** An Ed25519 key's `kid` and `x`, or what's wrong with it: an operator's typo, which fails at once, never skipped. */
|
|
12
|
+
const ed25519KeyOf = (jwk) => {
|
|
13
|
+
if (jwk.use !== undefined && jwk.use !== "sig")
|
|
14
|
+
return { problem: "use must be sig" };
|
|
15
|
+
if (typeof jwk.x !== "string" || fromBase64Url(jwk.x)?.length !== 32)
|
|
16
|
+
return { problem: "x must be a 32-byte key" };
|
|
17
|
+
if (typeof jwk.kid !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(jwk.kid))
|
|
18
|
+
return { problem: "kid must be 1 to 64 letters, digits, - or _" };
|
|
19
|
+
return { kid: jwk.kid, x: jwk.x };
|
|
20
|
+
};
|
|
21
|
+
// Each skipped key is logged once per process, and only so many: a fetched set is read again on every refetch.
|
|
22
|
+
const MAX_REPORTED_SKIPS = 32;
|
|
23
|
+
const reportedSkips = new Set();
|
|
24
|
+
const reportSkipped = (jwk) => {
|
|
25
|
+
const key = JSON.stringify({ kid: jwk.kid, kty: jwk.kty, crv: jwk.crv, alg: jwk.alg });
|
|
26
|
+
if (reportedSkips.has(key) || reportedSkips.size >= MAX_REPORTED_SKIPS)
|
|
27
|
+
return;
|
|
28
|
+
reportedSkips.add(key);
|
|
29
|
+
console.warn(`[zite] skipped a key of another kind in ${KEY_SET_NAME}: ${key.slice(0, 256)}`);
|
|
30
|
+
};
|
|
14
31
|
/**
|
|
15
|
-
* Parses the identity issuer's JWK Set
|
|
16
|
-
*
|
|
17
|
-
*
|
|
32
|
+
* Parses the identity issuer's JWK Set by the rule every verifier of it follows, restly's included. A key of a kind
|
|
33
|
+
* zitejs doesn't use (another `kty`, `crv` or `alg`, an RS256 key for other clients, say) is skipped and logged, as
|
|
34
|
+
* RFC 7517 §5 has it, so a key type the issuer adds later doesn't break an older zitejs. Anything else throws, so a bad
|
|
35
|
+
* deploy fails at once: a document that isn't a set, an Ed25519 key with a bad `x`, `kid` or `use`, a private member in
|
|
36
|
+
* any key, a `kid` two keys share, or no Ed25519 key at all.
|
|
18
37
|
*/
|
|
19
38
|
export const identityKeys = (json) => {
|
|
20
39
|
let parsed;
|
|
@@ -28,57 +47,160 @@ export const identityKeys = (json) => {
|
|
|
28
47
|
throw new Error(`${KEY_SET_NAME} must be a JSON object with a keys array`);
|
|
29
48
|
// No prototype, so a `kid` of `__proto__` is a key like any other.
|
|
30
49
|
const keys = Object.create(null);
|
|
31
|
-
for (const jwk of parsed.keys) {
|
|
32
|
-
const
|
|
33
|
-
|
|
50
|
+
for (const [index, jwk] of parsed.keys.entries()) {
|
|
51
|
+
const name = isRecord(jwk) && typeof jwk.kid === "string" ? jwk.kid.slice(0, 64) : `#${index}`;
|
|
52
|
+
const fail = (problem) => new Error(`${KEY_SET_NAME}: key ${name}: ${problem}`);
|
|
53
|
+
if (!isRecord(jwk))
|
|
54
|
+
throw fail("must be a JSON object");
|
|
55
|
+
if (PRIVATE_MEMBERS.some((member) => Object.hasOwn(jwk, member)))
|
|
56
|
+
throw fail("holds a private key");
|
|
57
|
+
if (!isEd25519Kind(jwk)) {
|
|
58
|
+
reportSkipped(jwk);
|
|
34
59
|
continue;
|
|
60
|
+
}
|
|
61
|
+
const key = ed25519KeyOf(jwk);
|
|
62
|
+
if ("problem" in key)
|
|
63
|
+
throw fail(key.problem);
|
|
35
64
|
if (Object.hasOwn(keys, key.kid))
|
|
36
65
|
throw new Error(`${KEY_SET_NAME}: key ${key.kid} is in it twice`);
|
|
37
66
|
keys[key.kid] = key.x;
|
|
38
67
|
}
|
|
68
|
+
if (Object.keys(keys).length === 0)
|
|
69
|
+
throw new Error(`${KEY_SET_NAME} holds no Ed25519 key`);
|
|
39
70
|
return keys;
|
|
40
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
|
+
};
|
|
41
82
|
/** Keys that never change: the dispatcher's configured set. */
|
|
42
|
-
export const staticIdentityKeys = (keys) => ({
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
+
};
|
|
46
88
|
const REFETCH_EVERY_MS = 60_000;
|
|
47
89
|
const FETCH_TIMEOUT_MS = 5_000;
|
|
48
|
-
//
|
|
49
|
-
|
|
90
|
+
// What the backend sends, and how long a set is held when its response names no max-age.
|
|
91
|
+
const DEFAULT_MAX_AGE_S = 300;
|
|
92
|
+
/** How long a response may be held, in seconds, by its `Cache-Control` (RFC 9111 §5.2.2): its `max-age`, or none. */
|
|
93
|
+
export const maxAgeOf = (response) => {
|
|
94
|
+
const directives = (response.headers.get("cache-control") ?? "")
|
|
95
|
+
.toLowerCase()
|
|
96
|
+
.split(",")
|
|
97
|
+
.map((directive) => directive.trim());
|
|
98
|
+
if (directives.includes("no-store") || directives.includes("no-cache"))
|
|
99
|
+
return 0;
|
|
100
|
+
const maxAge = directives.map((directive) => /^max-age=(\d+)$/.exec(directive)?.[1]).find((value) => value !== undefined);
|
|
101
|
+
return maxAge === undefined ? DEFAULT_MAX_AGE_S : Number(maxAge);
|
|
102
|
+
};
|
|
103
|
+
const getJson = (url, fetch = globalThis.fetch) => fetch(new Request(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }));
|
|
50
104
|
const fetched = new Map();
|
|
51
|
-
|
|
52
|
-
|
|
105
|
+
// Per process, each issuer's `jwks_uri`, once its discovery document named it.
|
|
106
|
+
const discovered = new Map();
|
|
107
|
+
/** For tests: forget every fetched key set and discovery document. */
|
|
108
|
+
export const resetFetchedIdentityKeys = () => {
|
|
109
|
+
fetched.clear();
|
|
110
|
+
discovered.clear();
|
|
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
|
+
};
|
|
53
118
|
/**
|
|
54
|
-
*
|
|
55
|
-
*
|
|
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.
|
|
56
122
|
*/
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
let refreshing;
|
|
60
|
-
const load = async () => {
|
|
61
|
-
const held = fetched.get(url);
|
|
62
|
-
const startedAt = now();
|
|
63
|
-
if (held && startedAt - held.startedAt < REFETCH_EVERY_MS)
|
|
64
|
-
return undefined;
|
|
65
|
-
fetched.set(url, { keys: held?.keys, startedAt });
|
|
123
|
+
const checkedFetch = (entry, fetch = globalThis.fetch) => async (url, init) => {
|
|
124
|
+
if (Date.now() >= entry.retryAt) {
|
|
66
125
|
try {
|
|
67
|
-
const
|
|
68
|
-
const response = await (options.fetch ?? fetch)(request);
|
|
126
|
+
const response = await fetch(new Request(url, init));
|
|
69
127
|
if (!response.ok)
|
|
70
128
|
throw new Error(`${response.status}`);
|
|
71
129
|
const keys = identityKeys(await response.text());
|
|
72
|
-
|
|
73
|
-
|
|
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);
|
|
74
132
|
}
|
|
75
133
|
catch (error) {
|
|
76
134
|
console.error(`[zite] couldn't fetch the identity keys from ${url}`, error);
|
|
77
|
-
|
|
135
|
+
entry.retryAt = Date.now() + REFETCH_EVERY_MS;
|
|
136
|
+
entry.maxAgeMs = REFETCH_EVERY_MS;
|
|
78
137
|
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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);
|
|
161
|
+
};
|
|
162
|
+
const isHttpUrl = (value) => {
|
|
163
|
+
try {
|
|
164
|
+
return typeof value === "string" && /^https?:$/.test(new URL(value).protocol);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* The `jwks_uri` of `issuer`'s discovery document (OpenID Connect Discovery 1.0 §4), fetched once per process. It must
|
|
172
|
+
* name this issuer (§4.3), and an http(s) URL. A failed fetch waits a minute, as the keys' does.
|
|
173
|
+
*/
|
|
174
|
+
const jwksUriOf = async (issuer, entry, fetch) => {
|
|
175
|
+
const held = discovered.get(issuer);
|
|
176
|
+
if (held)
|
|
177
|
+
return held;
|
|
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
|
+
}
|
|
197
|
+
};
|
|
198
|
+
/** Keys from the JWK Set `issuer`'s discovery document names, as {@link remoteIdentityKeys} holds them. */
|
|
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);
|
|
83
205
|
};
|
|
84
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 = "
|
|
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;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type IdentityKeySource } from "./keys.js";
|
|
2
2
|
export type IdentityMode = "live" | "preview" | "demo" | "dev";
|
|
3
3
|
/** The `typ` every identity token carries in its header, and nothing else does. */
|
|
4
4
|
export declare const IDENTITY_TOKEN_TYPE = "zite-id+jwt";
|
|
@@ -68,8 +68,9 @@ export type RefusalReport = {
|
|
|
68
68
|
kid?: string;
|
|
69
69
|
};
|
|
70
70
|
/**
|
|
71
|
-
* Verifies identity tokens against `keys`, in §6.1's order
|
|
72
|
-
*
|
|
71
|
+
* Verifies identity tokens against `keys`, in §6.1's order, the header's `alg` `EdDSA` or RFC 9864's `Ed25519`. A
|
|
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.
|
|
73
74
|
*/
|
|
74
75
|
export declare const createIdentityVerifier: (keys: IdentityKeySource, options?: {
|
|
75
76
|
onRefusal?: (report: RefusalReport) => void;
|