@skyphusion/create-prism 0.1.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.
Files changed (100) hide show
  1. package/LICENSE +235 -0
  2. package/NOTICE +3 -0
  3. package/README.md +114 -0
  4. package/index.js +195 -0
  5. package/package.json +44 -0
  6. package/template/CONTRIBUTING.md +80 -0
  7. package/template/LICENSE +235 -0
  8. package/template/MIGRATIONS.md +197 -0
  9. package/template/NOTICE +3 -0
  10. package/template/README.md +875 -0
  11. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
  12. package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
  13. package/template/docs/legal/README.md +11 -0
  14. package/template/docs/screenshot-desktop.jpg +0 -0
  15. package/template/docs/screenshot-mobile.jpg +0 -0
  16. package/template/gitignore +23 -0
  17. package/template/migrate-v0.164.0.sql +6 -0
  18. package/template/migrate-v0.167.0.sql +44 -0
  19. package/template/migrate-v0.20.0.sql +40 -0
  20. package/template/migrate-v0.20.2.sql +19 -0
  21. package/template/migrate-v0.20.3.sql +36 -0
  22. package/template/migrations/0001_init.sql +134 -0
  23. package/template/package.json +32 -0
  24. package/template/public/app.js +2778 -0
  25. package/template/public/apple-touch-icon.png +0 -0
  26. package/template/public/favicon-16.png +0 -0
  27. package/template/public/favicon-32.png +0 -0
  28. package/template/public/favicon.svg +5 -0
  29. package/template/public/icon-192.png +0 -0
  30. package/template/public/icon-512.png +0 -0
  31. package/template/public/index.html +329 -0
  32. package/template/public/manifest.webmanifest +14 -0
  33. package/template/public/streaming-client.js +207 -0
  34. package/template/public/stt.html +68 -0
  35. package/template/public/stt.js +16 -0
  36. package/template/public/styles.css +2068 -0
  37. package/template/public/voice-widget.js +195 -0
  38. package/template/schema.sql +283 -0
  39. package/template/src/ai-binding.ts +33 -0
  40. package/template/src/auth-kdf.ts +106 -0
  41. package/template/src/auth.ts +315 -0
  42. package/template/src/chunking.ts +161 -0
  43. package/template/src/discord.ts +353 -0
  44. package/template/src/env.ts +55 -0
  45. package/template/src/gateway-credentials.ts +97 -0
  46. package/template/src/health-schema.ts +25 -0
  47. package/template/src/index.ts +4180 -0
  48. package/template/src/longrun-params.ts +135 -0
  49. package/template/src/models.ts +214 -0
  50. package/template/src/output-extract.ts +128 -0
  51. package/template/src/parsers/anthropic-sse.ts +56 -0
  52. package/template/src/parsers/gemini-sse.ts +62 -0
  53. package/template/src/parsers/openai-sse.ts +60 -0
  54. package/template/src/parsers/sse-framer.ts +39 -0
  55. package/template/src/parsers/types.ts +16 -0
  56. package/template/src/parsers/workers-ai-sse.ts +43 -0
  57. package/template/src/parsers/xai-sse.ts +40 -0
  58. package/template/src/providers/anthropic.ts +208 -0
  59. package/template/src/providers/google.ts +150 -0
  60. package/template/src/providers/openai.ts +69 -0
  61. package/template/src/providers/workers-ai.ts +83 -0
  62. package/template/src/providers/xai.ts +159 -0
  63. package/template/src/proxied-image-params.ts +43 -0
  64. package/template/src/rate-limit.ts +77 -0
  65. package/template/src/searxng.ts +75 -0
  66. package/template/src/session.ts +114 -0
  67. package/template/src/stt-session.ts +206 -0
  68. package/template/src/stt-util.ts +19 -0
  69. package/template/src/types.ts +56 -0
  70. package/template/src/user-prefs.ts +63 -0
  71. package/template/src/utils.ts +73 -0
  72. package/template/src/zip.ts +137 -0
  73. package/template/tests/anthropic-sse.test.ts +149 -0
  74. package/template/tests/auth-kdf.test.ts +59 -0
  75. package/template/tests/auth-unit.test.ts +97 -0
  76. package/template/tests/chunking.test.ts +217 -0
  77. package/template/tests/discord.test.ts +184 -0
  78. package/template/tests/gateway-credentials.test.ts +65 -0
  79. package/template/tests/gemini-sse.test.ts +75 -0
  80. package/template/tests/google-gemini.test.ts +65 -0
  81. package/template/tests/health-schema.test.ts +35 -0
  82. package/template/tests/longrun-params.test.ts +128 -0
  83. package/template/tests/openai-sse.test.ts +71 -0
  84. package/template/tests/output-extract.test.ts +171 -0
  85. package/template/tests/proxied-image-params.test.ts +51 -0
  86. package/template/tests/rate-limit.test.ts +45 -0
  87. package/template/tests/searxng.test.ts +51 -0
  88. package/template/tests/sse-framer.test.ts +113 -0
  89. package/template/tests/stt-session.test.ts +35 -0
  90. package/template/tests/utils.test.ts +39 -0
  91. package/template/tests/workers-ai-sse.test.ts +67 -0
  92. package/template/tests/xai-sse.test.ts +60 -0
  93. package/template/tests/zip.test.ts +145 -0
  94. package/template/tests-integration/auth.test.ts +371 -0
  95. package/template/tests-integration/worker.test.ts +322 -0
  96. package/template/tsconfig.json +18 -0
  97. package/template/vitest.config.ts +18 -0
  98. package/template/vitest.node.config.ts +19 -0
  99. package/template/vitest.workers.config.ts +47 -0
  100. package/template/wrangler.example.toml +151 -0
