@skyphusion/create-prism 1.0.4 → 1.3.0
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/README.md +10 -8
- package/index.js +3 -2
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +18 -3
- package/template/MIGRATIONS.md +52 -0
- package/template/README.md +79 -52
- package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
- package/template/docs/legal/INSTANCE-PRIVACY.md +128 -27
- package/template/migrations/0005_auth_attempts_retention.sql +23 -0
- package/template/package.json +6 -6
- package/template/public/app.js +21 -8
- package/template/public/index.html +23 -9
- package/template/public/styles.css +45 -7
- package/template/public/url-safety.js +6 -6
- package/template/schema.sql +6 -0
- package/template/src/ai-binding.ts +125 -3
- package/template/src/auth.ts +6 -0
- package/template/src/env.ts +38 -10
- package/template/src/gateway-credentials.ts +118 -22
- package/template/src/index.ts +2 -0
- package/template/src/providers/anthropic.ts +4 -4
- package/template/src/providers/openai-image.ts +10 -0
- package/template/src/providers/xai.ts +4 -4
- package/template/src/rate-limit.ts +26 -0
- package/template/src/routes/chat.ts +18 -9
- package/template/src/routes/prefs.ts +46 -5
- package/template/src/routes/rag.ts +135 -61
- package/template/src/routes/shared.ts +27 -11
- package/template/src/routes/workflow.ts +2 -5
- package/template/src/skyphusion-search.ts +108 -0
- package/template/src/user-prefs.ts +16 -3
- package/template/src/version.ts +1 -1
- package/template/tests/ai-binding-rest.test.ts +154 -0
- package/template/tests/csp.test.ts +11 -6
- package/template/tests/gateway-credentials.test.ts +101 -3
- package/template/tests/openai-image.test.ts +21 -1
- package/template/tests/rag-metadata-filter.test.ts +135 -0
- package/template/tests/skip-link.test.ts +164 -0
- package/template/tests/skyphusion-search.test.ts +144 -0
- package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
- package/template/tests-integration/auth.test.ts +346 -2
- package/template/tests-integration/pdf-extract.test.ts +71 -0
- package/template/wrangler.example.toml +26 -11
- package/template/src/searxng.ts +0 -75
- package/template/tests/searxng.test.ts +0 -51
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// env.AI binding wrappers (v0.19.3; per-user gateway v0.164.0
|
|
1
|
+
// env.AI binding wrappers (v0.19.3; per-user gateway v0.164.0; account-scoped
|
|
2
|
+
// REST transport v1.1.0).
|
|
2
3
|
//
|
|
3
4
|
// Extracted from src/index.ts so provider modules and other code paths that
|
|
4
5
|
// call env.AI.run share one binding wrapper rather than each constructing its
|
|
@@ -8,26 +9,147 @@
|
|
|
8
9
|
// return the raw Response (rather than a parsed object) for binary-output
|
|
9
10
|
// models like TTS.
|
|
10
11
|
//
|
|
11
|
-
// `aiLogId` reads the Cloudflare AI Gateway log ID
|
|
12
|
-
//
|
|
12
|
+
// `aiLogId` reads the Cloudflare AI Gateway log ID after a call, when one
|
|
13
|
+
// exists.
|
|
14
|
+
//
|
|
15
|
+
// v1.1.0: two transports, chosen by the credentials, never by the model.
|
|
16
|
+
// - accountId null: env.AI.run on this worker's binding. Cloudflare pins the
|
|
17
|
+
// binding's gateway to the worker's own account and pre-authenticates it,
|
|
18
|
+
// so this bills the deployer. Access mode (private self-host) only.
|
|
19
|
+
// - accountId set: POST api.cloudflare.com/client/v4/accounts/{account}/ai/run
|
|
20
|
+
// with the user's token and cf-aig-gateway-id, which bills the user's
|
|
21
|
+
// account. This is the only way to reach another account's gateway; the
|
|
22
|
+
// binding cannot, whatever gateway id it is handed.
|
|
23
|
+
// `gatewayProviderUrl` applies the same split to the provider-native
|
|
24
|
+
// gateway.ai.cloudflare.com endpoints (legacy Anthropic / xAI paths).
|
|
13
25
|
|
|
14
26
|
import type { Env } from "./env";
|
|
15
27
|
import type { GatewayCredentials } from "./gateway-credentials";
|
|
28
|
+
import { base64ToBytes } from "./utils";
|
|
16
29
|
|
|
17
30
|
export interface AiContext {
|
|
18
31
|
env: Env;
|
|
19
32
|
gateway: GatewayCredentials;
|
|
33
|
+
/** v1.1.0: cf-aig-log-id from the last REST call (the binding tracks its own). */
|
|
34
|
+
lastLogId?: string | null;
|
|
20
35
|
}
|
|
21
36
|
|
|
22
37
|
type RunOpts = { gateway: { id: string }; returnRawResponse?: boolean };
|
|
23
38
|
type RunFn = (model: string, params: unknown, opts?: RunOpts) => Promise<unknown>;
|
|
24
39
|
|
|
40
|
+
export const CF_API_BASE = "https://api.cloudflare.com/client/v4";
|
|
41
|
+
export const AI_GATEWAY_BASE = "https://gateway.ai.cloudflare.com/v1";
|
|
42
|
+
|
|
25
43
|
export function aiRun(ctx: AiContext, model: string, params: unknown, returnRaw = false): Promise<unknown> {
|
|
44
|
+
if (ctx.gateway.accountId) return restRun(ctx, ctx.gateway.accountId, model, params, returnRaw);
|
|
26
45
|
const opts: RunOpts = { gateway: { id: ctx.gateway.gatewayId } };
|
|
27
46
|
if (returnRaw) opts.returnRawResponse = true;
|
|
28
47
|
return (ctx.env.AI as unknown as { run: RunFn }).run(model, params, opts);
|
|
29
48
|
}
|
|
30
49
|
|
|
31
50
|
export function aiLogId(ctx: AiContext): string | null {
|
|
51
|
+
// An account-scoped context never reads the binding: its log id belongs to
|
|
52
|
+
// whatever the binding last did on OUR account, not to this call.
|
|
53
|
+
if (ctx.gateway.accountId) return ctx.lastLogId ?? null;
|
|
32
54
|
return (ctx.env.AI as unknown as { aiGatewayLogId?: string }).aiGatewayLogId ?? null;
|
|
33
55
|
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Base URL of a provider-native AI Gateway endpoint
|
|
59
|
+
* (https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/{provider}).
|
|
60
|
+
* Account-scoped credentials build it from the user's account; otherwise the
|
|
61
|
+
* binding's getUrl supplies this worker's own account.
|
|
62
|
+
*/
|
|
63
|
+
export async function gatewayProviderUrl(ctx: AiContext, provider: string): Promise<string> {
|
|
64
|
+
const { accountId, gatewayId } = ctx.gateway;
|
|
65
|
+
if (accountId) {
|
|
66
|
+
return `${AI_GATEWAY_BASE}/${accountId}/${encodeURIComponent(gatewayId)}/${provider}`;
|
|
67
|
+
}
|
|
68
|
+
return (ctx.env.AI as unknown as {
|
|
69
|
+
gateway: (id: string) => { getUrl: (provider: string) => Promise<string> };
|
|
70
|
+
}).gateway(gatewayId).getUrl(provider);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Workers AI (@cf/) models use the model-in-path endpoint, the one Cloudflare
|
|
74
|
+
// documents for billing @cf calls to the gateway's credits; partner models use
|
|
75
|
+
// the /ai/run envelope ({ model, input }). Both take cf-aig-gateway-id.
|
|
76
|
+
export function buildRestRunRequest(
|
|
77
|
+
accountId: string,
|
|
78
|
+
gateway: GatewayCredentials,
|
|
79
|
+
model: string,
|
|
80
|
+
params: unknown,
|
|
81
|
+
): { url: string; init: RequestInit } {
|
|
82
|
+
const base = `${CF_API_BASE}/accounts/${accountId}/ai/run`;
|
|
83
|
+
const isWorkersAi = model.startsWith("@cf/");
|
|
84
|
+
return {
|
|
85
|
+
url: isWorkersAi ? `${base}/${model}` : base,
|
|
86
|
+
init: {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: {
|
|
89
|
+
"authorization": `Bearer ${gateway.cfAigToken}`,
|
|
90
|
+
"cf-aig-gateway-id": gateway.gatewayId,
|
|
91
|
+
"content-type": "application/json",
|
|
92
|
+
},
|
|
93
|
+
body: JSON.stringify(isWorkersAi ? params : { model, input: params }),
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function restRun(
|
|
99
|
+
ctx: AiContext,
|
|
100
|
+
accountId: string,
|
|
101
|
+
model: string,
|
|
102
|
+
params: unknown,
|
|
103
|
+
returnRaw: boolean,
|
|
104
|
+
): Promise<unknown> {
|
|
105
|
+
const { url, init } = buildRestRunRequest(accountId, ctx.gateway, model, params);
|
|
106
|
+
const resp = await fetch(url, init);
|
|
107
|
+
ctx.lastLogId = resp.headers.get("cf-aig-log-id");
|
|
108
|
+
return unwrapRestResponse(resp, accountId, returnRaw);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Normalizes a REST response to what the binding would have returned, so no
|
|
112
|
+
// caller has to know which transport ran:
|
|
113
|
+
// - JSON: unwrap the Cloudflare API envelope ({ success, result, errors }).
|
|
114
|
+
// - SSE / binary: the body stream (the binding returns a ReadableStream).
|
|
115
|
+
// - returnRaw: a Response carrying the bytes (TTS reads arrayBuffer()).
|
|
116
|
+
export async function unwrapRestResponse(resp: Response, accountId: string, returnRaw: boolean): Promise<unknown> {
|
|
117
|
+
if (!resp.ok) {
|
|
118
|
+
const text = await resp.text().catch(() => "");
|
|
119
|
+
let detail = text.slice(0, 500);
|
|
120
|
+
try {
|
|
121
|
+
const parsed = JSON.parse(text) as { errors?: Array<{ code?: number; message?: string }> };
|
|
122
|
+
if (parsed.errors?.length) {
|
|
123
|
+
detail = parsed.errors.map((e) => `${e.code ?? ""} ${e.message ?? ""}`.trim()).join("; ");
|
|
124
|
+
}
|
|
125
|
+
} catch { /* non-JSON error body; keep the text */ }
|
|
126
|
+
let hint = "";
|
|
127
|
+
if (resp.status === 401 || resp.status === 403) {
|
|
128
|
+
hint = ` Check that your API token has Workers AI Read and AI Gateway Run on account ${accountId}.`;
|
|
129
|
+
}
|
|
130
|
+
throw new Error(`Cloudflare AI (your account) ${resp.status}: ${detail || resp.statusText}.${hint}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const ct = resp.headers.get("content-type") || "";
|
|
134
|
+
if (ct.includes("application/json")) {
|
|
135
|
+
const body = await resp.json() as { success?: boolean; result?: unknown; errors?: Array<{ message?: string }> };
|
|
136
|
+
let unwrapped: unknown = body;
|
|
137
|
+
if (body && typeof body === "object" && typeof body.success === "boolean") {
|
|
138
|
+
if (!body.success) {
|
|
139
|
+
const msg = body.errors?.map((e) => e.message).filter(Boolean).join("; ") || "request failed";
|
|
140
|
+
throw new Error(`Cloudflare AI (your account): ${msg}`);
|
|
141
|
+
}
|
|
142
|
+
unwrapped = body.result;
|
|
143
|
+
}
|
|
144
|
+
if (!returnRaw) return unwrapped;
|
|
145
|
+
// Raw callers want bytes. Some TTS models answer JSON { audio: base64 }.
|
|
146
|
+
const audio = (unwrapped as { audio?: unknown } | null)?.audio;
|
|
147
|
+
if (typeof audio === "string") {
|
|
148
|
+
return new Response(base64ToBytes(audio), { headers: { "content-type": "audio/mpeg" } });
|
|
149
|
+
}
|
|
150
|
+
throw new Error("Cloudflare AI (your account): expected binary output, got JSON without an audio field");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (returnRaw) return resp;
|
|
154
|
+
return resp.body;
|
|
155
|
+
}
|
package/template/src/auth.ts
CHANGED
|
@@ -313,6 +313,12 @@ export async function cascadeDeleteUserData(env: Env, userId: string): Promise<v
|
|
|
313
313
|
env.DB.prepare(`DELETE FROM documents WHERE user_email = ?`).bind(userId),
|
|
314
314
|
env.DB.prepare(`DELETE FROM projects WHERE user_email = ?`).bind(userId),
|
|
315
315
|
env.DB.prepare(`DELETE FROM chats WHERE user_email = ?`).bind(userId),
|
|
316
|
+
// prism#192: conversation_compact holds a model-written SUMMARY of this
|
|
317
|
+
// user's chat turns, so leaving it behind is exactly the shadow copy
|
|
318
|
+
// INSTANCE-PRIVACY.md says deletion does not keep. Deleting a single
|
|
319
|
+
// conversation already removes its row (routes/conversations.ts); account
|
|
320
|
+
// deletion is the path that skipped it.
|
|
321
|
+
env.DB.prepare(`DELETE FROM conversation_compact WHERE user_email = ?`).bind(userId),
|
|
316
322
|
env.DB.prepare(`DELETE FROM user_prefs WHERE user_email = ?`).bind(userId),
|
|
317
323
|
env.DB.prepare(`DELETE FROM sessions WHERE user_id = ?`).bind(userId),
|
|
318
324
|
env.DB.prepare(`DELETE FROM users WHERE id = ?`).bind(userId),
|
package/template/src/env.ts
CHANGED
|
@@ -12,11 +12,42 @@
|
|
|
12
12
|
// secret runtime paths surface meaningful errors instead of TypeScript
|
|
13
13
|
// telling deployers they need fields they may legitimately not have set.
|
|
14
14
|
|
|
15
|
+
// Subset of search-mcp AiSearchChunk that SearchEntrypoint.search returns.
|
|
16
|
+
// Extra fields on the wire are ignored. The mapper lives in
|
|
17
|
+
// src/skyphusion-search.ts.
|
|
18
|
+
export interface SearchChunk {
|
|
19
|
+
score?: number;
|
|
20
|
+
text?: string;
|
|
21
|
+
item?: {
|
|
22
|
+
key?: string;
|
|
23
|
+
metadata?: { repo?: string; path?: string };
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Named RPC entrypoint on the skyphusion-search Worker. The binding
|
|
28
|
+
// field in wrangler is `entrypoint = "SearchEntrypoint"`. The method
|
|
29
|
+
// is search(question), not POST /ask.
|
|
30
|
+
// https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/#named-entrypoints
|
|
31
|
+
export interface SearchEntrypoint extends Rpc.WorkerEntrypointBranded {
|
|
32
|
+
search(question: string): Promise<{ chunks: SearchChunk[] }>;
|
|
33
|
+
}
|
|
34
|
+
|
|
15
35
|
export interface Env {
|
|
16
36
|
AI: Ai;
|
|
17
37
|
DB: D1Database;
|
|
18
38
|
R2: R2Bucket;
|
|
19
39
|
VEC: VectorizeIndex;
|
|
40
|
+
/**
|
|
41
|
+
* Filter RAG retrieval by `user_email` in Vectorize itself (skyphusion-labs/fleet-chezmoi#1636).
|
|
42
|
+
* "on" (also "1" / "true") turns it on; anything else, including unset, is off.
|
|
43
|
+
*
|
|
44
|
+
* DEFAULT OFF, ON PURPOSE. The filter needs a `user_email` metadata index on the Vectorize index
|
|
45
|
+
* AND every existing vector re-upserted after that index exists (metadata indexes are not
|
|
46
|
+
* retroactive). Turned on before both are done, it hides every older vector and retrieval returns
|
|
47
|
+
* nothing. Order: create the metadata index, run scripts/vectorize-backfill-metadata.mjs, then set
|
|
48
|
+
* this. See MIGRATIONS.md.
|
|
49
|
+
*/
|
|
50
|
+
VEC_METADATA_FILTER?: string;
|
|
20
51
|
ASSETS: Fetcher;
|
|
21
52
|
// v0.167.0 (issue #80): deployment auth plane. "public" = first-party
|
|
22
53
|
// username/password accounts, session cookie identity, and fail-closed
|
|
@@ -57,14 +88,11 @@ export interface Env {
|
|
|
57
88
|
// stay on Unified Billing and render opaque. No other provider reads a
|
|
58
89
|
// deployer key.
|
|
59
90
|
OPENAI_API_KEY?: string;
|
|
60
|
-
//
|
|
61
|
-
//
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
|
|
65
|
-
//
|
|
66
|
-
|
|
67
|
-
// both are set; a self-hoster running an un-gated instance leaves them unset.
|
|
68
|
-
SEARXNG_ACCESS_CLIENT_ID?: string;
|
|
69
|
-
SEARXNG_ACCESS_CLIENT_SECRET?: string;
|
|
91
|
+
// Service binding to the skyphusion-search Worker, named entrypoint
|
|
92
|
+
// SearchEntrypoint. Optional: when the binding is absent, web search
|
|
93
|
+
// reports that source as "absent" and Wikipedia still runs. Declared
|
|
94
|
+
// in wrangler.example.toml as [[services]] binding = "SEARCH",
|
|
95
|
+
// service = "skyphusion-search", entrypoint = "SearchEntrypoint".
|
|
96
|
+
// search(question) returns { chunks }. This is not POST /ask.
|
|
97
|
+
SEARCH?: Service<SearchEntrypoint>;
|
|
70
98
|
}
|
|
@@ -2,11 +2,18 @@
|
|
|
2
2
|
//
|
|
3
3
|
// Supports two deployment modes:
|
|
4
4
|
// - Deployer secrets: GATEWAY_ID + CF_AIG_TOKEN on the worker (private install)
|
|
5
|
-
// - Public demo: no worker secrets; each user stores their own
|
|
6
|
-
// and
|
|
5
|
+
// - Public demo: no worker secrets; each user stores their own Cloudflare
|
|
6
|
+
// account id, gateway slug, and API token in D1 user_prefs
|
|
7
7
|
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
8
|
+
// v1.1.0: before this release a user stored only slug + token, and every call
|
|
9
|
+
// resolved that slug on the worker's AI binding, i.e. on OUR account (the
|
|
10
|
+
// binding cannot address another account). A user's own gateway was
|
|
11
|
+
// unreachable by construction. The account id is what makes it reachable, so
|
|
12
|
+
// it is required before user credentials count as configured.
|
|
13
|
+
//
|
|
14
|
+
// In access mode without a user account id, resolution merges user prefs over
|
|
15
|
+
// worker secrets field-by-field so a partial override still falls back to
|
|
16
|
+
// deployer defaults where unset.
|
|
10
17
|
//
|
|
11
18
|
// v0.167.0 (issue #80): when AUTH_MODE=public the worker secrets are ignored
|
|
12
19
|
// entirely (fail closed). A public deploy must never bill the host for visitor
|
|
@@ -20,10 +27,31 @@ import { loadUserPrefs, type UserPrefsJson } from "./user-prefs";
|
|
|
20
27
|
export interface GatewayCredentials {
|
|
21
28
|
gatewayId: string;
|
|
22
29
|
cfAigToken: string;
|
|
30
|
+
/**
|
|
31
|
+
* v1.1.0: the Cloudflare account that owns `gatewayId`. When set, every call
|
|
32
|
+
* leaves the worker over HTTP to that account (api.cloudflare.com REST or
|
|
33
|
+
* the gateway.ai.cloudflare.com provider endpoint) and bills it. When null,
|
|
34
|
+
* calls ride this worker's own AI binding, which Cloudflare pins to the
|
|
35
|
+
* worker's account ("Must be in the same account as your Worker"), so the
|
|
36
|
+
* deployer pays. Null is only reachable in access mode; public mode refuses
|
|
37
|
+
* credentials without an account id rather than fall back to ours.
|
|
38
|
+
*/
|
|
39
|
+
accountId: string | null;
|
|
23
40
|
}
|
|
24
41
|
|
|
25
42
|
export type GatewaySource = "user" | "worker" | "mixed" | "none";
|
|
26
43
|
|
|
44
|
+
/** Why no usable credentials resolved; each maps to one 412 code. */
|
|
45
|
+
export type GatewayProblem =
|
|
46
|
+
| "gateway_not_configured"
|
|
47
|
+
| "gateway_account_id_required"
|
|
48
|
+
| "cf_aig_token_required";
|
|
49
|
+
|
|
50
|
+
export interface GatewayResolution {
|
|
51
|
+
creds: GatewayCredentials | null;
|
|
52
|
+
problem: GatewayProblem | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
27
55
|
export interface GatewayStatus {
|
|
28
56
|
/**
|
|
29
57
|
* True when the user can run inference: AI Gateway BYOK (gateway id) and/or
|
|
@@ -34,15 +62,51 @@ export interface GatewayStatus {
|
|
|
34
62
|
source: GatewaySource;
|
|
35
63
|
gateway_id: string | null;
|
|
36
64
|
cf_aig_token_set: boolean;
|
|
65
|
+
/** v1.1.0: stored Cloudflare account id (not a secret; it is in every gateway URL). */
|
|
66
|
+
account_id: string | null;
|
|
67
|
+
/**
|
|
68
|
+
* v1.1.0: true for a public-mode user saved under the pre-v1.1.0 shape
|
|
69
|
+
* (slug and/or token but no account id). Their calls are refused until
|
|
70
|
+
* they add it; the SPA uses this to say exactly that instead of a generic
|
|
71
|
+
* "not configured".
|
|
72
|
+
*/
|
|
73
|
+
account_id_required: boolean;
|
|
37
74
|
control_plane_configured: boolean;
|
|
38
75
|
control_plane_key_set: boolean;
|
|
39
76
|
}
|
|
40
77
|
|
|
41
78
|
export const GATEWAY_NOT_CONFIGURED_MSG =
|
|
42
|
-
"Inference not configured. Open Account > AI Gateway and either (1) enter your Cloudflare gateway slug
|
|
79
|
+
"Inference not configured. Open Account > AI Gateway and either (1) enter your Cloudflare account ID, gateway slug, and API token (BYOK), or (2) paste a prism-control-plane client key (pcp_…) to bill chat through play-proxy.";
|
|
43
80
|
|
|
44
81
|
export const CF_AIG_TOKEN_REQUIRED_MSG =
|
|
45
|
-
"This model requires a Cloudflare API token
|
|
82
|
+
"This model requires a Cloudflare API token (Workers AI Read + AI Gateway Run on your account). Add it under Account > AI Gateway.";
|
|
83
|
+
|
|
84
|
+
export const GATEWAY_ACCOUNT_ID_REQUIRED_MSG =
|
|
85
|
+
"Your AI Gateway settings are missing your Cloudflare account ID. Without it a gateway slug resolves on this instance's account, not yours, so model calls are refused until you add it. Open Account > AI Gateway and paste the 32-character account ID from your Cloudflare dashboard.";
|
|
86
|
+
|
|
87
|
+
export function gatewayProblemMessage(problem: GatewayProblem): string {
|
|
88
|
+
switch (problem) {
|
|
89
|
+
case "gateway_account_id_required": return GATEWAY_ACCOUNT_ID_REQUIRED_MSG;
|
|
90
|
+
case "cf_aig_token_required": return CF_AIG_TOKEN_REQUIRED_MSG;
|
|
91
|
+
default: return GATEWAY_NOT_CONFIGURED_MSG;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Cloudflare account ids are 32 lowercase hex characters. Normalizes case so
|
|
96
|
+
// a pasted uppercase id still matches; returns null for anything else.
|
|
97
|
+
const ACCOUNT_ID_RE = /^[0-9a-f]{32}$/;
|
|
98
|
+
export function normalizeAccountId(raw: string | null | undefined): string | null {
|
|
99
|
+
const v = raw?.trim().toLowerCase() ?? "";
|
|
100
|
+
return ACCOUNT_ID_RE.test(v) ? v : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Gateway slugs become a URL path segment and a request header once they
|
|
104
|
+
// address a user account, so the charset is pinned at write time (and the
|
|
105
|
+
// URL builder still encodes it).
|
|
106
|
+
const GATEWAY_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
107
|
+
export function isValidGatewayId(raw: string): boolean {
|
|
108
|
+
return GATEWAY_ID_RE.test(raw.trim());
|
|
109
|
+
}
|
|
46
110
|
|
|
47
111
|
// True when this deployment is the public product; worker gateway secrets are
|
|
48
112
|
// then off-limits for billing resolution.
|
|
@@ -50,17 +114,41 @@ function isPublic(env: Env): boolean {
|
|
|
50
114
|
return env.AUTH_MODE === "public";
|
|
51
115
|
}
|
|
52
116
|
|
|
117
|
+
export function resolveGateway(prefs: UserPrefsJson | null, env: Env): GatewayResolution {
|
|
118
|
+
const userGateway = prefs?.gateway_id?.trim() || "";
|
|
119
|
+
const userToken = prefs?.cf_aig_token?.trim() || "";
|
|
120
|
+
const accountId = normalizeAccountId(prefs?.account_id);
|
|
121
|
+
|
|
122
|
+
// v1.1.0: account-scoped credentials are all-user. No field falls back to a
|
|
123
|
+
// worker secret, because the worker's token authorizes the worker's account
|
|
124
|
+
// and would be rejected by (or worse, meaningless against) the user's.
|
|
125
|
+
if (accountId) {
|
|
126
|
+
if (!userGateway) return { creds: null, problem: "gateway_not_configured" };
|
|
127
|
+
if (!userToken) return { creds: null, problem: "cf_aig_token_required" };
|
|
128
|
+
return { creds: { gatewayId: userGateway, cfAigToken: userToken, accountId }, problem: null };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Public mode: user prefs only, no worker-secret fallback (fail closed), and
|
|
132
|
+
// no account id means no route to the user's gateway. Refuse rather than
|
|
133
|
+
// resolve the slug on the host binding.
|
|
134
|
+
if (isPublic(env)) {
|
|
135
|
+
if (userGateway || userToken) return { creds: null, problem: "gateway_account_id_required" };
|
|
136
|
+
return { creds: null, problem: "gateway_not_configured" };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Access mode (private self-host): the slug names a gateway on this
|
|
140
|
+
// worker's own account and rides the binding. Deployer pays by design.
|
|
141
|
+
const gatewayId = userGateway || env.GATEWAY_ID?.trim() || "";
|
|
142
|
+
const cfAigToken = userToken || env.CF_AIG_TOKEN?.trim() || "";
|
|
143
|
+
if (!gatewayId) return { creds: null, problem: "gateway_not_configured" };
|
|
144
|
+
return { creds: { gatewayId, cfAigToken, accountId: null }, problem: null };
|
|
145
|
+
}
|
|
146
|
+
|
|
53
147
|
export function resolveGatewayFromParts(
|
|
54
148
|
prefs: UserPrefsJson | null,
|
|
55
149
|
env: Env,
|
|
56
150
|
): GatewayCredentials | null {
|
|
57
|
-
|
|
58
|
-
const workerGateway = isPublic(env) ? "" : (env.GATEWAY_ID?.trim() || "");
|
|
59
|
-
const workerToken = isPublic(env) ? "" : (env.CF_AIG_TOKEN?.trim() || "");
|
|
60
|
-
const gatewayId = (prefs?.gateway_id?.trim() || workerGateway);
|
|
61
|
-
const cfAigToken = (prefs?.cf_aig_token?.trim() || workerToken);
|
|
62
|
-
if (!gatewayId) return null;
|
|
63
|
-
return { gatewayId, cfAigToken };
|
|
151
|
+
return resolveGateway(prefs, env).creds;
|
|
64
152
|
}
|
|
65
153
|
|
|
66
154
|
export function gatewaySource(prefs: UserPrefsJson | null, env: Env): GatewaySource {
|
|
@@ -78,12 +166,16 @@ export function gatewaySource(prefs: UserPrefsJson | null, env: Env): GatewaySou
|
|
|
78
166
|
return "none";
|
|
79
167
|
}
|
|
80
168
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
169
|
+
/**
|
|
170
|
+
* Load credentials or throw the problem's user-facing message. For callers
|
|
171
|
+
* outside the HTTP gate (RAG embeddings, the long-run Workflow) that surface
|
|
172
|
+
* an Error rather than a 412.
|
|
173
|
+
*/
|
|
174
|
+
export async function requireGatewayCredentials(env: Env, userEmail: string): Promise<GatewayCredentials> {
|
|
85
175
|
const prefs = await loadUserPrefs(env.DB, userEmail);
|
|
86
|
-
|
|
176
|
+
const { creds, problem } = resolveGateway(prefs, env);
|
|
177
|
+
if (!creds) throw new Error(gatewayProblemMessage(problem ?? "gateway_not_configured"));
|
|
178
|
+
return creds;
|
|
87
179
|
}
|
|
88
180
|
|
|
89
181
|
/**
|
|
@@ -91,13 +183,17 @@ export async function loadGatewayCredentials(
|
|
|
91
183
|
* Control-plane pcp_ keys count as configured even with no gateway slug.
|
|
92
184
|
*/
|
|
93
185
|
export function buildGatewayStatus(prefs: UserPrefsJson | null, env: Env): GatewayStatus {
|
|
94
|
-
const
|
|
186
|
+
const { creds, problem } = resolveGateway(prefs, env);
|
|
95
187
|
const cp = resolveControlPlane(prefs, env);
|
|
96
188
|
return {
|
|
97
|
-
configured: !!
|
|
189
|
+
configured: !!creds || !!cp,
|
|
98
190
|
source: gatewaySource(prefs, env),
|
|
99
|
-
|
|
100
|
-
|
|
191
|
+
// Echo what the user saved even when it does not resolve yet, so a
|
|
192
|
+
// pre-v1.1.0 user sees their slug and only has to add the account id.
|
|
193
|
+
gateway_id: creds?.gatewayId ?? (prefs?.gateway_id?.trim() || null),
|
|
194
|
+
cf_aig_token_set: !!(creds?.cfAigToken || prefs?.cf_aig_token?.trim()),
|
|
195
|
+
account_id: normalizeAccountId(prefs?.account_id),
|
|
196
|
+
account_id_required: problem === "gateway_account_id_required",
|
|
101
197
|
control_plane_configured: !!cp,
|
|
102
198
|
control_plane_key_set: !!prefs?.control_plane_key?.trim(),
|
|
103
199
|
};
|
package/template/src/index.ts
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
// blocks with base64 source.
|
|
19
19
|
|
|
20
20
|
import type { AiContext } from "../ai-binding";
|
|
21
|
-
import { aiRun, aiLogId } from "../ai-binding";
|
|
21
|
+
import { aiRun, aiLogId, gatewayProviderUrl } from "../ai-binding";
|
|
22
22
|
import type { ModelEntry } from "../models";
|
|
23
23
|
import type { ProviderStreamEvent } from "../parsers/types";
|
|
24
24
|
import { CF_AIG_TOKEN_REQUIRED_MSG } from "../gateway-credentials";
|
|
@@ -92,9 +92,9 @@ async function prepareAnthropicRequest(
|
|
|
92
92
|
): Promise<{ url: string; headers: Record<string, string>; body: string }> {
|
|
93
93
|
const { system, messages: aMessages } = transformToAnthropic(messages, systemPrompt);
|
|
94
94
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
95
|
+
// v1.1.0: built from the caller's own account when the credentials carry
|
|
96
|
+
// one; the binding's getUrl would always name this worker's account.
|
|
97
|
+
const baseUrl = await gatewayProviderUrl(ctx, "anthropic");
|
|
98
98
|
|
|
99
99
|
// Strip the "anthropic/" prefix we use in our internal IDs; Anthropic's API
|
|
100
100
|
// expects just the model name (e.g. "claude-opus-4-6").
|
|
@@ -13,8 +13,18 @@
|
|
|
13
13
|
// GPT image models ALWAYS return base64 (data[0].b64_json); the `url` response
|
|
14
14
|
// format is unsupported for them. `background: "transparent"` with
|
|
15
15
|
// `output_format: "png"` yields an RGBA PNG.
|
|
16
|
+
import type { Env } from "../env";
|
|
16
17
|
import { base64ToBytes } from "../utils";
|
|
17
18
|
|
|
19
|
+
// The deployer key to use for transparent PNG, or null for the opaque proxy.
|
|
20
|
+
// prism#193 (v1.0.5): AUTH_MODE=public ignores OPENAI_API_KEY entirely, the
|
|
21
|
+
// same fail-closed rule gateway-credentials.ts applies to GATEWAY_ID /
|
|
22
|
+
// CF_AIG_TOKEN, so a stray host secret cannot bill the host for a visitor.
|
|
23
|
+
export function resolveOpenAIImageKey(env: Env): string | null {
|
|
24
|
+
if (env.AUTH_MODE === "public") return null;
|
|
25
|
+
return env.OPENAI_API_KEY?.trim() || null;
|
|
26
|
+
}
|
|
27
|
+
|
|
18
28
|
export interface GeneratedImage {
|
|
19
29
|
bytes: Uint8Array;
|
|
20
30
|
mime: string;
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
// rather than the older max_tokens field.
|
|
21
21
|
|
|
22
22
|
import type { AiContext } from "../ai-binding";
|
|
23
|
-
import { aiRun, aiLogId } from "../ai-binding";
|
|
23
|
+
import { aiRun, aiLogId, gatewayProviderUrl } from "../ai-binding";
|
|
24
24
|
import type { ModelEntry } from "../models";
|
|
25
25
|
import type { ProviderStreamEvent } from "../parsers/types";
|
|
26
26
|
import { CF_AIG_TOKEN_REQUIRED_MSG } from "../gateway-credentials";
|
|
@@ -38,9 +38,9 @@ async function prepareXaiRequest(
|
|
|
38
38
|
messages: Array<unknown>,
|
|
39
39
|
opts: { stream: boolean },
|
|
40
40
|
): Promise<{ url: string; headers: Record<string, string>; body: string }> {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
41
|
+
// v1.1.0: built from the caller's own account when the credentials carry
|
|
42
|
+
// one; the binding's getUrl would always name this worker's account.
|
|
43
|
+
const baseUrl = await gatewayProviderUrl(ctx, "grok");
|
|
44
44
|
|
|
45
45
|
// Strip "xai/" prefix; xAI's API expects just the model name (e.g. "grok-4.3").
|
|
46
46
|
const modelName = model.id.replace(/^xai\//, "");
|
|
@@ -6,6 +6,20 @@
|
|
|
6
6
|
// pure function so it is unit-testable without D1; the DB layer only does the
|
|
7
7
|
// epoch conversion and the upsert.
|
|
8
8
|
|
|
9
|
+
// prism#192: how long a rate-limit bucket may survive its own window.
|
|
10
|
+
//
|
|
11
|
+
// Before this, rows were removed only by resetRateLimit on a SUCCESSFUL login,
|
|
12
|
+
// so a `signup:<ip>` bucket, or any `login:<ip>:<username>` bucket that never
|
|
13
|
+
// saw a success, lived in D1 forever. The hosted privacy notice heads that
|
|
14
|
+
// section "transient IP processing", and indefinite retention of failed-login
|
|
15
|
+
// IP-plus-username pairs is not transient.
|
|
16
|
+
//
|
|
17
|
+
// 24h is deliberately far beyond the longest live window (SIGNUP_WINDOW, 1h in
|
|
18
|
+
// src/auth.ts), so a prune can never discard a bucket a limiter decision still
|
|
19
|
+
// depends on: past its window rateLimitDecision already treats the row as a
|
|
20
|
+
// fresh start, making an aged row functionally dead weight.
|
|
21
|
+
export const AUTH_ATTEMPT_RETENTION_HOURS = 24;
|
|
22
|
+
|
|
9
23
|
export interface RateLimitDecision {
|
|
10
24
|
allowed: boolean;
|
|
11
25
|
nextCount: number;
|
|
@@ -65,6 +79,18 @@ export async function checkRateLimit(
|
|
|
65
79
|
.bind(bucketKey, decision.nextCount, decision.nextWindowStart)
|
|
66
80
|
.run();
|
|
67
81
|
|
|
82
|
+
// Retention as an executed deletion, not an intention -- the csp_reports
|
|
83
|
+
// pattern (src/routes/csp-report.ts). Prune-on-write needs no cron, no new
|
|
84
|
+
// trigger and no binding, and it cannot drift out of sync with the write path
|
|
85
|
+
// because it IS the write path. That matters here specifically: the shipped
|
|
86
|
+
// wrangler.example.toml has `crons = []` and there is no scheduled handler,
|
|
87
|
+
// so anything cron-shaped would be retention that never actually runs, and a
|
|
88
|
+
// self-host would silently inherit indefinite retention.
|
|
89
|
+
await db
|
|
90
|
+
.prepare(`DELETE FROM auth_attempts WHERE window_start < datetime('now', ?)`)
|
|
91
|
+
.bind(`-${AUTH_ATTEMPT_RETENTION_HOURS} hours`)
|
|
92
|
+
.run();
|
|
93
|
+
|
|
68
94
|
return decision.allowed;
|
|
69
95
|
}
|
|
70
96
|
|
|
@@ -17,7 +17,7 @@ import { callXai, callXaiStream } from "../providers/xai";
|
|
|
17
17
|
import { callWorkersAIStream } from "../providers/workers-ai";
|
|
18
18
|
import { callOpenAI, callOpenAIStream } from "../providers/openai";
|
|
19
19
|
import { callGemini, callGeminiStream } from "../providers/google";
|
|
20
|
-
import { generateOpenAIImage } from "../providers/openai-image";
|
|
20
|
+
import { generateOpenAIImage, resolveOpenAIImageKey } from "../providers/openai-image";
|
|
21
21
|
import { buildProxiedImageParams } from "../proxied-image-params";
|
|
22
22
|
import {
|
|
23
23
|
json,
|
|
@@ -43,9 +43,11 @@ import {
|
|
|
43
43
|
retrieveContext,
|
|
44
44
|
RETRIEVE_TOP_K,
|
|
45
45
|
searchWeb,
|
|
46
|
+
noWebSearch,
|
|
46
47
|
formatRetrievalForSystemPrompt,
|
|
47
48
|
formatWebForSystemPrompt,
|
|
48
49
|
looksBinary,
|
|
50
|
+
type WebSearchOutcome,
|
|
49
51
|
} from "./rag";
|
|
50
52
|
import { resolveProjectForChat } from "./projects";
|
|
51
53
|
import type { LongRunParams } from "./workflow";
|
|
@@ -237,10 +239,10 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
237
239
|
// v0.17.0: web search runs in parallel with RAG retrieval and the
|
|
238
240
|
// attachment walk. Per-source timeouts + catches inside searchWeb bound
|
|
239
241
|
// the worst-case latency to WEB_SEARCH_TIMEOUT_MS.
|
|
240
|
-
const webSearchPromise: Promise<
|
|
242
|
+
const webSearchPromise: Promise<WebSearchOutcome> =
|
|
241
243
|
body.use_web_search
|
|
242
244
|
? searchWeb(env, body.user_input)
|
|
243
|
-
: Promise.resolve(
|
|
245
|
+
: Promise.resolve(noWebSearch());
|
|
244
246
|
|
|
245
247
|
// Walk inputs: write images / video frames to R2, transcribe audio via
|
|
246
248
|
// Whisper. Build three parallel structures used after the loop:
|
|
@@ -360,7 +362,7 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
360
362
|
const { chunks: retrievedChunks, error: retrievalError } = await retrievePromise;
|
|
361
363
|
|
|
362
364
|
// v0.17.0: web-search retrieval, same parallelism pattern as RAG.
|
|
363
|
-
const { results: webResults, error: webSearchError } = await webSearchPromise;
|
|
365
|
+
const { results: webResults, error: webSearchError, sources: webSources } = await webSearchPromise;
|
|
364
366
|
const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
|
|
365
367
|
|
|
366
368
|
// Build the effective system prompt: user-supplied prompt, optional compact
|
|
@@ -522,6 +524,9 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
|
|
|
522
524
|
effective_system_prompt: (body.use_docs || body.use_web_search) ? effectiveSystemPrompt : undefined,
|
|
523
525
|
retrieval_error: body.use_docs ? retrievalError : undefined,
|
|
524
526
|
web_search_error: body.use_web_search ? webSearchError : undefined,
|
|
527
|
+
// Per-source status. "ok" with count 0 is zero hits. "failed" is a
|
|
528
|
+
// broken web source. "absent" means the SEARCH binding is not configured.
|
|
529
|
+
sources: body.use_web_search ? webSources : undefined,
|
|
525
530
|
});
|
|
526
531
|
}
|
|
527
532
|
|
|
@@ -566,14 +571,16 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
|
|
|
566
571
|
// sole OpenAI transparent-PNG carve-out: when OPENAI_API_KEY is set on
|
|
567
572
|
// openai/* image models, call api.openai.com directly (proxy rejects
|
|
568
573
|
// background/output_format). No other provider uses a deployer key.
|
|
574
|
+
// Public mode ignores the key (prism#193, v1.0.5): see resolveOpenAIImageKey.
|
|
569
575
|
//
|
|
570
576
|
// Unified Billing response shapes:
|
|
571
577
|
// URL: { state, result: { image: "https://..." } } or images[]
|
|
572
578
|
// inline: { state, result: { image: "<b64|data-uri>" } } // xAI Grok Imagine
|
|
573
579
|
// xAI requires response_format:b64_json (ZDR-managed credentials reject
|
|
574
580
|
// URL output). extractProxiedImageAsset normalizes both.
|
|
575
|
-
|
|
576
|
-
|
|
581
|
+
const openaiImageKey = model.provider === "openai" ? resolveOpenAIImageKey(env) : null;
|
|
582
|
+
if (openaiImageKey) {
|
|
583
|
+
const gen = await generateOpenAIImage(openaiImageKey, model.id, body.user_input);
|
|
577
584
|
bytes = gen.bytes;
|
|
578
585
|
mime = gen.mime;
|
|
579
586
|
logId = null; // direct OpenAI; no AI Gateway log
|
|
@@ -1272,10 +1279,10 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1272
1279
|
: Promise.resolve({ chunks: [], error: null });
|
|
1273
1280
|
|
|
1274
1281
|
// v0.17.0: web search runs in parallel with RAG retrieval, same as runChat.
|
|
1275
|
-
const webSearchPromise: Promise<
|
|
1282
|
+
const webSearchPromise: Promise<WebSearchOutcome> =
|
|
1276
1283
|
body.use_web_search
|
|
1277
1284
|
? searchWeb(env, body.user_input)
|
|
1278
|
-
: Promise.resolve(
|
|
1285
|
+
: Promise.resolve(noWebSearch());
|
|
1279
1286
|
|
|
1280
1287
|
// Attachment walk. Reach completion before any bytes flow back; streaming
|
|
1281
1288
|
// helps with time-to-last-token, not time-to-first-token on multimodal turns.
|
|
@@ -1372,7 +1379,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1372
1379
|
}
|
|
1373
1380
|
|
|
1374
1381
|
const { chunks: retrievedChunks } = await retrievePromise;
|
|
1375
|
-
const { results: webResults } = await webSearchPromise;
|
|
1382
|
+
const { results: webResults, error: webSearchError, sources: webSources } = await webSearchPromise;
|
|
1376
1383
|
const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
|
|
1377
1384
|
|
|
1378
1385
|
const userSystemPrompt = body.system_prompt?.trim() ?? "";
|
|
@@ -1495,6 +1502,8 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
|
|
|
1495
1502
|
tokens_out: usageOut,
|
|
1496
1503
|
conversation_id: conversationId,
|
|
1497
1504
|
turn_index: turnIndex,
|
|
1505
|
+
web_search_error: body.use_web_search ? webSearchError : undefined,
|
|
1506
|
+
sources: body.use_web_search ? webSources : undefined,
|
|
1498
1507
|
});
|
|
1499
1508
|
} catch (err) {
|
|
1500
1509
|
// Self-triggered AbortError (we aborted because client disconnected)
|