Spaces:
Running
Running
Sync from felladrin/MiniSearch@757fca5 (part 2)
Browse filesFiles changed (38)
- package-lock.json+51-51
- server/biEncoderService.test.tsAdded+125
- server/biEncoderService.ts+34-5
- server/cacheServerHook.test.tsAdded+65
- server/cacheServerHook.ts+20-1
- server/configEndpointServerHook.test.tsAdded+48
- server/configEndpointServerHook.ts+3-1
- server/dynamicCacheHeaders.test.tsAdded+152
- server/fallbackSearchService.test.ts+108-1
- server/fallbackSearchService.ts+93-11
- server/internalApiEndpointServerHook.test.ts+55-3
- server/internalApiEndpointServerHook.ts+14-7
- server/outboundUserAgent.tsAdded+11
- server/pageContentEndpointServerHook.test.ts+28
- server/pageContentEndpointServerHook.ts+9-2
- server/pageContentService.test.ts+63
- server/pageContentService.ts+20-7
- server/parseCommaSeparatedList.test.tsAdded+26
- server/parseCommaSeparatedList.tsAdded+11
- server/searchEndpointServerHook.test.ts+22
- server/searchEndpointServerHook.ts+9-5
- server/statusEndpointServerHook.test.ts+81-1
- server/statusEndpointServerHook.ts+12-1
- server/thumbnailEndpointServerHook.test.ts+112-3
- server/thumbnailEndpointServerHook.ts+37-38
- server/utils/pinnedFetch.test.ts+7-1
- server/utils/pinnedFetch.ts+5-2
- server/utils/publicUrl.ts+34
- server/utils/requestUrl.test.tsAdded+51
- server/utils/requestUrl.tsAdded+39
- server/utils/streamUtils.test.tsAdded+111
- server/utils/streamUtils.ts+20-17
- server/validateAccessKeyServerHook.test.ts+52
- server/validateAccessKeyServerHook.ts+4-1
- server/viteConfigAllowedHosts.test.tsAdded+34
- shared/relativeDates.test.ts+264
- shared/relativeDates.ts+165-51
- vite.config.ts+4-4
95 unmodified lines96979899100101991001011021031041051051061071084 unmodified lines1131141151161171181161171181191201211221221231241253 unmodified lines12913013113213313413213313413513613721 unmodified lines159160161162163164162163164165166167476 unmodified lines6446456466476486496476486496506516526536526536546556561 unmodified line6586596606616626636616626636646656666676686696706716706716726736746756766776786796776786796806816823 unmodified lines6866876886896896906916926936946956966976956966976986997005 unmodified lines7067077087097107117097107117127137147157167177187197207187197207217227237237247257267277287277287297307317327337347357367347357367377387392099 unmodified lines28392840284128422843284428422843284428452846284728472848284928492850285128521654 unmodified lines45074508450945104511451245104511451245134514451595 unmodified lines "license": "MIT" }, "node_modules/@ai-sdk/gateway": { "version": "4.0.150", "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.150.tgz", "integrity": "sha512-39jDj4UIN2M5kI/wW0IVMsD1PpjmZHSMFUU/yZSQerE4mg0Oo9AKPOSwn6Vu0MJ31aK+Mi9rUiUgl88Q2lkorg==", "version": "4.0.152", "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.152.tgz", "integrity": "sha512-8LYMe0uMPbT3XW/Urhca52TSgHXAlQok74EUkWL3qXWJI7naTxJGSF6B7hvIHur+V6ttSyLLZN0rJk+Qu9psqA==", "license": "Apache-2.0", "dependencies": { "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.82", "@ai-sdk/provider-utils": "5.0.83", "@vercel/oidc": "3.2.0" }, "engines": {4 unmodified lines } }, "node_modules/@ai-sdk/openai-compatible": { "version": "3.0.93", "resolved": "https://registry.npmjs.org/@ai-sdk/openai-compatible/-/openai-compatible-3.0.93.tgz", "integrity": "sha512-6/eIx/Y0/4xt6ncUovieFp5HFa0+LW1hy8TcgJQonBJ+5qZpdK5zqdBZ6RRoQ8cSSpuQC6X5kYhzDKrom9Q7+g==", "version": "3.0.94", "resolved": "https://registry.npmjs.org/@ai-sdk/openai-compatible/-/openai-compatible-3.0.94.tgz", "integrity": "sha512-UY2AE3/QT110AMpiBoBOBXlUJJG8NAL61y8yID6X8dPe9RjRy9QPfW9XdrifEnTOEM5MdEJP+A4Mf+NTJ93g4A==", "license": "Apache-2.0", "dependencies": { "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.82" "@ai-sdk/provider-utils": "5.0.83" }, "engines": { "node": ">=22"3 unmodified lines } }, "node_modules/@ai-sdk/openai-compatible/node_modules/@ai-sdk/provider-utils": { "version": "5.0.82", "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.82.tgz", "integrity": "sha512-9s3Le9LsTR0exy14H8SERw4uMgFhiP0yJVoLefzfQCnnptj71noYh1AoVEsjfJjmMH1y16+1OqBVTDpTpU6M3Q==", "version": "5.0.83", "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.83.tgz", "integrity": "sha512-5lInsmNnh64eKi2L3fQjPy5VnV2y69lwyGnZ3vfz82Tlkgy8pWsvYueUrSJGxi8gXOM67jB9tN7LtDjjEFsNLQ==", "license": "Apache-2.0", "dependencies": { "@ai-sdk/provider": "4.0.39",21 unmodified lines } }, "node_modules/@ai-sdk/provider-utils": { "version": "5.0.82", "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.82.tgz", "integrity": "sha512-9s3Le9LsTR0exy14H8SERw4uMgFhiP0yJVoLefzfQCnnptj71noYh1AoVEsjfJjmMH1y16+1OqBVTDpTpU6M3Q==", "version": "5.0.83", "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.83.tgz", "integrity": "sha512-5lInsmNnh64eKi2L3fQjPy5VnV2y69lwyGnZ3vfz82Tlkgy8pWsvYueUrSJGxi8gXOM67jB9tN7LtDjjEFsNLQ==", "license": "Apache-2.0", "dependencies": { "@ai-sdk/provider": "4.0.39",476 unmodified lines "license": "MIT" }, "node_modules/@mantine/carousel": { "version": "9.8.1", "resolved": "https://registry.npmjs.org/@mantine/carousel/-/carousel-9.8.1.tgz", "integrity": "sha512-gxwoxpgioxEdfauCCZKB81aMkS/Cp8PV4vn+4+QZqp8wQ2Xze86r2Pe9WCxhEsVoozN+S5Zxbt4PzugCeZUFSA==", "version": "9.8.2", "resolved": "https://registry.npmjs.org/@mantine/carousel/-/carousel-9.8.2.tgz", "integrity": "sha512-bN5e+mwxYquyMEfU7CP/tnhpP7mls0wmMYIroaFJOZpQyWiGRfezSqGkGqPV0cDnwn+9yn4rG77obU6yAHW32g==", "license": "MIT", "peerDependencies": { "@mantine/core": "9.8.1", "@mantine/hooks": "9.8.1", "@mantine/core": "9.8.2", "@mantine/hooks": "9.8.2", "embla-carousel": ">=8.0.0", "embla-carousel-react": ">=8.0.0", "react": "^19.2.0",1 unmodified line } }, "node_modules/@mantine/code-highlight": { "version": "9.8.1", "resolved": "https://registry.npmjs.org/@mantine/code-highlight/-/code-highlight-9.8.1.tgz", "integrity": "sha512-1khAA57Py/XLiJylaNGDxJConbeITZTz7YnvSsbz6NASdbTYylH6a290IMOdV6H4vfyMbweWS5g/v50O2XdPFw==", "version": "9.8.2", "resolved": "https://registry.npmjs.org/@mantine/code-highlight/-/code-highlight-9.8.2.tgz", "integrity": "sha512-L+69TylIuDw5T45DQWTnC/JbOckpyl5JFtdPjSVTrgTS3LLCAsQk+BVF2fZXhKG2/YrxlV7LYvTR1gJXrNpowA==", "license": "MIT", "dependencies": { "clsx": "^2.1.1", "diff": "^9.0.0" }, "peerDependencies": { "@mantine/core": "9.8.1", "@mantine/hooks": "9.8.1", "@mantine/core": "9.8.2", "@mantine/hooks": "9.8.2", "react": "^19.2.0", "react-dom": "^19.2.0" } }, "node_modules/@mantine/core": { "version": "9.8.1", "resolved": "https://registry.npmjs.org/@mantine/core/-/core-9.8.1.tgz", "integrity": "sha512-+ayBTxun7MslJL6x4qaylVy6TyHu3o68+PH22gt70eJSHgy0CHYR/c2q+BYxS8WvORuc4f5mr0xFbi0vzlgHug==", "version": "9.8.2", "resolved": "https://registry.npmjs.org/@mantine/core/-/core-9.8.2.tgz", "integrity": "sha512-PEBlIr5A80Indc8mIp+JcMzmmtv2YioubzXsLossk4cDhgm3YX2DBFQi/hQknmOaU6wt9h8l4T8s4gh6WPM21Q==", "license": "MIT", "dependencies": { "@floating-ui/react": "^0.27.20",3 unmodified lines "type-fest": "^5.10.0" }, "peerDependencies": { "@mantine/hooks": "9.8.1", "@mantine/hooks": "9.8.2", "react": "^19.2.0", "react-dom": "^19.2.0" } }, "node_modules/@mantine/form": { "version": "9.8.1", "resolved": "https://registry.npmjs.org/@mantine/form/-/form-9.8.1.tgz", "integrity": "sha512-BLD6BlsccoM31ZfKMiFWb53A1QW9vR0mKlR2GaDcjJGaQhxfGm5rLZCdBHBnsBXlNdz1Pyf52rQUfNhi6fXePQ==", "version": "9.8.2", "resolved": "https://registry.npmjs.org/@mantine/form/-/form-9.8.2.tgz", "integrity": "sha512-+wMxQ5NwSUt/WTc5dNI1J/c9WIF3jGRv8yu9SpzVFscmFGMAXhoquaHIOGM4gnF8JpM4bMQ5KukH45T+o9o6mA==", "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.1.0",5 unmodified lines } }, "node_modules/@mantine/hooks": { "version": "9.8.1", "resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.8.1.tgz", "integrity": "sha512-aAbY3zcqrS/n+wbMnKBXMiF5TJ7HZ06sH455Cf4ZkWRXko9Td2FYSe9aONCzXFaW62XqaWHBICyeIsAmUds3uA==", "version": "9.8.2", "resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.8.2.tgz", "integrity": "sha512-BZa+6fLEvAxaos2qInPZfNzq0k1WSIIkHA3CdD4quozJhmp7Kt1KE05YAkVPNrPisCx3c5YgmkRqtu9NcRegCw==", "license": "MIT", "peerDependencies": { "react": "^19.2.0" } }, "node_modules/@mantine/notifications": { "version": "9.8.1", "resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.8.1.tgz", "integrity": "sha512-lqi9+HfXMbMKzEsAIUkWRFw2rURzgVMv8//oCyq0rhy27X6NjSMMlzvwsjbSazT/+WugDIYLJ8khZ+JMW1gkMQ==", "version": "9.8.2", "resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.8.2.tgz", "integrity": "sha512-kKhT1jEl6sadOvB7efMJZuWfSRiyCDrAzWw0u4oaCKfOlAgrSo8wooIQ9gIgWct6jejdzIUK8ovBOVeLLx/dnA==", "license": "MIT", "dependencies": { "@mantine/store": "9.8.1", "@mantine/store": "9.8.2", "react-transition-group": "4.4.5" }, "peerDependencies": { "@mantine/core": "9.8.1", "@mantine/hooks": "9.8.1", "@mantine/core": "9.8.2", "@mantine/hooks": "9.8.2", "react": "^19.2.0", "react-dom": "^19.2.0" } }, "node_modules/@mantine/store": { "version": "9.8.1", "resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.8.1.tgz", "integrity": "sha512-Wb5+6i6m3GdNgOjX1IbDPYrP76v9y4zThRoKDWH9Es+qY2c6gT2NpH7n10/zYgNPL8ipB6H6gGUPhLurs1o4kg==", "version": "9.8.2", "resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.8.2.tgz", "integrity": "sha512-22kVzhs231cpcXdsKcQlRrmpzkbEMdJ7C+YKOVUBk5sUiP6bSAu4XY4Avj23Yjxy949G7Y4X4eAVSzjPgSUURA==", "license": "MIT", "peerDependencies": { "react": "^19.2.0"2099 unmodified lines } }, "node_modules/ai": { "version": "7.0.177", "resolved": "https://registry.npmjs.org/ai/-/ai-7.0.177.tgz", "integrity": "sha512-DQNKH2lL4h+5Rxe34AxTdxXtNu3EnsDHpxIE6p4ETsi+r7sM187nP6JKrbASoSNEbR355H3FCGlSP7mj+m6Pzw==", "version": "7.0.179", "resolved": "https://registry.npmjs.org/ai/-/ai-7.0.179.tgz", "integrity": "sha512-WT2ad3qEQPLne/5RDE/utNMSKYUuNpnGkI46AO/6Lv+IbEJ3kRwbatLX3HNfk25Y7N8LpdqOcSnMLcdw11VyIQ==", "license": "Apache-2.0", "dependencies": { "@ai-sdk/gateway": "4.0.150", "@ai-sdk/gateway": "4.0.152", "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.82" "@ai-sdk/provider-utils": "5.0.83" }, "engines": { "node": ">=22"1654 unmodified lines } }, "node_modules/knip": { "version": "6.46.1", "resolved": "https://registry.npmjs.org/knip/-/knip-6.46.1.tgz", "integrity": "sha512-5/ajqjZfmuv8O74+McrKBOSArKG6tsUgy6yJird36VZh9HiUq75qY4U39uqf9wjchEUOLrStuOZpFP057CZFRw==", "version": "6.47.0", "resolved": "https://registry.npmjs.org/knip/-/knip-6.47.0.tgz", "integrity": "sha512-nYmQnk0YqDXIJrYViJz88c8xw3tBDkpuAmofo58EkVPnKr6DnRKYtf6oIqcGVHZvXDE+gtmFuYx277/QsWng+A==", "dev": true, "funding": [ {123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SCORE_TIMEOUT_MS, scorePassages, startBiEncoderService, stopBiEncoderService,} from "./biEncoderService";import type { BiEncoderRequest } from "./biEncoderWorkerProtocol";
const { FakeWorker } = await vi.hoisted(async () => { const { EventEmitter } = await import("node:events");
/** * Stands in for the worker thread: it reports nothing on its own, so each * test decides whether a request gets a reply, a late reply or none at all. */ class FakeWorker extends EventEmitter { static latest: FakeWorker; readonly requests: BiEncoderRequest[] = [];
constructor() { super(); FakeWorker.latest = this; }
postMessage(request: BiEncoderRequest) { this.requests.push(request); }
async terminate() { return 0; }
reply(id: number, scores: number[]) { this.emit("message", { type: "scores", id, scores }); } }
return { FakeWorker };});
vi.mock("node:worker_threads", () => ({ Worker: FakeWorker }));
async function startWithFakeWorker() { const started = startBiEncoderService(); FakeWorker.latest.emit("message", { type: "ready" }); await started; return FakeWorker.latest;}
/** Settles a promise without awaiting it, so a test can see it is pending. */function track<T>(promise: Promise<T>) { const state: { settled: boolean; value?: T } = { settled: false }; promise.then((value) => { state.settled = true; state.value = value; }); return state;}
describe("scorePassages", () => { beforeEach(() => { vi.useFakeTimers(); });
afterEach(async () => { await stopBiEncoderService(); vi.useRealTimers(); });
it("answers empty scores when a ready worker never replies", async () => { await startWithFakeWorker();
const result = track(scorePassages("query", ["a", "b"])); await vi.advanceTimersByTimeAsync(SCORE_TIMEOUT_MS - 1); expect(result.settled).toBe(false);
await vi.advanceTimersByTimeAsync(1); expect(result).toEqual({ settled: true, value: [] }); expect(vi.getTimerCount()).toBe(0); });
it("resolves with the reply's scores and clears its timer", async () => { const fakeWorker = await startWithFakeWorker();
const scores = scorePassages("query", ["a", "b"]); fakeWorker.reply(fakeWorker.requests[0].id, [0.25, 0.75]);
await expect(scores).resolves.toEqual([0.25, 0.75]); expect(vi.getTimerCount()).toBe(0); });
it("ignores a reply after the timeout and still serves the next request", async () => { const fakeWorker = await startWithFakeWorker();
const timedOut = scorePassages("query", ["a"]); await vi.advanceTimersByTimeAsync(SCORE_TIMEOUT_MS); await expect(timedOut).resolves.toEqual([]); fakeWorker.reply(fakeWorker.requests[0].id, [0.5]);
const next = scorePassages("query", ["b"]); fakeWorker.reply(fakeWorker.requests[1].id, [0.9]); await expect(next).resolves.toEqual([0.9]); });
it("answers empty scores and clears timers when the service stops", async () => { await startWithFakeWorker();
const scores = scorePassages("query", ["a"]); await stopBiEncoderService();
await expect(scores).resolves.toEqual([]); expect(vi.getTimerCount()).toBe(0); });
it("answers empty scores and clears timers when the worker exits", async () => { const fakeWorker = await startWithFakeWorker();
const scores = scorePassages("query", ["a"]); fakeWorker.emit("exit", 1);
await expect(scores).resolves.toEqual([]); expect(vi.getTimerCount()).toBe(0); });});21 unmodified lines222324252627282930313233343536373825394041422 unmodified lines454647344849505152535420 unmodified lines7576776162787980818283848571 unmodified lines1571581591601611621631641651661671681411691701711721 unmodified line17417517617717817918021 unmodified lineslet isReady = false;let nextRequestId = 0;
/** * How long a scoring request may wait for the worker before it is answered * with empty scores, so a worker that is alive but stuck degrades ranking to * lexical instead of holding every page-content read. Sized from the budget * the client already enforces: its 20 s `/page-content` abort, minus the 6 s * page-read deadline, minus margin for the rest of the request. */export const SCORE_TIMEOUT_MS = 10_000;
interface PendingScore { resolve: (scores: number[]) => void; timer: ReturnType<typeof setTimeout>;}
const pendingScores = new Map<number, (scores: number[]) => void>();const pendingScores = new Map<number, PendingScore>();
/** * Answers every in-flight request with empty scores. Empty is the signal2 unmodified lines * page-content reads waiting for a reply that is never coming. */function resolvePendingEmpty() { for (const resolve of pendingScores.values()) resolve([]); for (const { resolve, timer } of pendingScores.values()) { clearTimeout(timer); resolve([]); } pendingScores.clear();}
20 unmodified lines biEncoderWorker.on("message", (message: BiEncoderResponse) => { if (message.type === "ready") return;
const resolve = pendingScores.get(message.id); if (!resolve) return; const pending = pendingScores.get(message.id); if (!pending) return; pendingScores.delete(message.id); clearTimeout(pending.timer); const { resolve } = pending;
if (message.type === "failed") { printMessage(`Bi-encoder scoring failed: ${message.message}`);71 unmodified lines const id = nextRequestId++;
return new Promise<number[]>((resolve) => { // A late reply after the timeout finds no entry and is ignored. const timer = setTimeout(() => { pendingScores.delete(id); printMessage( `Bi-encoder scoring did not answer within ${SCORE_TIMEOUT_MS} ms; falling back to lexical ranking.`, ); resolve([]); }, SCORE_TIMEOUT_MS); timer.unref(); pendingScores.set(id, resolve); pendingScores.set(id, { resolve, timer });
const request: BiEncoderRequest = { type: "score", id, query, passages }; try {1 unmodified line } catch (error) { // The worker was terminated between the check above and this send. pendingScores.delete(id); clearTimeout(timer); printMessage( `Could not reach the bi-encoder worker: ${error instanceof Error ? error.message : String(error)}`, );1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { cacheServerHook } from "./cacheServerHook";
let root: string;
beforeAll(() => { root = mkdtempSync(path.join(tmpdir(), "cache-hook-")); mkdirSync(path.join(root, "dist", "assets"), { recursive: true }); writeFileSync(path.join(root, "dist", "assets", "index-abc123.js"), ""); writeFileSync(path.join(root, "dist", "secret.txt"), "");});
afterAll(() => { rmSync(root, { recursive: true, force: true });});
async function cacheControlFor(url: string) { const use = vi.fn(); cacheServerHook({ middlewares: { use }, config: { root, build: { outDir: "dist" } }, } as never); const handler = use.mock.calls[0][0] as ( req: { url: string }, res: { setHeader: (name: string, value: string) => void }, next: () => void, ) => Promise<void>; const setHeader = vi.fn(); const next = vi.fn(); await handler({ url }, { setHeader }, next); expect(next).toHaveBeenCalled(); return setHeader.mock.calls[0][1] as string;}
describe("cacheServerHook", () => { it("marks an existing hashed asset immutable", async () => { expect(await cacheControlFor("/assets/index-abc123.js")).toBe( "public, max-age=31536000, immutable", ); expect(await cacheControlFor("/assets/index-abc123.js?v=1")).toBe( "public, max-age=31536000, immutable", ); });
it("does not mark a missing asset immutable", async () => { expect(await cacheControlFor("/assets/index-OLD.js")).toBe("no-cache"); expect(await cacheControlFor("/assets/")).toBe("no-cache"); });
it("does not look outside the assets folder", async () => { expect(await cacheControlFor("/assets/..%2fsecret.txt")).toBe("no-cache"); expect(await cacheControlFor("/assets/%E0%A4%A.js")).toBe("no-cache"); });
it("keeps HTML on no-cache and other files on a one-day cache", async () => { expect(await cacheControlFor("/")).toBe("no-cache"); expect(await cacheControlFor("/index.html")).toBe("no-cache"); expect(await cacheControlFor("/favicon.png")).toBe( "public, max-age=86400, must-revalidate", ); });});12345678910111213141015161718192021227 unmodified lines30313233343536373839404142import { stat } from "node:fs/promises";import path from "node:path";import type { PreviewServer, ViteDevServer } from "vite";
/** Cache-Control per asset class: immutable for hashed assets, no-cache for HTML. */export function cacheServerHook<T extends ViteDevServer | PreviewServer>( server: T,) { const outDir = path.resolve(server.config.root, server.config.build.outDir); const assetsDir = path.join(outDir, "assets");
server.middlewares.use(async (request, response, next) => { let cacheControlValue = "public, max-age=86400, must-revalidate"; if (request.url?.startsWith("/assets/")) { cacheControlValue = "public, max-age=31536000, immutable"; // A missing asset falls through to the SPA fallback or a 404, and caching // that body for a year would poison the URL once the real file is deployed. cacheControlValue = (await isFileIn(assetsDir, outDir, request.url)) ? "public, max-age=31536000, immutable" : "no-cache"; } else if ( request.url === "/" || request.url?.startsWith("/?") ||7 unmodified lines next(); });}
async function isFileIn(dir: string, outDir: string, url: string) { try { const { pathname } = new URL(url, "http://localhost"); const file = path.join(outDir, decodeURIComponent(pathname)); return file.startsWith(dir + path.sep) && (await stat(file)).isFile(); } catch { return false; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("./searchToken", () => ({ getSearchToken: () => "test-search-token",}));
afterEach(() => { vi.unstubAllEnvs();});
async function requestConfig() { const { configEndpointServerHook } = await import( "./configEndpointServerHook" ); const use = vi.fn(); configEndpointServerHook({ middlewares: { use } } as never); const handler = use.mock.calls[0][0] as ( req: { url: string; method: string }, res: { setHeader: unknown; end: (body: string) => void }, next: () => void, ) => void; const end = vi.fn(); handler( { url: "/api/config", method: "GET" }, { setHeader: vi.fn(), end }, vi.fn(), ); return JSON.parse(end.mock.calls[0][0] as string) as { accessKeysEnabled: boolean; };}
describe("configEndpointServerHook", () => { it("reports access keys as enabled when a key is configured", async () => { vi.stubEnv("ACCESS_KEYS", "key1, key2"); expect((await requestConfig()).accessKeysEnabled).toBe(true); });
it("reports access keys as disabled when none are configured", async () => { vi.stubEnv("ACCESS_KEYS", ""); expect((await requestConfig()).accessKeysEnabled).toBe(false); });
it("reports access keys as disabled when the list holds no usable key", async () => { vi.stubEnv("ACCESS_KEYS", " , ,"); expect((await requestConfig()).accessKeysEnabled).toBe(false); });});5 unmodified lines67891011129 unmodified lines2223242425262728295 unmodified lines DEFAULT_WLLAMA_MODEL_ID, type ServerConfig,} from "../shared/serverConfig.ts";import { parseCommaSeparatedList } from "./parseCommaSeparatedList.ts";import { getSearchToken } from "./searchToken.ts";
/**9 unmodified lines }
const config: ServerConfig = { accessKeysEnabled: Boolean(process.env.ACCESS_KEYS), accessKeysEnabled: parseCommaSeparatedList(process.env.ACCESS_KEYS).length > 0, accessKeyTimeoutHours: Number(process.env.ACCESS_KEY_TIMEOUT_HOURS) || 0, wllamaDefaultModelId: process.env.WLLAMA_DEFAULT_MODEL_ID || DEFAULT_WLLAMA_MODEL_ID,123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import type { IncomingMessage, ServerResponse } from "node:http";import { tmpdir } from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
// Every request is refused before it reaches a service, so the test needs no// network: an unverified token, an exhausted rate limit.vi.mock("./handleTokenVerification", () => ({ handleTokenVerification: vi.fn( async (_token: unknown, response: ServerResponse) => { response.statusCode = 401; response.end("Unauthorized"); return { shouldContinue: false }; }, ),}));vi.mock("./verifyTokenAndRateLimit", async (importOriginal) => ({ ...(await importOriginal<typeof import("./verifyTokenAndRateLimit")>()), consumeRateLimitPoint: vi.fn(async () => false),}));vi.mock("./fallbackSearchService", () => ({ assertSearchFallbackConfiguration: vi.fn(), fetchFallbackTextResults: vi.fn(), isSearchFallbackEnabled: vi.fn(() => false), getFallbackProviderStats: vi.fn(() => ({})),}));vi.mock("./biEncoderService.ts", () => ({ getBiEncoderStatus: async () => true,}));vi.mock("./rerankerService.ts", () => ({ getRerankerStatus: async () => true,}));vi.mock("./webSearchService.ts", () => ({ getWebSearchServiceStatus: async () => "healthy", getSearchCircuitStats: () => ({ circuitState: "closed", circuitOpens: 0 }),}));
import { cacheServerHook } from "./cacheServerHook";import { configEndpointServerHook } from "./configEndpointServerHook";import { internalApiEndpointServerHook } from "./internalApiEndpointServerHook";import { pageContentEndpointServerHook } from "./pageContentEndpointServerHook";import { searchEndpointServerHook } from "./searchEndpointServerHook";import { statusEndpointServerHook } from "./statusEndpointServerHook";import { validateAccessKeyServerHook } from "./validateAccessKeyServerHook";
type Middleware = ( request: IncomingMessage, response: ServerResponse, next: () => void,) => unknown;
let root: string;const middlewares: Middleware[] = [];
beforeAll(() => { root = mkdtempSync(path.join(tmpdir(), "dynamic-cache-")); mkdirSync(path.join(root, "dist", "assets"), { recursive: true }); writeFileSync(path.join(root, "dist", "assets", "index-abc123.js"), "");
const server = { middlewares: { use: (handler: Middleware) => middlewares.push(handler) }, config: { root, build: { outDir: "dist" }, define: { VITE_BUILD_DATE_TIME: new Date().toISOString() }, }, } as never; // The order of the preview server in vite.config.ts. for (const hook of [ configEndpointServerHook, searchEndpointServerHook, pageContentEndpointServerHook, statusEndpointServerHook, cacheServerHook, validateAccessKeyServerHook, internalApiEndpointServerHook, ]) { hook(server); }});
afterAll(() => { rmSync(root, { recursive: true, force: true });});
/** The Cache-Control a request leaves with, answered or passed through. */function cacheControlFor(url: string, method = "GET"): Promise<unknown> { return new Promise((resolve) => { const headers = new Map<string, unknown>(); const response = { statusCode: 200, headersSent: false, writableEnded: false, setHeader: (name: string, value: unknown) => headers.set(name.toLowerCase(), value), getHeader: (name: string) => headers.get(name.toLowerCase()), hasHeader: (name: string) => headers.has(name.toLowerCase()), removeHeader: (name: string) => headers.delete(name.toLowerCase()), write: () => true, end: () => resolve(headers.get("cache-control")), on: () => response, once: () => response, }; const request = { url, method, headers: { host: "localhost" }, socket: { remoteAddress: "127.0.0.1" }, on: () => request, once: () => request, }; let index = 0; const next = () => { const middleware = middlewares[index++]; if (!middleware) { resolve(headers.get("cache-control")); return; } middleware( request as unknown as IncomingMessage, response as unknown as ServerResponse, next, ); }; next(); });}
describe("Cache-Control across the preview middleware stack", () => { it.each([ ["/api/validate-access-key", "POST"], ["/inference", "GET"], ["/search/text?q=a&token=x", "GET"], ["/search/images?q=a&token=x", "GET"], ["/page-content?token=x", "GET"], ["/status", "GET"], ["/api/config", "GET"], ])("answers %s (%s) with no-store", async (url, method) => { expect(await cacheControlFor(url, method)).toBe("no-store"); });
it("leaves the static paths to the cache hook", async () => { expect(await cacheControlFor("/assets/index-abc123.js")).toBe( "public, max-age=31536000, immutable", ); expect(await cacheControlFor("/")).toBe("no-cache"); expect(await cacheControlFor("/favicon.png")).toBe( "public, max-age=86400, must-revalidate", ); });});88 unmodified lines899091929394959617 unmodified lines1141151161171181191201238 unmodified lines13591360136113591362136313641365544 unmodified lines1910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201988 unmodified linesconst PARALLEL_URL = "https://search.parallel.ai/mcp";const YOUCOM_KEYLESS_URL = "https://api.you.com/mcp?profile=free";const YOUCOM_AUTHENTICATED_URL = "https://api.you.com/mcp";const KEENABLE_KEYLESS_URL = "https://api.keenable.ai/mcp-public";const KEENABLE_AUTHENTICATED_URL = "https://api.keenable.ai/mcp";
const DESCRIPTION = "A plain description that You.com returns for a page that matched the query, long enough to read as a summary.";17 unmodified lines "SEARCH_FALLBACK_PROVIDERS", "SEARCH_FALLBACK_PARALLEL_API_KEY", "SEARCH_FALLBACK_YOUCOM_API_KEY", "SEARCH_FALLBACK_KEENABLE_API_KEY", "SEARCH_FALLBACK_PROVIDER", "SEARCH_FALLBACK_API_KEY",] as const;1238 unmodified lines listProviders("parallel, Bing");
expect(() => assertSearchFallbackConfiguration()).toThrow( "SEARCH_FALLBACK_PROVIDERS has unknown provider names: bing; valid names: parallel, youcom.", "SEARCH_FALLBACK_PROVIDERS has unknown provider names: bing; valid names: parallel, youcom, keenable.", ); await expect( fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),544 unmodified lines expect(getFallbackProviderStats()).toEqual({ parallel: zero, youcom: zero, keenable: zero, }); });});
describe("Keenable", () => { const KEENABLE_KEY_VARIABLE = "SEARCH_FALLBACK_KEENABLE_API_KEY"; const keenableDocumentWith = (results: unknown[]) => toolReply({ query: QUERY, mode: "pro", results }); const runKeenable = async (results: unknown[], limit = 10) => { process.env.SEARCH_FALLBACK_PROVIDERS = "keenable"; mockExchange(keenableDocumentWith(results), { initializeSession: null }); return fetchFallbackTextResults(QUERY, limit, FULL_BUDGET_MS); };
it("is left out of the default list while it has no key", async () => { delete process.env.SEARCH_FALLBACK_PROVIDERS; vi.spyOn(Math, "random").mockReturnValue(0.99); mockExchange(documentWith([])); mockExchange(youcomDocumentWith([]), { initializeSession: null });
await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
const urls = fetchMock.mock.calls.map(([requestUrl]) => String(requestUrl)); expect(new Set(urls)).toEqual(new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL])); });
it("joins the default list when its key is set", async () => { delete process.env.SEARCH_FALLBACK_PROVIDERS; process.env[KEENABLE_KEY_VARIABLE] = "keenable-test-value"; vi.spyOn(Math, "random").mockReturnValue(0.99); mockExchange(documentWith([])); mockExchange(youcomDocumentWith([]), { initializeSession: null }); mockExchange(keenableDocumentWith([]), { initializeSession: null });
await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
const urls = fetchMock.mock.calls.map(([requestUrl]) => String(requestUrl)); expect(new Set(urls)).toEqual( new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL, KEENABLE_AUTHENTICATED_URL]), ); });
it("calls the keyless endpoint with the app name and no key header", async () => { await runKeenable([]);
expect(fetchMock).toHaveBeenCalledTimes(2); for (const [index, [requestUrl]] of fetchMock.mock.calls.entries()) { expect(String(requestUrl)).toBe(KEENABLE_KEYLESS_URL); expect(requestHeaders(index)["X-Keenable-Title"]).toBe("MiniSearch"); expect(requestHeaders(index)["X-API-Key"]).toBeUndefined(); expect(requestHeaders(index).Authorization).toBeUndefined(); } expect(requestBody(1).params?.name).toBe("search_web_pages"); expect(requestBody(1).params?.arguments).toEqual({ query: QUERY, max_results: 10, output_format: "json", disable_cards: true, }); });
it("sends a key as X-API-Key, never as a Bearer token, on the keyed endpoint", async () => { process.env[KEENABLE_KEY_VARIABLE] = "keenable-test-value";
await runKeenable([]);
for (const [index, [requestUrl]] of fetchMock.mock.calls.entries()) { expect(String(requestUrl)).toBe(KEENABLE_AUTHENTICATED_URL); expect(requestHeaders(index)["X-API-Key"]).toBe("keenable-test-value"); expect(requestHeaders(index).Authorization).toBeUndefined(); } });
it("asks for at most 50 results", async () => { await runKeenable([], 80);
expect(requestBody(1).params?.arguments?.max_results).toBe(50); });
it("maps the snippet like an excerpt and keeps the endpoint's order", async () => { const results = await runKeenable([ { title: "First", url: "https://example.com/1", snippet: `# Heading\n${EXCERPT}`, }, { title: "No snippet", url: "https://example.com/2", snippet: "" }, { title: "Second", url: "https://example.com/3", snippet: EXCERPT }, "not an object", ]);
expect(results).toEqual([ ["First", EXCERPT, "https://example.com/1"], ["Second", EXCERPT, "https://example.com/3"], ]); });
it("throws when the document has no results array", async () => { process.env.SEARCH_FALLBACK_PROVIDERS = "keenable"; mockExchange(toolReply({ query: QUERY }), { initializeSession: null });
await expect( fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS), ).rejects.toThrow("without a results array"); });});24 unmodified lines252627282930313231 unmodified lines6465666768697071727374757677786779808182718384851 unmodified line8788899091929394959697989910010133 unmodified lines13513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917085 unmodified lines256257258210259260261262263264265266267213 unmodified lines48148248343048448548648748848949049171 unmodified lines563564565508509510511512566567568569117 unmodified lines6876886896366906916926938 unmodified lines70270370465170570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873924 unmodified linesconst DEFAULT_RATE_LIMIT_PAUSE_MS = 60_000;const MAX_RATE_LIMIT_PAUSE_MS = 3_600_000;const MIN_RATE_LIMIT_PAUSE_MS = 1_000;// The most results one Keenable search returns; it refuses a larger count.const KEENABLE_MAX_RESULTS = 50;
// One per server process: Parallel uses it for free-tier rate limiting and// one MiniSearch instance is one client, so a fresh one per request would shed31 unmodified lines results?: { web?: YoucomWebResult[] };}
interface KeenableSearchResult { url?: string; title?: string | null; snippet?: string | null;}
interface KeenableSearchDocument { results?: KeenableSearchResult[];}
type TextualResult = [title: string, content: string, url: string];
type ProviderName = "parallel" | "youcom";type ProviderName = "parallel" | "youcom" | "keenable";
interface MappedResults { results: TextualResult[]; received: number; /** The provider's longer text per result URL, kept for `/page-content`. */ pageTexts?: Map<string, string>;}1 unmodified lineinterface FallbackProvider { name: ProviderName; apiKeyVariable: string; /** * Left out of the default list: tried only when SEARCH_FALLBACK_PROVIDERS * names it or its key is set, so adding it changes nothing for an instance * that already runs the fallback. */ optIn?: boolean; endpointUrl: (apiKey: string) => string; /** The headers that carry the key, and any the provider needs on every request. Bearer when absent. */ headers?: (apiKey: string) => Record<string, string>; toolCall: ( query: string, limit: number,33 unmodified lines mapResults: (document, limit) => mapYoucomResults(document as YoucomSearchDocument, limit), }, { name: "keenable", apiKeyVariable: "SEARCH_FALLBACK_KEENABLE_API_KEY", optIn: true, endpointUrl: (apiKey) => apiKey ? "https://api.keenable.ai/mcp" : "https://api.keenable.ai/mcp-public", // Keenable reads a key from X-API-Key; a Bearer token there is taken for // an OAuth sign-in and refused. The app name identifies the caller on the // keyless endpoint. headers: (apiKey) => ({ "X-Keenable-Title": "MiniSearch", ...(apiKey ? { "X-API-Key": apiKey } : {}), }), // `output_format: json` returns the raw search response instead of the // readable text the tool sends by default. Cards (prices, rates) carry // URLs that expire after a day, so they are left out. toolCall: (query, limit) => ({ name: "search_web_pages", arguments: { query, max_results: Math.min(limit, KEENABLE_MAX_RESULTS), output_format: "json", disable_cards: true, }, }), mapResults: (document, limit) => mapKeenableResults(document as KeenableSearchDocument, limit), },];
const PROVIDER_NAMES = PROVIDERS.map((provider) => provider.name);85 unmodified lines }
const value = process.env.SEARCH_FALLBACK_PROVIDERS ?? ""; if (value.trim() === "") return [...PROVIDERS]; if (value.trim() === "") { return PROVIDERS.filter( ({ optIn, apiKeyVariable }) => !optIn || (process.env[apiKeyVariable] ?? "").trim() !== "", ); }
const names = value .split(",")213 unmodified lines const headers: Record<string, string> = { "Content-Type": "application/json", Accept: "application/json, text/event-stream", ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), ...(provider.headers ? provider.headers(apiKey) : apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), };
const initializeResponse = await fetch(endpointUrl, {71 unmodified lines }
const document = await readSearchDocument<object>(callResponse, 2); const mapped = provider.mapResults(document, limit); printMessage( `Fallback search usable text results from ${provider.name}: ${mapped.results.length} of ${mapped.received}.`, ); return mapped; return provider.mapResults(document, limit);}
/**117 unmodified lines return toSnippet(text); });
return { results, received: document.results.length, pageTexts }; return { results, pageTexts };}
function mapYoucomResults(8 unmodified lines
return { results: mapEntries(document.results.web, limit, buildYoucomSnippet), received: document.results.web.length, };}
/** * Keenable's snippet is markdown cut from the page for the query, the same * kind of text as a Parallel excerpt, so each result is read as a Parallel * result with that one excerpt: cleaned the same way, and kept whole for * `/page-content`. */function mapKeenableResults( document: KeenableSearchDocument, limit: number,): MappedResults { if (!Array.isArray(document.results)) return mapParallelResults({}, limit);
return mapParallelResults( { results: document.results.map((result) => result && typeof result === "object" ? { url: result.url, title: result.title, excerpts: typeof result.snippet === "string" ? [result.snippet] : [], } : result, ), }, limit, );}
function mapEntries<Entry extends { url?: string; title?: string | null }>( entries: Entry[], limit: number,177 unmodified lines178179180181182183184185186187188189190191192193194195196197198199200201202224 unmodified lines427428429430431432433434435436437438439440350 unmodified lines791792793767794795796797798799800413 unmodified lines12141215121611871188121712181219122012211222122312241225388 unmodified lines161416151616161716181619162016211622162316241625162616271628162916301631163216331634177 unmodified lines expect(response.end).not.toHaveBeenCalled(); });
it.each([ ["GET", "/inferences"], ["POST", "/inferenceX?token=abc"], ["POST", "/inference/extra?token=abc"], ])( "passes through %s %s, which is not the /inference route", async (method, url) => { const handler = getRegisteredHandler(); const next = vi.fn(); const response = createResponse(); const request = createRequest({}, method); request.url = url; await handler(request, response, next); expect(next).toHaveBeenCalledTimes(1); expect(response.end).not.toHaveBeenCalled(); expect(handleTokenVerification).not.toHaveBeenCalled(); }, );
it("passes on a request without a URL instead of answering for it", async () => { const handler = getRegisteredHandler(); const next = vi.fn();224 unmodified lines "Content-Type", "text/event-stream", ); expect(response.setHeader).toHaveBeenCalledWith( "Cache-Control", "no-store", ); expect(response.setHeader).not.toHaveBeenCalledWith( "Cache-Control", "no-cache", ); const writeCalls = response.write.mock.calls.map((c) => c[0]); expect( writeCalls.some((s: string) => s.includes('"content":"Hello"')),350 unmodified lines response, vi.fn(), ); expect(response.setHeader).not.toHaveBeenCalled(); expect(response.setHeader).not.toHaveBeenCalledWith( "Content-Type", "text/event-stream", ); expect(streamText).not.toHaveBeenCalled(); });
413 unmodified lines try { const handler = getRegisteredHandler(); const response = createResponse(); response.setHeader.mockImplementationOnce(() => { throw new Error("setHeader exploded"); let thrown = false; response.setHeader.mockImplementation((name: string) => { if (!thrown && name === "Content-Type") { thrown = true; throw new Error("setHeader exploded"); } }); await handler( createRequest({ messages: [{ role: "user", content: "hi" }] }),388 unmodified lines }); });});
describe("internalApiEndpointServerHook with a malformed Host header", () => { it("answers 400 and keeps the handler promise from rejecting", async () => { vi.mocked(handleTokenVerification).mockClear(); const request = createRequest({ messages: [] }); request.headers.host = "bad host"; const response = createResponse(); const next = vi.fn();
await expect( getRegisteredHandler()(request, response, next), ).resolves.toBeUndefined();
expect(response.statusCode).toBe(400); expect(handleTokenVerification).not.toHaveBeenCalled(); expect(next).not.toHaveBeenCalled(); });});22 unmodified lines2324252627282951 unmodified lines818283838485868751 unmodified lines1391401411421431441451461471481491501515 unmodified lines15715815915215315415515615716016116216316416516616722 unmodified lines recordStreamEndedWithoutFinish,} from "./inferencesSinceLastRestart.ts";import { sendJsonError } from "./utils/httpResponse.ts";import { parseRequestUrl } from "./utils/requestUrl.ts";import { calculateBackoffTime, isResponseWritable,51 unmodified lines if (response.headersSent) return;
response.setHeader("Content-Type", "text/event-stream"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Cache-Control", "no-store"); response.setHeader("Connection", "keep-alive");}
51 unmodified lines return next(); }
// The gate above is only cheap; the route is the exact pathname. if (new URL(request.url, "http://localhost").pathname !== "/inference") { return next(); }
response.setHeader("Cache-Control", "no-store");
if (request.method !== "POST") { response.setHeader("Allow", "POST"); sendJsonError(response, 405, { error: "Method Not Allowed" });5 unmodified lines return; }
const hostHeader = request.headers.host; const baseUrl = typeof hostHeader === "string" && hostHeader.length > 0 ? `http://${hostHeader}` : "http://localhost"; const url = new URL(request.url, baseUrl); const url = parseRequestUrl(request); if (!url) { sendJsonError(response, 400, { error: "Malformed request" }); return; } const token = url.searchParams.get("token"); const { shouldContinue } = await handleTokenVerification( token,1234567891011import { repository, version } from "../package.json" with { type: "json" };
const appName = repository.url.slice(repository.url.lastIndexOf("/") + 1);
/** * How the server identifies itself on its outbound requests to third * parties: name, version and where to read about it. Some hosts refuse a * request that carries no User-Agent; upload.wikimedia.org answers it with * 403. */export const OUTBOUND_USER_AGENT = `Mozilla/5.0 (compatible; ${appName}/${version}; +${repository.url})`;234 unmodified lines235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265234 unmodified lines expect(getPageReadStats().grounding.requests).toBe(before.requests + 2); });});
describe("pageContentEndpointServerHook with a malformed Host header", () => { it("answers 400 and keeps the handler promise from rejecting", async () => { vi.clearAllMocks(); const use = vi.fn(); pageContentEndpointServerHook({ middlewares: { use }, } as unknown as Parameters<typeof pageContentEndpointServerHook>[0]); const response = { statusCode: 200, setHeader: vi.fn(), end: vi.fn(), } as unknown as RecordedResponse; const next = vi.fn(); const request = { url: "/page-content?url=http://example.com&token=abc", headers: { host: "bad host" }, } as unknown as IncomingMessage;
await expect( (use.mock.calls[0][0] as Handler)(request, response, next), ).resolves.toBeUndefined();
expect(response.statusCode).toBe(400); expect(handleTokenVerification).not.toHaveBeenCalled(); expect(next).not.toHaveBeenCalled(); });});2 unmodified lines345667891040 unmodified lines51525353545556575859606162632 unmodified linesimport { handleTokenVerification } from "./handleTokenVerification.ts";import { fetchPageContents } from "./pageContentService.ts";import { recordGroundingOutcome } from "./pageReadsSinceLastRestart.ts";import { sendValidationError } from "./utils/httpResponse.ts";import { sendJsonError, sendValidationError } from "./utils/httpResponse.ts";import { parseRequestUrl } from "./utils/requestUrl.ts";
const MAX_QUERY_LENGTH = 2000;const MAX_URL_LENGTH = 2048;40 unmodified lines server.middlewares.use(async (request, response, next) => { if (!request.url?.startsWith("/page-content")) return next();
const url = new URL(request.url, `http://${request.headers.host}`); response.setHeader("Cache-Control", "no-store");
const url = parseRequestUrl(request); if (!url) { sendJsonError(response, 400, { error: "Malformed request" }); return; } if (url.pathname !== "/page-content") return next();
// Verified before the parameters are read, so malformed requests from an95 unmodified lines96979899100101102103104105106107108109110111112113114115116117118119120740 unmodified lines861862863864865866867868869870871872873874875876877878879880881882883884132 unmodified lines1017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104895 unmodified lines };}
/** * `AbortSignal.timeout` runs on Node's own timer, which fake timers do not * move, so a test that needs the 6 s deadline to pass hands out signals * driven by the faked `setTimeout` instead of waiting it out for real. */function useFakeDeadlines() { return vi.spyOn(AbortSignal, "timeout").mockImplementation((ms) => { const controller = new AbortController(); setTimeout( () => controller.abort( new DOMException("The operation timed out.", "TimeoutError"), ), ms, ); return controller.signal; });}
describe("extractReadableText", () => { it("keeps the article and drops site chrome, scripts and styles", () => { const text = extractReadableText(articlePage);740 unmodified lines ).toEqual({ failed: 1 }); });
it("bounds a hanging DNS lookup with the same deadline and counts it as a timeout", async () => { // Matches REQUEST_TIMEOUT_MS in pageContentService.ts. const requestTimeoutMs = 6000; lookupMock.mockImplementation(() => new Promise(() => {})); vi.useFakeTimers(); const deadlines = useFakeDeadlines(); try { const counted = countOutcomes("https://hanging-dns.example.com/"); await vi.advanceTimersByTimeAsync(requestTimeoutMs);
expect((await counted).skipped).toEqual({ timedOut: 1 }); expect(fetchMock).not.toHaveBeenCalled(); } finally { deadlines.mockRestore(); vi.useRealTimers(); } });
it("counts a page that yielded almost no text", async () => { respondWithHtml("<html><body><p>Accept cookies</p></body></html>");
132 unmodified lines ).toEqual({ skippedByBreaker: 1 }); });
it("counts a DNS lookup that outlasts the deadline toward the box", async () => { const breaker = new PageReadHostBreaker(breakerOptions); lookupMock.mockImplementation(() => new Promise(() => {})); const deadlines = useFakeDeadlines(); try { for (const page of ["a", "b", "c"]) { const counted = countOutcomes( `https://hanging-dns.example.com/${page}`, breaker, ); await vi.advanceTimersByTimeAsync(6000); await counted; } } finally { deadlines.mockRestore(); }
lookupMock.mockResolvedValue([{ address: "93.184.216.34", family: 4 }]); respondWithHtml(articlePage); expect( (await countOutcomes("https://hanging-dns.example.com/d", breaker)) .skipped, ).toEqual({ skippedByBreaker: 1 }); expect(breaker.getOpens()).toBe(1); });
it("does not count a dead link or a thin page, and either one ends a run of refusals", async () => { const breaker = new PageReadHostBreaker(breakerOptions);
123345674 unmodified lines12131415151617189 unmodified lines28293031323132333435363937383940508 unmodified lines54955055155255355455555655755855956056156256356456556656756817 unmodified lines586587588577578589590591592593594import { convert as convertHtmlToPlainText } from "html-to-text";import { PDFParse } from "pdf-parse";import { repository, version } from "../package.json" with { type: "json" };import { scorePassages } from "./biEncoderService.ts";import { OUTBOUND_USER_AGENT } from "./outboundUserAgent.ts";import { type PageReadHostBreaker, pageReadHostBreaker,4 unmodified lines recordPageServedFromSearchExcerpts,} from "./pageReadsSinceLastRestart.ts";import { recallSearchExcerpts } from "./searchExcerptStore.ts";import { resolvePublicUrl } from "./utils/publicUrl.ts";import { resolvePublicUrl, resolveWithinDeadline } from "./utils/publicUrl.ts";import { readCappedBytes } from "./utils/streamUtils.ts";
const REQUEST_TIMEOUT_MS = 6000;9 unmodified linesconst MAX_DENSE_PASSAGES = 256;const RRF_K = 60;
const appName = repository.url.slice(repository.url.lastIndexOf("/") + 1);
const REQUEST_HEADERS = { Accept: "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.8", // No language preference: searches arrive in every language, and asking for // English made a multilingual site serve its English edition for a query // written in something else. "Accept-Language": "*", "User-Agent": `Mozilla/5.0 (compatible; ${appName}/${version}; +${repository.url})`, "User-Agent": OUTBOUND_USER_AGENT,} as const;
const READABLE_CONTENT_TYPES =508 unmodified lines }}
/** * A lookup that runs out the deadline never reaches `admit`, so the host it * was resolving is charged here: it cost the batch the whole wait, the way a * read that hangs does. Admitting first keeps a half-open host to one probe. */function chargeLookupTimeout( target: string, breaker: PageReadHostBreaker,): DownloadResult { const host = URL.parse(target)?.host; if (host && breaker.admit(host)) breaker.settle(host, "timedOut"); return { outcome: "timedOut" };}
/** * Follows redirects by hand so that every hop is validated: `redirect: * "follow"` would let a public URL bounce the server into a private address.17 unmodified lines for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { let url: URL; try { url = await resolvePublicUrl(target); } catch { url = await resolveWithinDeadline(deadline, resolvePublicUrl(target)); } catch (error) { if (isTimeout(error)) return chargeLookupTimeout(target, breaker); return { outcome: "blocked" }; }
1234567891011121314151617181920212223242526import { describe, expect, it } from "vitest";import { parseCommaSeparatedList } from "./parseCommaSeparatedList";
describe("parseCommaSeparatedList", () => { it("splits on commas", () => { expect(parseCommaSeparatedList("a,b,c")).toEqual(["a", "b", "c"]); });
it("trims whitespace around each entry", () => { expect(parseCommaSeparatedList("localhost, example.com ")).toEqual([ "localhost", "example.com", ]); });
it("drops empty entries", () => { expect(parseCommaSeparatedList("key1, key2,")).toEqual(["key1", "key2"]); expect(parseCommaSeparatedList(",")).toEqual([]); expect(parseCommaSeparatedList(" , ,")).toEqual([]); });
it("returns an empty list for an unset or empty value", () => { expect(parseCommaSeparatedList(undefined)).toEqual([]); expect(parseCommaSeparatedList("")).toEqual([]); });});1234567891011/** * Splits a comma-separated environment value into its entries, trimming each * one and dropping the empty ones. `.env` files commonly carry `A, B,`, and * the spaces and the trailing comma are never part of an entry. */export function parseCommaSeparatedList(value: string | undefined): string[] { return (value ?? "") .split(",") .map((entry) => entry.trim()) .filter(Boolean);}938 unmodified lines939940941942943944945946947948949950951952953954955956957958959960961962963938 unmodified lines }); });});
describe("searchEndpointServerHook with a malformed Host header", () => { it("answers 400 and keeps the handler promise from rejecting", async () => { vi.mocked(handleTokenVerification).mockResolvedValue({ shouldContinue: true, }); const request = { url: "/search/text?q=cats&token=abc", headers: { host: "bad host" }, } as unknown as IncomingMessage; const response = createResponse(); const next = vi.fn();
await expect( getRegisteredHandler()(request, response, next), ).resolves.toBeUndefined();
expect(response.statusCode).toBe(400); expect(handleTokenVerification).not.toHaveBeenCalled(); expect(next).not.toHaveBeenCalled(); });});27 unmodified lines282930313132333435143 unmodified lines17918018118118218318418518618718818919019157 unmodified lines24925025124524624725225325427 unmodified lines recordSearchDuration, type SearchType,} from "./searchesSinceLastRestart.ts";import { sendValidationError } from "./utils/httpResponse.ts";import { sendJsonError, sendValidationError } from "./utils/httpResponse.ts";import { parseRequestUrl } from "./utils/requestUrl.ts";import { fetchSearXNG, fetchSupplementarySearXNG } from "./webSearchService.ts";
const DEFAULT_SEARCH_LIMIT = 30;143 unmodified lines server.middlewares.use(async (request, response, next) => { if (!request.url?.startsWith("/search/")) return next();
const url = new URL(request.url, `http://${request.headers.host}`); response.setHeader("Cache-Control", "no-store");
const url = parseRequestUrl(request); if (!url) { sendJsonError(response, 400, { error: "Malformed request" }); return; }
// Verified before the parameters are read, matching `/page-content`: a // malformed query from an unauthenticated caller has to cost the caller a57 unmodified lines remainingMs, ); incrementSearchesServedByFallback(); console.log( "SearXNG failed, served text results from the fallback search", ); } catch (fallbackError) { incrementSearchesFailedOnFallback(); // Fixed text plus the error's message, which by construction58 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011136 unmodified lines14814915010415115215315427 unmodified lines18218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621758 unmodified lines}
describe("statusEndpointServerHook", () => { it.each(["/statuses", "/statusX?token=abc", "/status/extra"])( "passes through %s, which is not the /status route", async (url) => { const use = vi.fn(); statusEndpointServerHook({ middlewares: { use }, config: { define: { VITE_BUILD_DATE_TIME: new Date().toISOString() } }, } as unknown as Parameters<typeof statusEndpointServerHook>[0]); const response = { setHeader: vi.fn(), end: vi.fn(), } as unknown as RecordedResponse; const next = vi.fn();
await (use.mock.calls[0][0] as Handler)( { url, headers: {} } as unknown as IncomingMessage, response, next, );
expect(next).toHaveBeenCalledTimes(1); expect(response.end).not.toHaveBeenCalled(); }, );
it("still answers /status with a query string", async () => { const use = vi.fn(); statusEndpointServerHook({ middlewares: { use }, config: { define: { VITE_BUILD_DATE_TIME: new Date().toISOString() } }, } as unknown as Parameters<typeof statusEndpointServerHook>[0]); const response = { setHeader: vi.fn(), end: vi.fn(), } as unknown as RecordedResponse; const next = vi.fn();
await (use.mock.calls[0][0] as Handler)( { url: "/status?probe=1", headers: {} } as unknown as IncomingMessage, response, next, );
expect(next).not.toHaveBeenCalled(); expect(response.end).toHaveBeenCalledTimes(1); });
it("publishes the web search verdict and the per-engine tally", async () => { const status = await callStatus();
36 unmodified lines Object.keys( (status.searches as { fallbackProviders: object }).fallbackProviders, ), ).toEqual(["parallel", "youcom"]); ).toEqual(["parallel", "youcom", "keenable"]); });
it("publishes the page-read circuit count beside the outcome counters", async () => {27 unmodified lines } });});
describe("statusEndpointServerHook with a malformed build define", () => { it("answers 500 instead of rejecting the middleware", async () => { const use = vi.fn(); statusEndpointServerHook({ middlewares: { use }, config: { define: { VITE_BUILD_DATE_TIME: new Date().toISOString(), VITE_COMMIT_SHORT_HASH: "{not json", }, }, } as unknown as Parameters<typeof statusEndpointServerHook>[0]); const response = { statusCode: 200, setHeader: vi.fn(), end: vi.fn(), } as unknown as RecordedResponse;
await expect( (use.mock.calls[0][0] as Handler)( { url: "/status", headers: {} } as unknown as IncomingMessage, response, () => undefined, ), ).resolves.toBeUndefined();
expect(response.statusCode).toBe(500); expect(JSON.parse(response.end.mock.calls[0][0])).toEqual({ error: "Malformed VITE_COMMIT_SHORT_HASH build define", }); });});21 unmodified lines2223242526272811 unmodified lines404142434445464748495021 unmodified lines7273746975767778798081828321 unmodified lines getThumbnailStats, getUnresponsiveEngineStats,} from "./searchesSinceLastRestart.ts";import { sendJsonError } from "./utils/httpResponse.ts";import { getActiveSessionsAmount, getVerifiedTokensAmount,11 unmodified lines>(server: T) { server.middlewares.use(async (request, response, next) => { if (!request.url?.startsWith("/status")) return next(); if (new URL(request.url, "http://localhost").pathname !== "/status") { return next(); }
response.setHeader("Cache-Control", "no-store");
const sessions = getVerifiedTokensAmount(); const textualSearches = getTextualSearchesSinceLastRestart();21 unmodified lines server.config.define?.VITE_COMMIT_SHORT_HASH || '""', ); } catch { throw new Error("Malformed VITE_COMMIT_SHORT_HASH build define"); // Throwing here would reject the async middleware, which Node treats as // an unhandled rejection and exits the process. sendJsonError(response, 500, { error: "Malformed VITE_COMMIT_SHORT_HASH build define", }); return; }
const status = {12345107 unmodified lines1131141151161171181191201211 unmodified line1231241251221261271281291301311321331341351361377 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167219 unmodified lines387388389390391392393394395396397398399400401402403404405406407408409410163 unmodified lines5745755765335775785795805815825 unmodified lines58858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463554763663763863964032 unmodified lines673674675676677678679680681682683684685686687688689690691692693694695import type { IncomingMessage, ServerResponse } from "node:http";import debug from "debug";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const lookupMock = vi.hoisted(() => vi.fn());107 unmodified lines}
describe("thumbnailEndpointServerHook", () => { let logLines: string[]; let originalLog: typeof debug.log;
beforeEach(() => { vi.clearAllMocks(); pinnedRequestMock.mockReset();1 unmodified line vi.mocked(handleTokenVerification).mockResolvedValue({ shouldContinue: true, }); vi.spyOn(console, "warn").mockImplementation(() => {}); logLines = []; originalLog = debug.log; debug.log = (...args: unknown[]) => { logLines.push(args.map(String).join(" ")); }; });
afterEach(() => { debug.log = originalLog; vi.restoreAllMocks(); });
7 unmodified lines expect(pinnedRequestMock).not.toHaveBeenCalled(); });
it.each([ "/thumbnails", "/thumbnailX?token=abc", "/thumbnail/extra?token=abc", ])("passes through %s, which is not the /thumbnail route", async (url) => { const handler = getRegisteredHandler(); const next = vi.fn(); const response = createResponse();
await handler(createRequest(url), response, next);
expect(next).toHaveBeenCalledTimes(1); expect(response.end).not.toHaveBeenCalled(); expect(handleTokenVerification).not.toHaveBeenCalled(); expect(pinnedRequestMock).not.toHaveBeenCalled(); });
it("stops processing when token verification fails", async () => { vi.mocked(handleTokenVerification).mockResolvedValue({ shouldContinue: false,219 unmodified lines expect(recordThumbnailDropped).toHaveBeenCalledTimes(1); });
it("logs why a fetch failed, never the thumbnail URL or its host", async () => { pinnedRequestMock.mockResolvedValue( fakeIncoming(new Uint8Array(), 403, {}), ); const handler = getRegisteredHandler(); const thumbnailUrl = publicThumbnailUrl();
await handler( createRequest(requestUrlFor(thumbnailUrl)), createResponse(), vi.fn(), );
const output = logLines.join("\n"); expect(output).toContain("Thumbnail fetch failed: HTTP 403"); expect(output).not.toContain(new URL(thumbnailUrl).hostname); });
it("answers 502 when the upstream answer is not an accepted image type", async () => { pinnedRequestMock.mockResolvedValue( fakeIncoming(new TextEncoder().encode("<html></html>"), 200, {163 unmodified lines expect(recordThumbnailDropped).toHaveBeenCalledTimes(1); });
it("truncates an oversized body to the byte cap", async () => { it("answers 502 instead of serving a body over the byte cap cut off", async () => { // The cap is 500_000 bytes; the first 500_000 of this body would decode // as a damaged image. const bigBody = new Uint8Array(600_000).fill(7); pinnedRequestMock.mockResolvedValue(imageResponse(bigBody)); const handler = getRegisteredHandler();5 unmodified lines vi.fn(), );
expect(response.statusCode).toBe(502); expect(response.setHeader).toHaveBeenCalledWith( "Cache-Control", "no-store", ); expect(response.end).toHaveBeenCalledWith( JSON.stringify({ error: "Thumbnail could not be fetched" }), ); expect(recordThumbnailDropped).toHaveBeenCalledTimes(1); expect(logLines.join("\n")).toContain( "Thumbnail fetch failed: larger than 500000 bytes", ); });
it("does not cache a body over the byte cap, so the next load fetches again", async () => { const url = publicThumbnailUrl(); pinnedRequestMock .mockResolvedValueOnce(imageResponse(new Uint8Array(600_000).fill(7))) .mockResolvedValueOnce(imageResponse()); const handler = getRegisteredHandler();
const first = createResponse(); await handler(createRequest(requestUrlFor(url)), first, vi.fn()); expect(first.statusCode).toBe(502);
const second = createResponse(); await handler(createRequest(requestUrlFor(url)), second, vi.fn()); expect(second.statusCode).toBe(200); expect(pinnedRequestMock).toHaveBeenCalledTimes(2); });
it("serves a body of exactly the byte cap", async () => { const capSizedBody = new Uint8Array(500_000).fill(7); pinnedRequestMock.mockResolvedValue(imageResponse(capSizedBody)); const handler = getRegisteredHandler(); const response = createResponse();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), response, vi.fn(), );
expect(response.statusCode).toBe(200); const body = response.end.mock.calls[0][0] as Buffer; // The cap is 500_000 bytes; a 600_000-byte body must be truncated. expect(body.length).toBe(500_000); expect(recordThumbnailDropped).not.toHaveBeenCalled(); });
it("evicts the least recently used entry, not the least recently loaded one", async () => {32 unmodified lines expect(fetched(secondUrl)).toBe(2); });});
describe("thumbnailEndpointServerHook with a malformed Host header", () => { it("answers 400 instead of 500", async () => { vi.mocked(handleTokenVerification).mockClear(); const request = { url: "/thumbnail?u=https%3A%2F%2Fexample.com%2Fa.png&token=abc", headers: { host: "bad host" }, } as unknown as IncomingMessage; const response = createResponse(); const next = vi.fn();
await expect( getRegisteredHandler()(request, response, next), ).resolves.toBeUndefined();
expect(response.statusCode).toBe(400); expect(handleTokenVerification).not.toHaveBeenCalled(); expect(next).not.toHaveBeenCalled(); });});1234565 unmodified lines1213141315161718192021222324252627282916 unmodified lines464748394950515253110 unmodified lines16416516615615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718816716816971 unmodified lines2412422432442452672462472482492502512521 unmodified line25425525625725825926026126226326426526626726826947 unmodified lines31731831932032132232332433032532632732832933033133242 unmodified lines375376377379378379380381import type { IncomingMessage, ServerResponse } from "node:http";import { basename } from "node:path";import debug from "debug";import type { PreviewServer, ViteDevServer } from "vite";import { handleTokenVerification } from "./handleTokenVerification.ts";import {5 unmodified lines readCappedStream, requestPinnedToVettedAddress,} from "./utils/pinnedFetch.ts";import { resolvePublicUrlAndAddress } from "./utils/publicUrl.ts";import { resolvePublicUrlAndAddress, resolveWithinDeadline,} from "./utils/publicUrl.ts";import { parseRequestUrl } from "./utils/requestUrl.ts";import { safeEndResponse } from "./utils/streamUtils.ts";import { thumbnailRateLimiter } from "./verifyTokenAndRateLimit.ts";
const fileName = basename(import.meta.url);const printMessage = debug(fileName);printMessage.enabled = true;
/** * Where each SSRF defense of this endpoint lives: *16 unmodified lines * shared deadline. * - Content-Type: raster-only allowlist below; SVG is deliberately * excluded because served same-origin it is a script-carrying document. * - Response size: `MAX_THUMBNAIL_BYTES` via `readCappedStream`. * - Response size: `MAX_THUMBNAIL_BYTES` via `readCappedStream`; a body * over the cap is refused, never served or cached cut off. * - Timeout: `THUMBNAIL_TIMEOUT_MS`, shared across DNS and every hop. * - Rate limiting: per client IP via `thumbnailRateLimiter`, a dedicated * 60-per-10s budget so a grid of tiles cannot exhaust the search110 unmodified lines return status >= 300 && status < 400 && status !== 304;}
/** * `resolvePublicUrlAndAddress`'s DNS lookup does not take a signal, so it * is raced against the hop deadline: a hanging resolver would otherwise * add its own timeout on top of the one that is documented to bound the * whole chain. */function timeoutError(): Error { const error = new Error("The operation was aborted"); error.name = "TimeoutError"; return error;}
function resolveWithinDeadline<T>( deadline: AbortSignal, work: Promise<T>,): Promise<T> { if (deadline.aborted) return Promise.reject(timeoutError()); return new Promise<T>((resolve, reject) => { const onAbort = () => reject(timeoutError()); deadline.addEventListener("abort", onAbort, { once: true }); work.then( (value) => { deadline.removeEventListener("abort", onAbort); resolve(value); }, (error) => { deadline.removeEventListener("abort", onAbort); reject(error); }, ); });}
/** * Follows redirects by hand so that every hop is validated and pinned, the * way `pageContentService` follows them: `redirect: "follow"` would let a71 unmodified lines }
let bytes: Uint8Array; let truncated: boolean; try { ({ bytes } = await readCappedStream(response, MAX_THUMBNAIL_BYTES)); ({ bytes, truncated } = await readCappedStream( response, MAX_THUMBNAIL_BYTES, )); } catch (error) { return { kind: "failed",1 unmodified line }; }
// An image cut at the cap is a damaged image: a baseline JPEG loses // everything below the cut, other formats may not decode at all. Served, // it would also sit in the LRU and the browser cache for an hour. if (truncated) { return { kind: "failed", reason: `larger than ${MAX_THUMBNAIL_BYTES} bytes`, }; }
if (bytes.byteLength === 0) { return { kind: "failed", reason: "empty body" }; }47 unmodified lines>(server: T) { server.middlewares.use(async (request, response, next) => { if (!request.url?.startsWith("/thumbnail")) return next(); if (new URL(request.url, "http://localhost").pathname !== "/thumbnail") { return next(); }
try { const url = new URL(request.url, `http://${request.headers.host}`); const url = parseRequestUrl(request); if (!url) { serveError(response, 400, "Malformed request"); return; }
const { shouldContinue } = await handleTokenVerification( url.searchParams.get("token"),42 unmodified lines
if (outcome.kind === "failed") { recordThumbnailDropped(); console.warn(`Thumbnail fetch failed: ${outcome.reason}`); printMessage(`Thumbnail fetch failed: ${outcome.reason}`); serveError(response, 502, "Thumbnail could not be fetched"); return; }144 unmodified lines14514614714814814915015115215315415515615715815911 unmodified lines171172173174175176177178179180144 unmodified lines expect(httpsRequestMock).not.toHaveBeenCalled(); });
it("dials the pinned address end-to-end while the server sees the original Host", async () => { it("dials the pinned address end-to-end while the server sees the original Host and the User-Agent", async () => { // pinned-host.test has no DNS record: the request can only succeed if // the socket goes where the pin says, not where a resolver would. let seenHost = ""; let seenUserAgent = ""; let seenTarget = ""; const server = http.createServer((request, response) => { seenHost = request.headers.host ?? ""; seenUserAgent = request.headers["user-agent"] ?? ""; seenTarget = request.url ?? ""; response.writeHead(200, { "content-type": "image/png" }); response.end(Buffer.from([9, 8, 7]));11 unmodified lines expect(response.statusCode).toBe(200); expect(Array.from(bytes)).toEqual([9, 8, 7]); expect(seenHost).toBe(`pinned-host.test:${port}`); // upload.wikimedia.org answers a request without a User-Agent with 403. expect(seenUserAgent).toMatch( /^Mozilla\/5\.0 \(compatible; MiniSearch\/[^;]+; \+https:\/\/github\.com\/felladrin\/MiniSearch\)$/, ); expect(seenTarget).toBe("/img.png?v=1"); } finally { server.close();1 unmodified line234567814 unmodified lines2324252526272829303122 unmodified lines54555654575859601 unmodified lineimport http from "node:http";import https from "node:https";import { isIP } from "node:net";import { OUTBOUND_USER_AGENT } from "../outboundUserAgent.ts";
/** * What the capped reader needs from a response body: an async stream of14 unmodified lines * The original hostname survives the pin three ways: it stays the request's * `hostname`, so TLS SNI and certificate verification run against it, not * against the IP being dialled, and the `Host` header is set explicitly so * virtual-host routing is unaffected. * virtual-host routing is unaffected. Every request also carries the * server's `User-Agent`, because some image hosts refuse a request without * one (upload.wikimedia.org answers 403). * * @throws When the protocol is not http(s) or the request fails */22 unmodified lines // SNI and certificate verification follow the hostname, not the pinned // address, so a wrong-host certificate still fails the request. servername: isTls ? hostname : undefined, headers: { Host: hostHeader }, headers: { Host: hostHeader, "User-Agent": OUTBOUND_USER_AGENT }, // The pin itself: the socket connects to the vetted address and no // resolver is consulted, so the address checked is the address reached. // Node's Happy Eyeballs path (autoSelectFamily, on by default since189 unmodified lines190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226189 unmodified linesexport async function resolvePublicUrl(rawUrl: string): Promise<URL> { return (await resolvePublicUrlAndAddress(rawUrl)).url;}
function timeoutError(): Error { const error = new Error("The operation was aborted"); error.name = "TimeoutError"; return error;}
/** * The DNS lookup behind `resolvePublicUrl` and `resolvePublicUrlAndAddress` * does not take a signal, so callers race it against their request deadline: * a hanging resolver would otherwise add its own timeout on top of the one * that is documented to bound the whole redirect chain. The lookup itself * keeps running, but the caller settles on time with a `TimeoutError`. */export function resolveWithinDeadline<T>( deadline: AbortSignal, work: Promise<T>,): Promise<T> { if (deadline.aborted) return Promise.reject(timeoutError()); return new Promise<T>((resolve, reject) => { const onAbort = () => reject(timeoutError()); deadline.addEventListener("abort", onAbort, { once: true }); work.then( (value) => { deadline.removeEventListener("abort", onAbort); resolve(value); }, (error) => { deadline.removeEventListener("abort", onAbort); reject(error); }, ); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import { describe, expect, it } from "vitest";import { parseRequestUrl } from "./requestUrl.ts";
function parse(url: string | undefined, host?: string) { return parseRequestUrl({ url, headers: host === undefined ? {} : { host }, });}
describe("parseRequestUrl", () => { it("reads the path and query parameters the same way for a valid Host", () => { const url = parse("/search/text?q=a%20b&token=t", "localhost:7860"); expect(url?.pathname).toBe("/search/text"); expect(url?.searchParams.get("q")).toBe("a b"); expect(url?.searchParams.get("token")).toBe("t"); });
it.each([ undefined, "", "localhost", "localhost:7860", "example.com", "my_service:3000", "127.0.0.1:80", "[::1]:7860", ])("accepts the Host header %j", (host) => { expect(parse("/x", host)).not.toBeNull(); });
it.each([ "bad host", "localhost:99999", "local host:80", "host/path", "host?x=1", "host:80:80", "[::1", "a b\tc", ])("returns null for the malformed Host header %j", (host) => { expect(parse("/x", host)).toBeNull(); });
it("does not let the Host header change the parsed path or query", () => { const url = parse("/page-content?url=http://a.test", "evil.test:1"); expect(url?.pathname).toBe("/page-content"); expect(url?.searchParams.get("url")).toBe("http://a.test"); expect(url?.host).toBe("localhost"); });});123456789101112131415161718192021222324252627282930313233343536373839import type { IncomingMessage } from "node:http";
const REQUEST_URL_BASE = "http://localhost";
// A hostname (letters, digits, dot, hyphen, underscore) or a bracketed IPv6// literal, with an optional port.const HOST_HEADER_PATTERN = /^(?:[A-Za-z0-9._-]+|\[[0-9A-Fa-f:.]+\])(?::(\d{1,5}))?$/;
function isValidHostHeader(host: string): boolean { const match = HOST_HEADER_PATTERN.exec(host); if (!match) return false; return match[1] === undefined || Number(match[1]) <= 65535;}
/** * Parses the request target, or returns `null` for a request that should be * answered with a 400. * * The URL is parsed against a fixed base instead of the Host header: the * endpoint hooks read only `pathname` and `searchParams`, and a Host header such * as `bad host` makes `new URL(path, "http://bad host")` throw. Inside an async * middleware that throw is an unhandled rejection, and Node exits. A Host * header that is present but malformed is refused here, as RFC 9112 asks. */export function parseRequestUrl( request: Pick<IncomingMessage, "url" | "headers">,): URL | null { const host = request.headers.host; if (typeof host === "string" && host.length > 0 && !isValidHostHeader(host)) { return null; }
try { return new URL(request.url ?? "/", REQUEST_URL_BASE); } catch { return null; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import { describe, expect, it, vi } from "vitest";import { readCappedBytes } from "./streamUtils";
function fakeResponse(chunks: Uint8Array[]) { let index = 0; const cancel = vi.fn().mockResolvedValue(undefined); const reader = { read: vi.fn(async () => { if (index < chunks.length) { return { done: false, value: chunks[index++] }; } return { done: true, value: undefined }; }), cancel, }; const response = { body: { getReader: () => reader, }, } as unknown as Response; return { response, reader, cancel };}
describe("readCappedBytes", () => { it("reads an exact-fit body in a single chunk without truncation", async () => { const { response, cancel } = fakeResponse([new Uint8Array([1, 2, 3, 4])]); const { bytes, truncated } = await readCappedBytes(response, 4);
expect(Array.from(bytes)).toEqual([1, 2, 3, 4]); expect(truncated).toBe(false); expect(cancel).toHaveBeenCalled(); });
it("reads an exact-fit body split across chunks without truncation", async () => { const { response, cancel } = fakeResponse([ new Uint8Array([1, 2]), new Uint8Array([3, 4]), ]); const { bytes, truncated } = await readCappedBytes(response, 4);
expect(Array.from(bytes)).toEqual([1, 2, 3, 4]); expect(truncated).toBe(false); expect(cancel).toHaveBeenCalled(); });
it("truncates at the cap when a single chunk exceeds maxBytes", async () => { const { response, cancel } = fakeResponse([ new Uint8Array([1, 2, 3, 4, 5]), ]); const { bytes, truncated } = await readCappedBytes(response, 4);
expect(Array.from(bytes)).toEqual([1, 2, 3, 4]); expect(truncated).toBe(true); expect(cancel).toHaveBeenCalled(); });
it("truncates at the cap when the boundary lands on a chunk boundary", async () => { const { response, cancel } = fakeResponse([ new Uint8Array([1, 2, 3, 4]), new Uint8Array([5]), ]); const { bytes, truncated } = await readCappedBytes(response, 4);
expect(Array.from(bytes)).toEqual([1, 2, 3, 4]); expect(truncated).toBe(true); expect(cancel).toHaveBeenCalled(); });
it("returns all bytes and truncated false when body is under cap", async () => { const { response, cancel } = fakeResponse([new Uint8Array([1, 2, 3])]); const { bytes, truncated } = await readCappedBytes(response, 10);
expect(Array.from(bytes)).toEqual([1, 2, 3]); expect(truncated).toBe(false); expect(cancel).toHaveBeenCalled(); });
it("returns empty buffer and truncated false for an empty body", async () => { const { response, cancel } = fakeResponse([]); const { bytes, truncated } = await readCappedBytes(response, 10);
expect(bytes.byteLength).toBe(0); expect(truncated).toBe(false); expect(cancel).toHaveBeenCalled(); });
it("returns empty buffer and truncated false when response has no body", async () => { const { bytes, truncated } = await readCappedBytes({} as Response, 10);
expect(bytes.byteLength).toBe(0); expect(truncated).toBe(false); });
it("cancels reader even if an error occurs during reading", async () => { const cancel = vi.fn().mockResolvedValue(undefined); const reader = { read: vi.fn().mockRejectedValue(new Error("network failure")), cancel, }; const response = { body: { getReader: () => reader, }, } as unknown as Response;
await expect(readCappedBytes(response, 10)).rejects.toThrow( "network failure", ); expect(cancel).toHaveBeenCalled(); });});14 unmodified lines151617181819202122232425262728293031202122232433252627282930313233343536373839403637414243444546444748495014 unmodified lines
const chunks: Uint8Array[] = []; let bytesRead = 0; let reachedEnd = false; let truncated = false;
while (bytesRead < maxBytes) { const { done, value } = await reader.read(); if (done) { reachedEnd = true; break; }
const remaining = maxBytes - bytesRead; const chunk = value.byteLength > remaining ? value.subarray(0, remaining) : value; bytesRead += chunk.byteLength; chunks.push(chunk); try { while (true) { const { done, value } = await reader.read(); if (done) break;
if (chunk.byteLength < value.byteLength) break; const remaining = maxBytes - bytesRead; if (value.byteLength > remaining) { if (remaining > 0) { chunks.push(value.subarray(0, remaining)); bytesRead = maxBytes; } truncated = true; break; } chunks.push(value); bytesRead += value.byteLength; } } finally { await reader.cancel().catch(() => {}); }
await reader.cancel().catch(() => {});
const bytes = new Uint8Array(bytesRead); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } return { bytes, truncated: !reachedEnd }; return { bytes, truncated };}
export function calculateBackoffTime(137 unmodified lines138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195137 unmodified lines expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1); });
it("ignores spaces and empty entries in the configured ACCESS_KEYS list", async () => { process.env.ACCESS_KEYS = "test-key, other-key,"; mockArgon2Verify.mockImplementation( async ({ password }: { password: string }) => { if (password === "") throw new Error("Password must be specified"); return password === "other-key"; }, ); const { validateAccessKeyServerHook } = await import( "./validateAccessKeyServerHook" ); const use = vi.fn(); validateAccessKeyServerHook({ middlewares: { use }, } as never); const handler = use.mock.calls[0][0] as ( req: { url: string; method: string; on: (event: string, cb: (chunk: string) => void) => void; }, res: { setHeader: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn>; }, next: () => void, ) => void;
const res = makeMockResponse(); const req = makeMockRequest( "/api/validate-access-key", "POST", JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("valid") }), );
await new Promise<void>((resolve) => { void handler(req as never, res as never, () => {}); setImmediate(() => { for (const cb of req.endCallbacks) { cb(); } setTimeout(resolve, 50); }); });
expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true })); const verifiedPasswords = mockArgon2Verify.mock.calls.map( ([options]) => (options as { password: string }).password, ); expect(verifiedPasswords).toEqual(["test-key", "other-key"]); });
it("responds 429 and skips the argon2 loop when the limiter refuses", async () => { process.env.ACCESS_KEYS = "test-key"; mockConsumeRateLimitPoint.mockResolvedValue(false);123456711 unmodified lines19202122232425267 unmodified lines3435363437383940import { argon2Verify } from "hash-wasm";import type { PreviewServer, ViteDevServer } from "vite";import { ARGON2_HASH_PREFIX } from "../shared/argon2Parameters.ts";import { parseCommaSeparatedList } from "./parseCommaSeparatedList.ts";import { consumeRateLimitPoint } from "./verifyTokenAndRateLimit.ts";
/**11 unmodified lines return next(); }
res.setHeader("Cache-Control", "no-store");
// Consume a rate-limit point before the argon2 loop. A wrong hash costs one // full argon2 verification per configured key, so nothing may bound that // work other than the limiter - the same lever the search token path closes.7 unmodified lines return; }
const accessKeys = process.env.ACCESS_KEYS?.split(",") ?? []; const accessKeys = parseCommaSeparatedList(process.env.ACCESS_KEYS);
const chunks: Buffer[] = []; let bodyBytes = 0;12345678910111213141516171819202122232425262728293031323334import { afterEach, describe, expect, it, vi } from "vitest";
afterEach(() => { vi.unstubAllEnvs(); vi.resetModules();});
async function loadAllowedHosts() { const { default: defineViteConfig } = await import("../vite.config"); const config = await ( defineViteConfig as unknown as (env: { command: string; mode: string; }) => Promise<{ preview?: { allowedHosts?: unknown } }> )({ command: "serve", mode: "test" }); return config.preview?.allowedHosts;}
describe("vite.config preview allowedHosts", () => { it("allows any host when ALLOWED_HOSTS is not set", async () => { vi.stubEnv("ALLOWED_HOSTS", ""); expect(await loadAllowedHosts()).toBe(true); });
it("accepts a host that follows a comma and a space", async () => { vi.stubEnv("ALLOWED_HOSTS", "localhost, example.com"); expect(await loadAllowedHosts()).toEqual(["localhost", "example.com"]); });
it("does not open the preview server to every host for a list without hosts", async () => { vi.stubEnv("ALLOWED_HOSTS", ","); expect(await loadAllowedHosts()).toEqual([]); });});113 unmodified lines114115116117118119120121122123124125125 unmodified lines25125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043177 unmodified lines509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595113 unmodified lines ); });
it("trims the query on both sides when an anchor is appended", () => { expect(normalizeRelativeDates(" next year ", AS_OF).searchQuery).toBe( "next year 2027", ); });
it("leaves an empty query alone", () => { for (const query of ["", " "]) { expect(normalizeRelativeDates(query, AS_OF)).toEqual({125 unmodified lines expect(searchQuery).not.toContain("December 2026"); expect(searchQuery.length).toBeLessThanOrEqual(2000); });
it("cuts an over-long query with no relative date to the limit", () => { const long = "x".repeat(2100);
expect( normalizeRelativeDates(long, new Date(2026, 10, 3), { maxLength: 2000 }), ).toEqual({ searchQuery: "x".repeat(2000), replacements: [] }); });
it("cuts an over-long query whose anchor no longer fits to the limit", () => { const long = `${"x".repeat(2095)} next year`;
expect( normalizeRelativeDates(long, new Date(2026, 10, 3), { maxLength: 2000 }), ).toEqual({ searchQuery: "x".repeat(2000), replacements: [] }); });
it("drops the trailing space left by the cut", () => { const long = `${"x".repeat(1999)} ${"y".repeat(100)}`;
expect( normalizeRelativeDates(long, new Date(2026, 10, 3), { maxLength: 2000 }) .searchQuery, ).toBe("x".repeat(1999)); });
describe("spelling variants", () => { it.each(["'", "\u2018", "\u2019", "\u02bc", "\uff07"])( "skips the possessive headline form with the apostrophe %j", (apostrophe) => { const query = `next year${apostrophe}s champion`;
expect(normalizeRelativeDates(query, AS_OF)).toEqual({ searchQuery: query, replacements: [], }); }, );
it.each([ "last\u00a0month\u00a0of pregnancy symptoms", "last month of pregnancy symptoms", "the last\u00a0year\u00a0of college", ])("skips a blacklisted phrase written with odd spacing: %j", (query) => { expect(normalizeRelativeDates(query, AS_OF)).toEqual({ searchQuery: query, replacements: [], }); });
it.each(["next\u00a0year", "next year"])( "anchors a trigger written with the spacing %j", (phrase) => { expect(normalizeRelativeDates(`${phrase} champion`, AS_OF)).toEqual({ searchQuery: `${phrase} champion 2027`, replacements: [{ phrase, anchor: "2027" }], }); }, );
it("reports the phrase as typed after a letter that grows when lowercased", () => { // "İ".toLowerCase() is two code units, which used to shift every index // computed on the lowercased copy. expect(normalizeRelativeDates("İstanbul next year", AS_OF)).toEqual({ searchQuery: "İstanbul next year 2027", replacements: [{ phrase: "next year", anchor: "2027" }], }); }); });
describe("dates the query already carries", () => { it.each([ "events in 2026 December next month", "events in December 2026 next month", "events in Dec 2026 next month", "events in Dec. 2026 next month", "events in Sept 2026 and 2026-12 next month", "events in 2026-12 next month", "events in 2026/12 next month", ])("does not add December 2026 to %j", (query) => { expect(normalizeRelativeDates(query, AS_OF)).toEqual({ searchQuery: query, replacements: [], }); });
it.each(["2026年12月的活动 下个月", "2026 年 12 月的活动 下个月"])( "does not add 2026年12月 to %j", (query) => { expect(normalizeRelativeDates(query, AS_OF)).toEqual({ searchQuery: query, replacements: [], }); }, );
it("still adds a month when the query names only the year", () => { expect( normalizeRelativeDates("events in 2026 next month", AS_OF), ).toEqual({ searchQuery: "events in 2026 next month December 2026", replacements: [{ phrase: "next month", anchor: "December 2026" }], }); });
it("still adds a month when the query names another month", () => { expect( normalizeRelativeDates("events in January 2026 next month", AS_OF) .replacements, ).toEqual([{ phrase: "next month", anchor: "December 2026" }]); });
it("does not take a year inside a longer number for a year", () => { expect(normalizeRelativeDates("ticket 120265 this year", AS_OF)).toEqual({ searchQuery: "ticket 120265 this year 2026", replacements: [{ phrase: "this year", anchor: "2026" }], }); });
it("does not take a season for a month", () => { // 2011-12 is a season (the second number follows the first year), not // December 2011, so next month's anchor is still worth adding. expect( normalizeRelativeDates( "2011-12 season next month", new Date(2011, 10, 3, 12), ).replacements, ).toEqual([{ phrase: "next month", anchor: "December 2011" }]); }); });
describe("which month a written date carries", () => { const JANUARY_2026 = new Date(2026, 0, 10, 12);
it("takes the month written inside the date over a month name behind it", () => { // "Nov" belongs to "Nov 2026", not to 2026-12, so December is written. expect( normalizeRelativeDates("report 2026-12 Nov 2026 next month", AS_OF), ).toEqual({ searchQuery: "report 2026-12 Nov 2026 next month", replacements: [], }); expect( normalizeRelativeDates("2026年12月 November 2026 next month", AS_OF) .replacements, ).toEqual([]); });
it("gives a month name to the date it stands in front of, not the one before", () => { // "2023-2025 Dec 2026" is a range, then December 2026. December 2025, // which last month resolves to in January 2026, is not written. expect( normalizeRelativeDates("2023-2025 Dec 2026 last month", JANUARY_2026) .replacements, ).toEqual([{ phrase: "last month", anchor: "December 2025" }]); });
it("does not give a month to a year range", () => { expect( normalizeRelativeDates("2023-2025 December last month", JANUARY_2026) .replacements, ).toEqual([{ phrase: "last month", anchor: "December 2025" }]); });
it("gives a month name in front of a range to its first year only", () => { expect( normalizeRelativeDates("December 2025-2027 last month", JANUARY_2026) .replacements, ).toEqual([]); expect( normalizeRelativeDates("December 2023-2025 last month", JANUARY_2026) .replacements, ).toEqual([{ phrase: "last month", anchor: "December 2025" }]); }); });});
describe("normalizeFollowUpDates", () => {77 unmodified lines }).searchQuery, ).toBe("who won"); });
it("cuts an over-long query to the limit", () => { const long = "x".repeat(2100);
expect( normalizeFollowUpDates(long, [long], AS_OF, { maxLength: 2000 }) .searchQuery, ).toBe("x".repeat(2000)); expect( normalizeFollowUpDates(long, ["who won it last year"], AS_OF, { maxLength: 2000, }).searchQuery, ).toHaveLength(2000); });
describe("anchors already written", () => { it("does not repeat a year the user typed that the anchor resolves to", () => { expect( normalizeFollowUpDates( "2025 election results", ["2025 election results", "what happened last year?"], AS_OF, ), ).toEqual({ searchQuery: "2025 election results", replacements: [] }); });
it("does not repeat a month the user typed, written another way", () => { expect( normalizeFollowUpDates( "new releases in Dec 2026", ["new releases in Dec 2026", "and next month?"], AS_OF, ), ).toEqual({ searchQuery: "new releases in Dec 2026", replacements: [] }); });
it("keeps the anchor that is not already written", () => { expect( normalizeFollowUpDates( "2025 election results", ["2025 election results", "and what about next year?"], AS_OF, ).searchQuery, ).toBe("2025 election results 2027"); }); });
describe("a query that is only a written date", () => { it("gets its anchor without a leading space", () => { expect( normalizeFollowUpDates("2025", ["what happened last year?"], AS_OF), ).toEqual({ searchQuery: "2025", replacements: [{ phrase: "last year", anchor: "2025" }], }); });
it.each(["2025", " 2025 ", "2024-25", "2026年"])( "returns a trimmed query for the model's %j", (query) => { const result = normalizeFollowUpDates( query, ["what happened last year?"], AS_OF, );
expect(result.replacements).not.toEqual([]); expect(result.searchQuery).toBe(result.searchQuery.trim()); }, ); });
describe("abbreviated months", () => { it("drops the model's abbreviated month together with its year", () => { // Only the year used to go, which left a dangling "Dec" in the query. expect( normalizeFollowUpDates("results and Dec 2026", ["what 去年"], AS_OF), ).toEqual({ searchQuery: "results and 2025年", replacements: [{ phrase: "去年", anchor: "2025年" }], }); }); });});54 unmodified lines555657585960616263646566114 unmodified lines1811821831781791841851861871881891901911921931941951961971981992002012022031821831841851861871881891901911921931941951961971981992002012022032042052042052062072082072082092092102112122112132142152162172182192208 unmodified lines2292302312262322332342352362372322332382392402412422372382392402412422432442452462478 unmodified lines2562572582592602612622639 unmodified lines2732742752722732762772782792802816 unmodified lines28828929029129229329429529629729829930030130230330430529129229330630730830931031131231329531431529731631731831932032132230232332432532632732832933033133233333431131233533633733833931534034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842922 unmodified lines45245345445545645745845946034946146246346446546654 unmodified lines anchor: string;}
/** A date as a query writes it; `month` is 1 to 12 when the query names one. */interface WrittenDate { year: number; month?: number;}
/** * Month arithmetic in local calendar terms: December plus one month is January * of the next year, not a wrapped month inside the same one.114 unmodified lines "last year of",];
function isAsciiLetter(char: string): boolean { return (char >= "A" && char <= "Z") || (char >= "a" && char <= "z");/** Keyboards type any of these: ' U+2018 U+2019 U+02BC U+FF07. */const APOSTROPHES = "'\u2018\u2019\u02bc\uff07";
/** * Whitespace of any kind matches a space and any apostrophe variant matches * `'`. The pattern runs on the original text rather than a lowercased copy, so * a match keeps its position: "İ".toLowerCase() is two code units. */function compilePhrase(phrase: string, wordBounded: boolean): RegExp { const body = phrase .replace(/[.*+?^${}()|[\]\\]/g, "\\$&") .replace(/ /g, "\\s+") .replace(/'/g, `[${APOSTROPHES}]`);
return new RegExp( wordBounded ? `(?<![A-Za-z])${body}(?![A-Za-z])` : body, "gi", );}
function findOccurrences( text: string, phrase: string, wordBounded: boolean,): Occurrence[] { const haystack = text.toLowerCase(); const needle = phrase.toLowerCase(); const occurrences: Occurrence[] = []; let from = 0;
while (from + needle.length <= haystack.length) { const start = haystack.indexOf(needle, from); if (start === -1) break;
const end = start + needle.length; const touchesWord = wordBounded && (isAsciiLetter(haystack.charAt(start - 1)) || isAsciiLetter(haystack.charAt(end)));
if (touchesWord) { from = start + 1; continue; }const COMPILED_RULES = RULES.map((rule) => ({ rule, pattern: compilePhrase(rule.phrase, rule.wordBounded),}));
occurrences.push({ start, end }); from = end; }const BLACKLIST_PATTERNS = BLACKLIST_PHRASES.map((phrase) => compilePhrase(phrase, false),);
return occurrences;function findOccurrences(text: string, pattern: RegExp): Occurrence[] { return [...text.matchAll(pattern)].map((match) => ({ start: match.index, end: match.index + match[0].length, }));}
function overlaps(occurrence: Occurrence, ranges: readonly Occurrence[]) {8 unmodified lines options?: { maxLength?: number },): { searchQuery: string; replacements: RelativeDateReplacement[] } { const unchanged = { searchQuery: query, searchQuery: clampToMaxLength(query, options?.maxLength), replacements: [] as RelativeDateReplacement[], };
if (query.trim() === "") return unchanged;
const blacklistRanges = BLACKLIST_PHRASES.flatMap((phrase) => findOccurrences(query, phrase, false), const blacklistRanges = BLACKLIST_PATTERNS.flatMap((pattern) => findOccurrences(query, pattern), );
const hits: Hit[] = []; for (const rule of RULES) { for (const occurrence of findOccurrences( query, rule.phrase, rule.wordBounded, )) { for (const { rule, pattern } of COMPILED_RULES) { for (const occurrence of findOccurrences(query, pattern)) { // A trigger inside a title or a longer word is a false positive; the // blacklist owns that run of text. if (overlaps(occurrence, blacklistRanges)) continue;8 unmodified lines
if (hits.length === 0) return unchanged;
const writtenInQuery = writtenDates(query);
hits.sort( (left, right) => left.start - right.start ||9 unmodified lines if (selected.some((chosen) => overlaps(hit, [chosen]))) continue; // An anchor the query already spells out is not worth repeating: the // search engine has that year already, and a doubled anchor only dilutes // the query. if (query.toLowerCase().includes(hit.anchor.toLowerCase())) continue; // the query. Compared as dates, so "Dec 2026" meets December 2026 and the // "2026" inside "120265" meets nothing. if (isAlreadyWritten(writtenInQuery, hit.anchor)) continue;
usedAnchors.add(hit.anchor); selected.push(hit);6 unmodified lines );}
/** * The query cut to `maxLength` characters, so the result never exceeds the * limit the search endpoint enforces. A query within the limit is returned * as is. */function clampToMaxLength(query: string, maxLength?: number): string { if (maxLength === undefined || query.length <= maxLength) return query; return query.slice(0, maxLength).trimEnd();}
function appendAnchors( query: string, replacements: RelativeDateReplacement[], maxLength = Number.POSITIVE_INFINITY,): { searchQuery: string; replacements: RelativeDateReplacement[] } { // The search endpoint rejects an over-long query, so an anchor that would // push it past the limit is dropped rather than turning a search into a // failed request. No anchor left over means the query goes out untouched. // The search endpoint rejects an over-long query, so the query itself is cut // to the limit, and an anchor that would push it past the limit is dropped // rather than turning a search into a failed request. No anchor left over // means the query goes out as it came, cut only when it was too long. const base = clampToMaxLength(query, maxLength); const appended: RelativeDateReplacement[] = []; // Both ends, so a query that is only a written date gets no leading space, // which would give the same search a second cache key. let searchQuery = query.trimEnd(); let searchQuery = base.trim(); for (const replacement of replacements) { const candidate = `${searchQuery} ${replacement.anchor}`; const candidate = searchQuery ? `${searchQuery} ${replacement.anchor}` : replacement.anchor; if (candidate.length > maxLength) break; searchQuery = candidate; appended.push(replacement); } if (appended.length === 0) return { searchQuery: query, replacements: [] }; if (appended.length === 0) return { searchQuery: base, replacements: [] };
return { searchQuery, replacements: appended };}
const YEAR = "(?<!\\d)(?:19|20)\\d{2}(?!\\d)";
/** A month name or its three-letter abbreviation ("Sept" too), as a whole word. */const MONTH_WORD = `(?:${MONTH_NAMES.flatMap((name) => [name, name.slice(0, 3)]).join("|")}|Sept)\\b`;
/** * A year a model writes into a query, alone, as a range or a season, after a * month name, or glued to Chinese text: "2023", "2023-2025", "2024-25", * "November 2026", "2026年11月", "2025 年". * month name (written out or abbreviated), or glued to Chinese text: "2023", * "2023-2025", "2024-25", "November 2026", "Dec 2026", "2026年11月", * "2025 年 3 月". */const WRITTEN_DATE = new RegExp( `(?:\\b(?:${MONTH_NAMES.join("|")})\\s+)?${YEAR}(?:\\s*[-–/]\\s*${YEAR}|[-–/]\\d{2}(?!\\d))?(?:\\s*年(?:\\d{1,2}月)?)?`, `(?:\\b${MONTH_WORD}\\.?\\s+)?${YEAR}(?:\\s*[-–/]\\s*${YEAR}|[-–/]\\d{2}(?!\\d))?(?:\\s*年(?:\\s*\\d{1,2}\\s*月)?)?`, "gi",);
function monthNumber(word: string): number { const prefix = word.slice(0, 3).toLowerCase(); return ( MONTH_NAMES.findIndex((name) => name.slice(0, 3).toLowerCase() === prefix) + 1 );}
/** * A month written inside the date wins ("2026年12月", "2026-12", which is a * season rather than a month when it reads "2024-25"), then a name in front of * the year, then one behind it, unless the next date starts with that name. A * range takes a month only from a name in front, and only for its first year. */function monthOfWrittenDate( match: RegExpExecArray, nextMatch: RegExpExecArray | undefined, text: string, yearCount: number,): number | undefined { const written = match[0];
if (yearCount === 1) { const chinese = written.match(/年\s*(\d{1,2})\s*月/); if (chinese) return Number(chinese[1]);
const iso = written.match(/(?:19|20)(\d{2})[-/](\d{2})(?!\d)/); if (iso) { const [yearDigits, month] = [Number(iso[1]), Number(iso[2])]; const isSeason = month === (yearDigits + 1) % 100; if (!isSeason && month >= 1 && month <= 12) return month; } }
const leading = written.match(new RegExp(`^${MONTH_WORD}`, "i")); if (leading) return monthNumber(leading[0]);
if (yearCount !== 1) return undefined;
const end = match.index + written.length; const trailing = text .slice(end) .match(new RegExp(`^[,\\s]+(${MONTH_WORD})`, "i")); if (!trailing) return undefined;
const wordStart = end + trailing[0].length - trailing[1].length; return nextMatch?.index === wordStart ? undefined : monthNumber(trailing[1]);}
function writtenDates(text: string): WrittenDate[] { const matches = [...text.matchAll(WRITTEN_DATE)];
return matches.flatMap((match, index) => { const years = (match[0].match(new RegExp(YEAR, "g")) ?? []).map(Number); const month = monthOfWrittenDate( match, matches[index + 1], text, years.length, );
return years.map((year, position) => ({ year, month: position === 0 ? month : undefined, })); });}
/** A year-only anchor is met by any written date in that year. */function isAlreadyWritten( written: readonly WrittenDate[], anchor: string,): boolean { const [wanted] = writtenDates(anchor); if (!wanted) return false;
return written.some( (date) => date.year === wanted.year && (wanted.month === undefined || date.month === wanted.month), );}
/** * Anchors the relative dates of the question the user typed onto the query a * model wrote for it. The model often replaces "last year" with a year of its22 unmodified lines .replace(/\s+/g, " ") .trim();
// A date the user typed survives the cleaning above, and its anchor would // repeat it. const writtenInQuery = writtenDates(queryWithoutModelDates);
return appendAnchors( queryWithoutModelDates, replacements, replacements.filter( ({ anchor }) => !isAlreadyWritten(writtenInQuery, anchor), ), options?.maxLength, );}12 unmodified lines1314151617181944 unmodified lines6465666667686967686970717212 unmodified linesimport { crossOriginServerHook } from "./server/crossOriginServerHook.ts";import { internalApiEndpointServerHook } from "./server/internalApiEndpointServerHook.ts";import { pageContentEndpointServerHook } from "./server/pageContentEndpointServerHook.ts";import { parseCommaSeparatedList } from "./server/parseCommaSeparatedList.ts";import { rerankerServiceHook } from "./server/rerankerServiceHook.ts";import { searchEndpointServerHook } from "./server/searchEndpointServerHook.ts";import { statusEndpointServerHook } from "./server/statusEndpointServerHook.ts";44 unmodified lines preview: { host: process.env.HOST, port: process.env.PORT ? Number(process.env.PORT) : undefined, allowedHosts: process.env.ALLOWED_HOSTS && process.env.ALLOWED_HOSTS.length > 0 ? process.env.ALLOWED_HOSTS.split(",") : true, allowedHosts: process.env.ALLOWED_HOSTS ? parseCommaSeparatedList(process.env.ALLOWED_HOSTS) : true, }, build: { target: "esnext",package-lock.json+51-51
server/biEncoderService.test.tsAdded+125
server/biEncoderService.ts+34-5
server/cacheServerHook.test.tsAdded+65
server/cacheServerHook.ts+20-1
server/configEndpointServerHook.test.tsAdded+48
server/configEndpointServerHook.ts+3-1
server/dynamicCacheHeaders.test.tsAdded+152
server/fallbackSearchService.test.ts+108-1
server/fallbackSearchService.ts+93-11
server/internalApiEndpointServerHook.test.ts+55-3
server/internalApiEndpointServerHook.ts+14-7
server/outboundUserAgent.tsAdded+11
server/pageContentEndpointServerHook.test.ts+28
server/pageContentEndpointServerHook.ts+9-2
server/pageContentService.test.ts+63
server/pageContentService.ts+20-7
server/parseCommaSeparatedList.test.tsAdded+26
server/parseCommaSeparatedList.tsAdded+11
server/searchEndpointServerHook.test.ts+22
server/searchEndpointServerHook.ts+9-5
server/statusEndpointServerHook.test.ts+81-1
server/statusEndpointServerHook.ts+12-1
server/thumbnailEndpointServerHook.test.ts+112-3
server/thumbnailEndpointServerHook.ts+37-38
server/utils/pinnedFetch.test.ts+7-1
server/utils/pinnedFetch.ts+5-2
server/utils/publicUrl.ts+34
server/utils/requestUrl.test.tsAdded+51
server/utils/requestUrl.tsAdded+39
server/utils/streamUtils.test.tsAdded+111
server/utils/streamUtils.ts+20-17
server/validateAccessKeyServerHook.test.ts+52
server/validateAccessKeyServerHook.ts+4-1
server/viteConfigAllowedHosts.test.tsAdded+34
shared/relativeDates.test.ts+264
shared/relativeDates.ts+165-51
vite.config.ts+4-4