zitejs 0.10.0-start.24 → 0.10.0-start.27

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 (42) hide show
  1. package/dist/cjs/dev/signin.d.ts +2 -2
  2. package/dist/cjs/dev/signin.js +5 -5
  3. package/dist/cjs/start/provider.d.ts +8 -6
  4. package/dist/cjs/start/provider.js +98 -37
  5. package/dist/cjs/start/types.d.ts +54 -10
  6. package/dist/esm/dev/signin.d.ts +2 -2
  7. package/dist/esm/dev/signin.js +6 -6
  8. package/dist/esm/signin/conformance.js +1 -1
  9. package/dist/esm/signin/index.d.ts +1 -1
  10. package/dist/esm/signin/index.js +1 -1
  11. package/dist/esm/signin/keys.d.ts +11 -20
  12. package/dist/esm/signin/keys.js +32 -28
  13. package/dist/esm/signin/verify.d.ts +2 -2
  14. package/dist/esm/signin/verify.js +3 -6
  15. package/dist/esm/start/direct.d.ts +3 -3
  16. package/dist/esm/start/direct.js +14 -16
  17. package/dist/esm/start/index.d.ts +1 -1
  18. package/dist/esm/start/localSignIn.d.ts +1 -1
  19. package/dist/esm/start/localSignIn.js +1 -1
  20. package/dist/esm/start/pageHead.d.ts +3 -3
  21. package/dist/esm/start/pageHead.js +3 -8
  22. package/dist/esm/start/provider.d.ts +8 -6
  23. package/dist/esm/start/provider.js +96 -35
  24. package/dist/esm/start/sdk/axios.d.ts +76 -0
  25. package/dist/esm/start/sdk/axios.js +210 -0
  26. package/dist/esm/start/sdk/nodeFetch.d.ts +41 -0
  27. package/dist/esm/start/sdk/nodeFetch.js +33 -0
  28. package/dist/esm/start/sdk/undici.d.ts +34 -0
  29. package/dist/esm/start/sdk/undici.js +18 -0
  30. package/dist/esm/start/sdkPatches.d.ts +22 -0
  31. package/dist/esm/start/sdkPatches.js +359 -0
  32. package/dist/esm/start/server.d.ts +3 -3
  33. package/dist/esm/start/server.js +17 -18
  34. package/dist/esm/start/types.d.ts +54 -10
  35. package/dist/esm/start/version.d.ts +1 -1
  36. package/dist/esm/start/version.js +1 -1
  37. package/dist/esm/start/vite.js +2 -0
  38. package/package.json +2 -1
  39. package/dist/cjs/internal/appToken.d.ts +0 -17
  40. package/dist/cjs/internal/appToken.js +0 -26
  41. package/dist/esm/internal/appToken.d.ts +0 -17
  42. package/dist/esm/internal/appToken.js +0 -22
@@ -9,8 +9,8 @@ export type DevSignInResult = {
9
9
  reason: string;
10
10
  };
11
11
  /**
12
- * Writes the app's `.zite/dev.env` from its dev token's `appUrl`: issuer `<appUrl>/auth`, client `<app>:dev`. Keeps
13
- * the secret a previous run wrote, so sessions outlive a restart.
12
+ * Writes the app's `.zite/dev.env` from the app URL the backend gives its dev token: issuer `<appUrl>/auth`, client
13
+ * `<app>:dev`. Keeps the secret a previous run wrote, so sessions outlive a restart.
14
14
  */
15
15
  export declare function writeDevSignIn(appDir: string, shell?: Env): Promise<DevSignInResult>;
16
16
  export {};
@@ -8,7 +8,6 @@ const node_crypto_1 = require("node:crypto");
8
8
  const node_fs_1 = require("node:fs");
9
9
  const node_path_1 = require("node:path");
10
10
  const dotenv_1 = require("dotenv");
11
- const appToken_js_1 = require("../internal/appToken.js");
12
11
  const provider_js_1 = require("../start/provider.js");
13
12
  exports.DEV_ENV_FILE = (0, node_path_1.join)(".zite", "dev.env");
