zitejs 0.10.0-start.24 → 0.10.0-start.26

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/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/keys.d.ts +3 -7
  10. package/dist/esm/signin/keys.js +4 -10
  11. package/dist/esm/start/direct.d.ts +3 -3
  12. package/dist/esm/start/direct.js +14 -16
  13. package/dist/esm/start/index.d.ts +1 -1
  14. package/dist/esm/start/pageHead.d.ts +3 -3
  15. package/dist/esm/start/pageHead.js +3 -8
  16. package/dist/esm/start/provider.d.ts +8 -6
  17. package/dist/esm/start/provider.js +96 -35
  18. package/dist/esm/start/sdk/axios.d.ts +76 -0
  19. package/dist/esm/start/sdk/axios.js +210 -0
  20. package/dist/esm/start/sdk/nodeFetch.d.ts +41 -0
  21. package/dist/esm/start/sdk/nodeFetch.js +33 -0
  22. package/dist/esm/start/sdk/undici.d.ts +34 -0
  23. package/dist/esm/start/sdk/undici.js +18 -0
  24. package/dist/esm/start/sdkPatches.d.ts +22 -0
  25. package/dist/esm/start/sdkPatches.js +359 -0
  26. package/dist/esm/start/server.d.ts +3 -3
  27. package/dist/esm/start/server.js +17 -18
  28. package/dist/esm/start/types.d.ts +54 -10
  29. package/dist/esm/start/version.d.ts +1 -1
  30. package/dist/esm/start/version.js +1 -1
  31. package/dist/esm/start/vite.js +2 -0
  32. package/package.json +2 -1
  33. package/dist/cjs/internal/appToken.d.ts +0 -17
  34. package/dist/cjs/internal/appToken.js +0 -26
  35. package/dist/esm/internal/appToken.d.ts +0 -17
  36. 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
  });
@@ -16,13 +16,10 @@ export type IdentityKeySource = {
16
16
  refresh(): Promise<IdentityKeys | undefined>;
17
17
  };
18
18
  /**
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.
19
+ * Parses the key map with `parseAppTokenPublicKeys`'s rules: a malformed entry throws, so a bad deploy fails at once.
20
+ * Keys of other kinds are kept as they are and never used, so a kind added later doesn't break an older zitejs.
22
21
  */
23
- export declare const identityKeys: (json: string, options?: {
24
- localDev?: boolean;
25
- }) => IdentityKeys;
22
+ export declare const identityKeys: (json: string) => IdentityKeys;
26
23
  /** Keys that never change: the dispatcher's configured map. */
27
24
  export declare const staticIdentityKeys: (keys: IdentityKeys) => IdentityKeySource;
28
25
  /** For tests: forget every fetched key map. */
@@ -33,7 +30,6 @@ export declare const resetFetchedIdentityKeys: () => void;
33
30
  */
34
31
  export declare const remoteIdentityKeys: (url: string, options?: {
35
32
  initial?: IdentityKeys;
36
- localDev?: boolean;
37
33
  fetch?: (request: Request) => Promise<Response>;
38
34
  now?: () => number;
39
35
  }) => IdentityKeySource;
@@ -1,15 +1,12 @@
1
1
  import { fromBase64Url, isRecord } from "./encoding.js";
2
2
  /** The only kind of key an identity token may be signed with. App-token keys share the map under other kinds. */
3
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
4
  const KEY_MAP_NAME = "the public-key map";
7
5
  /**
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.
6
+ * Parses the key map with `parseAppTokenPublicKeys`'s rules: a malformed entry throws, so a bad deploy fails at once.
7
+ * Keys of other kinds are kept as they are and never used, so a kind added later doesn't break an older zitejs.
11
8
  */