@@ -0,0 +1,83 @@
1
+ // Workers AI chat dispatch (v0.19.3).
2
+ //
3
+ // Extracted from src/index.ts as the final stage of the v0.19.x provider
4
+ // dispatcher split. Owns the streaming chat path for all Workers AI chat
5
+ // models (Llama, Qwen, DeepSeek, Mistral, Gemma, GLM, Nemotron, Granite,
6
+ // Hermes, GPT-OSS, Kimi).
7
+ //
8
+ // Unlike the other three providers, Workers AI has no separate non-streaming
9
+ // "callWorkersAI" function: the non-streaming path calls aiRun directly with
10
+ // { messages } and unwraps the response inline in the dispatch. Only the
11
+ // streaming path needs its own dispatcher because it consumes a ReadableStream
12
+ // and parses SSE frames.
13
+
14
+ import type { AiContext } from "../ai-binding";
15
+ import type { ModelEntry } from "../models";
16
+ import type { ProviderStreamEvent } from "../parsers/types";
17
+ import { aiRun } from "../ai-binding";
18
+ import { extractSSEDataPayloads } from "../parsers/sse-framer";
19
+ import { interpretWorkersAISSEFrame } from "../parsers/workers-ai-sse";
20
+
21
+ // Async generator: drives a Workers AI chat model via env.AI.run with
22
+ // stream:true and yields normalized text + usage events.
23
+ //
24
+ // Workers AI streaming returns a ReadableStream from env.AI.run, already
25
+ // SSE-formatted. Event shape is OpenAI-compatible:
26
+ // data: {"response":"..."} // one per token chunk
27
+ // data: {"response":"","usage":{...}} // final usage chunk
28
+ // data: [DONE] // terminal sentinel
29
+ //
30
+ // Abort handling: env.AI.run doesn't accept an AbortSignal directly, so we
31
+ // bridge by listening for the signal on the consumer side and calling
32
+ // reader.cancel() to release the upstream stream when the client disconnects.
33
+
34
+ export async function* callWorkersAIStream(
35
+ ctx: AiContext,
36
+ model: ModelEntry,
37
+ messages: Array<unknown>,
38
+ signal: AbortSignal,
39
+ ): AsyncGenerator<ProviderStreamEvent> {
40
+ const result = await aiRun(ctx, model.id, { messages, stream: true });
41
+
42
+ if (!(result instanceof ReadableStream)) {
43
+ throw new Error(`Workers AI did not return a stream (got ${typeof result}). Ensure stream:true is honored by this model.`);
44
+ }
45
+
46
+ const reader = result.getReader();
47
+ const decoder = new TextDecoder();
48
+ let buffer = "";
49
+
50
+ // Bridge AbortSignal -> reader.cancel(). If the signal is already aborted
51
+ // by the time we get here, cancel immediately.
52
+ const onAbort = () => { try { reader.cancel(); } catch { /* fine */ } };
53
+ if (signal.aborted) {
54
+ onAbort();
55
+ } else {
56
+ signal.addEventListener("abort", onAbort, { once: true });
57
+ }
58
+
59
+ try {
60
+ while (true) {
61
+ const { done, value } = await reader.read();
62
+ if (done) break;
63
+
64
+ buffer += decoder.decode(value, { stream: true });
65
+
66
+ const { payloads, remainder } = extractSSEDataPayloads(buffer);
67
+ buffer = remainder;
68
+
69
+ for (const payload of payloads) {
70
+ let data: unknown;
71
+ try {
72
+ data = JSON.parse(payload);
73
+ } catch {
74
+ continue;
75
+ }
76
+ for (const event of interpretWorkersAISSEFrame(data)) yield event;
77
+ }
78
+ }
79
+ } finally {
80
+ signal.removeEventListener("abort", onAbort);
81
+ try { reader.releaseLock(); } catch { /* fine */ }
82
+ }
83
+ }
@@ -0,0 +1,159 @@
1
+ // xAI Unified Billing chat dispatch (v0.19.1; billing migration v0.164.0).
2
+ //
3
+ // Extracted from src/index.ts following the v0.19.0 pattern set by
4
+ // src/providers/anthropic.ts. Owns the request builder, non-streaming
5
+ // caller, and streaming caller for xAI Grok models through Cloudflare
6
+ // AI Gateway.
7
+ //
8
+ // xAI's API is OpenAI-compatible (same wire format), so no message transform
9
+ // is needed. Routed through AI Gateway's xAI provider endpoint for caching,
10
+ // logging, and rate-limiting.
11
+ //
12
+ // Auth strategy: Unified Billing (keyless). We hit the AI Gateway grok
13
+ // endpoint with cf-aig-authorization: Bearer <CF_AIG_TOKEN> and send NO
14
+ // provider key. Cloudflare uses its own upstream credentials and rolls the
15
+ // cost into the Cloudflare bill. An Authorization: Bearer <xai-key> would
16
+ // flip the gateway back to BYOK / pass-through billing, so we deliberately
17
+ // never set one. CF_AIG_TOKEN is therefore required for this provider.
18
+ //
19
+ // Note: Grok 4.x models are reasoning models that expect max_completion_tokens
20
+ // rather than the older max_tokens field.
21
+
22
+ import type { AiContext } from "../ai-binding";
23
+ import type { ModelEntry } from "../models";
24
+ import type { ProviderStreamEvent } from "../parsers/types";
25
+ import { CF_AIG_TOKEN_REQUIRED_MSG } from "../gateway-credentials";
26
+ import { extractSSEDataPayloads } from "../parsers/sse-framer";
27
+ import { interpretXaiSSEFrame } from "../parsers/xai-sse";
28
+
29
+ // Shared request builder for both callXai (non-streaming) and callXaiStream
30
+ // (SSE). All the URL/headers/body construction lives here; callers differ
31
+ // only in whether they pass `signal`, whether they read `cf-aig-log-id`,
32
+ // and how they consume the response body.
33
+
34
+ async function prepareXaiRequest(
35
+ ctx: AiContext,
36
+ model: ModelEntry,
37
+ messages: Array<unknown>,
38
+ opts: { stream: boolean },
39
+ ): Promise<{ url: string; headers: Record<string, string>; body: string }> {
40
+ const baseUrl = await (ctx.env.AI as unknown as {
41
+ gateway: (id: string) => { getUrl: (provider: string) => Promise<string> };
42
+ }).gateway(ctx.gateway.gatewayId).getUrl("grok");
43
+
44
+ // Strip "xai/" prefix; xAI's API expects just the model name (e.g. "grok-4.3").
45
+ const modelName = model.id.replace(/^xai\//, "");
46
+
47
+ const body: Record<string, unknown> = {
48
+ model: modelName,
49
+ messages,
50
+ max_completion_tokens: 4096,
51
+ };
52
+ if (opts.stream) {
53
+ body.stream = true;
54
+ // include_usage:true asks xAI to send token counts in the final pre-[DONE]
55
+ // chunk. Without this, usage stays null on streamed responses.
56
+ body.stream_options = { include_usage: true };
57
+ }
58
+
59
+ const headers: Record<string, string> = {
60
+ "content-type": "application/json",
61
+ };
62
+ if (!ctx.gateway.cfAigToken) {
63
+ throw new Error(CF_AIG_TOKEN_REQUIRED_MSG);
64
+ }
65
+ headers["cf-aig-authorization"] = `Bearer ${ctx.gateway.cfAigToken}`;
66
+
67
+ return {
68
+ url: `${baseUrl}/v1/chat/completions`,
69
+ headers,
70
+ body: JSON.stringify(body),
71
+ };
72
+ }
73
+
74
+ export async function callXai(
75
+ ctx: AiContext,
76
+ model: ModelEntry,
77
+ messages: Array<unknown>,
78
+ ): Promise<{ raw: unknown; logId: string | null }> {
79
+ const { url, headers, body } = await prepareXaiRequest(ctx, model, messages, { stream: false });
80
+
81
+ const resp = await fetch(url, { method: "POST", headers, body });
82
+
83
+ const logId = resp.headers.get("cf-aig-log-id");
84
+
85
+ if (!resp.ok) {
86
+ const errText = await resp.text();
87
+ throw new Error(`xAI API ${resp.status}: ${errText.slice(0, 500)}`);
88
+ }
89
+
90
+ const raw = await resp.json();
91
+ return { raw, logId };
92
+ }
93
+
94
+ // Async generator: drives an xAI Grok model via direct fetch with stream:true
95
+ // and yields normalized text + usage events.
96
+ //
97
+ // xAI uses standard OpenAI-compatible SSE:
98
+ // data: {"choices":[{"delta":{"content":"..."}}]} // per chunk
99
+ // data: {"choices":[],"usage":{...}} // final usage chunk
100
+ // data: [DONE] // terminal sentinel
101
+ //
102
+ // The usage chunk only fires when stream_options.include_usage:true is set
103
+ // on the request, which we do. The gateway proxies the SSE body through
104
+ // transparently.
105
+ //
106
+ // Abort handling: fetch() takes the AbortSignal directly. When the client
107
+ // disconnects, runChatStream aborts the controller and the upstream fetch
108
+ // is cancelled mid-stream, releasing the worker invocation immediately.
109
+
110
+ export async function* callXaiStream(
111
+ ctx: AiContext,
112
+ model: ModelEntry,
113
+ messages: Array<unknown>,
114
+ signal: AbortSignal,
115
+ ): AsyncGenerator<ProviderStreamEvent> {
116
+ const { url, headers, body } = await prepareXaiRequest(ctx, model, messages, { stream: true });
117
+
118
+ const resp = await fetch(url, {
119
+ method: "POST",
120
+ headers,
121
+ body,
122
+ signal,
123
+ });
124
+
125
+ if (!resp.ok) {
126
+ const errText = await resp.text();
127
+ throw new Error(`xAI API ${resp.status}: ${errText.slice(0, 500)}`);
128
+ }
129
+ if (!resp.body) {
130
+ throw new Error("xAI streaming: response body missing");
131
+ }
132
+
133
+ const reader = resp.body.getReader();
134
+ const decoder = new TextDecoder();
135
+ let buffer = "";
136
+
137
+ try {
138
+ while (true) {
139
+ const { done, value } = await reader.read();
140
+ if (done) break;
141
+ buffer += decoder.decode(value, { stream: true });
142
+
143
+ const { payloads, remainder } = extractSSEDataPayloads(buffer);
144
+ buffer = remainder;
145
+
146
+ for (const payload of payloads) {
147
+ let data: unknown;
148
+ try {
149
+ data = JSON.parse(payload);
150
+ } catch {
151
+ continue;
152
+ }
153
+ for (const event of interpretXaiSSEFrame(data)) yield event;
154
+ }
155
+ }
156
+ } finally {
157
+ try { reader.releaseLock(); } catch { /* fine */ }
158
+ }
159
+ }
@@ -0,0 +1,43 @@
1
+ // Per-provider request params for proxied (non-@cf) image models (v0.22.0).
2
+ //
3
+ // Every proxied image schema is additionalProperties:false (verified against
4
+ // the CF model pages), so each provider gets ONLY the keys it accepts; the @cf
5
+ // { width, height, steps, negative_prompt } shape is rejected by all of them.
6
+ //
7
+ // Lives in its own module (not inline in index.ts) for the same reason
8
+ // output-extract.ts does: index.ts imports cloudflare:workers and can't load
9
+ // under the plain-Node vitest pool, so an inline helper wouldn't be unit-
10
+ // testable. This takes the two primitives it needs rather than the ModelEntry/
11
+ // ChatRequest objects, keeping it free of any Workers-runtime import.
12
+ //
13
+ // google (nano-banana family): { prompt, output_format } -> PNG URL
14
+ // openai (gpt-image-1.5): opaque. The CF proxy schema is strictly
15
+ // { prompt, images, quality, size, style } and
16
+ // 7003-rejects background/output_format, so no
17
+ // alpha channel is reachable. (v0.166.0 retired
18
+ // the OPENAI_API_KEY BYOK transparent path.)
19
+ // recraft (recraftv4): opaque, art-directed. No alpha flag exists
20
+ // on the CF proxy schema (only an opaque
21
+ // background_color). Returns webp.
22
+ import type { Provider } from "./models";
23
+
24
+ export function buildProxiedImageParams(
25
+ provider: Provider | undefined,
26
+ prompt: string,
27
+ ): Record<string, unknown> {
28
+ switch (provider) {
29
+ case "google":
30
+ return { prompt, output_format: "png" };
31
+ case "openai":
32
+ // gpt-image-1.5 / gpt-image-2 via the CF proxy. The proxy's schema is
33
+ // strictly { prompt, images, quality, size, style } and 7003-rejects
34
+ // anything else, so background/output_format CANNOT be requested here.
35
+ // This path is therefore OPAQUE; v0.166.0 retired the OPENAI_API_KEY
36
+ // BYOK transparent-PNG path (prism#93), so this is the only image path.
37
+ return { prompt, quality: "high", size: "1024x1024" };
38
+ case "recraft":
39
+ return { prompt, size: "1024x1024", style: "digital_illustration" };
40
+ default:
41
+ return { prompt };
42
+ }
43
+ }
@@ -0,0 +1,77 @@
1
+ // Signup/login rate limiting (v0.167.0, issue #80).
2
+ //
3
+ // A D1 counter per bucket key (e.g. "login:<ip>:<username>" or "signup:<ip>"),
4
+ // windowed. Zero new binding, transactional with the auth store; Turnstile / WAF
5
+ // are documented follow-ons, not first-cut blockers. The window decision is a
6
+ // pure function so it is unit-testable without D1; the DB layer only does the
7
+ // epoch conversion and the upsert.
8
+
9
+ export interface RateLimitDecision {
10
+ allowed: boolean;
11
+ nextCount: number;
12
+ nextWindowStart: number; // epoch seconds
13
+ }
14
+
15
+ // Sliding fixed-window decision. A fresh window (no prior record, or the prior
16
+ // window has fully elapsed) resets the count to 1 and always allows. Within a
17
+ // live window the count increments and the attempt is allowed only while the
18
+ // post-increment count stays within the limit. Denied attempts still count, so
19
+ // sustained pressure keeps the bucket closed until the window rolls over.
20
+ export function rateLimitDecision(
21
+ nowSec: number,
22
+ windowStartSec: number | null,
23
+ count: number,
24
+ limit: number,
25
+ windowSeconds: number,
26
+ ): RateLimitDecision {
27
+ if (windowStartSec === null || nowSec - windowStartSec >= windowSeconds) {
28
+ return { allowed: true, nextCount: 1, nextWindowStart: nowSec };
29
+ }
30
+ const nextCount = count + 1;
31
+ return { allowed: nextCount <= limit, nextCount, nextWindowStart: windowStartSec };
32
+ }
33
+
34
+ // Record an attempt against a bucket and report whether it is allowed. Every
35
+ // call is one attempt; the caller should invoke this exactly once per
36
+ // signup/login try, before doing the expensive work.
37
+ export async function checkRateLimit(
38
+ db: D1Database,
39
+ bucketKey: string,
40
+ limit: number,
41
+ windowSeconds: number,
42
+ ): Promise<boolean> {
43
+ const row = await db
44
+ .prepare(
45
+ `SELECT count, CAST(strftime('%s', window_start) AS INTEGER) AS ws
46
+ FROM auth_attempts WHERE bucket_key = ?`,
47
+ )
48
+ .bind(bucketKey)
49
+ .first<{ count: number; ws: number }>();
50
+ const nowRow = await db
51
+ .prepare(`SELECT CAST(strftime('%s','now') AS INTEGER) AS now`)
52
+ .first<{ now: number }>();
53
+ const now = nowRow?.now ?? 0;
54
+
55
+ const decision = rateLimitDecision(now, row?.ws ?? null, row?.count ?? 0, limit, windowSeconds);
56
+
57
+ await db
58
+ .prepare(
59
+ `INSERT INTO auth_attempts (bucket_key, count, window_start)
60
+ VALUES (?, ?, datetime(?, 'unixepoch'))
61
+ ON CONFLICT(bucket_key) DO UPDATE SET
62
+ count = excluded.count,
63
+ window_start = excluded.window_start`,
64
+ )
65
+ .bind(bucketKey, decision.nextCount, decision.nextWindowStart)
66
+ .run();
67
+
68
+ return decision.allowed;
69
+ }
70
+
71
+ // Clear a bucket outright. Used to reset the login limiter on a SUCCESSFUL
72
+ // login so that successful sign-ins never count toward the failed-attempt cap
73
+ // (the check stays pre-verify to throttle the flood case; success just wipes
74
+ // the tally).
75
+ export async function resetRateLimit(db: D1Database, bucketKey: string): Promise<void> {
76
+ await db.prepare(`DELETE FROM auth_attempts WHERE bucket_key = ?`).bind(bucketKey).run();
77
+ }
@@ -0,0 +1,75 @@
1
+ // SearXNG web retrieval (v0.166.0).
2
+ //
3
+ // Self-hosted metasearch source, slotted in beside the keyless Wikipedia
4
+ // retriever (replacing the retired Tavily + Brave SaaS sources, prism#93).
5
+ // Requests the JSON API: GET {SEARXNG_URL}/search?q=...&format=json.
6
+ //
7
+ // When the instance is gated by Cloudflare Access (our deploy at
8
+ // search.skyphusion.org is), a per-function Access service token is sent as
9
+ // the standard CF-Access-Client-Id / CF-Access-Client-Secret headers. A
10
+ // self-hoster running an un-gated instance sets neither, and no Access headers
11
+ // are sent.
12
+
13
+ export interface SearxngHit {
14
+ title: string;
15
+ url: string;
16
+ snippet: string;
17
+ }
18
+
19
+ // Pure parser for the SearXNG JSON response. The relevant shape is
20
+ // { results: [ { url, title, content }, ... ] }; other top-level keys
21
+ // (query, number_of_results, suggestions, ...) are ignored. Rows missing a
22
+ // url or title are dropped; content is the snippet (may be absent).
23
+ export function mapSearxngResults(data: unknown, maxResults: number): SearxngHit[] {
24
+ const root = data as {
25
+ results?: Array<{ title?: string; url?: string; content?: string }>;
26
+ };
27
+ const items = root.results ?? [];
28
+ return items
29
+ .filter((r) => r.url && r.title)
30
+ .slice(0, maxResults)
31
+ .map((r) => ({
32
+ title: r.title!,
33
+ url: r.url!,
34
+ snippet: normalizeSearxngSnippet(r.content ?? ""),
35
+ }));
36
+ }
37
+
38
+ function normalizeSearxngSnippet(text: string): string {
39
+ return text.replace(/\s+/g, " ").trim();
40
+ }
41
+
42
+ export async function searchSearxngWeb(
43
+ baseUrl: string,
44
+ query: string,
45
+ opts: {
46
+ maxResults: number;
47
+ timeoutMs: number;
48
+ accessClientId?: string;
49
+ accessClientSecret?: string;
50
+ },
51
+ ): Promise<SearxngHit[]> {
52
+ // baseUrl may or may not carry a trailing slash; URL() with an absolute
53
+ // "/search" path normalizes either way.
54
+ const url = new URL("/search", baseUrl);
55
+ url.searchParams.set("q", query);
56
+ url.searchParams.set("format", "json");
57
+
58
+ const headers: Record<string, string> = { Accept: "application/json" };
59
+ // Access service-token headers are sent ONLY when both halves are set, so an
60
+ // un-gated self-hosted instance is reached with no headers.
61
+ if (opts.accessClientId && opts.accessClientSecret) {
62
+ headers["CF-Access-Client-Id"] = opts.accessClientId;
63
+ headers["CF-Access-Client-Secret"] = opts.accessClientSecret;
64
+ }
65
+
66
+ const resp = await fetch(url.toString(), {
67
+ headers,
68
+ signal: AbortSignal.timeout(opts.timeoutMs),
69
+ });
70
+ if (!resp.ok) {
71
+ throw new Error(`SearXNG ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
72
+ }
73
+ const data: unknown = await resp.json();
74
+ return mapSearxngResults(data, opts.maxResults);
75
+ }
@@ -0,0 +1,114 @@
1
+ // Session tokens and cookies for first-party auth (v0.167.0, issue #80).
2
+ //
3
+ // The session is an opaque 256-bit random token delivered as an httpOnly
4
+ // cookie. D1 stores only the SHA-256 hash of the token, never the raw value,
5
+ // so a leaked sessions table cannot be replayed as live cookies (same
6
+ // discipline as password hashing). This gives instant server-side revocation
7
+ // (logout and account-delete drop the row) with no JWT signing-key custody and
8
+ // no new runtime dependency.
9
+ //
10
+ // Cookie: __Host-prism_session. The __Host- prefix requires Secure + Path=/
11
+ // and forbids Domain, pinning the cookie to the exact host (no subdomain
12
+ // leak). SameSite=Lax lets the same-origin app and the same-origin STT
13
+ // WebSocket upgrade carry it while blocking cross-site POSTs (first-cut CSRF
14
+ // cover for a same-origin app).
15
+
16
+
17
+ export const SESSION_COOKIE = "__Host-prism_session";
18
+ const TOKEN_BYTES = 32;
19
+ export const SESSION_TTL_SECONDS = 60 * 60 * 24 * 30; // 30 days
20
+
21
+ // base64url without padding, cookie-safe.
22
+ function toB64Url(bytes: Uint8Array): string {
23
+ let bin = "";
24
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
25
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
26
+ }
27
+
28
+ export function generateSessionToken(): string {
29
+ return toB64Url(crypto.getRandomValues(new Uint8Array(TOKEN_BYTES)));
30
+ }
31
+
32
+ // SHA-256 of the token, lowercase hex. This is the sessions primary key; the
33
+ // raw token exists only in the cookie.
34
+ export async function hashToken(token: string): Promise<string> {
35
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
36
+ const bytes = new Uint8Array(digest);
37
+ let hex = "";
38
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
39
+ return hex;
40
+ }
41
+
42
+ // Read our session token out of the request Cookie header. Returns null when
43
+ // absent. Tolerant of surrounding cookies and whitespace.
44
+ export function parseSessionCookie(request: Request): string | null {
45
+ const header = request.headers.get("cookie");
46
+ if (!header) return null;
47
+ for (const part of header.split(";")) {
48
+ const eq = part.indexOf("=");
49
+ if (eq === -1) continue;
50
+ const name = part.slice(0, eq).trim();
51
+ if (name === SESSION_COOKIE) return part.slice(eq + 1).trim() || null;
52
+ }
53
+ return null;
54
+ }
55
+
56
+ export function buildSessionCookie(token: string, maxAgeSeconds: number = SESSION_TTL_SECONDS): string {
57
+ return `${SESSION_COOKIE}=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAgeSeconds}`;
58
+ }
59
+
60
+ // Expire the cookie immediately (logout, account delete). Same attributes as
61
+ // the set cookie so the browser matches and clears it.
62
+ export function clearSessionCookie(): string {
63
+ return `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
64
+ }
65
+
66
+ // Mint a session for a user and return the raw token (to put in the cookie).
67
+ // Only the hash is persisted.
68
+ export async function createSession(
69
+ db: D1Database,
70
+ userId: string,
71
+ ttlSeconds: number = SESSION_TTL_SECONDS,
72
+ ): Promise<string> {
73
+ const token = generateSessionToken();
74
+ const tokenHash = await hashToken(token);
75
+ await db
76
+ .prepare(
77
+ `INSERT INTO sessions (token_hash, user_id, expires_at)
78
+ VALUES (?, ?, datetime('now', ?))`,
79
+ )
80
+ .bind(tokenHash, userId, `+${ttlSeconds} seconds`)
81
+ .run();
82
+ return token;
83
+ }
84
+
85
+ // Resolve a raw token to its user id, or null if unknown or expired. Expired
86
+ // rows are opportunistically deleted so the table self-prunes on access.
87
+ export async function lookupSession(db: D1Database, token: string): Promise<string | null> {
88
+ const tokenHash = await hashToken(token);
89
+ const row = await db
90
+ .prepare(
91
+ `SELECT user_id, expires_at FROM sessions WHERE token_hash = ?`,
92
+ )
93
+ .bind(tokenHash)
94
+ .first<{ user_id: string; expires_at: string }>();
95
+ if (!row) return null;
96
+ const expired = await db
97
+ .prepare(`SELECT (expires_at <= datetime('now')) AS expired FROM sessions WHERE token_hash = ?`)
98
+ .bind(tokenHash)
99
+ .first<{ expired: number }>();
100
+ if (expired?.expired) {
101
+ await db.prepare(`DELETE FROM sessions WHERE token_hash = ?`).bind(tokenHash).run();
102
+ return null;
103
+ }
104
+ return row.user_id;
105
+ }
106
+
107
+ export async function deleteSession(db: D1Database, token: string): Promise<void> {
108
+ const tokenHash = await hashToken(token);
109
+ await db.prepare(`DELETE FROM sessions WHERE token_hash = ?`).bind(tokenHash).run();
110
+ }
111
+
112
+ export async function deleteAllUserSessions(db: D1Database, userId: string): Promise<void> {
113
+ await db.prepare(`DELETE FROM sessions WHERE user_id = ?`).bind(userId).run();
114
+ }