zitejs 0.10.0-start.23 → 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.
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/dev/signin.d.ts +2 -2
- package/dist/cjs/dev/signin.js +5 -5
- package/dist/cjs/start/provider.d.ts +8 -6
- package/dist/cjs/start/provider.js +102 -41
- package/dist/cjs/start/types.d.ts +57 -13
- package/dist/esm/cli.js +1 -1
- package/dist/esm/dev/signin.d.ts +2 -2
- package/dist/esm/dev/signin.js +6 -6
- package/dist/esm/signin/conformance.js +1 -1
- package/dist/esm/signin/keys.d.ts +3 -7
- package/dist/esm/signin/keys.js +4 -10
- package/dist/esm/start/direct.d.ts +3 -3
- package/dist/esm/start/direct.js +14 -16
- package/dist/esm/start/index.d.ts +1 -1
- package/dist/esm/start/outbound.d.ts +4 -4
- package/dist/esm/start/outbound.js +33 -33
- package/dist/esm/start/pageHead.d.ts +3 -3
- package/dist/esm/start/pageHead.js +3 -8
- package/dist/esm/start/provider.d.ts +8 -6
- package/dist/esm/start/provider.js +100 -39
- package/dist/esm/start/sdk/axios.d.ts +76 -0
- package/dist/esm/start/sdk/axios.js +210 -0
- package/dist/esm/start/sdk/nodeFetch.d.ts +41 -0
- package/dist/esm/start/sdk/nodeFetch.js +33 -0
- package/dist/esm/start/sdk/undici.d.ts +34 -0
- package/dist/esm/start/sdk/undici.js +18 -0
- package/dist/esm/start/sdkPatches.d.ts +22 -0
- package/dist/esm/start/sdkPatches.js +359 -0
- package/dist/esm/start/server.d.ts +3 -3
- package/dist/esm/start/server.js +19 -20
- package/dist/esm/start/types.d.ts +57 -13
- package/dist/esm/start/version.d.ts +1 -1
- package/dist/esm/start/version.js +1 -1
- package/dist/esm/start/vite.js +2 -0
- package/package.json +2 -1
- package/dist/cjs/internal/appToken.d.ts +0 -17
- package/dist/cjs/internal/appToken.js +0 -26
- package/dist/esm/internal/appToken.d.ts +0 -17
- package/dist/esm/internal/appToken.js +0 -22
package/dist/esm/start/direct.js
CHANGED
|
@@ -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 (
|
|
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
|
|
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
|
|
174
|
-
const
|
|
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
|
|
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
|
|
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
|
-
|
|
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";
|
|
@@ -2,18 +2,18 @@
|
|
|
2
2
|
* Every fetch an app makes on the server, wrapped as classic's runtime wraps
|
|
3
3
|
* it: logged, every secret it knows redacted, with the connection whose token
|
|
4
4
|
* it carries and what an org's own AI key used; a 401 on a connection's token
|
|
5
|
-
* refreshed and sent once more; and a call on Zite's own AI key sent to
|
|
6
|
-
*
|
|
5
|
+
* refreshed and sent once more; and a call on Zite's own AI key sent to Zite's
|
|
6
|
+
* gateway on the request's app token.
|
|
7
7
|
*/
|
|
8
8
|
import type { HostRequestState } from "./types.js";
|
|
9
9
|
/** At the gateway, the connection a call on Zite's AI key bills to: the marker's, which the token takes the place of. */
|
|
10
|
-
export declare const
|
|
10
|
+
export declare const GATEWAY_CONNECTION_HEADER = "x-zite-gateway-connection";
|
|
11
11
|
/** An `integrations.get` answer, whose values name the calls that carry them. */
|
|
12
12
|
export declare const rememberConnection: (host: HostRequestState, name: string, connection: unknown) => void;
|
|
13
13
|
/** An `integrations.get` answer with each token this isolate has since refreshed swapped for its replacement. */
|
|
14
14
|
export declare const withRefreshedTokens: (answer: unknown) => unknown;
|
|
15
15
|
/** A connection on Zite's AI key as `integrations.get` answers it, its `baseUrl` at the provider's gateway. */
|
|
16
|
-
export declare const
|
|
16
|
+
export declare const withGatewayUrl: (host: HostRequestState, answer: unknown) => unknown;
|
|
17
17
|
export declare const createOutboundFetch: (nativeFetch: typeof fetch) => typeof fetch;
|
|
18
18
|
/** Wraps the global fetch once. Next patches fetch for the same reason: the run log must hear of each. */
|
|
19
19
|
export declare const watchOutboundFetches: () => void;
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Every fetch an app makes on the server, wrapped as classic's runtime wraps
|
|
3
3
|
* it: logged, every secret it knows redacted, with the connection whose token
|
|
4
4
|
* it carries and what an org's own AI key used; a 401 on a connection's token
|
|
5
|
-
* refreshed and sent once more; and a call on Zite's own AI key sent to
|
|
6
|
-
*
|
|
5
|
+
* refreshed and sent once more; and a call on Zite's own AI key sent to Zite's
|
|
6
|
+
* gateway on the request's app token.
|
|
7
7
|
*/
|
|
8
8
|
import { isPlatformRequest } from "../internal/platformFetch.js";
|
|
9
9
|
import { AI_USAGE_HOSTS, meterAiResponse, withStreamUsage } from "./aiUsage.js";
|
|
@@ -17,11 +17,11 @@ const MIN_TOKEN_LENGTH = 8;
|
|
|
17
17
|
// As classic: Workers send no User-Agent, and some APIs (GitHub) refuse a request without one.
|
|
18
18
|
const DEFAULT_USER_AGENT = "zite";
|
|
19
19
|
// The backend's stand-in for Zite's own AI key, naming the connection a call bills to. Nowhere is it a key.
|
|
20
|
-
const
|
|
21
|
-
// The gateway's name in a connection's `baseUrl`, which zitejs resolves to the provider's `urls.
|
|
22
|
-
const
|
|
20
|
+
const GATEWAY_MARKER = /^zite_gateway:[a-z]+:(.+)$/;
|
|
21
|
+
// The gateway's name in a connection's `baseUrl`, which zitejs resolves to the provider's `urls.gateway`.
|
|
22
|
+
const GATEWAY_HOST = "zite-gateway.invalid";
|
|
23
23
|
/** At the gateway, the connection a call on Zite's AI key bills to: the marker's, which the token takes the place of. */
|
|
24
|
-
export const
|
|
24
|
+
export const GATEWAY_CONNECTION_HEADER = "x-zite-gateway-connection";
|
|
25
25
|
// A provider's own base URL at the host: `/v1` is OpenAI's, Anthropic's SDK sends it in the path.
|
|
26
26
|
const AI_PROVIDER_HOSTS = {
|
|
27
27
|
"api.openai.com": { provider: "openai", strip: "/v1" },
|
|
@@ -36,7 +36,7 @@ const SECRET_HEADER = /auth|key|token|secret|signature|password|cookie|session/i
|
|
|
36
36
|
// Usage still being read when the request's log is flushed isn't waited on for longer.
|
|
37
37
|
const USAGE_WAIT_MS = 10_000;
|
|
38
38
|
// A request's calls on Zite's AI key at once, until each is answered, as the host once had them.
|
|
39
|
-
const
|
|
39
|
+
const GATEWAY_CONCURRENCY = 4;
|
|
40
40
|
// Tokens refreshed in this isolate, which a later request's props may not name yet.
|
|
41
41
|
const MAX_REFRESHED = 50;
|
|
42
42
|
const refreshedTokens = new Map();
|
|
@@ -93,7 +93,7 @@ const secretsOf = (host) => {
|
|
|
93
93
|
const values = new Set([...refreshedTokens.keys(), ...replacements.values()]);
|
|
94
94
|
// A connection's own URL (an instance, an account) says which call failed; a user's secret may be a URL.
|
|
95
95
|
const add = (value, urls) => {
|
|
96
|
-
if (typeof value !== "string" || value.length < MIN_TOKEN_LENGTH ||
|
|
96
|
+
if (typeof value !== "string" || value.length < MIN_TOKEN_LENGTH || GATEWAY_MARKER.test(value))
|
|
97
97
|
return;
|
|
98
98
|
if (urls || !isUrl(value))
|
|
99
99
|
values.add(value);
|
|
@@ -113,7 +113,7 @@ const secretsOf = (host) => {
|
|
|
113
113
|
/** The values a request's own credential headers carry, which the log redacts too. */
|
|
114
114
|
const headerSecrets = (headers) => [...headers].flatMap(([name, value]) => {
|
|
115
115
|
const secret = bare(value);
|
|
116
|
-
return SECRET_HEADER.test(name) && secret.length >= MIN_TOKEN_LENGTH && !
|
|
116
|
+
return SECRET_HEADER.test(name) && secret.length >= MIN_TOKEN_LENGTH && !GATEWAY_MARKER.test(secret) ? [secret] : [];
|
|
117
117
|
});
|
|
118
118
|
/** `text` cut to `max`, every secret in it redacted, none cut in half first, however it was written. */
|
|
119
119
|
const loggable = (text, secrets, max) => {
|
|
@@ -228,9 +228,9 @@ const swapHeaders = (headers, from, to) => {
|
|
|
228
228
|
headers.set(name, value.split(from).join(to));
|
|
229
229
|
}
|
|
230
230
|
};
|
|
231
|
-
/** The provider's
|
|
231
|
+
/** The provider's gateway, from `urls.gateway`. */
|
|
232
232
|
const gatewayOf = (host) => {
|
|
233
|
-
const configured = host.provider?.urls?.
|
|
233
|
+
const configured = host.provider?.urls?.gateway;
|
|
234
234
|
if (!configured)
|
|
235
235
|
return undefined;
|
|
236
236
|
try {
|
|
@@ -249,10 +249,10 @@ const underBase = (url, basePath) => {
|
|
|
249
249
|
return { provider, path: `/${rest.join("/")}${url.search}` };
|
|
250
250
|
};
|
|
251
251
|
/** A call on Zite's AI key, whether the app named the provider, the `baseUrl` it was given, or the gateway itself. */
|
|
252
|
-
const
|
|
253
|
-
const found = [...headers].map(([, value]) =>
|
|
252
|
+
const gatewayCallOf = (url, headers, gateway) => {
|
|
253
|
+
const found = [...headers].map(([, value]) => GATEWAY_MARKER.exec(bare(value))).find(Boolean);
|
|
254
254
|
const marker = found ? { marker: found[0], connection: found[1] } : { marker: undefined, connection: undefined };
|
|
255
|
-
if (url.hostname ===
|
|
255
|
+
if (url.hostname === GATEWAY_HOST) {
|
|
256
256
|
const route = underBase(url, "");
|
|
257
257
|
return route && { ...route, ...marker };
|
|
258
258
|
}
|
|
@@ -269,7 +269,7 @@ const aiCallOf = (url, headers, gateway) => {
|
|
|
269
269
|
return { provider: route.provider, path: `${path}${url.search}`, ...marker };
|
|
270
270
|
};
|
|
271
271
|
/** A connection on Zite's AI key as `integrations.get` answers it, its `baseUrl` at the provider's gateway. */
|
|
272
|
-
export const
|
|
272
|
+
export const withGatewayUrl = (host, answer) => {
|
|
273
273
|
const gateway = gatewayOf(host);
|
|
274
274
|
const baseUrl = answer?.baseUrl;
|
|
275
275
|
if (!gateway || typeof baseUrl !== "string" || !answer || typeof answer !== "object")
|
|
@@ -281,7 +281,7 @@ export const withAiGatewayUrl = (host, answer) => {
|
|
|
281
281
|
catch {
|
|
282
282
|
return answer;
|
|
283
283
|
}
|
|
284
|
-
if (url.hostname !==
|
|
284
|
+
if (url.hostname !== GATEWAY_HOST)
|
|
285
285
|
return answer;
|
|
286
286
|
return { ...answer, baseUrl: `${gateway.origin}${gateway.pathname.replace(/\/+$/, "")}${url.pathname}` };
|
|
287
287
|
};
|
|
@@ -320,24 +320,24 @@ const freshToken = async (host, token, connection) => {
|
|
|
320
320
|
}
|
|
321
321
|
return value;
|
|
322
322
|
};
|
|
323
|
-
const
|
|
324
|
-
const
|
|
325
|
-
? "Zite's AI key needs
|
|
326
|
-
: "Zite's AI key needs
|
|
323
|
+
const refusal = (status, type, message) => Response.json({ error: { type, code: type, message } }, { status });
|
|
324
|
+
const gatewayUnavailable = (host) => refusal(503, "unavailable", host.provider?.kind === "local"
|
|
325
|
+
? "Zite's AI key needs Zite's gateway: name gateway in ZITE_URLS"
|
|
326
|
+
: "Zite's AI key needs Zite's gateway, which this request wasn't given");
|
|
327
327
|
/**
|
|
328
328
|
* A call on Zite's AI key at the gateway, the marker swapped for the request's app token. The token goes to the
|
|
329
329
|
* gateway's origin alone: the target is built from it, and a redirect is handed back rather than followed.
|
|
330
330
|
*/
|
|
331
|
-
const
|
|
331
|
+
const toGateway = async (nativeFetch, base, headers, call, gateway, token) => {
|
|
332
332
|
const target = new URL(`${gateway.origin}${gateway.pathname.replace(/\/+$/, "")}/${call.provider}${call.path}`);
|
|
333
333
|
const sent = new Headers(headers);
|
|
334
|
-
sent.delete(
|
|
334
|
+
sent.delete(GATEWAY_CONNECTION_HEADER);
|
|
335
335
|
sent.delete("content-length");
|
|
336
336
|
// As for a connection's call: a Node SDK that asks for gzip inflates a body Workers already inflated.
|
|
337
337
|
sent.delete("accept-encoding");
|
|
338
338
|
if (call.marker && call.connection) {
|
|
339
339
|
swapHeaders(sent, call.marker, token);
|
|
340
|
-
sent.set(
|
|
340
|
+
sent.set(GATEWAY_CONNECTION_HEADER, call.connection);
|
|
341
341
|
}
|
|
342
342
|
// Whole, so it goes with its length and the gateway holds only what it is.
|
|
343
343
|
const body = base.body ? await base.arrayBuffer() : undefined;
|
|
@@ -360,8 +360,8 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
|
|
|
360
360
|
headers.set("user-agent", DEFAULT_USER_AGENT);
|
|
361
361
|
const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
|
|
362
362
|
const gateway = gatewayOf(host);
|
|
363
|
-
const
|
|
364
|
-
const found =
|
|
363
|
+
const gatewayCall = gatewayCallOf(url, headers, gateway);
|
|
364
|
+
const found = gatewayCall ? undefined : carried(headers, url, tokensOf(host));
|
|
365
365
|
const startedAt = Date.now();
|
|
366
366
|
const sentBody = bodyText(init?.body);
|
|
367
367
|
const sentHeaderSecrets = headerSecrets(headers);
|
|
@@ -369,7 +369,7 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
|
|
|
369
369
|
const fetches = (host.fetches ??= []);
|
|
370
370
|
if (fetches.length >= MAX_FETCHES)
|
|
371
371
|
return undefined;
|
|
372
|
-
const connection =
|
|
372
|
+
const connection = gatewayCall?.connection ?? found?.connection;
|
|
373
373
|
const secrets = [...sentHeaderSecrets, ...secretsOf(host)].sort((a, b) => b.length - a.length);
|
|
374
374
|
const bodyRoom = Math.min(MAX_BODY_CHARS, MAX_LOGGED_CHARS - (host.fetchLogChars ?? 0));
|
|
375
375
|
const requestBody = sentBody !== undefined && bodyRoom > 0 ? loggable(sentBody, secrets, bodyRoom) : undefined;
|
|
@@ -386,13 +386,13 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
|
|
|
386
386
|
error: loggable(outcome.error instanceof Error ? outcome.error.message : String(outcome.error), secrets, MAX_ERROR_CHARS),
|
|
387
387
|
}),
|
|
388
388
|
...(connection && { connection }),
|
|
389
|
-
...(
|
|
389
|
+
...(gatewayCall && { ziteAi: true }),
|
|
390
390
|
...(outcome.retried && { retried: true }),
|
|
391
391
|
};
|
|
392
392
|
fetches.push(entry);
|
|
393
393
|
return entry;
|
|
394
394
|
};
|
|
395
|
-
if (!
|
|
395
|
+
if (!gatewayCall && !found) {
|
|
396
396
|
try {
|
|
397
397
|
// The app's own call, `cf` and all; only the headers are ours.
|
|
398
398
|
const response = await nativeFetch(input, { ...init, headers });
|
|
@@ -410,19 +410,19 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
|
|
|
410
410
|
if (usageBody !== undefined)
|
|
411
411
|
headers.delete("content-length");
|
|
412
412
|
const base = new Request(input, usageBody === undefined ? init : { ...init, body: usageBody });
|
|
413
|
-
if (
|
|
413
|
+
if (gatewayCall) {
|
|
414
414
|
try {
|
|
415
415
|
// As the gateway and the host refuse it: a demo has no AI on Zite's key.
|
|
416
416
|
if (host.mode === "demo") {
|
|
417
|
-
const refused =
|
|
417
|
+
const refused = refusal(403, "permission_denied", DEMO_UNAVAILABLE_MESSAGE);
|
|
418
418
|
record({ status: refused.status });
|
|
419
419
|
return refused;
|
|
420
420
|
}
|
|
421
421
|
const access = gateway ? await directAccess(host) : undefined;
|
|
422
422
|
if (gateway && access) {
|
|
423
|
-
const release = await (host.
|
|
423
|
+
const release = await (host.gatewaySlots ??= limiter(GATEWAY_CONCURRENCY))();
|
|
424
424
|
try {
|
|
425
|
-
const response = await
|
|
425
|
+
const response = await toGateway(nativeFetch, base, headers, gatewayCall, gateway, access.token);
|
|
426
426
|
record({ status: response.status });
|
|
427
427
|
return response;
|
|
428
428
|
}
|
|
@@ -430,7 +430,7 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
|
|
|
430
430
|
release();
|
|
431
431
|
}
|
|
432
432
|
}
|
|
433
|
-
const refused =
|
|
433
|
+
const refused = gatewayUnavailable(host);
|
|
434
434
|
record({ status: refused.status });
|
|
435
435
|
return refused;
|
|
436
436
|
}
|
|
@@ -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
|
|
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
|
-
|
|
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,
|
|
@@ -1,15 +1,11 @@
|
|
|
1
|
-
// The platform's part of every page's head: its runtime, the badge and analytics config, an installable app's manifest,
|
|
2
|
-
// the metadata the app's settings set, and what the app's own head() leaves out. Isomorphic: head() runs on the server and again in the browser.
|
|
3
|
-
import { appTokenClaims } from "../internal/appToken.js";
|
|
4
1
|
/** Where the runtime posts a page's analytics: its `endpointUrl` and then its own path. */
|
|
5
2
|
export const ANALYTICS_PATH = "/__zite/public/zite/analytics";
|
|
6
3
|
const ANALYTICS_ENDPOINT = "/__zite";
|
|
7
4
|
/** Served by the platform when the app is installable. */
|
|
8
5
|
const MANIFEST_PATH = "/manifest.webmanifest";
|
|
9
|
-
/** For one request: the plan its host sent, the badge its
|
|
6
|
+
/** For one request: the plan its host sent, the badge its org's plan shows, and analytics on a live page. */
|
|
10
7
|
export const platformHeadOf = (page, request) => {
|
|
11
8
|
const { plan } = page;
|
|
12
|
-
const claims = request.token ? appTokenClaims(request.token) : undefined;
|
|
13
9
|
const image = plan.seoImage ?? plan.image;
|
|
14
10
|
return {
|
|
15
11
|
title: plan.seoTitle ?? plan.fallbackTitle,
|
|
@@ -26,10 +22,9 @@ export const platformHeadOf = (page, request) => {
|
|
|
26
22
|
...(plan.manifest && { manifest: { themeColor: plan.manifest.theme_color, shortName: plan.manifest.short_name } }),
|
|
27
23
|
...(page.runtimeUrl && { runtimeUrl: page.runtimeUrl }),
|
|
28
24
|
...(page.demo && { demo: { listingSlug: page.demo.listingSlug, listingUrl: page.demo.listingUrl } }),
|
|
29
|
-
|
|
30
|
-
branding: claims?.branding ?? true,
|
|
25
|
+
branding: request.context.showZiteBadge,
|
|
31
26
|
analytics: {
|
|
32
|
-
appId:
|
|
27
|
+
appId: request.context.appId,
|
|
33
28
|
// Previews are the builder's own visits; demos aren't the app's.
|
|
34
29
|
enabled: request.mode === "live",
|
|
35
30
|
endpointUrl: `${new URL(request.url).origin}${ANALYTICS_ENDPOINT}`,
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
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
|
-
/**
|
|
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<
|
|
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,43 +1,57 @@
|
|
|
1
|
-
// The one place zitejs knows where the platform is. `zite`: Zite's dispatcher hands each request its app token,
|
|
2
|
-
// platform's URLs and who is calling, in props. `local`: a developer's machine, with
|
|
3
|
-
|
|
1
|
+
// The one place zitejs knows where the platform is. `zite`: Zite's dispatcher hands each request its app token, what
|
|
2
|
+
// the platform says of the app, the platform's URLs and who is calling, in props. `local`: a developer's machine, with
|
|
3
|
+
// a dev token the backend minted, which the backend also describes. The token is opaque here: zitejs only sends it.
|
|
4
4
|
import { platformFetch } from "../internal/platformFetch.js";
|
|
5
5
|
import { devAppId } from "./devApp.js";
|
|
6
6
|
// A streamed answer can outlive the request's deadline, which the token's expiry follows.
|
|
7
7
|
const RENEW_WITHIN_MS = 30_000;
|
|
8
|
-
const expiresWithin = (
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
const expiresWithin = (expiresAt, ms) => expiresAt !== undefined && expiresAt - Date.now() < ms;
|
|
9
|
+
const isExpiringToken = (value) => {
|
|
10
|
+
const given = value;
|
|
11
|
+
return typeof given?.token === "string" && given.token !== "" && typeof given.expiresAt === "number" && Number.isFinite(given.expiresAt);
|
|
11
12
|
};
|
|
12
|
-
const
|
|
13
|
-
|
|
13
|
+
const contextOf = ({ appId, buildId, baseId, mode, orgSettingsVersion, showZiteBadge, appUrl }) => ({
|
|
14
|
+
appId,
|
|
15
|
+
buildId,
|
|
16
|
+
baseId,
|
|
17
|
+
mode,
|
|
18
|
+
orgSettingsVersion,
|
|
19
|
+
showZiteBadge,
|
|
20
|
+
appUrl,
|
|
21
|
+
});
|
|
22
|
+
const URL_NAMES = ["baseRunner", "backend", "gateway", "runs", "email", "pdf", "uploads", "steps"];
|
|
23
|
+
// `local` may leave out the gateway (a call on Zite's AI key is then refused), `runs` (a preview sends no analytics,
|
|
14
24
|
// and `local` keeps no run detail) and each service's own URL (the backend then answers it).
|
|
15
|
-
const OPTIONAL_URLS = new Set(["
|
|
25
|
+
const OPTIONAL_URLS = new Set(["gateway", "runs", "email", "pdf", "uploads", "steps"]);
|
|
16
26
|
const trimmed = (urls) => Object.fromEntries(URL_NAMES.flatMap((name) => (urls[name] ? [[name, urls[name].replace(/\/+$/, "")]] : [])));
|
|
17
27
|
export const ziteProvider = (props) => {
|
|
18
|
-
let current = props.appToken
|
|
28
|
+
let current = props.appToken
|
|
29
|
+
? { token: props.appToken, expiresAt: props.appTokenExpiresAt }
|
|
30
|
+
: undefined;
|
|
19
31
|
let renewing;
|
|
32
|
+
// Kept before `renewing` clears, so a caller that comes between them doesn't renew again.
|
|
20
33
|
const renew = async () => {
|
|
21
34
|
try {
|
|
22
35
|
const fresh = await props.platform.appToken();
|
|
23
|
-
|
|
36
|
+
if (isExpiringToken(fresh))
|
|
37
|
+
current = fresh;
|
|
24
38
|
}
|
|
25
39
|
catch (error) {
|
|
26
40
|
// The token held still serves until it expires.
|
|
27
41
|
console.error("[zite] couldn't renew the app token", error);
|
|
28
|
-
return undefined;
|
|
29
42
|
}
|
|
30
43
|
};
|
|
44
|
+
const context = contextOf(props);
|
|
31
45
|
return {
|
|
32
46
|
kind: "zite",
|
|
33
47
|
urls: props.urls && trimmed(props.urls),
|
|
34
48
|
user: () => props.user,
|
|
49
|
+
context: async () => context,
|
|
35
50
|
token: async () => {
|
|
36
|
-
if (!current || !expiresWithin(current, RENEW_WITHIN_MS))
|
|
37
|
-
return current;
|
|
38
|
-
renewing ??= renew().finally(() => (renewing = undefined));
|
|
39
|
-
|
|
40
|
-
return current;
|
|
51
|
+
if (!current || !expiresWithin(current.expiresAt, RENEW_WITHIN_MS))
|
|
52
|
+
return current?.token;
|
|
53
|
+
await (renewing ??= renew().finally(() => (renewing = undefined)));
|
|
54
|
+
return current.token;
|
|
41
55
|
},
|
|
42
56
|
};
|
|
43
57
|
};
|
|
@@ -56,7 +70,7 @@ export const localUrls = (raw) => {
|
|
|
56
70
|
const given = (parsed ?? {});
|
|
57
71
|
const isUrl = (value) => typeof value === "string" && /^https?:\/\//.test(value);
|
|
58
72
|
if (URL_NAMES.some((name) => (given[name] === undefined ? !OPTIONAL_URLS.has(name) : !isUrl(given[name])))) {
|
|
59
|
-
throw new Error(`${LOCAL_ENV.urls} must be JSON naming the baseRunner and backend URLs, and may name
|
|
73
|
+
throw new Error(`${LOCAL_ENV.urls} must be JSON naming the baseRunner and backend URLs, and may name gateway, runs, email, pdf, uploads and steps`);
|
|
60
74
|
}
|
|
61
75
|
return trimmed(given);
|
|
62
76
|
};
|
|
@@ -82,49 +96,89 @@ const localUser = (raw) => {
|
|
|
82
96
|
isInternal: given.isInternal === true,
|
|
83
97
|
};
|
|
84
98
|
};
|
|
85
|
-
const MODES = new Set(["live", "preview", "demo"]);
|
|
86
|
-
/** The mode a dev token names; preview for one it doesn't. */
|
|
87
|
-
export const localModeOf = (claims) => MODES.has(claims?.mode) ? claims?.mode : "preview";
|
|
88
99
|
// The backend mints them for 15 minutes.
|
|
89
100
|
const RENEW_DEV_TOKEN_WITHIN_MS = 60_000;
|
|
90
|
-
const
|
|
91
|
-
// Per isolate, only
|
|
101
|
+
const BACKEND_TIMEOUT_MS = 10_000;
|
|
102
|
+
// Per isolate, only answers, never a pending call: Workers ties a request's I/O to that request.
|
|
92
103
|
let held;
|
|
93
|
-
|
|
104
|
+
let described;
|
|
105
|
+
/** For tests: forget the minted dev token and what the backend said of it. */
|
|
94
106
|
export const resetDevToken = () => {
|
|
95
107
|
held = undefined;
|
|
108
|
+
described = undefined;
|
|
109
|
+
};
|
|
110
|
+
const reasonOf = (response, answer) => {
|
|
111
|
+
const why = [answer?.message, answer?.error].find((text) => typeof text === "string");
|
|
112
|
+
return `${response.status}${why ? ` ${why}` : ""}`;
|
|
96
113
|
};
|
|
97
114
|
export const mintDevToken = async (backend, appId, apiKey) => {
|
|
98
115
|
const response = await platformFetch(new Request(`${backend}/v1/start/apps/${encodeURIComponent(appId)}/dev-token`, {
|
|
99
116
|
method: "POST",
|
|
100
117
|
headers: { authorization: `Bearer ${apiKey}` },
|
|
101
|
-
signal: AbortSignal.timeout(
|
|
118
|
+
signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
|
|
102
119
|
}));
|
|
103
120
|
const answer = (await response.json().catch(() => null));
|
|
104
|
-
if (response.ok &&
|
|
105
|
-
return answer.token;
|
|
106
|
-
|
|
107
|
-
|
|
121
|
+
if (response.ok && isExpiringToken(answer))
|
|
122
|
+
return { token: answer.token, expiresAt: answer.expiresAt };
|
|
123
|
+
throw new Error(`The backend didn't mint a dev token for app ${appId} with ${LOCAL_ENV.apiKey}: ${reasonOf(response, answer)}`);
|
|
124
|
+
};
|
|
125
|
+
const MODES = new Set(["live", "preview", "demo"]);
|
|
126
|
+
const isWhole = (value) => Number.isSafeInteger(value) && value >= 0;
|
|
127
|
+
const isText = (value) => typeof value === "string" && value !== "";
|
|
128
|
+
const isTextOrNull = (value) => value === null || isText(value);
|
|
129
|
+
/** The backend's `/context` answer, or undefined when it isn't one. */
|
|
130
|
+
const appContextOf = (answer) => {
|
|
131
|
+
const given = answer;
|
|
132
|
+
if (!given ||
|
|
133
|
+
!isText(given.appId) ||
|
|
134
|
+
!isWhole(given.buildId) ||
|
|
135
|
+
!isTextOrNull(given.baseId) ||
|
|
136
|
+
!MODES.has(given.mode) ||
|
|
137
|
+
!(given.orgSettingsVersion === null || isWhole(given.orgSettingsVersion)) ||
|
|
138
|
+
typeof given.showZiteBadge !== "boolean" ||
|
|
139
|
+
!isTextOrNull(given.appUrl)) {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
return contextOf(given);
|
|
108
143
|
};
|
|
109
|
-
/**
|
|
144
|
+
/**
|
|
145
|
+
* What the backend says of a dev token, from the claims it verified, as OAuth's token introspection answers: asked
|
|
146
|
+
* once per token, whose claims never change. Throws, saying why, when it won't say.
|
|
147
|
+
*/
|
|
148
|
+
export const describeDevToken = async (backend, token) => {
|
|
149
|
+
const key = `${backend} ${token}`;
|
|
150
|
+
if (described?.key === key)
|
|
151
|
+
return described.context;
|
|
152
|
+
const response = await platformFetch(new Request(`${backend}/v1/start/app/context`, {
|
|
153
|
+
headers: { authorization: `Bearer ${token}` },
|
|
154
|
+
signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
|
|
155
|
+
}));
|
|
156
|
+
const answer = await response.json().catch(() => null);
|
|
157
|
+
const context = response.ok ? appContextOf(answer) : undefined;
|
|
158
|
+
if (!context)
|
|
159
|
+
throw new Error(`The backend didn't say which app the dev token is for: ${reasonOf(response, answer)}`);
|
|
160
|
+
described = { key, context };
|
|
161
|
+
return context;
|
|
162
|
+
};
|
|
163
|
+
/** The app's dev token, minted with the developer's key, and minted again when the mint's expiry is near. */
|
|
110
164
|
const mintedDevToken = (backend, appId, apiKey) => {
|
|
111
165
|
const key = `${backend} ${appId} ${apiKey}`;
|
|
112
166
|
let minting;
|
|
113
167
|
return async () => {
|
|
114
|
-
const current = held?.key === key ? held.
|
|
115
|
-
if (current && !expiresWithin(current, RENEW_DEV_TOKEN_WITHIN_MS))
|
|
116
|
-
return current;
|
|
168
|
+
const current = held?.key === key ? held.minted : undefined;
|
|
169
|
+
if (current && !expiresWithin(current.expiresAt, RENEW_DEV_TOKEN_WITHIN_MS))
|
|
170
|
+
return current.token;
|
|
117
171
|
minting ??= mintDevToken(backend, appId, apiKey).finally(() => (minting = undefined));
|
|
118
172
|
try {
|
|
119
|
-
const
|
|
120
|
-
held = { key,
|
|
121
|
-
return token;
|
|
173
|
+
const minted = await minting;
|
|
174
|
+
held = { key, minted };
|
|
175
|
+
return minted.token;
|
|
122
176
|
}
|
|
123
177
|
catch (error) {
|
|
124
|
-
if (!current || expiresWithin(current, 0))
|
|
178
|
+
if (!current || expiresWithin(current.expiresAt, 0))
|
|
125
179
|
throw error;
|
|
126
180
|
console.error("[zite] couldn't renew the dev token; using the one held until it expires", error);
|
|
127
|
-
return current;
|
|
181
|
+
return current.token;
|
|
128
182
|
}
|
|
129
183
|
};
|
|
130
184
|
};
|
|
@@ -146,5 +200,12 @@ export const localPlatform = (env = processEnv() ?? {}, appId = devAppId) => {
|
|
|
146
200
|
return undefined;
|
|
147
201
|
const urls = localUrls(env[LOCAL_ENV.urls]);
|
|
148
202
|
const user = localUser(env[LOCAL_ENV.user]);
|
|
149
|
-
|
|
203
|
+
const tokenOf = token(urls.backend);
|
|
204
|
+
return {
|
|
205
|
+
kind: "local",
|
|
206
|
+
urls,
|
|
207
|
+
user: () => user,
|
|
208
|
+
token: tokenOf,
|
|
209
|
+
context: async () => describeDevToken(urls.backend, await tokenOf()),
|
|
210
|
+
};
|
|
150
211
|
};
|