12
- export const identityKeys = (json, options = {}) => {
9
+ export const identityKeys = (json) => {
13
10
  let parsed;
14
11
  try {
15
12
  parsed = JSON.parse(json);
@@ -27,9 +24,6 @@ export const identityKeys = (json, options = {}) => {
27
24
  const identity = entry.iss === IDENTITY_KEY_KIND;
28
25
  if (identity && fromBase64Url(entry.key)?.length !== 32)
29
26
  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
27
  keys[kid] = { kind: entry.iss, key: entry.key };
34
28
  }
35
29
  return keys;
@@ -64,7 +58,7 @@ export const remoteIdentityKeys = (url, options = {}) => {
64
58
  const response = await (options.fetch ?? fetch)(request);
65
59
  if (!response.ok)
66
60
  throw new Error(`${response.status}`);
67
- const keys = identityKeys(await response.text(), { localDev: options.localDev });
61
+ const keys = identityKeys(await response.text());
68
62
  fetched.set(url, { keys, startedAt });
69
63
  return keys;
70
64
  }
@@ -1,4 +1,4 @@
1
- import type { HostRequestState, PagePlan, PlatformCallInput, PlatformCallResult, PlatformUrls } from "./types.js";
1
+ import type { AppContext, HostRequestState, PagePlan, PlatformCallInput, PlatformCallResult, PlatformUrls } from "./types.js";
2
2
  export type DirectAccess = {
3
3
  token: string;
4
4
  urls: PlatformUrls;
@@ -32,9 +32,9 @@ export declare const directDataFetch: (host: HostRequestState) => ({ method, pat
32
32
  * The backend's `GET connections` on the token, once per reuse window: all `local` has, and what an app on Zite asks
33
33
  * when the host didn't hand them over. Stale if the backend didn't answer.
34
34
  */
35
- export declare const connectionsOnToken: (access: DirectAccess) => Promise<Connections>;
35
+ export declare const connectionsOnToken: (access: DirectAccess, context: AppContext | undefined) => Promise<Connections>;
36
36
  /** The build's page settings for `local`, which has no host to send them; null when the backend has none to give. */
37
- export declare const localPagePlan: (access: DirectAccess) => Promise<PagePlan | null>;
37
+ export declare const localPagePlan: (access: DirectAccess, context: AppContext) => Promise<PagePlan | null>;
38
38
  /** For tests: forget what this isolate learned. */
39
39
  export declare const resetLocalConnections: () => void;
40
40
  /** A platform call on the token; a throw without one. Errors come back as values, as the relay's did. */
@@ -1,7 +1,6 @@
1
1
  // Data and services on the request's app token, sent straight to the platform. Each answer is shaped as the host's relay
2
2
  // shaped it, so what an app sees didn't change when the relay went. A request with no token or platform URLs reaches
3
3
  // nothing: the host dispatches every request with both, and `local` mints its own.
4
- import { appTokenClaims } from "../internal/appToken.js";
5
4
  import { platformFetch } from "../internal/platformFetch.js";
6
5
  import { serviceUrl } from "../internal/serviceUrls.js";
7
6
  import { INTEGRATIONS_PLATFORM_ID } from "./credentials.js";
@@ -138,7 +137,7 @@ const steps = async (host, access, { methodName, params }) => {
138
137
  if (host.invoke?.kind !== "workflow")
139
138
  return refused("step.run runs only in a workflow");
140
139
  // Before any step's value leaves the app: with no workspace database there's nowhere to keep it.
141
- if (appTokenClaims(access.token)?.base === null)
140
+ if ((await host.provider?.context())?.baseId === null)
142
141
  return refused("Durable steps need the workspace database, and this app has none");
143
142
  const url = serviceUrl(access.urls, "steps");
144
143
  if (methodName === "load") {
@@ -160,7 +159,7 @@ const steps = async (host, access, { methodName, params }) => {
160
159
  });
161
160
  return { value: { persisted: true } };
162
161
  };
163
- // Per isolate, as the host keeps them: until the token's settings version moves, or a minute without one.
162
+ // Per isolate, as the host keeps them: until the request's settings version moves, or a minute without one.
164
163
  const CONNECTIONS_REUSE_MS = 60_000;
165
164
  const CONNECTIONS_MAX_AGE_MS = 10 * 60_000;
166
165
  // Only answers, never a pending call: Workers ties a request's I/O to that request.
@@ -169,10 +168,9 @@ let tokenHeld;
169
168
  * The backend's `GET connections` on the token, once per reuse window: all `local` has, and what an app on Zite asks
170
169
  * when the host didn't hand them over. Stale if the backend didn't answer.
171
170
  */
172
- export const connectionsOnToken = async (access) => {
173
- const claims = appTokenClaims(access.token);
174
- const key = `${claims?.app ?? ""}:${claims?.build ?? ""}:${claims?.ver ?? ""}`;
175
- const reuseMs = typeof claims?.ver === "number" ? CONNECTIONS_MAX_AGE_MS : CONNECTIONS_REUSE_MS;
171
+ export const connectionsOnToken = async (access, context) => {
172
+ const key = `${context?.appId ?? ""}:${context?.buildId ?? ""}:${context?.orgSettingsVersion ?? ""}`;
173
+ const reuseMs = typeof context?.orgSettingsVersion === "number" ? CONNECTIONS_MAX_AGE_MS : CONNECTIONS_REUSE_MS;
176
174
  if (tokenHeld?.key === key && Date.now() - tokenHeld.at < reuseMs)
177
175
  return tokenHeld.answer;
178
176
  try {
@@ -194,9 +192,8 @@ export const connectionsOnToken = async (access) => {
194
192
  const PAGE_REUSE_MS = 60_000;
195
193
  let localPage;
196
194
  /** The build's page settings for `local`, which has no host to send them; null when the backend has none to give. */
197
- export const localPagePlan = async (access) => {
198
- const claims = appTokenClaims(access.token);
199
- const key = `${claims?.app ?? ""}:${claims?.build ?? ""}`;
195
+ export const localPagePlan = async (access, context) => {
196
+ const key = `${context.appId}:${context.buildId}`;
200
197
  if (localPage?.key === key && Date.now() - localPage.at < PAGE_REUSE_MS)
201
198
  return localPage.plan;
202
199
  let plan = null;
@@ -212,9 +209,8 @@ export const localPagePlan = async (access) => {
212
209
  // The app's place in Zite, which moves only with the app, and with it the dev token's base.
213
210
  let localWorkspace;
214
211
  /** `ZiteMeta.getWorkspace()` for `local`, which has no build config in props: the backend's, for the dev token's app. */
215
- const localWorkspaceOf = async (access) => {
216
- const claims = appTokenClaims(access.token);
217
- const key = `${claims?.app ?? ""}:${claims?.base ?? ""}`;
212
+ const localWorkspaceOf = async (access, context) => {
213
+ const key = `${context.appId}:${context.baseId ?? ""}`;
218
214
  if (localWorkspace?.key === key)
219
215
  return localWorkspace.workspace;
220
216
  const { workspace } = await backendJson(access, "GET", "/workspace");
@@ -319,7 +315,8 @@ const connectionsOf = async (host, name) => {
319
315
  if (!access)
320
316
  throw new NoPlatformError();
321
317
  try {
322
- return (await (host.connectionsLoad ??= connectionsOnToken(access))).connections;
318
+ const context = await host.provider?.context();
319
+ return (await (host.connectionsLoad ??= connectionsOnToken(access, context))).connections;
323
320
  }
324
321
  catch (error) {
325
322
  console.error("[zite] couldn't load the app's connections", error);
@@ -390,8 +387,9 @@ export const directCall = async (host, input) => {
390
387
  let workspace = host.workspace;
391
388
  if (!workspace) {
392
389
  const granted = await access();
393
- if (host.provider?.kind === "local" && input.methodName === "getWorkspace")
394
- workspace = await localWorkspaceOf(granted);
390
+ if (host.provider?.kind === "local" && input.methodName === "getWorkspace") {
391
+ workspace = await localWorkspaceOf(granted, await host.provider.context());
392
+ }
395
393
  }
396
394
  return noted(host, input, metaAnswer(input.methodName, workspace));
397
395
  }
@@ -1,5 +1,5 @@
1
1
  import type { User } from "./types.js";
2
- export type { Role, User } from "./types.js";
2
+ export type { AppContext, ExpiringToken, HostConnection, HostPage, HostProps, PlatformBinding, Role, User } from "./types.js";
3
3
  export { isSignInRequired, SIGN_IN_REQUIRED, ZiteError, ZITE_ERROR_STATUS, type ZiteErrorCode, type ZiteErrorOptions, } from "./errors.js";
4
4
  export { createZiteRouter, type ZiteRouterContext } from "./router.js";
5
5
  export { createAutomation, type StartProviderTrigger, type StartTrigger, type Automation, type AutomationArgs, type AutomationConfig, } from "./workflow.js";
@@ -1,4 +1,4 @@
1
- import type { HostMode, HostPage, PlatformHead } from "./types.js";
1
+ import type { AppContext, HostMode, HostPage, PlatformHead } from "./types.js";
2
2
  /** Where the runtime posts a page's analytics: its `endpointUrl` and then its own path. */
3
3
  export declare const ANALYTICS_PATH = "/__zite/public/zite/analytics";
4
4
  type Tag = Record<string, unknown>;
@@ -15,11 +15,11 @@ export type RouteHead = {
15
15
  scripts?: Array<Tag | undefined>;
16
16
  styles?: unknown;
17
17
  };
18
- /** For one request: the plan its host sent, the badge its token carries, and analytics on a live page. */
18
+ /** For one request: the plan its host sent, the badge its org's plan shows, and analytics on a live page. */
19
19
  export declare const platformHeadOf: (page: HostPage, request: {
20
20
  url: string;
21
21
  mode: HostMode;
22
- token: string | undefined;
22
+ context: Pick<AppContext, "appId" | "showZiteBadge">;
23
23
  }) => PlatformHead;
24
24
  /**
25
25
  * The root route's head: the platform's entries first, so TanStack lets the app's own win wherever both set a title,