vomebook commited on
Commit ·
0c658c5
1
Parent(s): 875f1ae
Serve reader dependencies locally and support build proxies
Browse files- scripts/build/build_static_assets.mjs +1 -1
- scripts/build/check_reader_release.mjs +19 -0
- scripts/build/copy_reader_vendor.mjs +144 -51
- scripts/build/fetch_foliate_reader.mjs +31 -17
- scripts/reader/check_reader_media_coverage.mjs +14 -0
- static/reader-resources.js +20 -4
- static/reader.js +1 -1
- static/sw.js +10 -4
- tests/gates/ci-test-inventory.json +12 -0
- tests/gates/test_static_contract.py +5 -7
- tests/reader/copy_reader_vendor.test.mjs +252 -0
- tests/reader/media/test_ruffle_closure.mjs +28 -0
- tests/reader/test_foliate_proxy.mjs +114 -0
- tests/service_worker/test_ruffle_retention.js +35 -0
scripts/build/build_static_assets.mjs
CHANGED
|
@@ -50,6 +50,6 @@ for (const filename of ["index.html", "reader.html", "sw.js"]) {
|
|
| 50 |
if (filename === "index.html") content = stripBundledScripts(content);
|
| 51 |
content = rewrite(content, filename);
|
| 52 |
if (filename === "sw.js") content = content.replace(/CURRENT_HASHED_ASSETS\s*=\s*\[\]/,
|
| 53 |
-
"CURRENT_HASHED_ASSETS=" + JSON.stringify([...replacements.values()].filter(url => url.startsWith("/")).concat([...currentVendorAssets], resources.djvuDecoderAssets("/static/"))));
|
| 54 |
writeFileSync(path, content);
|
| 55 |
}
|
|
|
|
| 50 |
if (filename === "index.html") content = stripBundledScripts(content);
|
| 51 |
content = rewrite(content, filename);
|
| 52 |
if (filename === "sw.js") content = content.replace(/CURRENT_HASHED_ASSETS\s*=\s*\[\]/,
|
| 53 |
+
"CURRENT_HASHED_ASSETS=" + JSON.stringify([...replacements.values()].filter(url => url.startsWith("/")).concat([...currentVendorAssets], resources.djvuDecoderAssets("/static/"), resources.ruffleAssets("/static/"))));
|
| 54 |
writeFileSync(path, content);
|
| 55 |
}
|
scripts/build/check_reader_release.mjs
CHANGED
|
@@ -54,7 +54,26 @@ function checkBehavior(root) {
|
|
| 54 |
}
|
| 55 |
}
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
function checkAssets(output, hashed = false) {
|
|
|
|
| 58 |
const djvuFiles = {
|
| 59 |
"release-a03526f445b4-a99c0e299e95/scalar/djvu_rs.js": "4174a8f1da0f63206a6c3aa447e396ae24c3926ff5c9ed72fc7184c627513e1f",
|
| 60 |
"release-a03526f445b4-a99c0e299e95/simd128/djvu_rs.js": "4174a8f1da0f63206a6c3aa447e396ae24c3926ff5c9ed72fc7184c627513e1f",
|
|
|
|
| 54 |
}
|
| 55 |
}
|
| 56 |
|
| 57 |
+
export function checkRuffleAssets(output) {
|
| 58 |
+
const expected = {
|
| 59 |
+
"ruffle.js": "26036a94567088dfb3de88a759e8ed10a4cea07b29500af36f345eef42420098",
|
| 60 |
+
"core.ruffle.16d61072ac7fdc4d5013.js": "d27c6bdce2a34afb32e8dfa40970bc7e86cbcb912f92db7eb3e1ac70e943bd82",
|
| 61 |
+
"core.ruffle.994eeef0a471a88cd0e3.js": "d89e507ee60d550629e9229aa1e4dd4f9e75ec7db271e0135cbc87dab042ea51",
|
| 62 |
+
"172de42e6619eac8f371.wasm": "1ed33b9b71a6b01b9aafafed660be343ffeb2d246c5d79e6425a32bf93e38207",
|
| 63 |
+
"878d548199cddef07035.wasm": "af9b6a13a8f5e8d305bc3ce28a4edf3f6242df1183e8576ad4ca086e9f21eaea",
|
| 64 |
+
"LICENSE_APACHE": "62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a",
|
| 65 |
+
"LICENSE_MIT": "4de9338a7879c68e911742a7d691f0797ff1ef8d8a6fb978b0c711e258fe959c"
|
| 66 |
+
};
|
| 67 |
+
assert(JSON.stringify(Object.keys(expected)) === JSON.stringify(resources.ruffleArchive.files), "Ruffle inventory mismatch");
|
| 68 |
+
for (const [file, digest] of Object.entries(expected)) {
|
| 69 |
+
const target = path.join(output, resources.ruffleArchive.directory, file);
|
| 70 |
+
assert(fs.existsSync(target) && fs.statSync(target).isFile() && hash(target) === digest,
|
| 71 |
+
`Ruffle asset missing or integrity mismatch: ${target}`);
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
function checkAssets(output, hashed = false) {
|
| 76 |
+
checkRuffleAssets(output);
|
| 77 |
const djvuFiles = {
|
| 78 |
"release-a03526f445b4-a99c0e299e95/scalar/djvu_rs.js": "4174a8f1da0f63206a6c3aa447e396ae24c3926ff5c9ed72fc7184c627513e1f",
|
| 79 |
"release-a03526f445b4-a99c0e299e95/simd128/djvu_rs.js": "4174a8f1da0f63206a6c3aa447e396ae24c3926ff5c9ed72fc7184c627513e1f",
|
scripts/build/copy_reader_vendor.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
import { createHash } from "node:crypto";
|
| 2 |
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
| 3 |
-
import { get } from "node:https";
|
| 4 |
import { dirname, join } from "node:path";
|
| 5 |
import { gunzipSync } from "node:zlib";
|
| 6 |
import { createRequire } from "node:module";
|
|
|
|
| 7 |
const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js"));
|
| 8 |
|
| 9 |
const output = process.argv[2] || "static/vendor";
|
|
@@ -14,85 +15,177 @@ const foliateOutput = foliateOutputArgument >= 0
|
|
| 14 |
? process.argv[foliateOutputArgument + 1]
|
| 15 |
: process.argv.includes("--refresh-foliate")
|
| 16 |
? join(process.cwd(), "static/foliate-reader/vendor") : null;
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
return new Promise((resolve, reject) => {
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
});
|
| 34 |
-
request.
|
| 35 |
-
request.on("error", reject);
|
| 36 |
});
|
| 37 |
}
|
| 38 |
|
| 39 |
-
async function downloadWithRetry(url) {
|
| 40 |
let lastError;
|
| 41 |
for (let attempt = 0; attempt < 4; attempt++) {
|
| 42 |
-
|
|
|
|
|
|
|
| 43 |
catch (error) {
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
}
|
| 47 |
}
|
| 48 |
throw lastError;
|
| 49 |
}
|
| 50 |
|
| 51 |
async function main() {
|
| 52 |
-
const
|
| 53 |
-
const
|
| 54 |
-
|
| 55 |
-
const
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
const header = tar.subarray(offset, offset + 512), name = header.subarray(0, 100).toString().replace(/\0.*$/, "");
|
| 58 |
if (!name) break;
|
| 59 |
-
const
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
const target = join(output, relative);
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
if (foliateOutput)
|
| 66 |
-
const foliateTarget = join(foliateOutput, "pdfjs", relative);
|
| 67 |
-
mkdirSync(dirname(foliateTarget), { recursive: true });
|
| 68 |
-
writeFileSync(foliateTarget, tar.subarray(offset + 512, offset + 512 + size));
|
| 69 |
-
}
|
| 70 |
}
|
| 71 |
offset += 512 + Math.ceil(size / 512) * 512;
|
| 72 |
}
|
| 73 |
-
for (const
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
| 78 |
const versioned = path.slice("vendor/".length);
|
| 79 |
-
|
| 80 |
-
writeFileSync(join(output, versioned), bytes);
|
| 81 |
if (foliateOutput && (name === "pdf" || name === "pdfWorker")) {
|
| 82 |
const filename = name === "pdf" ? "pdf.mjs" : "pdf.worker.mjs";
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
rmSync(join(foliateOutput, "pdfjs", filename + ".map"), { force: true });
|
| 86 |
}
|
| 87 |
}
|
| 88 |
-
if (foliateOutput) for (const
|
| 89 |
-
const bytes =
|
| 90 |
-
const actual = createHash("sha256").update(bytes).digest("hex");
|
| 91 |
-
if (actual !== expected) throw new Error(`${url}: SHA-256 ${actual} does not match ${expected}`);
|
| 92 |
const target = join(foliateOutput, file);
|
|
|
|
|
|
|
|
|
|
| 93 |
mkdirSync(dirname(target), { recursive: true });
|
| 94 |
writeFileSync(target, bytes);
|
| 95 |
}
|
|
|
|
| 96 |
}
|
| 97 |
|
| 98 |
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
|
|
|
| 1 |
import { createHash } from "node:crypto";
|
| 2 |
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
| 3 |
+
import { Agent, get } from "node:https";
|
| 4 |
import { dirname, join } from "node:path";
|
| 5 |
import { gunzipSync } from "node:zlib";
|
| 6 |
import { createRequire } from "node:module";
|
| 7 |
+
import { setTimeout as delay } from "node:timers/promises";
|
| 8 |
const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js"));
|
| 9 |
|
| 10 |
const output = process.argv[2] || "static/vendor";
|
|
|
|
| 15 |
? process.argv[foliateOutputArgument + 1]
|
| 16 |
: process.argv.includes("--refresh-foliate")
|
| 17 |
? join(process.cwd(), "static/foliate-reader/vendor") : null;
|
| 18 |
+
// proxyEnv is supported by Node 22.21+, 24.5+, and later major versions.
|
| 19 |
+
const [major, minor] = process.versions.node.split(".").map(Number);
|
| 20 |
+
if (major < 22 || (major === 22 && minor < 21) || major === 23 || (major === 24 && minor < 5))
|
| 21 |
+
throw new Error("Node.js 22.21+, 24.5+, or later is required for proxy support");
|
| 22 |
+
const agent = new Agent({ proxyEnv: process.env });
|
| 23 |
+
// Per attempt, across redirects; allow ample room for the compressed PDF and Ruffle archives.
|
| 24 |
+
const DOWNLOAD_DEADLINE_MS = 180000;
|
| 25 |
+
const MAX_DOWNLOAD_BYTES = 128 * 1024 * 1024;
|
| 26 |
+
// Pinned PDF.js and Ruffle tars are ~36.3 MiB and ~29.3 MiB respectively.
|
| 27 |
+
const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024;
|
| 28 |
+
function download(url, signal, redirects = 0) {
|
| 29 |
return new Promise((resolve, reject) => {
|
| 30 |
+
let parsed;
|
| 31 |
+
try { parsed = new URL(url); } catch { return reject(new Error("Invalid download URL")); }
|
| 32 |
+
if (parsed.protocol !== "https:") return reject(new Error("Download requires HTTPS"));
|
| 33 |
+
const request = get(parsed, { agent, signal }, (response) => {
|
| 34 |
+
if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location && redirects < 5) {
|
| 35 |
+
response.resume();
|
| 36 |
+
let next;
|
| 37 |
+
try { next = new URL(response.headers.location, parsed); }
|
| 38 |
+
catch { return reject(new Error("Invalid download redirect")); }
|
| 39 |
+
return download(next, signal, redirects + 1).then(resolve, reject);
|
| 40 |
+
}
|
| 41 |
+
if (response.statusCode !== 200) {
|
| 42 |
+
response.resume();
|
| 43 |
+
return reject(new Error(`Download failed (HTTP ${response.statusCode})`));
|
| 44 |
+
}
|
| 45 |
+
const length = response.headers["content-length"];
|
| 46 |
+
if (length && /^\d+$/.test(length) && Number(length) > MAX_DOWNLOAD_BYTES) {
|
| 47 |
+
reject(new Error("Download response too large"));
|
| 48 |
+
response.destroy();
|
| 49 |
+
return;
|
| 50 |
+
}
|
| 51 |
+
const chunks = [];
|
| 52 |
+
let size = 0;
|
| 53 |
+
response.on("data", (chunk) => {
|
| 54 |
+
size += chunk.length;
|
| 55 |
+
if (size > MAX_DOWNLOAD_BYTES) {
|
| 56 |
+
reject(new Error("Download response too large"));
|
| 57 |
+
response.destroy();
|
| 58 |
+
} else chunks.push(chunk);
|
| 59 |
+
});
|
| 60 |
+
response.on("end", () => resolve(Buffer.concat(chunks, size)));
|
| 61 |
+
response.on("error", () => reject(new Error("Download response failed")));
|
| 62 |
+
response.on("aborted", () => reject(new Error("Download response aborted")));
|
| 63 |
});
|
| 64 |
+
request.on("error", () => reject(new Error("Download request failed")));
|
|
|
|
| 65 |
});
|
| 66 |
}
|
| 67 |
|
| 68 |
+
async function downloadWithRetry(url, signal) {
|
| 69 |
let lastError;
|
| 70 |
for (let attempt = 0; attempt < 4; attempt++) {
|
| 71 |
+
signal.throwIfAborted();
|
| 72 |
+
const deadline = AbortSignal.timeout(DOWNLOAD_DEADLINE_MS);
|
| 73 |
+
try { return await download(url, AbortSignal.any([signal, deadline])); }
|
| 74 |
catch (error) {
|
| 75 |
+
signal.throwIfAborted();
|
| 76 |
+
lastError = deadline.aborted ? new Error("Download deadline exceeded") : error;
|
| 77 |
+
if (attempt < 3) await delay(1000 * (2 ** attempt), undefined, { signal });
|
| 78 |
}
|
| 79 |
}
|
| 80 |
throw lastError;
|
| 81 |
}
|
| 82 |
|
| 83 |
async function main() {
|
| 84 |
+
const vendors = Object.entries(resources.vendors);
|
| 85 |
+
const foliateVendors = foliateOutput ? Object.values(resources.foliateVendors) : [];
|
| 86 |
+
const items = [resources.pdfArchive, ...vendors.map(([, value]) => value), ...foliateVendors, resources.ruffleArchive];
|
| 87 |
+
const downloaded = new Array(items.length);
|
| 88 |
+
let next = 0;
|
| 89 |
+
const controller = new AbortController();
|
| 90 |
+
async function worker() {
|
| 91 |
+
while (!controller.signal.aborted && next < items.length) {
|
| 92 |
+
const index = next++;
|
| 93 |
+
try {
|
| 94 |
+
const { url, sha256 } = items[index];
|
| 95 |
+
const bytes = await downloadWithRetry(url, controller.signal);
|
| 96 |
+
const actual = createHash("sha256").update(bytes).digest("hex");
|
| 97 |
+
if (actual !== sha256) throw new Error("SHA-256 mismatch");
|
| 98 |
+
downloaded[index] = bytes;
|
| 99 |
+
} catch (error) {
|
| 100 |
+
if (!controller.signal.aborted) {
|
| 101 |
+
// Index identifies the entry in items without exposing URLs or proxy credentials.
|
| 102 |
+
const message = typeof error?.message === "string" && /^(?:SHA-256 mismatch|Invalid download URL|Download requires HTTPS|Invalid download redirect|Download failed \(HTTP \d+\)|Download response failed|Download response aborted|Download request failed|Download response too large|Download deadline exceeded)$/.test(error.message)
|
| 103 |
+
? error.message : "unexpected error";
|
| 104 |
+
const failure = new Error(`Resource ${index} download failed: ${message}`);
|
| 105 |
+
controller.abort(failure);
|
| 106 |
+
agent.destroy();
|
| 107 |
+
throw failure;
|
| 108 |
+
}
|
| 109 |
+
throw error;
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
await Promise.all(Array.from({ length: Math.min(4, items.length) }, worker));
|
| 114 |
+
const ruffleTar = gunzipSync(downloaded[downloaded.length - 1], { maxOutputLength: MAX_ARCHIVE_BYTES });
|
| 115 |
+
const expectedRuffle = new Set(resources.ruffleArchive.files);
|
| 116 |
+
const extractedRuffle = new Map();
|
| 117 |
+
for (let offset = 0; offset < ruffleTar.length;) {
|
| 118 |
+
if (offset + 512 > ruffleTar.length) throw new Error("Truncated Ruffle archive");
|
| 119 |
+
const header = ruffleTar.subarray(offset, offset + 512);
|
| 120 |
+
const name = header.subarray(0, 100).toString().replace(/\0.*$/, "");
|
| 121 |
+
if (!name) break;
|
| 122 |
+
const sizeText = header.subarray(124, 136).toString().replace(/\0.*$/, "").trim() || "0";
|
| 123 |
+
if (!/^[0-7]+$/.test(sizeText)) throw new Error("Invalid Ruffle archive entry size");
|
| 124 |
+
const size = parseInt(sizeText, 8);
|
| 125 |
+
if (!Number.isSafeInteger(size) || offset + 512 + Math.ceil(size / 512) * 512 > ruffleTar.length) throw new Error("Truncated Ruffle archive");
|
| 126 |
+
const file = name.startsWith("package/") ? name.slice(8) : "";
|
| 127 |
+
if (expectedRuffle.has(file)) {
|
| 128 |
+
if ((header[156] !== 0 && header[156] !== 48) || extractedRuffle.has(file)) throw new Error("Invalid Ruffle archive entry");
|
| 129 |
+
extractedRuffle.set(file, ruffleTar.subarray(offset + 512, offset + 512 + size));
|
| 130 |
+
}
|
| 131 |
+
offset += 512 + Math.ceil(size / 512) * 512;
|
| 132 |
+
}
|
| 133 |
+
if (extractedRuffle.size !== expectedRuffle.size) throw new Error("Ruffle archive missing required files");
|
| 134 |
+
// Prepare every operation before touching existing output. Disk errors during the
|
| 135 |
+
// commit below can still leave partial updates; this is not an atomic rollback.
|
| 136 |
+
const writes = [];
|
| 137 |
+
const removals = [];
|
| 138 |
+
const ruffleOutput = join(output, resources.ruffleArchive.directory.slice("vendor/".length));
|
| 139 |
+
for (const [file, bytes] of extractedRuffle) writes.push([join(ruffleOutput, file), bytes]);
|
| 140 |
+
const tar = gunzipSync(downloaded[0], { maxOutputLength: MAX_ARCHIVE_BYTES });
|
| 141 |
+
const pdfGroups = new Set(["cmaps", "standard_fonts", "wasm"]);
|
| 142 |
+
const pdfFiles = new Set();
|
| 143 |
+
for (let offset = 0; offset < tar.length;) {
|
| 144 |
+
if (offset + 512 > tar.length) throw new Error("Truncated PDF archive");
|
| 145 |
const header = tar.subarray(offset, offset + 512), name = header.subarray(0, 100).toString().replace(/\0.*$/, "");
|
| 146 |
if (!name) break;
|
| 147 |
+
const sizeText = header.subarray(124, 136).toString().replace(/\0.*$/, "").trim() || "0";
|
| 148 |
+
if (!/^[0-7]+$/.test(sizeText)) throw new Error("Invalid PDF archive entry size");
|
| 149 |
+
const size = parseInt(sizeText, 8);
|
| 150 |
+
if (!Number.isSafeInteger(size) || offset + 512 + Math.ceil(size / 512) * 512 > tar.length)
|
| 151 |
+
throw new Error("Truncated PDF archive");
|
| 152 |
+
const relative = name.startsWith("package/") ? name.slice(8) : "";
|
| 153 |
+
const parts = relative.split("/");
|
| 154 |
+
if (pdfGroups.has(parts[0]) && parts.length > 1 && !relative.endsWith("/")) {
|
| 155 |
+
if ((header[156] !== 0 && header[156] !== 48) || parts.some(part => !part || part === "." || part === "..") || pdfFiles.has(relative))
|
| 156 |
+
throw new Error("Invalid PDF archive entry");
|
| 157 |
+
pdfFiles.add(relative);
|
| 158 |
const target = join(output, relative);
|
| 159 |
+
const bytes = tar.subarray(offset + 512, offset + 512 + size);
|
| 160 |
+
writes.push([target, bytes]);
|
| 161 |
+
if (foliateOutput) writes.push([join(foliateOutput, "pdfjs", relative), bytes]);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
}
|
| 163 |
offset += 512 + Math.ceil(size / 512) * 512;
|
| 164 |
}
|
| 165 |
+
for (const group of pdfGroups) {
|
| 166 |
+
if (![...pdfFiles].some(file => file.startsWith(group + "/")))
|
| 167 |
+
throw new Error(`PDF archive missing required files: ${group}`);
|
| 168 |
+
}
|
| 169 |
+
for (const [index, [name, {path}]] of vendors.entries()) {
|
| 170 |
+
const bytes = downloaded[index + 1];
|
| 171 |
const versioned = path.slice("vendor/".length);
|
| 172 |
+
writes.push([join(output, versioned), bytes]);
|
|
|
|
| 173 |
if (foliateOutput && (name === "pdf" || name === "pdfWorker")) {
|
| 174 |
const filename = name === "pdf" ? "pdf.mjs" : "pdf.worker.mjs";
|
| 175 |
+
writes.push([join(foliateOutput, "pdfjs", filename), bytes]);
|
| 176 |
+
removals.push(join(foliateOutput, "pdfjs", filename + ".map"));
|
|
|
|
| 177 |
}
|
| 178 |
}
|
| 179 |
+
if (foliateOutput) for (const [index, {file}] of foliateVendors.entries()) {
|
| 180 |
+
const bytes = downloaded[1 + vendors.length + index];
|
|
|
|
|
|
|
| 181 |
const target = join(foliateOutput, file);
|
| 182 |
+
writes.push([target, bytes]);
|
| 183 |
+
}
|
| 184 |
+
for (const [target, bytes] of writes) {
|
| 185 |
mkdirSync(dirname(target), { recursive: true });
|
| 186 |
writeFileSync(target, bytes);
|
| 187 |
}
|
| 188 |
+
for (const target of removals) rmSync(target, { force: true });
|
| 189 |
}
|
| 190 |
|
| 191 |
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
scripts/build/fetch_foliate_reader.mjs
CHANGED
|
@@ -3,9 +3,14 @@ import { createRequire } from "node:module";
|
|
| 3 |
import { dirname, join, relative, resolve, sep } from "node:path";
|
| 4 |
import { fileURLToPath } from "node:url";
|
| 5 |
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
| 6 |
-
import { get } from "node:https";
|
| 7 |
import { gunzipSync } from "node:zlib";
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js"));
|
| 10 |
const output = resolve(process.argv[2] || "static/foliate-reader");
|
| 11 |
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
|
@@ -14,24 +19,33 @@ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(enc
|
|
| 14 |
throw new Error("Foliate local adaptation patch is not valid base64");
|
| 15 |
const localPatch = Buffer.from(encodedPatch, "base64").toString("utf8");
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
function download(url, redirects = 0) {
|
| 18 |
return new Promise((resolvePromise, reject) => {
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
});
|
| 36 |
}
|
| 37 |
|
|
|
|
| 3 |
import { dirname, join, relative, resolve, sep } from "node:path";
|
| 4 |
import { fileURLToPath } from "node:url";
|
| 5 |
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
| 6 |
+
import { Agent, get } from "node:https";
|
| 7 |
import { gunzipSync } from "node:zlib";
|
| 8 |
|
| 9 |
+
// proxyEnv is supported by Node 22.21+, 24.5+, and later major versions.
|
| 10 |
+
const [major, minor] = process.versions.node.split(".").map(Number);
|
| 11 |
+
if (major < 22 || (major === 22 && minor < 21) || major === 23 || (major === 24 && minor < 5))
|
| 12 |
+
throw new Error("Node.js 22.21+, 24.5+, or later is required for proxy support");
|
| 13 |
+
|
| 14 |
const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js"));
|
| 15 |
const output = resolve(process.argv[2] || "static/foliate-reader");
|
| 16 |
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
|
|
|
| 19 |
throw new Error("Foliate local adaptation patch is not valid base64");
|
| 20 |
const localPatch = Buffer.from(encodedPatch, "base64").toString("utf8");
|
| 21 |
|
| 22 |
+
// The proxy-aware agent honors HTTP(S)_PROXY and NO_PROXY, including on redirects.
|
| 23 |
+
const agent = new Agent({ proxyEnv: process.env });
|
| 24 |
+
|
| 25 |
function download(url, redirects = 0) {
|
| 26 |
return new Promise((resolvePromise, reject) => {
|
| 27 |
+
// Never propagate transport errors or URLs: either can contain proxy credentials.
|
| 28 |
+
const fail = () => reject(new Error("Foliate archive download failed"));
|
| 29 |
+
try {
|
| 30 |
+
const request = get(url, { agent }, (response) => {
|
| 31 |
+
if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location && redirects < 5) {
|
| 32 |
+
response.resume();
|
| 33 |
+
try { return download(new URL(response.headers.location, url), redirects + 1).then(resolvePromise, reject); }
|
| 34 |
+
catch { return fail(); }
|
| 35 |
+
}
|
| 36 |
+
if (response.statusCode !== 200) {
|
| 37 |
+
response.resume();
|
| 38 |
+
return reject(new Error(`Foliate archive download: HTTP ${response.statusCode}`));
|
| 39 |
+
}
|
| 40 |
+
const chunks = [];
|
| 41 |
+
response.on("data", chunk => chunks.push(chunk));
|
| 42 |
+
response.on("end", () => resolvePromise(Buffer.concat(chunks)));
|
| 43 |
+
response.on("error", fail);
|
| 44 |
+
response.on("aborted", fail);
|
| 45 |
+
});
|
| 46 |
+
request.setTimeout(180000, () => request.destroy());
|
| 47 |
+
request.on("error", fail);
|
| 48 |
+
} catch { fail(); }
|
| 49 |
});
|
| 50 |
}
|
| 51 |
|
scripts/reader/check_reader_media_coverage.mjs
CHANGED
|
@@ -43,4 +43,18 @@ if (result.status !== 0 || rows.length !== 1 || rows[0].some((value, index) => v
|
|
| 43 |
['# tests ', '# pass ', '# fail ', '# cancelled '].some(prefix => lines.filter(line => line.startsWith(prefix)).length !== 1)) {
|
| 44 |
console.error('Reader media requires named contracts and exactly one source row above each minimum');
|
| 45 |
process.exitCode = 1;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
}
|
|
|
|
| 43 |
['# tests ', '# pass ', '# fail ', '# cancelled '].some(prefix => lines.filter(line => line.startsWith(prefix)).length !== 1)) {
|
| 44 |
console.error('Reader media requires named contracts and exactly one source row above each minimum');
|
| 45 |
process.exitCode = 1;
|
| 46 |
+
} else {
|
| 47 |
+
// Keep these independent of the fixed TAP and coverage counts above.
|
| 48 |
+
for (const args of [
|
| 49 |
+
['--test', '--test-concurrency=1', 'tests/reader/copy_reader_vendor.test.mjs', 'tests/reader/test_foliate_proxy.mjs'],
|
| 50 |
+
['tests/reader/media/test_ruffle_closure.mjs'],
|
| 51 |
+
['tests/service_worker/test_ruffle_retention.js']
|
| 52 |
+
]) {
|
| 53 |
+
const extra = spawnSync(process.execPath, args, {stdio: 'inherit'});
|
| 54 |
+
if (extra.error) throw extra.error;
|
| 55 |
+
if (extra.status !== 0) {
|
| 56 |
+
process.exitCode = 1;
|
| 57 |
+
break;
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
}
|
static/reader-resources.js
CHANGED
|
@@ -19,14 +19,14 @@
|
|
| 19 |
sha256: "43710009ea26bfbcb615524946e46e3aaf8ad927514f5e465e8ff6d18044ffe9"
|
| 20 |
},
|
| 21 |
marked: {
|
| 22 |
-
url: "https://cdn.jsdelivr.net/npm/marked@18.
|
| 23 |
file: "marked.min.js",
|
| 24 |
-
sha256: "
|
| 25 |
},
|
| 26 |
purify: {
|
| 27 |
-
url: "https://cdn.jsdelivr.net/npm/dompurify@3.4.
|
| 28 |
file: "purify.min.js",
|
| 29 |
-
sha256: "
|
| 30 |
},
|
| 31 |
ruffle: {
|
| 32 |
url: "https://unpkg.com/@ruffle-rs/ruffle@0.7.1/ruffle.js",
|
|
@@ -44,6 +44,20 @@
|
|
| 44 |
vendor.file.slice(dot);
|
| 45 |
Object.freeze(vendor);
|
| 46 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
const pdfArchive = Object.freeze({
|
| 48 |
url: "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz",
|
| 49 |
sha256: "7461aefcd27c4ef0dd76f9ca5760f09466eb6b3f934432670c12132e7b3d6faa"
|
|
@@ -262,6 +276,8 @@
|
|
| 262 |
foliateArchive,
|
| 263 |
foliateFiles,
|
| 264 |
pdfArchive,
|
|
|
|
|
|
|
| 265 |
readerFiles,
|
| 266 |
readerComponentFiles,
|
| 267 |
vendorUrl,
|
|
|
|
| 19 |
sha256: "43710009ea26bfbcb615524946e46e3aaf8ad927514f5e465e8ff6d18044ffe9"
|
| 20 |
},
|
| 21 |
marked: {
|
| 22 |
+
url: "https://cdn.jsdelivr.net/npm/marked@18.2.0/lib/marked.umd.js",
|
| 23 |
file: "marked.min.js",
|
| 24 |
+
sha256: "392f4df89533b50f1dadff3f6dc0952350bd39c9f17def50a0374ef47d6147ef"
|
| 25 |
},
|
| 26 |
purify: {
|
| 27 |
+
url: "https://cdn.jsdelivr.net/npm/dompurify@3.4.18/dist/purify.min.js",
|
| 28 |
file: "purify.min.js",
|
| 29 |
+
sha256: "8053ee2a6a09f9d50f7fcd6fb7f07072f52c7f3fa9aa12147cab4feaf65ee970"
|
| 30 |
},
|
| 31 |
ruffle: {
|
| 32 |
url: "https://unpkg.com/@ruffle-rs/ruffle@0.7.1/ruffle.js",
|
|
|
|
| 44 |
vendor.file.slice(dot);
|
| 45 |
Object.freeze(vendor);
|
| 46 |
}
|
| 47 |
+
// Keep the upstream filenames together: Ruffle's webpack loader resolves its
|
| 48 |
+
// core chunks and WASM relative to ruffle.js, not relative to the page.
|
| 49 |
+
const ruffleArchive = Object.freeze({
|
| 50 |
+
url: "https://registry.npmjs.org/@ruffle-rs/ruffle/-/ruffle-0.7.1.tgz",
|
| 51 |
+
sha256: "dc9e7407549a91accc41a14932b0b9d9a9d51a3742ce6f020888c8a76682b157",
|
| 52 |
+
directory: "vendor/ruffle/release-dc9e7407549a",
|
| 53 |
+
files: Object.freeze([
|
| 54 |
+
"ruffle.js", "core.ruffle.16d61072ac7fdc4d5013.js",
|
| 55 |
+
"core.ruffle.994eeef0a471a88cd0e3.js", "172de42e6619eac8f371.wasm",
|
| 56 |
+
"878d548199cddef07035.wasm", "LICENSE_APACHE", "LICENSE_MIT"
|
| 57 |
+
])
|
| 58 |
+
});
|
| 59 |
+
/** @param {string} base */
|
| 60 |
+
const ruffleAssets = (base) => ruffleArchive.files.slice(0, 5).map(file => base + ruffleArchive.directory + "/" + file);
|
| 61 |
const pdfArchive = Object.freeze({
|
| 62 |
url: "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz",
|
| 63 |
sha256: "7461aefcd27c4ef0dd76f9ca5760f09466eb6b3f934432670c12132e7b3d6faa"
|
|
|
|
| 276 |
foliateArchive,
|
| 277 |
foliateFiles,
|
| 278 |
pdfArchive,
|
| 279 |
+
ruffleArchive,
|
| 280 |
+
ruffleAssets,
|
| 281 |
readerFiles,
|
| 282 |
readerComponentFiles,
|
| 283 |
vendorUrl,
|
static/reader.js
CHANGED
|
@@ -699,7 +699,7 @@ const PDFJS_CMAP_URL = "/static/vendor/cmaps/";
|
|
| 699 |
const PDFJS_STANDARD_FONT_URL = "/static/vendor/standard_fonts/";
|
| 700 |
const MARKED_URL = VoiceOfMLReaderResources.vendorUrl("marked", "/static/");
|
| 701 |
const PURIFY_URL = VoiceOfMLReaderResources.vendorUrl("purify", "/static/");
|
| 702 |
-
const RUFFLE_URL = VoiceOfMLReaderResources.
|
| 703 |
const READER_PROXY_TIMEOUT_MS = 120000;
|
| 704 |
const readerRequestManager = VoiceOfMLReaderRequests.createReaderRequestManager();
|
| 705 |
const readerRuntime = VoiceOfMLReaderRuntime.createReaderRuntime();
|
|
|
|
| 699 |
const PDFJS_STANDARD_FONT_URL = "/static/vendor/standard_fonts/";
|
| 700 |
const MARKED_URL = VoiceOfMLReaderResources.vendorUrl("marked", "/static/");
|
| 701 |
const PURIFY_URL = VoiceOfMLReaderResources.vendorUrl("purify", "/static/");
|
| 702 |
+
const RUFFLE_URL = VoiceOfMLReaderResources.ruffleAssets("/static/")[0];
|
| 703 |
const READER_PROXY_TIMEOUT_MS = 120000;
|
| 704 |
const readerRequestManager = VoiceOfMLReaderRequests.createReaderRequestManager();
|
| 705 |
const readerRuntime = VoiceOfMLReaderRuntime.createReaderRuntime();
|
static/sw.js
CHANGED
|
@@ -6,7 +6,7 @@ const CURRENT_HASHED_ASSETS = []; // Filled by the static build.
|
|
| 6 |
let cachePruning = Promise.resolve();
|
| 7 |
/** @param {string} pathname @returns {boolean} */
|
| 8 |
function isRetiredAsset(pathname) {
|
| 9 |
-
if (CURRENT_HASHED_ASSETS.length && isDjvuDecoderAsset(pathname)) return !CURRENT_HASHED_ASSETS.includes(pathname);
|
| 10 |
return CURRENT_HASHED_ASSETS.length > 0 &&
|
| 11 |
(/\.[0-9a-f]{12}\.(js|mjs|css)$/.test(pathname) || /^\/static\/(?:(?:reader|search)\/[^?]+|[^/]+)\.(js|mjs|css)$/.test(pathname)) &&
|
| 12 |
!CURRENT_HASHED_ASSETS.includes(pathname);
|
|
@@ -32,7 +32,7 @@ function pruneHashedAssets(cache, resetShell = false, activation = false) {
|
|
| 32 |
}
|
| 33 |
if (resetShell && url.pathname === "/static/reader.html") { await cache.delete(request); continue; }
|
| 34 |
if (!isRetiredAsset(url.pathname)) continue;
|
| 35 |
-
if (activation && (/\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url.pathname) || isDjvuDecoderAsset(url.href))) {
|
| 36 |
const response = await cache.match(request, { ignoreVary: true });
|
| 37 |
if (response) await cache.put(retainedKey(url.href), response);
|
| 38 |
}
|
|
@@ -47,7 +47,7 @@ function pruneHashedAssets(cache, resetShell = false, activation = false) {
|
|
| 47 |
/** @param {Request | string} request @returns {Request | string} */
|
| 48 |
function revalidatedRequest(request) {
|
| 49 |
const url = typeof request === "string" ? request : request.url;
|
| 50 |
-
if (/\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url) || isDjvuDecoderAsset(url) || typeof Request !== "function" ||
|
| 51 |
(typeof request !== "string" && request.cache && request.cache !== "default")) return request;
|
| 52 |
try { return new Request(request, { cache: "no-cache" }); } catch (_) { return request; }
|
| 53 |
}
|
|
@@ -58,6 +58,12 @@ function isDjvuDecoderAsset(value) {
|
|
| 58 |
catch (_) { return false; }
|
| 59 |
}
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
// Search navigations bypass this worker on HF, so "/" is not precached.
|
| 62 |
const PRECACHE_URLS = [
|
| 63 |
"/static/style.css",
|
|
@@ -121,7 +127,7 @@ readerWorkerScope.addEventListener("fetch", (event) => {
|
|
| 121 |
}
|
| 122 |
const networkFirst = !readerShell && READER_RUNTIME_PATHS.has(url.pathname);
|
| 123 |
const cacheKey = readerShell ? "/static/reader.html" : event.request;
|
| 124 |
-
const immutable = /\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url.pathname) || isDjvuDecoderAsset(url.href);
|
| 125 |
const cachePromise = caches.open(CACHE_NAME).catch(() => null);
|
| 126 |
// Pinned same-origin assets are identical across classic/module Origin headers.
|
| 127 |
const cachedPromise = cachePromise.then(cache => cache ? cache.match(cacheKey, { ignoreVary: immutable }) : undefined).catch(() => undefined);
|
|
|
|
| 6 |
let cachePruning = Promise.resolve();
|
| 7 |
/** @param {string} pathname @returns {boolean} */
|
| 8 |
function isRetiredAsset(pathname) {
|
| 9 |
+
if (CURRENT_HASHED_ASSETS.length && (isDjvuDecoderAsset(pathname) || isRuffleAsset(pathname))) return !CURRENT_HASHED_ASSETS.includes(pathname);
|
| 10 |
return CURRENT_HASHED_ASSETS.length > 0 &&
|
| 11 |
(/\.[0-9a-f]{12}\.(js|mjs|css)$/.test(pathname) || /^\/static\/(?:(?:reader|search)\/[^?]+|[^/]+)\.(js|mjs|css)$/.test(pathname)) &&
|
| 12 |
!CURRENT_HASHED_ASSETS.includes(pathname);
|
|
|
|
| 32 |
}
|
| 33 |
if (resetShell && url.pathname === "/static/reader.html") { await cache.delete(request); continue; }
|
| 34 |
if (!isRetiredAsset(url.pathname)) continue;
|
| 35 |
+
if (activation && (/\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url.pathname) || isDjvuDecoderAsset(url.href) || isRuffleAsset(url.href))) {
|
| 36 |
const response = await cache.match(request, { ignoreVary: true });
|
| 37 |
if (response) await cache.put(retainedKey(url.href), response);
|
| 38 |
}
|
|
|
|
| 47 |
/** @param {Request | string} request @returns {Request | string} */
|
| 48 |
function revalidatedRequest(request) {
|
| 49 |
const url = typeof request === "string" ? request : request.url;
|
| 50 |
+
if (/\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url) || isDjvuDecoderAsset(url) || isRuffleAsset(url) || typeof Request !== "function" ||
|
| 51 |
(typeof request !== "string" && request.cache && request.cache !== "default")) return request;
|
| 52 |
try { return new Request(request, { cache: "no-cache" }); } catch (_) { return request; }
|
| 53 |
}
|
|
|
|
| 58 |
catch (_) { return false; }
|
| 59 |
}
|
| 60 |
|
| 61 |
+
/** @param {string} value @returns {boolean} */
|
| 62 |
+
function isRuffleAsset(value) {
|
| 63 |
+
try { return /^\/static\/vendor\/ruffle\/release-[0-9a-f]{12}\/(?:ruffle\.js|core\.ruffle\.[0-9a-f]{20}\.js|[0-9a-f]{20}\.wasm)$/.test(value.startsWith('/') ? value.split(/[?#]/)[0] : new URL(value).pathname); }
|
| 64 |
+
catch (_) { return false; }
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
// Search navigations bypass this worker on HF, so "/" is not precached.
|
| 68 |
const PRECACHE_URLS = [
|
| 69 |
"/static/style.css",
|
|
|
|
| 127 |
}
|
| 128 |
const networkFirst = !readerShell && READER_RUNTIME_PATHS.has(url.pathname);
|
| 129 |
const cacheKey = readerShell ? "/static/reader.html" : event.request;
|
| 130 |
+
const immutable = /\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url.pathname) || isDjvuDecoderAsset(url.href) || isRuffleAsset(url.href);
|
| 131 |
const cachePromise = caches.open(CACHE_NAME).catch(() => null);
|
| 132 |
// Pinned same-origin assets are identical across classic/module Origin headers.
|
| 133 |
const cachedPromise = cachePromise.then(cache => cache ? cache.match(cacheKey, { ignoreVary: immutable }) : undefined).catch(() => undefined);
|
tests/gates/ci-test-inventory.json
CHANGED
|
@@ -434,6 +434,14 @@
|
|
| 434 |
"kind": "script",
|
| 435 |
"source": "scripts/reader/check_reader_lifecycle_coverage.mjs"
|
| 436 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
"tests/reader/media/test_reader_media_baseline.mjs": {
|
| 438 |
"kind": "script",
|
| 439 |
"source": "scripts/reader/check_reader_media_coverage.mjs"
|
|
@@ -874,6 +882,10 @@
|
|
| 874 |
"kind": "direct",
|
| 875 |
"source": "@reader-workflow"
|
| 876 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 877 |
"tests/service_worker/test_service_worker.js": {
|
| 878 |
"kind": "direct",
|
| 879 |
"source": "@reader-workflow"
|
|
|
|
| 434 |
"kind": "script",
|
| 435 |
"source": "scripts/reader/check_reader_lifecycle_coverage.mjs"
|
| 436 |
},
|
| 437 |
+
"tests/reader/media/test_ruffle_closure.mjs": {
|
| 438 |
+
"kind": "script",
|
| 439 |
+
"source": "scripts/reader/check_reader_media_coverage.mjs"
|
| 440 |
+
},
|
| 441 |
+
"tests/reader/test_foliate_proxy.mjs": {
|
| 442 |
+
"kind": "script",
|
| 443 |
+
"source": "scripts/reader/check_reader_media_coverage.mjs"
|
| 444 |
+
},
|
| 445 |
"tests/reader/media/test_reader_media_baseline.mjs": {
|
| 446 |
"kind": "script",
|
| 447 |
"source": "scripts/reader/check_reader_media_coverage.mjs"
|
|
|
|
| 882 |
"kind": "direct",
|
| 883 |
"source": "@reader-workflow"
|
| 884 |
},
|
| 885 |
+
"tests/service_worker/test_ruffle_retention.js": {
|
| 886 |
+
"kind": "script",
|
| 887 |
+
"source": "scripts/reader/check_reader_media_coverage.mjs"
|
| 888 |
+
},
|
| 889 |
"tests/service_worker/test_service_worker.js": {
|
| 890 |
"kind": "direct",
|
| 891 |
"source": "@reader-workflow"
|
tests/gates/test_static_contract.py
CHANGED
|
@@ -441,15 +441,13 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 441 |
self.assertIn("script-src 'self'", reader_html)
|
| 442 |
vendor_script = (ROOT / "scripts/build/copy_reader_vendor.mjs").read_text(encoding="utf-8") + (ROOT / "static/reader-resources.js").read_text(encoding="utf-8")
|
| 443 |
self.assertIn('pdfjs-dist@6.5.438', vendor_script)
|
| 444 |
-
self.assertIn('standard_fonts
|
| 445 |
-
self.assertIn('cmaps/', vendor_script)
|
| 446 |
-
self.assertIn('relative.startsWith("wasm/")', vendor_script)
|
| 447 |
self.assertIn('7461aefcd27c4ef0dd76f9ca5760f09466eb6b3f934432670c12132e7b3d6faa', vendor_script)
|
| 448 |
self.assertIn('3a88402882cfa3e7e72c2c9b5149f52f0f88baf1c5b62aa11a41abdbc2072440', vendor_script)
|
| 449 |
-
self.assertIn('marked@18.
|
| 450 |
-
self.assertIn('
|
| 451 |
-
self.assertIn('dompurify@3.4.
|
| 452 |
-
self.assertIn('
|
| 453 |
self.assertIn('@zip.js/zip.js@2.24.0/index.min.js', vendor_script)
|
| 454 |
self.assertIn('6c13caf4b90e08323f404f596c51549cdc6b01010bd43935a0bdc6a25bd61021', vendor_script)
|
| 455 |
self.assertNotIn('writeFileSync(join(output, target))', vendor_script)
|
|
|
|
| 441 |
self.assertIn("script-src 'self'", reader_html)
|
| 442 |
vendor_script = (ROOT / "scripts/build/copy_reader_vendor.mjs").read_text(encoding="utf-8") + (ROOT / "static/reader-resources.js").read_text(encoding="utf-8")
|
| 443 |
self.assertIn('pdfjs-dist@6.5.438', vendor_script)
|
| 444 |
+
self.assertIn('pdfGroups = new Set(["cmaps", "standard_fonts", "wasm"])', vendor_script)
|
|
|
|
|
|
|
| 445 |
self.assertIn('7461aefcd27c4ef0dd76f9ca5760f09466eb6b3f934432670c12132e7b3d6faa', vendor_script)
|
| 446 |
self.assertIn('3a88402882cfa3e7e72c2c9b5149f52f0f88baf1c5b62aa11a41abdbc2072440', vendor_script)
|
| 447 |
+
self.assertIn('marked@18.2.0/lib/marked.umd.js', vendor_script)
|
| 448 |
+
self.assertIn('392f4df89533b50f1dadff3f6dc0952350bd39c9f17def50a0374ef47d6147ef', vendor_script)
|
| 449 |
+
self.assertIn('dompurify@3.4.18', vendor_script)
|
| 450 |
+
self.assertIn('8053ee2a6a09f9d50f7fcd6fb7f07072f52c7f3fa9aa12147cab4feaf65ee970', vendor_script)
|
| 451 |
self.assertIn('@zip.js/zip.js@2.24.0/index.min.js', vendor_script)
|
| 452 |
self.assertIn('6c13caf4b90e08323f404f596c51549cdc6b01010bd43935a0bdc6a25bd61021', vendor_script)
|
| 453 |
self.assertNotIn('writeFileSync(join(output, target))', vendor_script)
|
tests/reader/copy_reader_vendor.test.mjs
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { test } from "node:test";
|
| 2 |
+
import assert from "node:assert/strict";
|
| 3 |
+
import { createHash } from "node:crypto";
|
| 4 |
+
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
| 5 |
+
import { tmpdir } from "node:os";
|
| 6 |
+
import { join, resolve } from "node:path";
|
| 7 |
+
import { spawn, spawnSync } from "node:child_process";
|
| 8 |
+
import https from "node:https";
|
| 9 |
+
import http from "node:http";
|
| 10 |
+
import net from "node:net";
|
| 11 |
+
import { gzipSync, gunzipSync } from "node:zlib";
|
| 12 |
+
|
| 13 |
+
const script = resolve("scripts/build/copy_reader_vendor.mjs");
|
| 14 |
+
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
| 15 |
+
const listen = (server) => new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
| 16 |
+
const close = (server) => new Promise((resolve) => server.close(resolve));
|
| 17 |
+
|
| 18 |
+
function tarGzip(files) {
|
| 19 |
+
const blocks = [];
|
| 20 |
+
for (const [name, content] of Object.entries(files)) {
|
| 21 |
+
const bytes = Buffer.from(content);
|
| 22 |
+
const header = Buffer.alloc(512);
|
| 23 |
+
header.write(`package/${name}`);
|
| 24 |
+
header.write("0000644\0", 100);
|
| 25 |
+
header.write("0000000\0", 108);
|
| 26 |
+
header.write("0000000\0", 116);
|
| 27 |
+
header.write(bytes.length.toString(8).padStart(11, "0") + "\0", 124);
|
| 28 |
+
header.write("00000000000\0", 136);
|
| 29 |
+
header.fill(32, 148, 156);
|
| 30 |
+
header[156] = 48;
|
| 31 |
+
header.write("ustar\0", 257);
|
| 32 |
+
header.write("00", 263);
|
| 33 |
+
const checksum = header.reduce((sum, byte) => sum + byte, 0);
|
| 34 |
+
header.write(checksum.toString(8).padStart(6, "0") + "\0 ", 148);
|
| 35 |
+
blocks.push(header, bytes, Buffer.alloc((512 - bytes.length % 512) % 512));
|
| 36 |
+
}
|
| 37 |
+
return gzipSync(Buffer.concat([...blocks, Buffer.alloc(1024)]));
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
async function run(cwd, env, scriptPath = script) {
|
| 41 |
+
return new Promise((resolve, reject) => {
|
| 42 |
+
const child = spawn(process.execPath, [scriptPath, "out", "--foliate-output", "foliate"], { cwd, env });
|
| 43 |
+
let stderr = "", timedOut = false;
|
| 44 |
+
const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, 15000);
|
| 45 |
+
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
| 46 |
+
child.on("error", (error) => { clearTimeout(timer); reject(error); });
|
| 47 |
+
child.on("close", (code) => {
|
| 48 |
+
clearTimeout(timer);
|
| 49 |
+
if (timedOut) reject(new Error(`vendor subprocess timed out: ${stderr}`));
|
| 50 |
+
else resolve({ code, stderr });
|
| 51 |
+
});
|
| 52 |
+
});
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
test("environment proxy, bounded concurrent downloads, bypass and hash failure", async () => {
|
| 56 |
+
const dir = mkdtempSync(join(tmpdir(), "reader-vendor-test-"));
|
| 57 |
+
let server, proxy;
|
| 58 |
+
const sockets = new Set();
|
| 59 |
+
const track = (socket) => {
|
| 60 |
+
sockets.add(socket);
|
| 61 |
+
socket.on("close", () => sockets.delete(socket));
|
| 62 |
+
};
|
| 63 |
+
try {
|
| 64 |
+
const key = join(dir, "key.pem"), cert = join(dir, "cert.pem");
|
| 65 |
+
const generated = spawnSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-out", cert, "-days", "1", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,DNS:example.test,IP:127.0.0.1"], { stdio: "ignore", timeout: 15000 });
|
| 66 |
+
assert.equal(generated.status, 0, "openssl is needed to generate the test certificate");
|
| 67 |
+
const ruffleFiles = { "ruffle.js": "ruffle loader", "core.js": "ruffle core", "core.wasm": "wasm bytes", "LICENSE": "license" };
|
| 68 |
+
const pdfFiles = { "cmaps/existing": "new pdf", "standard_fonts/font": "font", "wasm/decoder": "wasm" };
|
| 69 |
+
const bodies = { "/archive": tarGzip(pdfFiles), "/ruffle": tarGzip({ ...ruffleFiles, "ignored.txt": "ignored" }), "/a": Buffer.from("a"), "/b": Buffer.from("b"), "/c": Buffer.from("c"), "/d": Buffer.from("d"), "/f": Buffer.from("f") };
|
| 70 |
+
let active = 0, maxActive = 0, connects = 0, failureMode = false, limitMode = "";
|
| 71 |
+
let limitRequests = 0, limitClosed = 0;
|
| 72 |
+
const seen = [], blockedClosed = [];
|
| 73 |
+
server = https.createServer({ key: readFileSync(key), cert: readFileSync(cert) }, (req, res) => {
|
| 74 |
+
if (limitMode) {
|
| 75 |
+
if (req.url !== "/archive" && req.url !== "/slow") { res.end(bodies[req.url]); return; }
|
| 76 |
+
limitRequests++;
|
| 77 |
+
res.on("close", () => { limitClosed++; });
|
| 78 |
+
if (limitMode === "declared") { res.writeHead(200, { "Content-Length": "2048" }); res.flushHeaders(); }
|
| 79 |
+
else if (limitMode === "stream") { res.writeHead(200); res.write(Buffer.alloc(600)); res.write(Buffer.alloc(600)); }
|
| 80 |
+
else if (req.url === "/archive") { res.writeHead(302, { Location: "/slow" }); setTimeout(() => res.end(), 100); }
|
| 81 |
+
else {
|
| 82 |
+
res.writeHead(200);
|
| 83 |
+
const interval = setInterval(() => res.write("x"), 20);
|
| 84 |
+
res.on("close", () => clearInterval(interval));
|
| 85 |
+
}
|
| 86 |
+
return;
|
| 87 |
+
}
|
| 88 |
+
if (failureMode) {
|
| 89 |
+
seen.push(req.url);
|
| 90 |
+
if (req.url === "/a") { res.writeHead(503); res.end(); }
|
| 91 |
+
else if (req.url === "/archive") setTimeout(() => res.end(bodies[req.url]), 300);
|
| 92 |
+
else { res.on("close", () => blockedClosed.push(req.url)); }
|
| 93 |
+
return;
|
| 94 |
+
}
|
| 95 |
+
active++; maxActive = Math.max(active, maxActive);
|
| 96 |
+
setTimeout(() => { active--; res.end(bodies[req.url]); }, 80);
|
| 97 |
+
});
|
| 98 |
+
server.on("connection", track);
|
| 99 |
+
await listen(server);
|
| 100 |
+
proxy = http.createServer();
|
| 101 |
+
proxy.on("connection", track);
|
| 102 |
+
proxy.on("connect", (_req, client, head) => {
|
| 103 |
+
connects++;
|
| 104 |
+
const upstream = net.connect(server.address().port, "127.0.0.1", () => {
|
| 105 |
+
client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
|
| 106 |
+
if (head.length) upstream.write(head);
|
| 107 |
+
client.pipe(upstream).pipe(client);
|
| 108 |
+
});
|
| 109 |
+
track(upstream);
|
| 110 |
+
upstream.on("error", () => client.destroy());
|
| 111 |
+
client.on("error", () => upstream.destroy());
|
| 112 |
+
upstream.on("close", () => client.destroy());
|
| 113 |
+
client.on("close", () => upstream.destroy());
|
| 114 |
+
});
|
| 115 |
+
await listen(proxy);
|
| 116 |
+
mkdirSync(join(dir, "static"));
|
| 117 |
+
const resources = (host) => {
|
| 118 |
+
const url = (name) => `https://${host}:${server.address().port}/${name}`;
|
| 119 |
+
const entry = (name) => ({ url: url(name), sha256: hash(bodies[`/${name}`]), file: `${name}.js`, path: `vendor/${name}.js` });
|
| 120 |
+
return { pdfArchive: entry("archive"), vendors: { a: entry("a"), b: entry("b"), c: entry("c"), d: entry("d") }, foliateVendors: { f: entry("f") }, ruffleArchive: { ...entry("ruffle"), directory: "vendor/ruffle/release-test", files: Object.keys(ruffleFiles) } };
|
| 121 |
+
};
|
| 122 |
+
const save = (value) => writeFileSync(join(dir, "static/reader-resources.js"), `module.exports = ${JSON.stringify(value)};`);
|
| 123 |
+
const env = { ...process.env, NODE_EXTRA_CA_CERTS: cert, HTTPS_PROXY: `http://127.0.0.1:${proxy.address().port}`, https_proxy: "", NO_PROXY: "", no_proxy: "", HTTP_PROXY: "", http_proxy: "" };
|
| 124 |
+
save(resources("example.test"));
|
| 125 |
+
let result = await run(dir, env);
|
| 126 |
+
assert.equal(result.code, 0, result.stderr);
|
| 127 |
+
assert.ok(connects > 0, "HTTPS traffic passed through the proxy");
|
| 128 |
+
assert.ok(maxActive > 1 && maxActive <= 4, `concurrency: ${maxActive}`);
|
| 129 |
+
assert.equal(readFileSync(join(dir, "foliate/f.js"), "utf8"), "f");
|
| 130 |
+
for (const [file, content] of Object.entries(pdfFiles)) {
|
| 131 |
+
assert.equal(readFileSync(join(dir, "out", file), "utf8"), content);
|
| 132 |
+
assert.equal(readFileSync(join(dir, "foliate/pdfjs", file), "utf8"), content);
|
| 133 |
+
}
|
| 134 |
+
for (const [file, content] of Object.entries(ruffleFiles)) {
|
| 135 |
+
assert.equal(readFileSync(join(dir, "out/ruffle/release-test", file), "utf8"), content);
|
| 136 |
+
}
|
| 137 |
+
assert.throws(() => readFileSync(join(dir, "out/ruffle/release-test/ignored.txt")), { code: "ENOENT" });
|
| 138 |
+
|
| 139 |
+
const bad = resources("example.test");
|
| 140 |
+
bad.vendors.d.sha256 = "0".repeat(64);
|
| 141 |
+
save(bad);
|
| 142 |
+
writeFileSync(join(dir, "out/a.js"), "old");
|
| 143 |
+
writeFileSync(join(dir, "foliate/f.js"), "old foliate");
|
| 144 |
+
writeFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "old ruffle");
|
| 145 |
+
result = await run(dir, env);
|
| 146 |
+
assert.notEqual(result.code, 0);
|
| 147 |
+
assert.match(result.stderr, /SHA-256/);
|
| 148 |
+
assert.equal(readFileSync(join(dir, "out/a.js"), "utf8"), "old");
|
| 149 |
+
assert.equal(readFileSync(join(dir, "foliate/f.js"), "utf8"), "old foliate");
|
| 150 |
+
assert.equal(readFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "utf8"), "old ruffle");
|
| 151 |
+
|
| 152 |
+
// The hash matches, but a later PDF tar entry is malformed after a valid file.
|
| 153 |
+
const originalArchive = bodies["/archive"];
|
| 154 |
+
const malformedTar = gunzipSync(tarGzip({ "cmaps/existing": "new pdf", "wasm/broken": "broken" }));
|
| 155 |
+
malformedTar.write("not-octal!!\0", 1024 + 124);
|
| 156 |
+
bodies["/archive"] = gzipSync(malformedTar);
|
| 157 |
+
save(resources("example.test"));
|
| 158 |
+
mkdirSync(join(dir, "out/cmaps"), { recursive: true });
|
| 159 |
+
mkdirSync(join(dir, "foliate/pdfjs/cmaps"), { recursive: true });
|
| 160 |
+
writeFileSync(join(dir, "out/cmaps/existing"), "old pdf");
|
| 161 |
+
writeFileSync(join(dir, "foliate/pdfjs/cmaps/existing"), "old foliate pdf");
|
| 162 |
+
result = await run(dir, env);
|
| 163 |
+
assert.notEqual(result.code, 0);
|
| 164 |
+
assert.match(result.stderr, /Invalid PDF archive entry size/);
|
| 165 |
+
assert.equal(readFileSync(join(dir, "out/cmaps/existing"), "utf8"), "old pdf");
|
| 166 |
+
assert.equal(readFileSync(join(dir, "foliate/pdfjs/cmaps/existing"), "utf8"), "old foliate pdf");
|
| 167 |
+
assert.equal(readFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "utf8"), "old ruffle");
|
| 168 |
+
assert.equal(readFileSync(join(dir, "out/a.js"), "utf8"), "old");
|
| 169 |
+
assert.equal(readFileSync(join(dir, "foliate/f.js"), "utf8"), "old foliate");
|
| 170 |
+
// Each required group must contain a regular file, not just a directory or link.
|
| 171 |
+
for (const group of ["cmaps", "standard_fonts", "wasm"]) {
|
| 172 |
+
const files = Object.fromEntries(Object.entries(pdfFiles).filter(([name]) => !name.startsWith(group + "/")));
|
| 173 |
+
for (const type of ["missing", "directory", "symlink"]) {
|
| 174 |
+
const tar = gunzipSync(tarGzip({ ...files, ...(type === "missing" ? {} : { [group + (type === "directory" ? "/" : "/link")]: "" }) }));
|
| 175 |
+
if (type === "symlink") tar[2048 + 156] = 50;
|
| 176 |
+
bodies["/archive"] = gzipSync(tar);
|
| 177 |
+
save(resources("example.test"));
|
| 178 |
+
result = await run(dir, env);
|
| 179 |
+
assert.notEqual(result.code, 0, `${group}: ${type}`);
|
| 180 |
+
assert.match(result.stderr, type === "symlink" ? /Invalid PDF archive entry/ : new RegExp(`PDF archive missing required files: ${group}`));
|
| 181 |
+
assert.equal(readFileSync(join(dir, "out/cmaps/existing"), "utf8"), "old pdf");
|
| 182 |
+
assert.equal(readFileSync(join(dir, "foliate/pdfjs/cmaps/existing"), "utf8"), "old foliate pdf");
|
| 183 |
+
assert.equal(readFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "utf8"), "old ruffle");
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
bodies["/archive"] = originalArchive;
|
| 187 |
+
|
| 188 |
+
// Exercise the production gzip cap on each archive with a reduced test-only limit.
|
| 189 |
+
const archiveLimitScript = join(dir, "archive-limit.mjs");
|
| 190 |
+
const archiveSource = readFileSync(script, "utf8");
|
| 191 |
+
assert.match(archiveSource, /const MAX_ARCHIVE_BYTES = 128 \* 1024 \* 1024;/);
|
| 192 |
+
writeFileSync(archiveLimitScript, archiveSource.replace("const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024;", "const MAX_ARCHIVE_BYTES = 8192;"));
|
| 193 |
+
for (const path of ["/archive", "/ruffle"]) {
|
| 194 |
+
const original = bodies[path];
|
| 195 |
+
bodies[path] = gzipSync(Buffer.alloc(16384));
|
| 196 |
+
save(resources("example.test"));
|
| 197 |
+
result = await run(dir, env, archiveLimitScript);
|
| 198 |
+
assert.notEqual(result.code, 0, path);
|
| 199 |
+
assert.match(result.stderr, /ERR_BUFFER_TOO_LARGE|larger than 8192 bytes/);
|
| 200 |
+
assert.equal(readFileSync(join(dir, "out/cmaps/existing"), "utf8"), "old pdf");
|
| 201 |
+
assert.equal(readFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "utf8"), "old ruffle");
|
| 202 |
+
bodies[path] = original;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
const blocked = resources("example.test");
|
| 206 |
+
blocked.pdfArchive.sha256 = "0".repeat(64);
|
| 207 |
+
save(blocked);
|
| 208 |
+
failureMode = true;
|
| 209 |
+
const started = Date.now();
|
| 210 |
+
result = await run(dir, { ...env, HTTPS_PROXY: `http://proxy-user:proxy-secret@127.0.0.1:${proxy.address().port}` });
|
| 211 |
+
assert.notEqual(result.code, 0);
|
| 212 |
+
assert.match(result.stderr, /Resource 0 download failed: SHA-256 mismatch/);
|
| 213 |
+
assert.doesNotMatch(result.stderr, /proxy-user|proxy-secret/);
|
| 214 |
+
assert.ok(Date.now() - started < 3000, "failure interrupts blocked requests and retry delay");
|
| 215 |
+
assert.deepEqual([...seen].sort(), ["/a", "/archive", "/b", "/c"]);
|
| 216 |
+
assert.deepEqual([...blockedClosed].sort(), ["/b", "/c"]);
|
| 217 |
+
failureMode = false;
|
| 218 |
+
|
| 219 |
+
// Exercise production logic with smaller constants, without a runtime override in production.
|
| 220 |
+
const fastScript = join(dir, "limits.mjs");
|
| 221 |
+
const source = readFileSync(script, "utf8");
|
| 222 |
+
assert.match(source, /const DOWNLOAD_DEADLINE_MS = 180000;/);
|
| 223 |
+
assert.match(source, /const MAX_DOWNLOAD_BYTES = 128 \* 1024 \* 1024;/);
|
| 224 |
+
writeFileSync(fastScript, source.replace("const DOWNLOAD_DEADLINE_MS = 180000;", "const DOWNLOAD_DEADLINE_MS = 200;")
|
| 225 |
+
.replace("const MAX_DOWNLOAD_BYTES = 128 * 1024 * 1024;", "const MAX_DOWNLOAD_BYTES = 1024;"));
|
| 226 |
+
save(resources("example.test"));
|
| 227 |
+
const secretEnv = { ...env, HTTPS_PROXY: `http://proxy-user:proxy-secret@127.0.0.1:${proxy.address().port}` };
|
| 228 |
+
for (const mode of ["declared", "stream", "slow"]) {
|
| 229 |
+
limitMode = mode; limitRequests = 0; limitClosed = 0;
|
| 230 |
+
const start = Date.now();
|
| 231 |
+
result = await run(dir, secretEnv, fastScript);
|
| 232 |
+
assert.notEqual(result.code, 0);
|
| 233 |
+
assert.match(result.stderr, mode === "slow" ? /Download deadline exceeded/ : /Download response too large/);
|
| 234 |
+
assert.doesNotMatch(result.stderr, /proxy-user|proxy-secret|example\.test/);
|
| 235 |
+
assert.ok(Date.now() - start < 12000, `${mode} retries are bounded`);
|
| 236 |
+
assert.equal(limitRequests, mode === "slow" ? 8 : 4, `${mode} retries`);
|
| 237 |
+
assert.equal(limitClosed, limitRequests, `${mode} responses closed`);
|
| 238 |
+
}
|
| 239 |
+
limitMode = "";
|
| 240 |
+
|
| 241 |
+
save(resources("127.0.0.1"));
|
| 242 |
+
const before = connects;
|
| 243 |
+
result = await run(dir, { ...env, NO_PROXY: "127.0.0.1" });
|
| 244 |
+
assert.equal(result.code, 0, result.stderr);
|
| 245 |
+
assert.equal(connects, before, "NO_PROXY bypassed the proxy");
|
| 246 |
+
} finally {
|
| 247 |
+
for (const socket of sockets) socket.destroy();
|
| 248 |
+
if (proxy) await close(proxy);
|
| 249 |
+
if (server) await close(server);
|
| 250 |
+
rmSync(dir, { recursive: true, force: true });
|
| 251 |
+
}
|
| 252 |
+
});
|
tests/reader/media/test_ruffle_closure.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from 'node:assert/strict';
|
| 2 |
+
import fs from 'node:fs';
|
| 3 |
+
import os from 'node:os';
|
| 4 |
+
import path from 'node:path';
|
| 5 |
+
import { createRequire } from 'node:module';
|
| 6 |
+
import { checkRuffleAssets } from '../../../scripts/build/check_reader_release.mjs';
|
| 7 |
+
|
| 8 |
+
const resources = createRequire(import.meta.url)('../../../static/reader-resources.js');
|
| 9 |
+
const files = resources.ruffleArchive.files;
|
| 10 |
+
for (const base of ['/static/', '/search/static/', './']) {
|
| 11 |
+
const assets = resources.ruffleAssets(base);
|
| 12 |
+
assert.deepEqual(assets, files.slice(0, 5).map(file => `${base}${resources.ruffleArchive.directory}/${file}`));
|
| 13 |
+
assert.equal(new URL(assets[1], 'https://example.test/reader.html').pathname,
|
| 14 |
+
new URL(files[1], new URL(assets[0], 'https://example.test/reader.html')).pathname);
|
| 15 |
+
}
|
| 16 |
+
const output = fs.mkdtempSync(path.join(os.tmpdir(), 'ruffle-gate-'));
|
| 17 |
+
try {
|
| 18 |
+
assert.throws(() => checkRuffleAssets(output), /Ruffle asset missing/);
|
| 19 |
+
if (process.env.RUFFLE_EXTRACTED_PACKAGE) {
|
| 20 |
+
const dir = path.join(output, resources.ruffleArchive.directory);
|
| 21 |
+
fs.mkdirSync(dir, { recursive: true });
|
| 22 |
+
for (const file of files) fs.copyFileSync(path.join(process.env.RUFFLE_EXTRACTED_PACKAGE, file), path.join(dir, file));
|
| 23 |
+
checkRuffleAssets(output);
|
| 24 |
+
fs.appendFileSync(path.join(dir, files[3]), 'corruption');
|
| 25 |
+
assert.throws(() => checkRuffleAssets(output), /integrity mismatch/);
|
| 26 |
+
}
|
| 27 |
+
} finally { fs.rmSync(output, { recursive: true, force: true }); }
|
| 28 |
+
console.log('Ruffle closure inventory and release gate OK');
|
tests/reader/test_foliate_proxy.mjs
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { test, after } from "node:test";
|
| 2 |
+
import assert from "node:assert/strict";
|
| 3 |
+
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
| 4 |
+
import { tmpdir } from "node:os";
|
| 5 |
+
import { dirname, join, resolve } from "node:path";
|
| 6 |
+
import { fileURLToPath } from "node:url";
|
| 7 |
+
import { createHash } from "node:crypto";
|
| 8 |
+
import { execFileSync, spawn } from "node:child_process";
|
| 9 |
+
import http from "node:http";
|
| 10 |
+
import https from "node:https";
|
| 11 |
+
import net from "node:net";
|
| 12 |
+
|
| 13 |
+
const root = mkdtempSync(join(tmpdir(), "foliate-proxy-"));
|
| 14 |
+
after(() => rmSync(root, { recursive: true, force: true }));
|
| 15 |
+
const script = resolve(dirname(fileURLToPath(import.meta.url)), "../../scripts/build/fetch_foliate_reader.mjs");
|
| 16 |
+
const fixture = join(root, "fixture");
|
| 17 |
+
mkdirSync(join(fixture, "static"), { recursive: true });
|
| 18 |
+
mkdirSync(join(fixture, "scripts/build"), { recursive: true });
|
| 19 |
+
writeFileSync(join(fixture, "scripts/build/fetch.mjs"), readFileSync(script));
|
| 20 |
+
writeFileSync(join(fixture, "scripts/build/foliate-local.patch.b64"), Buffer.from(
|
| 21 |
+
"diff --git a/ok.txt b/ok.txt\n@@ -1 +1 @@\n-before\n+after\n"
|
| 22 |
+
).toString("base64"));
|
| 23 |
+
mkdirSync(join(root, "tree/foliate-js-rev"), { recursive: true });
|
| 24 |
+
writeFileSync(join(root, "tree/foliate-js-rev/ok.txt"), "before\n");
|
| 25 |
+
execFileSync("tar", ["-czf", join(root, "archive.tgz"), "-C", join(root, "tree"), "foliate-js-rev"]);
|
| 26 |
+
const archive = readFileSync(join(root, "archive.tgz"));
|
| 27 |
+
execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", join(root, "key"), "-out", join(root, "cert"), "-days", "1", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost"], { stdio: "ignore" });
|
| 28 |
+
const hits = [], connections = [], sockets = new Set();
|
| 29 |
+
const server = https.createServer({ key: readFileSync(join(root, "key")), cert: readFileSync(join(root, "cert")) }, (req, res) => {
|
| 30 |
+
hits.push(req.url);
|
| 31 |
+
if (req.url === "/redirect") res.writeHead(302, { location: "/archive" }).end();
|
| 32 |
+
else res.end(archive);
|
| 33 |
+
});
|
| 34 |
+
await new Promise(resolvePromise => server.listen(0, "127.0.0.1", resolvePromise));
|
| 35 |
+
const proxy = http.createServer();
|
| 36 |
+
proxy.on("connect", (req, client, head) => {
|
| 37 |
+
connections.push({ url: req.url, auth: req.headers["proxy-authorization"] });
|
| 38 |
+
const upstream = net.connect(server.address().port, "127.0.0.1", () => {
|
| 39 |
+
client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
|
| 40 |
+
if (head.length) upstream.write(head);
|
| 41 |
+
client.pipe(upstream).pipe(client);
|
| 42 |
+
});
|
| 43 |
+
for (const socket of [client, upstream]) {
|
| 44 |
+
sockets.add(socket);
|
| 45 |
+
socket.on("close", () => sockets.delete(socket));
|
| 46 |
+
socket.on("error", () => { client.destroy(); upstream.destroy(); });
|
| 47 |
+
}
|
| 48 |
+
});
|
| 49 |
+
await new Promise(resolvePromise => proxy.listen(0, "127.0.0.1", resolvePromise));
|
| 50 |
+
after(() => { for (const socket of sockets) socket.destroy(); server.close(); proxy.close(); });
|
| 51 |
+
const proxyUrl = `http://secretuser:secretpass@127.0.0.1:${proxy.address().port}`;
|
| 52 |
+
writeFileSync(join(fixture, "static/reader-resources.js"), `module.exports = ${JSON.stringify({
|
| 53 |
+
foliateRevision: "rev", foliateArchive: { url: `https://localhost:${server.address().port}/redirect`, sha256: createHash("sha256").update(archive).digest("hex") }, foliateFiles: ["ok.txt"]
|
| 54 |
+
})};`);
|
| 55 |
+
|
| 56 |
+
async function run(env = {}, preload) {
|
| 57 |
+
const args = preload ? ["--require", preload] : [];
|
| 58 |
+
const child = spawn(process.execPath, [...args, join(fixture, "scripts/build/fetch.mjs"), join(fixture, "out")], {
|
| 59 |
+
cwd: fixture, env: { PATH: process.env.PATH, NODE_EXTRA_CA_CERTS: join(root, "cert"), ...env }
|
| 60 |
+
});
|
| 61 |
+
let output = "";
|
| 62 |
+
child.stdout.on("data", data => output += data);
|
| 63 |
+
child.stderr.on("data", data => output += data);
|
| 64 |
+
const timer = setTimeout(() => child.kill("SIGKILL"), 5000);
|
| 65 |
+
const result = await new Promise((resolvePromise, reject) => {
|
| 66 |
+
child.on("error", reject);
|
| 67 |
+
child.on("close", (code, signal) => resolvePromise({ code, signal, output }));
|
| 68 |
+
}).finally(() => clearTimeout(timer));
|
| 69 |
+
assert.equal(result.signal, null, `child timed out: ${output}`);
|
| 70 |
+
assert.doesNotMatch(output, /secretuser|secretpass|c2VjcmV0dXNlcjpzZWNyZXRwYXNz/);
|
| 71 |
+
return result;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
test("version boundaries reject before modifying output or contacting the network", async () => {
|
| 75 |
+
for (const version of ["18.20.0", "22.20.0", "23.11.0", "24.4.0"]) {
|
| 76 |
+
const preload = join(root, "version.cjs");
|
| 77 |
+
writeFileSync(preload, `Object.defineProperty(process.versions, 'node', {value: ${JSON.stringify(version)}});`);
|
| 78 |
+
mkdirSync(join(fixture, "out"), { recursive: true });
|
| 79 |
+
writeFileSync(join(fixture, "out/sentinel"), version);
|
| 80 |
+
const previousHits = hits.length;
|
| 81 |
+
const result = await run({ HTTPS_PROXY: proxyUrl }, preload);
|
| 82 |
+
assert.equal(result.code, 1, version);
|
| 83 |
+
assert.match(result.output, /Node\.js 22\.21\+, 24\.5\+, or later is required for proxy support/);
|
| 84 |
+
assert.equal(readFileSync(join(fixture, "out/sentinel"), "utf8"), version);
|
| 85 |
+
assert.equal(hits.length, previousHits);
|
| 86 |
+
}
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
const [nodeMajor, nodeMinor] = process.versions.node.split(".").map(Number);
|
| 90 |
+
const supportsProxy = !(nodeMajor < 22 || (nodeMajor === 22 && nodeMinor < 21) || nodeMajor === 23 || (nodeMajor === 24 && nodeMinor < 5));
|
| 91 |
+
|
| 92 |
+
test("supported version boundaries allow proxy download, redirect and patch", { skip: !supportsProxy }, async () => {
|
| 93 |
+
for (const version of ["22.21.0", "24.5.0", "25.0.0", "26.0.0"]) {
|
| 94 |
+
const preload = join(root, "version.cjs");
|
| 95 |
+
writeFileSync(preload, `Object.defineProperty(process.versions, 'node', {value: ${JSON.stringify(version)}});`);
|
| 96 |
+
hits.length = 0; connections.length = 0;
|
| 97 |
+
const result = await run({ HTTPS_PROXY: proxyUrl }, preload);
|
| 98 |
+
assert.equal(result.code, 0, result.output);
|
| 99 |
+
assert.deepEqual(hits, ["/redirect", "/archive"]);
|
| 100 |
+
assert.equal(connections.length, 2);
|
| 101 |
+
assert.ok(connections.every(connection => connection.auth === "Basic c2VjcmV0dXNlcjpzZWNyZXRwYXNz"));
|
| 102 |
+
assert.equal(readFileSync(join(fixture, "out/ok.txt"), "utf8"), "after\n");
|
| 103 |
+
}
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
test("NO_PROXY bypasses the proxy and lowercase https_proxy works", { skip: !supportsProxy }, async () => {
|
| 107 |
+
connections.length = 0;
|
| 108 |
+
let result = await run({ HTTPS_PROXY: proxyUrl, NO_PROXY: "localhost" });
|
| 109 |
+
assert.equal(result.code, 0, result.output);
|
| 110 |
+
assert.equal(connections.length, 0);
|
| 111 |
+
result = await run({ https_proxy: proxyUrl });
|
| 112 |
+
assert.equal(result.code, 0, result.output);
|
| 113 |
+
assert.equal(connections.length, 2);
|
| 114 |
+
});
|
tests/service_worker/test_ruffle_retention.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const fs = require('fs');
|
| 2 |
+
const vm = require('vm');
|
| 3 |
+
const assert = require('assert');
|
| 4 |
+
|
| 5 |
+
(async () => {
|
| 6 |
+
const origin = 'https://example.test';
|
| 7 |
+
const current = '/static/vendor/ruffle/release-dc9e7407549a/ruffle.js';
|
| 8 |
+
const old = '/static/vendor/ruffle/release-aaaaaaaaaaaa/172de42e6619eac8f371.wasm';
|
| 9 |
+
const entries = new Map([[origin + current, {ok: true, current: true}], [origin + old, {ok: true, old: true}]]);
|
| 10 |
+
const cache = {keys: async () => [...entries.keys()].map(url => ({url})),
|
| 11 |
+
match: async req => entries.get(req.url || req),
|
| 12 |
+
put: async (req, response) => entries.set(req.url || req, response),
|
| 13 |
+
delete: async req => entries.delete(req.url || req)};
|
| 14 |
+
const listeners = {};
|
| 15 |
+
const source = fs.readFileSync('static/sw.js', 'utf8').replace('const CURRENT_HASHED_ASSETS = []',
|
| 16 |
+
`const CURRENT_HASHED_ASSETS = [${JSON.stringify(current)}]`);
|
| 17 |
+
vm.runInNewContext(source, {URL, console, importScripts() {},
|
| 18 |
+
VoiceOfMLReaderResources: require('../../static/reader-resources.js'),
|
| 19 |
+
caches: {open: async () => cache, keys: async () => ['voiceofml-search-hf-v1.0.0']},
|
| 20 |
+
fetch: async () => ({ok: false, status: 404}),
|
| 21 |
+
self: {location: {hostname: 'example.test'}, clients: {claim: async () => {}},
|
| 22 |
+
addEventListener: (name, fn) => { listeners[name] = fn; }}});
|
| 23 |
+
let pending;
|
| 24 |
+
listeners.activate({waitUntil: p => { pending = p; }});
|
| 25 |
+
await pending;
|
| 26 |
+
assert(entries.has(origin + current));
|
| 27 |
+
assert(!entries.has(origin + old));
|
| 28 |
+
assert(entries.has(origin + old + '?sw-retained-generation'));
|
| 29 |
+
let response;
|
| 30 |
+
listeners.fetch({request: {url: origin + old, method: 'GET'}, respondWith: p => { response = p; }, waitUntil() {}});
|
| 31 |
+
assert.equal((await response).old, true);
|
| 32 |
+
listeners.fetch({request: {url: origin + current, method: 'GET'}, respondWith: p => { response = p; }, waitUntil() {}});
|
| 33 |
+
assert.equal((await response).current, true);
|
| 34 |
+
console.log('Ruffle current and retained previous generation cache OK');
|
| 35 |
+
})().catch(error => { console.error(error); process.exitCode = 1; });
|