vomebook commited on
Commit ·
17df17b
1
Parent(s): 03490d9
Harden chapter search Worker protocol with strict checks
Browse filesFiles changed (15)
- Dockerfile+1
- config/types/jsconfig.chapter-worker-strict.jsonAdded+19
- package.json+1-1
- quality/baselines/strict-inventory-debt.json-1
- scripts/check_strict_inventory.py+4-2
- scripts/reader/check_chapter_search_worker_coverage.mjsAdded+28
- static/reader/search/reader-chapter-search-core.mjs+22-5
- static/reader/search/workers/reader-chapter-search-worker.mjs+118-52
- tests/gates/ci-test-inventory.json+4
- tests/gates/static_gate_ids.github.json+2
- tests/gates/static_gate_ids.hf.json+2
- tests/gates/test_static_checks.py+65
- tests/gates/test_static_contract.py+1
- tests/reader/chapter-search/test_reader_chapter_search.mjs+12
- tests/reader/chapter-search/test_reader_chapter_worker.mjsAdded+170
79 unmodified lines80818283848579 unmodified lines&& node scripts/reader/check_chapter_search_core_coverage.mjs \&& node scripts/reader/check_chapter_search_proxy_coverage.mjs \&& node scripts/reader/check_chapter_search_index_coverage.mjs \&& node --test tests/gates/test_tap_contracts.mjs \&& node tests/reader/pdf-v3/test_dataset_primary_policy.mjs \&& node scripts/search/check_download_controller_coverage.mjs \79 unmodified lines8081828384858679 unmodified lines&& node scripts/reader/check_chapter_search_core_coverage.mjs \&& node scripts/reader/check_chapter_search_proxy_coverage.mjs \&& node scripts/reader/check_chapter_search_index_coverage.mjs \&& node scripts/reader/check_chapter_search_worker_coverage.mjs \&& node --test tests/gates/test_tap_contracts.mjs \&& node tests/reader/pdf-v3/test_dataset_primary_policy.mjs \&& node scripts/search/check_download_controller_coverage.mjs \
12345678910111213141516171819{ "compilerOptions": { "allowJs": true, "checkJs": true, "noEmit": true, "strict": true, "target": "esnext", "lib": [ "esnext", "webworker" ], "module": "esnext", "moduleResolution": "bundler", "moduleDetection": "force" }, "files": [ "../../static/reader/search/workers/reader-chapter-search-worker.mjs" ]}18 unmodified lines1920212223242518 unmodified lines"scripts": {"lint": "eslint static scripts tests --max-warnings 0","markup": "node scripts/check_markup.mjs","types": "tsc --project config/types/jsconfig.check.json && tsc --project config/types/jsconfig.service-worker.json && tsc --project config/types/jsconfig.service-worker-strict.json && tsc --project config/types/jsconfig.strict.json && tsc --project config/types/jsconfig.search-exact.json && tsc --project config/types/jsconfig.reader-exact.json","check:static": "npm run lint && npm run markup && npm run types && python3 -B scripts/check_strict_inventory.py"},"_overrideNote": "minimatch 11.0.3 addresses GHSA-g3hv-75wg-m249 in the 10.x dependency; rerun checker regressions when updating ESLint.",18 unmodified lines1920212223242518 unmodified lines"scripts": {"lint": "eslint static scripts tests --max-warnings 0","markup": "node scripts/check_markup.mjs","types": "tsc --project config/types/jsconfig.check.json && tsc --project config/types/jsconfig.service-worker.json && tsc --project config/types/jsconfig.service-worker-strict.json && tsc --project config/types/jsconfig.chapter-worker-strict.json && tsc --project config/types/jsconfig.strict.json && tsc --project config/types/jsconfig.search-exact.json && tsc --project config/types/jsconfig.reader-exact.json","check:static": "npm run lint && npm run markup && npm run types && python3 -B scripts/check_strict_inventory.py"},"_overrideNote": "minimatch 11.0.3 addresses GHSA-g3hv-75wg-m249 in the 10.x dependency; rerun checker regressions when updating ESLint.",
26 unmodified lines2728293031323326 unmodified lines"static/reader/search/reader-dom-search.mjs","static/reader/search/reader-search-backends.mjs","static/reader/search/reader-search-controller.mjs","static/reader/search/workers/reader-chapter-search-worker.mjs","static/reader/search/workers/reader-pdf-book-search-worker.mjs","static/reader/ui/reader-bookmarks.mjs","static/reader/ui/reader-navigation.mjs",26 unmodified lines27282930313226 unmodified lines"static/reader/search/reader-dom-search.mjs","static/reader/search/reader-search-backends.mjs","static/reader/search/reader-search-controller.mjs","static/reader/search/workers/reader-pdf-book-search-worker.mjs","static/reader/ui/reader-bookmarks.mjs","static/reader/ui/reader-navigation.mjs",
63 unmodified lines6465666768697017 unmodified lines8889909192939463 unmodified linesdef compiler_files(root: Path, config: str) -> set[str]:if config not in ("config/types/jsconfig.check.json", "config/types/jsconfig.service-worker.json","config/types/jsconfig.service-worker-strict.json", "config/types/jsconfig.strict.json"):raise ValueError("unknown TypeScript configuration")node = shutil.which("node")if node is None:17 unmodified linesbasic = (compiler_files(ROOT, "config/types/jsconfig.check.json")| compiler_files(ROOT, "config/types/jsconfig.service-worker.json"))strict = (compiler_files(ROOT, "config/types/jsconfig.strict.json")| compiler_files(ROOT, "config/types/jsconfig.service-worker-strict.json"))py_config = json.loads((ROOT / "pyrightconfig.strict.json").read_text())if py_config.get("typeCheckingMode") != "strict":raise RuntimeError("backend strict type gate must use strict mode")63 unmodified lines646566676869707117 unmodified lines899091929394959663 unmodified linesdef compiler_files(root: Path, config: str) -> set[str]:if config not in ("config/types/jsconfig.check.json", "config/types/jsconfig.service-worker.json","config/types/jsconfig.service-worker-strict.json", "config/types/jsconfig.chapter-worker-strict.json","config/types/jsconfig.strict.json"):raise ValueError("unknown TypeScript configuration")node = shutil.which("node")if node is None:17 unmodified linesbasic = (compiler_files(ROOT, "config/types/jsconfig.check.json")| compiler_files(ROOT, "config/types/jsconfig.service-worker.json"))strict = (compiler_files(ROOT, "config/types/jsconfig.strict.json")| compiler_files(ROOT, "config/types/jsconfig.service-worker-strict.json")| compiler_files(ROOT, "config/types/jsconfig.chapter-worker-strict.json"))py_config = json.loads((ROOT / "pyrightconfig.strict.json").read_text())if py_config.get("typeCheckingMode") != "strict":raise RuntimeError("backend strict type gate must use strict mode")
12345678910111213141516171819202122232425262728// V8 coverage for chapter-search Worker protocol and loader, not complete Reader coverage.import {spawnSync} from 'node:child_process';import {hasPassingTapContracts} from '../check_tap_contracts.mjs';const minimum = [100, 92, 100];const test = 'tests/reader/chapter-search/test_reader_chapter_worker.mjs';const marker = 'chapter Worker: transport, integrity, cancellation, retry and paging passed';const result = spawnSync(process.execPath, ['--test', '--test-concurrency=1', '--test-reporter=tap', '--experimental-test-coverage', '--test-coverage-include=**/static/reader/search/workers/reader-chapter-search-worker.mjs', ...minimum.map((value,index)=>`--test-coverage-${['lines','branches','functions'][index]}=${value}`),test], {encoding:'utf8'});if (result.stdout) process.stdout.write(result.stdout);if (result.stderr) process.stderr.write(result.stderr);if (result.error) throw result.error;const text=result.stdout||'', lines=text.split(/\r?\n/);const rows=lines.flatMap(line=>{ const match=/^\s*#\s*reader-chapter-search-worker\.mjs\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|/.exec(line); return match?[match.slice(1).map(Number)]:[];});const summaries=['1..1','# tests 1','# pass 1','# fail 0','# cancelled 0','# skipped 0','# todo 0'];if(result.status!==0 || !hasPassingTapContracts(text,[{name:test,marker}]) || rows.length!==1 || rows[0].some((value,index)=>value<minimum[index]) || !summaries.every(value=>lines.filter(line=>line===value).length===1) || ['# tests ','# pass ','# fail ','# cancelled ','# skipped ','# todo '].some(prefix=> lines.filter(line=>line.startsWith(prefix)).length!==1) || lines.filter(line=>/^# duration_ms \d+(?:\.\d+)?$/.test(line)).length!==1 || ['# start of coverage report','# end of coverage report'].some(value=>lines.filter(line=>line===value).length!==1)) { console.error('Chapter search Worker requires its passing contract and exactly one source row above each minimum'); process.exitCode=1;}123436 unmodified lines414243444546474849501 unmodified line525354555657/** @typedef {{index: number, title: string, path: string, text: string, bigramFilter?: Uint8Array | undefined}} SearchChapter *//** @typedef {{ordinal: number, chapterIndex: number, start: number}} SearchCheckpoint *//** @typedef {{text: string, matchStart: number, matchLength: number, prefix: string, suffix: string}} SearchSnippet *//** @typedef {{chapterIndex: number, start: number, length: number, location: string, snippet: SearchSnippet}} SearchResult */36 unmodified linesreturn characters.slice(1).map((character, index) => bigramHashes(characters[index] + character));}/** @param {SearchChapter} chapter @param {number[][] | null} filters */export function chapterMayContainBigrams(chapter, filters) {const bloom = chapter.bigramFilter;if (!filters || !bloom) return true;const mask = bloom.length * 8 - 1;for (const hashes of filters) for (const hash of hashes) {const bit = hash & mask;1 unmodified line}return true;}/** @param {RegExp} pattern @param {string} part @param {number} start @param {number} next* @param {(start: number, length: number) => unknown} visit @returns {{next: number, stopped: boolean}} */123436 unmodified lines41424344454647484950511 unmodified line53545556575859606162636465666768697071727374/** @typedef {{index: number, title?: unknown, path: string, text: string, bigramFilter?: unknown}} SearchChapter *//** @typedef {{ordinal: number, chapterIndex: number, start: number}} SearchCheckpoint *//** @typedef {{text: string, matchStart: number, matchLength: number, prefix: string, suffix: string}} SearchSnippet *//** @typedef {{chapterIndex: number, start: number, length: number, location: string, snippet: SearchSnippet}} SearchResult */36 unmodified linesreturn characters.slice(1).map((character, index) => bigramHashes(characters[index] + character));}/** @param {unknown} value @param {string} key @returns {unknown} */function filterProperty(value, key) { return Reflect.get(Object(value), key); }/** @param {Uint8Array} bloom @param {number[][]} filters */function typedBloomMayContain(bloom, filters) {const mask = bloom.length * 8 - 1;for (const hashes of filters) for (const hash of hashes) {const bit = hash & mask;1 unmodified line}return true;}/** @param {unknown} bloom @param {number[][]} filters */function legacyBloomMayContain(bloom, filters) {const mask = Number(filterProperty(bloom, "length")) * 8 - 1;for (const hashes of filters) for (const hash of hashes) {const bit = hash & mask;if (!(Number(filterProperty(bloom, String(bit >> 3))) & (1 << (bit & 7)))) return false;}return true;}/** @param {SearchChapter} chapter @param {number[][] | null} filters */export function chapterMayContainBigrams(chapter, filters) {const bloom = chapter.bigramFilter;if (!filters || !bloom) return true;return bloom instanceof Uint8Array ? typedBloomMayContain(bloom, filters) : legacyBloomMayContain(bloom, filters);}/** @param {RegExp} pattern @param {string} part @param {number} start @param {number} next* @param {(start: number, length: number) => unknown} visit @returns {{next: number, stopped: boolean}} */
3 unmodified lines4567891022 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031043 unmodified linesimport {isSearchIndexProxyURL} from "../reader-chapter-search-proxy-url.mjs";import {validateIndex} from "../reader-chapter-search-index.mjs";async function readBounded(stream, limit, signal) {const reader = stream.getReader(), chunks = [];let size = 0;const cancel = () => reader.cancel().catch(() => {});22 unmodified lines}let configuration, indexPromise, chapters, active = 0, session, loadController;async function loadIndex() {if (chapters) return chapters;if (indexPromise) return indexPromise;const controller = new AbortController();loadController = controller;const timer = setTimeout(() => controller.abort(), 60000);indexPromise = (async () => {const { index, chapters: expected } = configuration;const url = new URL(index.url, self.location.origin);if (!isSearchIndexProxyURL(url, self.location.origin) ||!Number.isSafeInteger(index.bytes) || index.bytes <= 0 || index.bytes > PACKED_LIMIT ||!/^[0-9a-f]{64}$/.test(index.sha256)) throw new Error("全文搜索索引无效");const response = await fetch(url, { signal: controller.signal, credentials: "same-origin" });if (!response.ok) throw new Error(`全文搜索加载失败(HTTP ${response.status}),请重试`);const bytes = await readBounded(response.body, PACKED_LIMIT, controller.signal);const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));const sha = [...digest].map(value => value.toString(16).padStart(2, "0")).join("");if (bytes.length !== index.bytes || sha !== index.sha256) throw new Error("全文搜索索引校验失败,请重试");const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));const text = await readBounded(stream, TEXT_LIMIT, controller.signal);const loaded = validateIndex(JSON.parse(new TextDecoder().decode(text)), expected, index.text_profile);if (controller.signal.aborted) throw aborted();chapters = loaded;return loaded;})().finally(() => {clearTimeout(timer);indexPromise = null;if (loadController === controller) loadController = null;});return indexPromise;}if (typeof self !== "undefined" && typeof self.postMessage === "function") {self.onmessage = async ({ data }) => {if (data.type === "init") { configuration = data.configuration; return; }if (data.type === "cancel") { active++; session = null; loadController?.abort(); return; }const token = ++active, current = () => token === active;try {let offset = 0;if (data.type === "search") {session = null;const query = String(data.query || "").trim().replace(/\s+/gu, " ");if (!query || query.length > 2048) throw new Error("请输入 1–2048 个字符");// A cancelled download must settle before a later search retries it.if (loadController?.signal.aborted) await indexPromise.catch(() => {});const book = await loadIndex();if (!current()) return;const counts = await countMatches(book, query, current, async partial => {if (!current()) return;if (current()) self.postMessage({ id: data.id, progress: true,total: partial.total, scanned: partial.scanned, chapters: book.length,offset: 0, pageSize: PAGE_SIZE, results: partial.firstPage.slice() });});session = { ...counts, query, id: data.id };} else if (data.type === "page") {if (!session || data.session !== session.id) throw aborted();offset = Math.max(0, Math.min(Math.floor(data.offset / PAGE_SIZE) * PAGE_SIZE,Math.max(0, Math.ceil(session.total / PAGE_SIZE) - 1) * PAGE_SIZE));} else return;const result = offset ? await resultPage(chapters, session.query, session.counts, offset, current) : session.firstPage.slice();if (current()) self.postMessage({ id: data.id, session: session.id, total: session.total,offset, pageSize: PAGE_SIZE, results: result });} catch (error) {if (current()) self.postMessage({ id: data.id, error: error.name === "AbortError"? "全文搜索已取消或加载超时,请重试" : error.message });}};}3 unmodified lines45678910111222 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691703 unmodified linesimport {isSearchIndexProxyURL} from "../reader-chapter-search-proxy-url.mjs";import {validateIndex} from "../reader-chapter-search-index.mjs";/** @param {ReadableStream<Uint8Array<ArrayBuffer>> | null} stream @param {number} limit @param {AbortSignal} signal */async function readBounded(stream, limit, signal) {if (!stream) throw new Error("全文搜索索引无效");const reader = stream.getReader(), chunks = [];let size = 0;const cancel = () => reader.cancel().catch(() => {});22 unmodified lines}/** @typedef {import('../reader-chapter-search-index.mjs').ExpectedChapter} ExpectedChapter *//** @typedef {{url: string, bytes: number, sha256: string, text_profile?: string | undefined}} IndexReference *//** @typedef {{index: IndexReference, chapters: ExpectedChapter[]}} Configuration *//** @typedef {Awaited<ReturnType<typeof countMatches>> & {query: string, id: number}} SearchSession *//** @typedef {{type: 'init', configuration: Configuration} | {type: 'cancel'} |* {type: 'search', id: number, query: unknown} | {type: 'page', id: number, session: number, offset: number}} ChapterMessage *//** @param {unknown} value @returns {value is Record<string, unknown>} */function isRecord(value) { return value !== null && typeof value === 'object'; }/** @param {unknown} value @returns {value is Configuration} */function isConfiguration(value) {return isRecord(value) && isRecord(value.index) && typeof value.index.url === 'string' &&typeof value.index.bytes === 'number' && typeof value.index.sha256 === 'string' &&(value.index.text_profile === undefined || typeof value.index.text_profile === 'string') &&Array.isArray(value.chapters) && value.chapters.every(chapter => isRecord(chapter) &&typeof chapter.index === 'number' && typeof chapter.path === 'string');}/** @param {unknown} value @returns {value is ChapterMessage} */function isMessage(value) {if (!isRecord(value)) return false;if (value.type === 'init') return isConfiguration(value.configuration);if (value.type === 'cancel') return true;if (value.type === 'search') return typeof value.id === 'number';return value.type === 'page' && typeof value.id === 'number' && typeof value.session === 'number' && typeof value.offset === 'number';}/** @type {Configuration | undefined} */let configuration;/** @type {Promise<import('../reader-chapter-search-core.mjs').SearchChapter[]> | undefined} */let indexPromise;/** @type {import('../reader-chapter-search-core.mjs').SearchChapter[] | undefined} */let chapters;/** @type {SearchSession | null} */let session = null;/** @type {AbortController | null} */let loadController = null;let active = 0;/** @param {IndexReference} index @param {URL} url */function validateIndexReference(index,url) {if (!isSearchIndexProxyURL(url, self.location.origin) ||!Number.isSafeInteger(index.bytes) || index.bytes <= 0 || index.bytes > PACKED_LIMIT ||!/^[0-9a-f]{64}$/.test(index.sha256)) throw new Error("全文搜索索引无效");}/** @param {AbortController} controller @returns {Promise<import('../reader-chapter-search-core.mjs').SearchChapter[]>} */async function fetchIndex(controller) {if (!configuration) throw new Error("全文搜索索引无效");const { index, chapters: expected } = configuration;const url = new URL(index.url, self.location.origin);validateIndexReference(index,url);const response = await fetch(url, { signal: controller.signal, credentials: "same-origin" });if (!response.ok) throw new Error(`全文搜索加载失败(HTTP ${response.status}),请重试`);const bytes = await readBounded(response.body, PACKED_LIMIT, controller.signal);const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));const sha = [...digest].map(value => value.toString(16).padStart(2, "0")).join("");if (bytes.length !== index.bytes || sha !== index.sha256) throw new Error("全文搜索索引校验失败,请重试");const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));const text = await readBounded(stream, TEXT_LIMIT, controller.signal);/** @type {unknown} */const raw = JSON.parse(new TextDecoder().decode(text));const loaded = validateIndex(raw, expected, index.text_profile);if (controller.signal.aborted) throw aborted();chapters = loaded;return loaded;}async function loadIndex() {if (chapters) return chapters;if (indexPromise) return indexPromise;const controller = new AbortController();loadController = controller;const timer = setTimeout(() => controller.abort(), 60000);indexPromise = fetchIndex(controller).finally(() => {clearTimeout(timer);indexPromise = undefined;if (loadController === controller) loadController = null;});return indexPromise;}/** @param {string} query @param {number} id @param {() => boolean} current @param {{postMessage(message: unknown): void}} scope */async function beginSearch(query,id,current,scope) {session = null;query = String(query || "").trim().replace(/\s+/gu, " ");if (!query || query.length > 2048) throw new Error("请输入 1–2048 个字符");if (loadController?.signal.aborted) await indexPromise?.catch(() => {});const book=await loadIndex();if (!current()) return;const counts=await countMatches(book,query,current,async partial=>{if (current()) scope.postMessage({id,progress:true,total:partial.total,scanned:partial.scanned,chapters:book.length,offset:0,pageSize:PAGE_SIZE,results:partial.firstPage.slice()});});session={...counts,query,id};}/** @param {number} requested @param {number} expected */function pageOffset(requested,expected) {if (!session || expected !== session.id) throw aborted();return Math.max(0,Math.min(Math.floor(requested/PAGE_SIZE)*PAGE_SIZE,Math.max(0,Math.ceil(session.total/PAGE_SIZE)-1)*PAGE_SIZE));}/** @param {unknown} error */function requestError(error) {const detail=error instanceof Error ? error : new Error(String(error));return detail.name === "AbortError" ? "全文搜索已取消或加载超时,请重试" : detail.message;}/** @param {Extract<ChapterMessage,{type:'search'|'page'}>} data @param {{postMessage(message: unknown): void}} scope */async function handleRequest(data,scope) {const token=++active,current=()=>token===active;try {let offset=0;if (data.type === "search") {await beginSearch(String(data.query || ""),data.id,current,scope);if (!current()) return;} else offset=pageOffset(data.offset,data.session);if (!session || !chapters) throw aborted();const result=offset ? await resultPage(chapters,session.query,session.counts,offset,current) : session.firstPage.slice();if (current()) scope.postMessage({id:data.id,session:session.id,total:session.total,offset,pageSize:PAGE_SIZE,results:result});} catch (error) {if (current()) scope.postMessage({id:data.id,error:requestError(error)});}}if (typeof self !== "undefined" && typeof self.postMessage === "function") {const scope = self;scope.onmessage = event => {/** @type {unknown} */const data=event.data;if (!isMessage(data)) {if (isRecord(data) && data.type === 'init') configuration=undefined;if (isRecord(data) && typeof data.id === 'number') scope.postMessage({id:data.id,error:'全文搜索索引无效'});return;}if (data.type === "init") { configuration = data.configuration; return; }if (data.type === "cancel") { active++; session = null; loadController?.abort(); return; }return handleRequest(data,scope);};}
309 unmodified lines310311312313314315309 unmodified lines"kind": "excluded","reason": "Visual acceptance requires external pinned screenshot baselines not present here."},"tests/reader/chapter-search/test_reader_chapter_search.mjs": {"kind": "direct","source": "@reader-workflow"309 unmodified lines310311312313314315316317318319309 unmodified lines"kind": "excluded","reason": "Visual acceptance requires external pinned screenshot baselines not present here."},"tests/reader/chapter-search/test_reader_chapter_worker.mjs": {"kind": "script","source": "scripts/reader/check_chapter_search_worker_coverage.mjs"},"tests/reader/chapter-search/test_reader_chapter_search.mjs": {"kind": "direct","source": "@reader-workflow"
5 unmodified lines678910115 unmodified lines["tests.gates.test_static_checks.StaticGateTests.test_adapter_coverage_gate_fails_when_contract_tests_are_removed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_core_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_exact_signature_and_complexity","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_proxy_coverage_gate_fails_closed",5 unmodified lines6789101112135 unmodified lines["tests.gates.test_static_checks.StaticGateTests.test_adapter_coverage_gate_fails_when_contract_tests_are_removed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_core_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_worker_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_worker_strict_complexity_and_network_contract","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_exact_signature_and_complexity","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_proxy_coverage_gate_fails_closed",
5 unmodified lines678910115 unmodified lines["tests.gates.test_static_checks.StaticGateTests.test_adapter_coverage_gate_fails_when_contract_tests_are_removed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_core_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_exact_signature_and_complexity","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_proxy_coverage_gate_fails_closed",5 unmodified lines6789101112135 unmodified lines["tests.gates.test_static_checks.StaticGateTests.test_adapter_coverage_gate_fails_when_contract_tests_are_removed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_core_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_worker_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_worker_strict_complexity_and_network_contract","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_coverage_gate_fails_closed","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_exact_signature_and_complexity","tests.gates.test_static_checks.StaticGateTests.test_chapter_search_proxy_coverage_gate_fails_closed",
2979 unmodified lines2980298129822983298429852979 unmodified linessource.write_text(source.read_text() + f"\nfunction overlyComplex(value) {{ {choices} return 0; }}\n")self.assert_check(self.run_check(*check), False, "complexity")def test_chapter_search_index_coverage_gate_fails_closed(self):paths=['static/reader/search/reader-chapter-search-core.mjs','static/reader/search/reader-chapter-search-proxy-url.mjs',2979 unmodified lines298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930502979 unmodified linessource.write_text(source.read_text() + f"\nfunction overlyComplex(value) {{ {choices} return 0; }}\n")self.assert_check(self.run_check(*check), False, "complexity")def test_chapter_search_worker_coverage_gate_fails_closed(self):paths = ['static/reader/search/reader-chapter-search-core.mjs','static/reader/search/reader-chapter-search-proxy-url.mjs','static/reader/search/reader-chapter-search-index.mjs','static/reader/search/workers/reader-chapter-search-worker.mjs','tests/reader/chapter-search/test_reader_chapter_worker.mjs','scripts/reader/check_chapter_search_worker_coverage.mjs', 'scripts/check_tap_contracts.mjs']for name in paths:target=self.root / name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(ROOT / name,target)check=['node',paths[5]]message='Chapter search Worker requires its passing contract and exactly one source row'self.assert_check(self.run_check(*check),True,'reader-chapter-search-worker.mjs |')test=self.root / paths[4];original=test.read_text()marker='chapter Worker: transport, integrity, cancellation, retry and paging passed'self.assertEqual(original.count(marker),1);test.write_text(original.replace(marker,'renamed completion marker'))self.assert_check(self.run_check(*check),False,message)test.write_text(original+"\nthrow new Error('injected chapter Worker failure');\n")self.assert_check(self.run_check(*check),False,'injected chapter Worker failure')test.unlink();self.assert_check(self.run_check(*check),False,message);test.write_text(original)test.write_text(original+'\nconsole.log("end of coverage report");\n')self.assert_check(self.run_check(*check),False,message);test.write_text(original)gate=self.root / paths[5];gate_original=gate.read_text()for minimum in ('[100.01, 92, 100]', '[100, 101, 100]', '[100, 92, 100.01]'):self.assertEqual(gate_original.count('[100, 92, 100]'),1)gate.write_text(gate_original.replace('[100, 92, 100]',minimum))self.assert_check(self.run_check(*check),False,message)self.assertEqual(gate_original.count('reader-chapter-search-worker\\.mjs'),1)gate.write_text(gate_original.replace('reader-chapter-search-worker\\.mjs','missing-chapter-worker\\.mjs'))self.assert_check(self.run_check(*check),False,message)def test_chapter_search_worker_strict_complexity_and_network_contract(self):paths=['static/reader/search/reader-chapter-search-core.mjs','static/reader/search/reader-chapter-search-proxy-url.mjs','static/reader/search/reader-chapter-search-index.mjs','static/reader/search/workers/reader-chapter-search-worker.mjs']project=load_type_config('jsconfig.chapter-worker-strict.json')self.assertTrue(project['compilerOptions']['strict'])self.assertEqual(project['compilerOptions']['lib'],['esnext','webworker'])self.assertIn(paths[3],project['files'])self.assertIn('tsc --project config/types/jsconfig.chapter-worker-strict.json',json.loads((ROOT / 'package.json').read_text())['scripts']['types'])for name in paths:target=self.root / name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(ROOT / name,target)config=self.root / 'jsconfig.json';config.write_text(json.dumps(project))check=['node',ROOT / 'node_modules/typescript/bin/tsc','--project',config]self.assert_check(self.run_check(*check),True,'')local=self.root / paths[3];original=local.read_text()annotation='/** @param {IndexReference} index @param {URL} url */'self.assertEqual(original.count(annotation),1);local.write_text(original.replace(annotation,''))self.assert_check(self.run_check(*check),False,'TS7006');local.write_text(original)lint=['node',ROOT / 'node_modules/eslint/bin/eslint.js','--config',ROOT / 'eslint.config.mjs',local,'--rule','complexity: [error, 10]','--max-warnings','0']self.assert_check(self.run_check(*lint),True,'')choices=''.join(f'if (value === {n}) return {n}; ' for n in range(11))local.write_text(original+f'\nfunction overlyComplex(value) {{ {choices} return 0; }}\n')self.assert_check(self.run_check(*lint),False,'complexity')if (ROOT / 'Dockerfile').exists():self.assertIn('isSearchIndexProxyURL(url, self.location.origin)',original)self.assertIn('credentials: "same-origin"',original)self.assertNotIn('credentials: "omit"',original)else:self.assertIn('isSearchIndexProxyURL(url, "https://voiceofml-search.hf.space")',original)self.assertIn('credentials: "omit"',original)self.assertNotIn('credentials: "same-origin"',original)def test_chapter_search_index_coverage_gate_fails_closed(self):paths=['static/reader/search/reader-chapter-search-core.mjs','static/reader/search/reader-chapter-search-proxy-url.mjs',
526 unmodified lines527528529530531532526 unmodified linesself.assertIn("node scripts/reader/check_chapter_search_core_coverage.mjs", dockerfile)self.assertIn("node scripts/reader/check_chapter_search_proxy_coverage.mjs", dockerfile)self.assertIn("node scripts/reader/check_chapter_search_index_coverage.mjs", dockerfile)self.assertIn("node --test tests/search/baselines/test_search_response_validation_baseline.mjs", dockerfile)self.assertIn("node --test tests/search/baselines/test_search_stable_id_baseline.mjs", dockerfile)self.assertIn("COPY --from=source-check-node /check/ /check/", dockerfile)526 unmodified lines527528529530531532533526 unmodified linesself.assertIn("node scripts/reader/check_chapter_search_core_coverage.mjs", dockerfile)self.assertIn("node scripts/reader/check_chapter_search_proxy_coverage.mjs", dockerfile)self.assertIn("node scripts/reader/check_chapter_search_index_coverage.mjs", dockerfile)self.assertIn("node scripts/reader/check_chapter_search_worker_coverage.mjs", dockerfile)self.assertIn("node --test tests/search/baselines/test_search_response_validation_baseline.mjs", dockerfile)self.assertIn("node --test tests/search/baselines/test_search_stable_id_baseline.mjs", dockerfile)self.assertIn("COPY --from=source-check-node /check/ /check/", dockerfile)
78 unmodified lines79808182838478 unmodified linesassert.equal(queryBigramFilters("A"), null);assert.equal((await countMatches([chapter], "手机", () => true)).total, 1);}// Force a cooperative yield without timing dependence. The currentness guard// executes inside the real scan; after the yield it must check cancellation.{78 unmodified lines79808182838485868788899091929394959678 unmodified linesassert.equal(queryBigramFilters("A"), null);assert.equal((await countMatches([chapter], "手机", () => true)).total, 1);}// Version-1 historical JSON can contain array-like filter properties rather// than the decoded Uint8Array; preserve the old coercion and bit decisions.{const filters = queryBigramFilters("手机");const bloom = Object.assign({length:32}, Object.fromEntries(Array.from({length:32}, (_, i) => [i,255])));const chapter = {index:1,title:42,path:"one",text:"手机",bigramFilter:bloom};assert.equal(chapterMayContainBigrams(chapter, filters), true);for (let i=0;i<32;i++) bloom[i]=0;assert.equal(chapterMayContainBigrams(chapter, filters), false);chapter.bigramFilter = {};assert.equal(chapterMayContainBigrams(chapter, filters), false);}// Force a cooperative yield without timing dependence. The currentness guard// executes inside the real scan; after the yield it must check cancellation.{
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170import assert from "node:assert/strict";import {webcrypto} from "node:crypto";import {gzipSync} from "node:zlib";
// The real module's message handler, loader, SHA verification and search core// execute with a controlled Worker-like global and a deterministic transport.const isSpace = true;const localOrigin = "https://reader.example";const proxyOrigin = isSpace ? localOrigin : "https://voiceofml-search.hf.space";const messages = [], requests = [];const scope = {location: {origin: localOrigin}, postMessage: value => messages.push(structuredClone(value))};Object.defineProperty(globalThis, "crypto", {configurable: true, value: webcrypto});globalThis.self = scope;let responseMode = "valid", packed, firstRead, firstFetch, releaseFetch, expire;let streamCancelled = false;const nativeSetTimeout = globalThis.setTimeout;globalThis.setTimeout = (fn, delay, ...args) => { if (delay === 60000) expire = fn; return nativeSetTimeout(fn, delay, ...args);};globalThis.fetch = async (url, options) => { requests.push({url: String(url), credentials: options.credentials, signal: options.signal}); if (responseMode === "http") return new Response("unavailable", {status: 503}); if (responseMode === "null") return new Response(null, {status: 204}); if (responseMode === "throw") throw new Error("transport failed"); if (responseMode === "throw-string") throw "transport string failure"; if (responseMode === "stream-error") return new Response(new ReadableStream({ pull() { throw new Error("stream read failed"); } })); if (responseMode === "wrong-bytes") return new Response(packed.subarray(1)); if (responseMode === "too-large") { const chunk = new Uint8Array(16 * 1024 * 1024); return new Response(new ReadableStream({ pull(controller) { controller.enqueue(chunk); }, cancel() { streamCancelled = true; } })); } if (responseMode === "shared-fetch") { firstFetch(); return new Promise(resolve => { releaseFetch = () => resolve(new Response(packed.subarray(1))); }); } if (responseMode === "held-fetch") { responseMode = "valid"; firstFetch(); return new Promise((resolve, reject) => { options.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), {once: true}); }); } if (responseMode === "held-stream") { responseMode = "valid"; return new Response(new ReadableStream({ pull() { firstRead(); return new Promise(() => {}); }, cancel() { streamCancelled = true; throw new Error("injected stream cancel error"); } })); } return new Response(packed);};await import("../../../static/reader/search/workers/reader-chapter-search-worker.mjs");const send = async data => { await scope.onmessage({data}); };const latest = () => messages.at(-1);let id = 0;async function search(query = "needle") { await send({type:"search", id:++id, query}); return latest(); }async function buildConfiguration(data, chapters = [{index:1, path:"one", title:"First"}]) { packed = gzipSync(Buffer.from(JSON.stringify(data))); const sha256 = Buffer.from(await crypto.subtle.digest("SHA-256", packed)).toString("hex"); return {index:{url:proxyOrigin + "/api/reader-content?url=source", bytes:packed.length, sha256}, chapters};}// Legacy manifests may use non-string titles and version-1 filters represented// as array-like JSON. Neither was rejected by the previous implementation.const legacyFilter = Object.assign({length:32}, Object.fromEntries(Array.from({length:32}, (_, i) => [i,255])));const goodIndex = {version:1, kind:"epub-search-index", chapters:[ {index:1,path:"one",text:"needle ".repeat(120)+"手机",bigramFilter:legacyFilter}]};let config = await buildConfiguration(goodIndex, [{index:1,path:"one",title:42}]);assert.match((await search()).error, /索引无效/);await send({type:"init", configuration:null});assert.match((await search()).error, /索引无效/);const before = messages.length;await send(null); await send({type:"cancel"});assert.equal(messages.length, before);await send({type:"page", id:++id, session:null, offset:"bad"});assert.match(latest().error, /索引无效/);await send({type:"unknown", id:++id});assert.match(latest().error, /索引无效/);for (const index of [ {...config.index, url:"https://evil.example/api/reader-content"}, {...config.index, bytes:0}, {...config.index, bytes:64*1024*1024+1}, {...config.index, sha256:"bad"}, {...config.index, url:proxyOrigin+"/api/reader-bucket-resource?path=../bad"}]) { await send({type:"init", configuration:{...config,index}}); const count = requests.length; assert.match((await search()).error, /索引无效/); assert.equal(requests.length, count);}for (const [mode, expected] of [["http",/HTTP 503/],["null",/索引无效/], ["throw",/transport failed/],["throw-string",/transport string failure/], ["stream-error",/stream read failed/],["wrong-bytes",/校验失败/],["too-large",/超过大小限制/]]) { responseMode = mode; await send({type:"init", configuration:config}); assert.match((await search()).error, expected, mode);}assert.equal(streamCancelled, true);// Abort while the response stream is blocked in read(): the Worker must cancel// the underlying stream and a subsequent fetch must still be possible.responseMode = "held-stream"; streamCancelled = false;await send({type:"init", configuration:config});let reading = new Promise(resolve => { firstRead = resolve; });const streamId = ++id, streamSearch = send({type:"search", id:streamId, query:"needle"});await reading; await send({type:"cancel"}); await streamSearch;assert.equal(streamCancelled, true);assert.equal(messages.some(value => value.id === streamId), false);responseMode = "valid";config = await buildConfiguration({...goodIndex, kind:"invalid"});await send({type:"init", configuration:config});assert.match((await search()).error, /索引不完整/);config = await buildConfiguration(goodIndex, [{index:1,path:"one",title:42}]);await send({type:"init", configuration:config});assert.match((await search(" ")).error, /1–2048/);assert.match((await search("x".repeat(2049))).error, /1–2048/);
// Overlapping searches share one in-flight load; if that load fails, only the// latest request receives the error and a later search is allowed to retry.responseMode = "shared-fetch";let sharedStarted = new Promise(resolve => { firstFetch = resolve; });const requestCount = requests.length;const oldId = ++id, old = send({type:"search", id:oldId, query:"needle"});await sharedStarted;const currentId = ++id, current = send({type:"search", id:currentId, query:"手机"});assert.equal(requests.length, requestCount + 1);releaseFetch(); await Promise.all([old, current]);assert.equal(messages.some(value => value.id === oldId), false);assert.equal(latest().id, currentId); assert.match(latest().error, /校验失败/);
// Drive the actual 60-second load deadline deterministically, without waiting.responseMode = "held-fetch";let timedStart = new Promise(resolve => { firstFetch = resolve; });const timedId = ++id, timed = send({type:"search", id:timedId, query:"needle"});await timedStart; assert.equal(typeof expire, "function"); expire(); await timed;assert.equal(latest().id, timedId); assert.match(latest().error, /取消或加载超时/);
// Cancel while fetch is pending and retry before the aborted promise settles.responseMode = "held-fetch";let started = new Promise(resolve => { firstFetch = resolve; });const abandonedId = ++id, abandoned = send({type:"search", id:abandonedId, query:"needle"});await started; await send({type:"cancel"});const resumedId = ++id, resumed = send({type:"search", id:resumedId, query:"needle"});await Promise.all([abandoned, resumed]);assert.equal(messages.some(value => value.id === abandonedId), false);assert.equal(latest().id, resumedId); assert.equal(latest().total, 120);assert.equal(latest().results.length, 50);assert.equal(latest().results[0].location, "第 1 章 · 42");const loadedRequests = requests.length;const cached = await search("手机");assert.equal(cached.total, 1);assert.equal(requests.length, loadedRequests); // the validated index is cachedawait send({type:"search", id:resumedId, query:"needle"});assert.equal(latest().total, 120);assert.equal(requests.at(-1).credentials, isSpace ? "same-origin" : "omit");assert.ok(requests.at(-1).url.startsWith(proxyOrigin));await send({type:"page", id:++id, session:resumedId, offset:100});assert.equal(latest().offset, 100); assert.equal(latest().results.length, 20);await send({type:"page", id:++id, session:resumedId, offset:9999});assert.equal(latest().offset, 100); assert.equal(latest().results.length, 20);await send({type:"page", id:++id, session:999, offset:0});assert.match(latest().error, /取消/);await send({type:"cancel"});await send({type:"page", id:++id, session:resumedId, offset:0});assert.match(latest().error, /取消/);globalThis.setTimeout = nativeSetTimeout;console.log("chapter Worker: transport, integrity, cancellation, retry and paging passed");Dockerfile+1
config/types/jsconfig.chapter-worker-strict.jsonAdded+19
package.json+1-1
quality/baselines/strict-inventory-debt.json-1
scripts/check_strict_inventory.py+4-2
scripts/reader/check_chapter_search_worker_coverage.mjsAdded+28
static/reader/search/reader-chapter-search-core.mjs+22-5
static/reader/search/workers/reader-chapter-search-worker.mjs+118-52
tests/gates/ci-test-inventory.json+4
tests/gates/static_gate_ids.github.json+2
tests/gates/static_gate_ids.hf.json+2
tests/gates/test_static_checks.py+65
tests/gates/test_static_contract.py+1
tests/reader/chapter-search/test_reader_chapter_search.mjs+12
tests/reader/chapter-search/test_reader_chapter_worker.mjsAdded+170