14
13
  const readEnvFile = (path) => {
@@ -43,8 +42,8 @@ const ignoreDevEnv = (appDir) => {
43
42
  (0, node_fs_1.writeFileSync)(path, `${current}${current && !current.endsWith("\n") ? "\n" : ""}dev.env\n`);
44
43
  };
45
44
  /**
46
- * Writes the app's `.zite/dev.env` from its dev token's `appUrl`: issuer `<appUrl>/auth`, client `<app>:dev`. Keeps
47
- * the secret a previous run wrote, so sessions outlive a restart.
45
+ * Writes the app's `.zite/dev.env` from the app URL the backend gives its dev token: issuer `<appUrl>/auth`, client
46
+ * `<app>:dev`. Keeps the secret a previous run wrote, so sessions outlive a restart.
48
47
  */
49
48
  async function writeDevSignIn(appDir, shell = process.env) {
50
49
  const env = appEnvOf(appDir, shell);
@@ -55,8 +54,9 @@ async function writeDevSignIn(appDir, shell = process.env) {
55
54
  const given = env[provider_js_1.LOCAL_ENV.token];
56
55
  if (!given && !apiKey)
57
56
  return { written: false, reason: `neither ${provider_js_1.LOCAL_ENV.token} nor ${provider_js_1.LOCAL_ENV.apiKey} is set` };
58
- const token = given ?? (await (0, provider_js_1.mintDevToken)((0, provider_js_1.localUrls)(env[provider_js_1.LOCAL_ENV.urls]).backend, appId, apiKey));
59
- const appUrl = (0, appToken_js_1.appTokenClaims)(token)?.appUrl;
57
+ const { backend } = (0, provider_js_1.localUrls)(env[provider_js_1.LOCAL_ENV.urls]);
58
+ const token = given ?? (await (0, provider_js_1.mintDevToken)(backend, appId, apiKey)).token;
59
+ const { appUrl } = await (0, provider_js_1.describeDevToken)(backend, token);
60
60
  if (!appUrl)
61
61
  return { written: false, reason: "the app has no live URL yet; publish it once to sign in under vite dev" };
62
62
  const issuer = `${new URL(appUrl).origin}/auth`;
@@ -1,5 +1,4 @@
1
- import { type AppTokenClaims } from "../internal/appToken.js";
2
- import type { HostMode, HostProps, PlatformProvider, PlatformUrls } from "./types.js";
1
+ import type { AppContext, ExpiringToken, HostProps, PlatformProvider, PlatformUrls } from "./types.js";
3
2
  export declare const ziteProvider: (props: HostProps) => PlatformProvider;
4
3
  /** What `local` reads, documented in `zitejs`'s help. */
5
4
  export declare const LOCAL_ENV: {
@@ -11,11 +10,14 @@ export declare const LOCAL_ENV: {
11
10
  type Env = Record<string, string | undefined>;
12
11
  /** `ZITE_URLS`, or a throw saying what it must name. */
13
12
  export declare const localUrls: (raw: string | undefined) => PlatformUrls;
14
- /** The mode a dev token names; preview for one it doesn't. */
15
- export declare const localModeOf: (claims: AppTokenClaims | undefined) => HostMode;
16
- /** For tests: forget the minted dev token. */
13
+ /** For tests: forget the minted dev token and what the backend said of it. */
17
14
  export declare const resetDevToken: () => void;
18
- export declare const mintDevToken: (backend: string, appId: string, apiKey: string) => Promise<string>;
15
+ export declare const mintDevToken: (backend: string, appId: string, apiKey: string) => Promise<ExpiringToken>;
16
+ /**
17
+ * What the backend says of a dev token, from the claims it verified, as OAuth's token introspection answers: asked
18
+ * once per token, whose claims never change. Throws, saying why, when it won't say.
19
+ */
20
+ export declare const describeDevToken: (backend: string, token: string) => Promise<AppContext>;
19
21
  /**
20
22
  * `local` when the developer set a dev token, or a key to mint them with, else undefined. Throws on env it can't read,
21
23
  * so a typo fails loudly rather than signing nobody in.
@@ -1,46 +1,60 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.localPlatform = exports.mintDevToken = exports.resetDevToken = exports.localModeOf = exports.localUrls = exports.LOCAL_ENV = exports.ziteProvider = void 0;
4
- // The one place zitejs knows where the platform is. `zite`: Zite's dispatcher hands each request its app token, the
5
- // platform's URLs and who is calling, in props. `local`: a developer's machine, with a dev token the backend minted.
6
- const appToken_js_1 = require("../internal/appToken.js");
3
+ exports.localPlatform = exports.describeDevToken = exports.mintDevToken = exports.resetDevToken = exports.localUrls = exports.LOCAL_ENV = exports.ziteProvider = void 0;
4
+ // The one place zitejs knows where the platform is. `zite`: Zite's dispatcher hands each request its app token, what
5
+ // the platform says of the app, the platform's URLs and who is calling, in props. `local`: a developer's machine, with
6
+ // a dev token the backend minted, which the backend also describes. The token is opaque here: zitejs only sends it.
7
7
  const platformFetch_js_1 = require("../internal/platformFetch.js");
8
8
  const devApp_js_1 = require("./devApp.js");
9
9
  // A streamed answer can outlive the request's deadline, which the token's expiry follows.
10
10
  const RENEW_WITHIN_MS = 30_000;
11
- const expiresWithin = (token, ms) => {
12
- const claims = (0, appToken_js_1.appTokenClaims)(token);
13
- return claims !== undefined && claims.exp * 1000 - Date.now() < ms;
11
+ const expiresWithin = (expiresAt, ms) => expiresAt !== undefined && expiresAt - Date.now() < ms;
12
+ const isExpiringToken = (value) => {
13
+ const given = value;
14
+ return typeof given?.token === "string" && given.token !== "" && typeof given.expiresAt === "number" && Number.isFinite(given.expiresAt);
14
15
  };
16
+ const contextOf = ({ appId, buildId, baseId, mode, orgSettingsVersion, showZiteBadge, appUrl }) => ({
17
+ appId,
18
+ buildId,
19
+ baseId,
20
+ mode,
21
+ orgSettingsVersion,
22
+ showZiteBadge,
23
+ appUrl,
24
+ });
15
25
  const URL_NAMES = ["baseRunner", "backend", "gateway", "runs", "email", "pdf", "uploads", "steps"];
16
26
  // `local` may leave out the gateway (a call on Zite's AI key is then refused), `runs` (a preview sends no analytics,
17
27
  // and `local` keeps no run detail) and each service's own URL (the backend then answers it).
18
28
  const OPTIONAL_URLS = new Set(["gateway", "runs", "email", "pdf", "uploads", "steps"]);
19
29
  const trimmed = (urls) => Object.fromEntries(URL_NAMES.flatMap((name) => (urls[name] ? [[name, urls[name].replace(/\/+$/, "")]] : [])));
20
30
  const ziteProvider = (props) => {
21
- let current = props.appToken;
31
+ let current = props.appToken
32
+ ? { token: props.appToken, expiresAt: props.appTokenExpiresAt }
33
+ : undefined;
22
34
  let renewing;
35
+ // Kept before `renewing` clears, so a caller that comes between them doesn't renew again.
23
36
  const renew = async () => {
24
37
  try {
25
38
  const fresh = await props.platform.appToken();
26
- return typeof fresh === "string" && fresh ? fresh : undefined;
39
+ if (isExpiringToken(fresh))
40
+ current = fresh;
27
41
  }
28
42
  catch (error) {
29
43
  // The token held still serves until it expires.
30
44
  console.error("[zite] couldn't renew the app token", error);
31
- return undefined;
32
45
  }
33
46
  };
47
+ const context = contextOf(props);
34
48
  return {
35
49
  kind: "zite",
36
50
  urls: props.urls && trimmed(props.urls),
37
51
  user: () => props.user,
52
+ context: async () => context,
38
53
  token: async () => {
39
- if (!current || !expiresWithin(current, RENEW_WITHIN_MS))
40
- return current;
41
- renewing ??= renew().finally(() => (renewing = undefined));
42
- current = (await renewing) ?? current;
43
- return current;
54
+ if (!current || !expiresWithin(current.expiresAt, RENEW_WITHIN_MS))
55
+ return current?.token;
56
+ await (renewing ??= renew().finally(() => (renewing = undefined)));
57
+ return current.token;
44
58
  },
45
59
  };
46
60
  };
@@ -87,52 +101,92 @@ const localUser = (raw) => {
87
101
  isInternal: given.isInternal === true,
88
102
  };
89
103
  };
90
- const MODES = new Set(["live", "preview", "demo"]);
91
- /** The mode a dev token names; preview for one it doesn't. */
92
- const localModeOf = (claims) => MODES.has(claims?.mode) ? claims?.mode : "preview";
93
- exports.localModeOf = localModeOf;
94
104
  // The backend mints them for 15 minutes.
95
105
  const RENEW_DEV_TOKEN_WITHIN_MS = 60_000;
96
- const MINT_TIMEOUT_MS = 10_000;
97
- // Per isolate, only a minted token, never a pending mint: Workers ties a request's I/O to that request.
106
+ const BACKEND_TIMEOUT_MS = 10_000;
107
+ // Per isolate, only answers, never a pending call: Workers ties a request's I/O to that request.
98
108
  let held;
99
- /** For tests: forget the minted dev token. */
109
+ let described;
110
+ /** For tests: forget the minted dev token and what the backend said of it. */
100
111
  const resetDevToken = () => {
101
112
  held = undefined;
113
+ described = undefined;
102
114
  };
103
115
  exports.resetDevToken = resetDevToken;
116
+ const reasonOf = (response, answer) => {
117
+ const why = [answer?.message, answer?.error].find((text) => typeof text === "string");
118
+ return `${response.status}${why ? ` ${why}` : ""}`;
119
+ };
104
120
  const mintDevToken = async (backend, appId, apiKey) => {
105
121
  const response = await (0, platformFetch_js_1.platformFetch)(new Request(`${backend}/v1/start/apps/${encodeURIComponent(appId)}/dev-token`, {
106
122
  method: "POST",
107
123
  headers: { authorization: `Bearer ${apiKey}` },
108
- signal: AbortSignal.timeout(MINT_TIMEOUT_MS),
124
+ signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
109
125
  }));
110
126
  const answer = (await response.json().catch(() => null));
111
- if (response.ok && typeof answer?.token === "string")
112
- return answer.token;
113
- const why = [answer?.message, answer?.error].find((text) => typeof text === "string");
114
- throw new Error(`The backend didn't mint a dev token for app ${appId} with ${exports.LOCAL_ENV.apiKey}: ${response.status}${why ? ` ${why}` : ""}`);
127
+ if (response.ok && isExpiringToken(answer))
128
+ return { token: answer.token, expiresAt: answer.expiresAt };
129
+ throw new Error(`The backend didn't mint a dev token for app ${appId} with ${exports.LOCAL_ENV.apiKey}: ${reasonOf(response, answer)}`);
115
130
  };
116
131
  exports.mintDevToken = mintDevToken;
117
- /** The app's dev token, minted with the developer's key, and minted again when it's about to expire. */
132
+ const MODES = new Set(["live", "preview", "demo"]);
133
+ const isWhole = (value) => Number.isSafeInteger(value) && value >= 0;
134
+ const isText = (value) => typeof value === "string" && value !== "";
135
+ const isTextOrNull = (value) => value === null || isText(value);
136
+ /** The backend's `/context` answer, or undefined when it isn't one. */
137
+ const appContextOf = (answer) => {
138
+ const given = answer;
139
+ if (!given ||
140
+ !isText(given.appId) ||
141
+ !isWhole(given.buildId) ||
142
+ !isTextOrNull(given.baseId) ||
143
+ !MODES.has(given.mode) ||
144
+ !(given.orgSettingsVersion === null || isWhole(given.orgSettingsVersion)) ||
145
+ typeof given.showZiteBadge !== "boolean" ||
146
+ !isTextOrNull(given.appUrl)) {
147
+ return undefined;
148
+ }
149
+ return contextOf(given);
150
+ };
151
+ /**
152
+ * What the backend says of a dev token, from the claims it verified, as OAuth's token introspection answers: asked
153
+ * once per token, whose claims never change. Throws, saying why, when it won't say.
154
+ */
155
+ const describeDevToken = async (backend, token) => {
156
+ const key = `${backend} ${token}`;
157
+ if (described?.key === key)
158
+ return described.context;
159
+ const response = await (0, platformFetch_js_1.platformFetch)(new Request(`${backend}/v1/start/app/context`, {
160
+ headers: { authorization: `Bearer ${token}` },
161
+ signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
162
+ }));
163
+ const answer = await response.json().catch(() => null);
164
+ const context = response.ok ? appContextOf(answer) : undefined;
165
+ if (!context)
166
+ throw new Error(`The backend didn't say which app the dev token is for: ${reasonOf(response, answer)}`);
167
+ described = { key, context };
168
+ return context;
169
+ };
170
+ exports.describeDevToken = describeDevToken;
171
+ /** The app's dev token, minted with the developer's key, and minted again when the mint's expiry is near. */
118
172
  const mintedDevToken = (backend, appId, apiKey) => {
119
173
  const key = `${backend} ${appId} ${apiKey}`;
120
174
  let minting;
121
175
  return async () => {
122
- const current = held?.key === key ? held.token : undefined;
123
- if (current && !expiresWithin(current, RENEW_DEV_TOKEN_WITHIN_MS))
124
- return current;
176
+ const current = held?.key === key ? held.minted : undefined;
177
+ if (current && !expiresWithin(current.expiresAt, RENEW_DEV_TOKEN_WITHIN_MS))
178
+ return current.token;
125
179
  minting ??= (0, exports.mintDevToken)(backend, appId, apiKey).finally(() => (minting = undefined));
126
180
  try {
127
- const token = await minting;
128
- held = { key, token };
129
- return token;
181
+ const minted = await minting;
182
+ held = { key, minted };
183
+ return minted.token;
130
184
  }
131
185
  catch (error) {
132
- if (!current || expiresWithin(current, 0))
186
+ if (!current || expiresWithin(current.expiresAt, 0))
133
187
  throw error;
134
188
  console.error("[zite] couldn't renew the dev token; using the one held until it expires", error);
135
- return current;
189
+ return current.token;
136
190
  }
137
191
  };
138
192
  };
@@ -154,6 +208,13 @@ const localPlatform = (env = processEnv() ?? {}, appId = devApp_js_1.devAppId) =
154
208
  return undefined;
155
209
  const urls = (0, exports.localUrls)(env[exports.LOCAL_ENV.urls]);
156
210
  const user = localUser(env[exports.LOCAL_ENV.user]);
157
- return { kind: "local", urls, user: () => user, token: token(urls.backend) };
211
+ const tokenOf = token(urls.backend);
212
+ return {
213
+ kind: "local",
214
+ urls,
215
+ user: () => user,
216
+ token: tokenOf,
217
+ context: async () => (0, exports.describeDevToken)(urls.backend, await tokenOf()),
218
+ };
158
219
  };
159
220
  exports.localPlatform = localPlatform;
@@ -117,19 +117,47 @@ export type PlatformProvider = {
117
117
  kind: "zite" | "local";
118
118
  /** The request's app token, renewed when it's about to expire; undefined when the host sent none. */
119
119
  token(): Promise<string | undefined>;
120
+ /** What the platform says of the request's app and build: the host's props, or `local`'s backend on the dev token. */
121
+ context(): Promise<AppContext>;
120
122
  user(): User | null;
121
123
  urls: PlatformUrls | undefined;
122
124
  };
125
+ /** An app token with its expiry, which travels beside it: zitejs never reads the token itself. */
126
+ export type ExpiringToken = {
127
+ token: string;
128
+ /** Milliseconds since the epoch. */
129
+ expiresAt: number;
130
+ };
123
131
  /**
124
132
  * What the host hands each request beside its app token: the token's renewal, for an answer that outlives the one it
125
133
  * was dispatched with. Its presence in props is what marks a request the host dispatched.
126
134
  */
127
135
  export type PlatformBinding = {
128
136
  /** The request's app token, signed again when it's about to expire; null once it can't be. */
129
- appToken(): Promise<string | null>;
137
+ appToken(): Promise<ExpiringToken | null>;
130
138
  };
131
139
  /** A demo is the published build serving a read-only visitor: as live, but every write is refused. */
132
140
  export type HostMode = "live" | "preview" | "demo" | "validate";
141
+ /**
142
+ * What the platform's records say of the request's app and build. The platform signs the same into the app token,
143
+ * which zitejs only sends: it learns these from the host's props, or under `vite dev` from the backend.
144
+ */
145
+ export type AppContext = {
146
+ /** The app's public identifier. */
147
+ appId: string;
148
+ /** The build's snapshot id; a dev token's is the app's newest. */
149
+ buildId: number;
150
+ /** The app's database: `process.env.ZITE_BASE_ID`. Null when the app has none. */
151
+ baseId: string | null;
152
+ /** Never `validate`, which no platform serves in. */
153
+ mode: Exclude<HostMode, "validate">;
154
+ /** The org settings version the request was served under; null when it couldn't be read. */
155
+ orgSettingsVersion: number | null;
156
+ /** Whether the org's plan shows Zite's badge. */
157
+ showZiteBadge: boolean;
158
+ /** The app's live URL, demo included: `process.env.ZITE_APP_URL`. Null when the platform has none to give. */
159
+ appUrl: string | null;
160
+ };
133
161
  /**
134
162
  * The build's page settings, as the platform baked them at publish from the app's settings and name. What the settings
135
163
  * set (`seo*`, `favicon`, an installable app's) replaces what a page sets; the rest fills what it leaves out.
@@ -205,17 +233,31 @@ export type HostInvoke = {
205
233
  kind: "webhook" | "describe" | "workflow" | "register" | "warm" | "authHook" | "function";
206
234
  name: string;
207
235
  };
236
+ /** One of `integrations.get`'s answers, as the platform resolved the connection for the request. */
237
+ export type HostConnection = {
238
+ status: "connected";
239
+ accessToken: string;
240
+ [extra: string]: string | undefined;
241
+ } | {
242
+ status: "missing" | "expired";
243
+ connectUrl: string;
244
+ } | {
245
+ status: "unavailable";
246
+ message: string;
247
+ userFacingMessage?: string;
248
+ connectUrl?: string;
249
+ serviceId?: number;
250
+ };
208
251
  /** The per-request props the host dispatches with. Only the host can set them. */
209
- export type HostProps = {
252
+ export type HostProps = AppContext & {
210
253
  platform: PlatformBinding;
211
254
  requestId: string;
212
255
  user: User | null;
213
- mode: HostMode;
214
- invoke: HostInvoke | null;
215
- /** The app's live URL, demo included: `process.env.ZITE_APP_URL`. */
216
- appUrl?: string;
217
- /** The app's database: `process.env.ZITE_BASE_ID`. */
218
- baseId?: string;
256
+ /** A warm-up or a describe goes without props. */
257
+ invoke: {
258
+ kind: Exclude<HostInvoke["kind"], "warm" | "describe">;
259
+ name: string;
260
+ } | null;
219
261
  /** An editor preview's access, which zitejs keeps on the app's links and calls. */
220
262
  previewClaim?: string;
221
263
  /** `process.env` as classic sets it: connections' vars, then the user's own secrets. */
@@ -228,18 +270,20 @@ export type HostProps = {
228
270
  runRoot?: string;
229
271
  /** This request's app token, sent only to `urls`. */
230
272
  appToken?: string;
273
+ /** When `appToken` expires, in milliseconds since the epoch; absent without one. */
274
+ appTokenExpiresAt?: number;
231
275
  urls?: PlatformUrls;
232
276
  /** Sent with a page or route request by a host that leaves its head to zitejs. */
233
277
  page?: HostPage;
234
278
  /** The app's access mode, from the platform's records: an internal app serves no page or call to nobody. */
235
- accessMode?: "internal" | "external";
279
+ accessMode: "internal" | "external";
236
280
  /** `ZiteMeta.getWorkspace()`'s answer, from the build's config; absent for a build published before it was kept. */
237
281
  workspace?: ZiteWorkspace;
238
282
  /**
239
283
  * `integrations.get`'s answers, by connection name, real as classic's, when the host already loaded them for the
240
284
  * request: a registration's one connection, and none for a demo. Without them the app asks the backend on its token.
241
285
  */
242
- connections?: Record<string, Record<string, unknown>>;
286
+ connections?: Record<string, HostConnection>;
243
287
  };
244
288
  /** What the host resolved for this request. Set by the generated server entry, never by the browser. */
245
289
  export type HostRequestState = {
@@ -9,8 +9,8 @@ export type DevSignInResult = {
9
9
  reason: string;
10
10
  };
11
11
  /**
12
- * Writes the app's `.zite/dev.env` from its dev token's `appUrl`: issuer `<appUrl>/auth`, client `<app>:dev`. Keeps
13
- * the secret a previous run wrote, so sessions outlive a restart.
12
+ * Writes the app's `.zite/dev.env` from the app URL the backend gives its dev token: issuer `<appUrl>/auth`, client
13
+ * `<app>:dev`. Keeps the secret a previous run wrote, so sessions outlive a restart.
14
14
  */
15
15
  export declare function writeDevSignIn(appDir: string, shell?: Env): Promise<DevSignInResult>;
16
16
  export {};
@@ -4,8 +4,7 @@ import { randomBytes } from "node:crypto";
4
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { parse } from "dotenv";
7
- import { appTokenClaims } from "../internal/appToken.js";
8
- import { LOCAL_ENV, localUrls, mintDevToken } from "../start/provider.js";
7
+ import { describeDevToken, LOCAL_ENV, localUrls, mintDevToken } from "../start/provider.js";
9
8
  export const DEV_ENV_FILE = join(".zite", "dev.env");
10
9
  const readEnvFile = (path) => {
11
10
  try {
@@ -39,8 +38,8 @@ const ignoreDevEnv = (appDir) => {
39
38
  writeFileSync(path, `${current}${current && !current.endsWith("\n") ? "\n" : ""}dev.env\n`);
40
39
  };
41
40
  /**
42
- * Writes the app's `.zite/dev.env` from its dev token's `appUrl`: issuer `<appUrl>/auth`, client `<app>:dev`. Keeps
43
- * the secret a previous run wrote, so sessions outlive a restart.
41
+ * Writes the app's `.zite/dev.env` from the app URL the backend gives its dev token: issuer `<appUrl>/auth`, client
42
+ * `<app>:dev`. Keeps the secret a previous run wrote, so sessions outlive a restart.
44
43
  */
45
44
  export async function writeDevSignIn(appDir, shell = process.env) {
46
45
  const env = appEnvOf(appDir, shell);
@@ -51,8 +50,9 @@ export async function writeDevSignIn(appDir, shell = process.env) {
51
50
  const given = env[LOCAL_ENV.token];
52
51
  if (!given && !apiKey)
53
52
  return { written: false, reason: `neither ${LOCAL_ENV.token} nor ${LOCAL_ENV.apiKey} is set` };
54
- const token = given ?? (await mintDevToken(localUrls(env[LOCAL_ENV.urls]).backend, appId, apiKey));
55
- const appUrl = appTokenClaims(token)?.appUrl;
53
+ const { backend } = localUrls(env[LOCAL_ENV.urls]);
54
+ const token = given ?? (await mintDevToken(backend, appId, apiKey)).token;
55
+ const { appUrl } = await describeDevToken(backend, token);
56
56
  if (!appUrl)
57
57
  return { written: false, reason: "the app has no live URL yet; publish it once to sign in under vite dev" };
58
58
  const issuer = `${new URL(appUrl).origin}/auth`;
@@ -231,7 +231,7 @@ export const scenarios = [
231
231
  const [app] = target.clientId.split(":");
232
232
  const otherMode = modeOf(target) === "live" ? "preview" : "live";
233
233
  const appToken = await target.mint({
234
- claims: { iss: "zite-host", aud: ["backend"], iat: baseClaims(target).iat, exp: baseClaims(target).exp, app, mode: "live", user: "u_forged" },
234
+ claims: { iss: "zite-host", aud: ["backend"], iat: baseClaims(target).iat, exp: baseClaims(target).exp, appId: app, mode: "live", appUserId: "u_forged" },
235
235
  header: { typ: "JWT" },
236
236
  key: "app-token",
237
237
  });
@@ -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 { IDENTITY_KEY_KIND, identityKeys, remoteIdentityKeys, staticIdentityKeys, type IdentityKeys, type IdentityKeySource, } from "./keys.js";
3
+ export { 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";
@@ -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 { IDENTITY_KEY_KIND, identityKeys, remoteIdentityKeys, staticIdentityKeys, } from "./keys.js";
5
+ export { 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,14 +1,8 @@
1
- /** The only kind of key an identity token may be signed with. App-token keys share the map under other kinds. */
2
- export declare const IDENTITY_KEY_KIND = "zite-identity";
3
1
  /**
4
- * The platform's public-key map as `ZITE_APP_TOKEN_PUBLIC_KEYS` holds it (`kid → { iss, key }`, where `iss` is the
5
- * key's kind and `key` its raw Ed25519 public key, base64url). Keys of every kind are kept so a token signed with
6
- * another kind's key is refused by name.
2
+ * The identity issuer's public keys by `kid`, each its raw Ed25519 key (base64url), as read from the issuer's JWK Set
3
+ * (RFC 7517): the dispatcher's `ZITE_IDENTITY_JWKS`, or the backend's `jwks_uri` off Zite.
7
4
  */
8
- export type IdentityKeys = Readonly<Record<string, {
9
- kind: string;
10
- key: string;
11
- }>>;
5
+ export type IdentityKeys = Readonly<Record<string, string>>;
12
6
  /** Where a verifier finds keys: what it holds now, and a refetch for a `kid` it doesn't know. */
13
7
  export type IdentityKeySource = {
14
8
  current(): IdentityKeys;
@@ -16,24 +10,21 @@ export type IdentityKeySource = {
16
10
  refresh(): Promise<IdentityKeys | undefined>;
17
11
  };
18
12
  /**
19
- * Parses the key map with `parseAppTokenPublicKeys`'s rules: a malformed entry throws, so a bad deploy fails at once,
20
- * and off a local stack local dev's key is refused. Keys of other kinds are kept as they are and never used, so a
21
- * kind added later doesn't break an older zitejs.
13
+ * Parses the identity issuer's JWK Set. A document that isn't one, or a `kid` two usable keys share, throws, so a bad
14
+ * deploy fails at once. A key it can't verify with (another key type or curve, another `alg` or `use`, no `kid`) is
15
+ * skipped, so a key type the issuer adds later doesn't break an older zitejs.
22
16
  */
23
- export declare const identityKeys: (json: string, options?: {
24
- localDev?: boolean;
25
- }) => IdentityKeys;
26
- /** Keys that never change: the dispatcher's configured map. */
17
+ export declare const identityKeys: (json: string) => IdentityKeys;
18
+ /** Keys that never change: the dispatcher's configured set. */
27
19
  export declare const staticIdentityKeys: (keys: IdentityKeys) => IdentityKeySource;
28
- /** For tests: forget every fetched key map. */
20
+ /** For tests: forget every fetched key set. */
29
21
  export declare const resetFetchedIdentityKeys: () => void;
30
22
  /**
31
- * Keys from `url` (the backend's static map), refetched on an unknown `kid` at most once a minute per process. Make
32
- * one per request; concurrent refreshes on it share one fetch.
23
+ * Keys from `url` (the backend's identity JWK Set), refetched on an unknown `kid` at most once a minute per process.
24
+ * Make one per request; concurrent refreshes on it share one fetch.
33
25
  */
34
26
  export declare const remoteIdentityKeys: (url: string, options?: {
35
27
  initial?: IdentityKeys;
36
- localDev?: boolean;
37
28
  fetch?: (request: Request) => Promise<Response>;
38
29
  now?: () => number;
39
30
  }) => IdentityKeySource;
@@ -1,15 +1,22 @@
1
1
  import { fromBase64Url, isRecord } from "./encoding.js";
2
- /** The only kind of key an identity token may be signed with. App-token keys share the map under other kinds. */
3
- export const IDENTITY_KEY_KIND = "zite-identity";
4
- /** Accepted only by a local stack: its private half is in restly's repo. */
5
- const LOCAL_DEV_PUBLIC_KEY = "SQn0d_i6VvM5J81X8IP4qtis0x-DI2pJVvdAbbG7las";
6
- const KEY_MAP_NAME = "the public-key map";
2
+ const KEY_SET_NAME = "the identity JWK Set";
3
+ const usableKey = (jwk) => isRecord(jwk) &&
4
+ jwk.kty === "OKP" &&
5
+ jwk.crv === "Ed25519" &&
6
+ (jwk.alg === undefined || jwk.alg === "EdDSA") &&
7
+ (jwk.use === undefined || jwk.use === "sig") &&
8
+ typeof jwk.kid === "string" &&
9
+ /^[A-Za-z0-9_-]{1,64}$/.test(jwk.kid) &&
10
+ typeof jwk.x === "string" &&
11
+ fromBase64Url(jwk.x)?.length === 32
12
+ ? { kid: jwk.kid, x: jwk.x }
13
+ : undefined;
7
14
  /**
8
- * Parses the key map with `parseAppTokenPublicKeys`'s rules: a malformed entry throws, so a bad deploy fails at once,
9
- * and off a local stack local dev's key is refused. Keys of other kinds are kept as they are and never used, so a
10
- * kind added later doesn't break an older zitejs.
15
+ * Parses the identity issuer's JWK Set. A document that isn't one, or a `kid` two usable keys share, throws, so a bad
16
+ * deploy fails at once. A key it can't verify with (another key type or curve, another `alg` or `use`, no `kid`) is
17
+ * skipped, so a key type the issuer adds later doesn't break an older zitejs.
11
18
  */
12
- export const identityKeys = (json, options = {}) => {
19
+ export const identityKeys = (json) => {
13
20
  let parsed;
14
21
  try {
15
22
  parsed = JSON.parse(json);
@@ -17,24 +24,21 @@ export const identityKeys = (json, options = {}) => {
17
24
  catch {
18
25
  parsed = undefined;
19
26
  }
20
- if (!isRecord(parsed))
21
- throw new Error(`${KEY_MAP_NAME} must be a JSON object`);
22
- const keys = {};
23
- for (const [kid, entry] of Object.entries(parsed)) {
24
- if (!/^[A-Za-z0-9_-]{1,64}$/.test(kid) || !isRecord(entry) || typeof entry.iss !== "string" || typeof entry.key !== "string") {
25
- throw new Error(`${KEY_MAP_NAME}: bad entry ${kid.slice(0, 64)}`);
26
- }
27
- const identity = entry.iss === IDENTITY_KEY_KIND;
28
- if (identity && fromBase64Url(entry.key)?.length !== 32)
29
- throw new Error(`${KEY_MAP_NAME}: ${kid} isn't a raw Ed25519 key`);
30
- if (identity && !options.localDev && entry.key === LOCAL_DEV_PUBLIC_KEY) {
31
- throw new Error(`${KEY_MAP_NAME}: ${kid} is local dev's key, which only a local stack takes`);
32
- }
33
- keys[kid] = { kind: entry.iss, key: entry.key };
27
+ if (!isRecord(parsed) || !Array.isArray(parsed.keys))
28
+ throw new Error(`${KEY_SET_NAME} must be a JSON object with a keys array`);
29
+ // No prototype, so a `kid` of `__proto__` is a key like any other.
30
+ const keys = Object.create(null);
31
+ for (const jwk of parsed.keys) {
32
+ const key = usableKey(jwk);
33
+ if (!key)
34
+ continue;
35
+ if (Object.hasOwn(keys, key.kid))
36
+ throw new Error(`${KEY_SET_NAME}: key ${key.kid} is in it twice`);
37
+ keys[key.kid] = key.x;
34
38
  }
35
39
  return keys;
36
40
  };
37
- /** Keys that never change: the dispatcher's configured map. */
41
+ /** Keys that never change: the dispatcher's configured set. */
38
42
  export const staticIdentityKeys = (keys) => ({
39
43
  current: () => keys,
40
44
  refresh: async () => undefined,
@@ -44,11 +48,11 @@ const FETCH_TIMEOUT_MS = 5_000;
44
48
  // Per process, only fetched keys and when a fetch last started: Workers ties a fetch to the request that made it, so a
45
49
  // pending one is never shared across requests. Another request inside the minute keeps the keys it has.
46
50
  const fetched = new Map();
47
- /** For tests: forget every fetched key map. */
51
+ /** For tests: forget every fetched key set. */
48
52
  export const resetFetchedIdentityKeys = () => fetched.clear();
49
53
  /**
50
- * Keys from `url` (the backend's static map), refetched on an unknown `kid` at most once a minute per process. Make
51
- * one per request; concurrent refreshes on it share one fetch.
54
+ * Keys from `url` (the backend's identity JWK Set), refetched on an unknown `kid` at most once a minute per process.
55
+ * Make one per request; concurrent refreshes on it share one fetch.
52
56
  */
53
57
  export const remoteIdentityKeys = (url, options = {}) => {
54
58
  const now = options.now ?? Date.now;
@@ -64,7 +68,7 @@ export const remoteIdentityKeys = (url, options = {}) => {
64
68
  const response = await (options.fetch ?? fetch)(request);
65
69
  if (!response.ok)
66
70
  throw new Error(`${response.status}`);
67
- const keys = identityKeys(await response.text(), { localDev: options.localDev });
71
+ const keys = identityKeys(await response.text());
68
72
  fetched.set(url, { keys, startedAt });
69
73
  return keys;
70
74
  }
@@ -1,4 +1,4 @@
1
- import { type IdentityKeySource } from "./keys.js";
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";
@@ -33,7 +33,7 @@ export type IdentityClaims = {
33
33
  };
34
34
  };
35
35
  /** Why a token was refused. Each is a forgery, a token from somewhere else, or a bug; never a lapse of time. */
36
- export type Refusal = "malformed" | "alg" | "typ" | "kid" | "key kind" | "signature" | "iss" | "aud" | "azp" | "iat" | "lifetime" | "sub" | "mode" | "claims" | "preview" | "nonce";
36
+ export type Refusal = "malformed" | "alg" | "typ" | "kid" | "signature" | "iss" | "aud" | "azp" | "iat" | "lifetime" | "sub" | "mode" | "claims" | "preview" | "nonce";
37
37
  /**
38
38
  * `expired` and `stale` (issued under another org settings version) are genuine and renewable; `refused` is not and
39
39
  * clears the cookie.