The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
tech(Deps): pdf.js aus dem RCE-Advisory, Sidecar an einen Commit gepinnt
Davida05b11f41a7a
diff --git a/package-lock.json b/package-lock.jsonindex a8c0a789..c1657ae0 100644--- a/package-lock.json+++ b/package-lock.json@@ -7,7 +7,7 @@"": {"name": "locally-uncensored","version": "2.6.7",- "license": "AGPL-3.0",+ "license": "AGPL-3.0-only","dependencies": {"@react-three/drei": "^10.7.7","@react-three/fiber": "^9.5.0",@@ -23,7 +23,7 @@"katex": "^0.17.0","lucide-react": "^1.0.1","mammoth": "^1.12.0",- "pdfjs-dist": "^5.6.205",+ "pdfjs-dist": "^6.3.289","react": "^19.2.4","react-dom": "^19.2.4","react-markdown": "^10.1.0",@@ -617,9 +617,9 @@}},"node_modules/@napi-rs/canvas": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.97.tgz",- "integrity": "sha512-8cFniXvrIEnVwuNSRCW9wirRZbHvrD3JVujdS2P5n5xiJZNZMOZcfOvJ1pb66c7jXMKHHglJEDVJGbm8XWFcXQ==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.0.8.tgz",+ "integrity": "sha512-/SaLcvlqGWdm0HSCWMgHu7cjJiQXfP8/mOY+6dUyV9flQz7sPBBZ+ed2zYtoukojPmxOaL7bm+d/G4GeWWoN7g==","license": "MIT","optional": true,"workspaces": [@@ -633,23 +633,23 @@"url": "https://github.com/sponsors/Brooooooklyn"},"optionalDependencies": {- "@napi-rs/canvas-android-arm64": "0.1.97",- "@napi-rs/canvas-darwin-arm64": "0.1.97",- "@napi-rs/canvas-darwin-x64": "0.1.97",- "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.97",- "@napi-rs/canvas-linux-arm64-gnu": "0.1.97",- "@napi-rs/canvas-linux-arm64-musl": "0.1.97",- "@napi-rs/canvas-linux-riscv64-gnu": "0.1.97",- "@napi-rs/canvas-linux-x64-gnu": "0.1.97",- "@napi-rs/canvas-linux-x64-musl": "0.1.97",- "@napi-rs/canvas-win32-arm64-msvc": "0.1.97",- "@napi-rs/canvas-win32-x64-msvc": "0.1.97"+ "@napi-rs/canvas-android-arm64": "1.0.8",+ "@napi-rs/canvas-darwin-arm64": "1.0.8",+ "@napi-rs/canvas-darwin-x64": "1.0.8",+ "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.8",+ "@napi-rs/canvas-linux-arm64-gnu": "1.0.8",+ "@napi-rs/canvas-linux-arm64-musl": "1.0.8",+ "@napi-rs/canvas-linux-riscv64-gnu": "1.0.8",+ "@napi-rs/canvas-linux-x64-gnu": "1.0.8",+ "@napi-rs/canvas-linux-x64-musl": "1.0.8",+ "@napi-rs/canvas-win32-arm64-msvc": "1.0.8",+ "@napi-rs/canvas-win32-x64-msvc": "1.0.8"}},"node_modules/@napi-rs/canvas-android-arm64": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.97.tgz",- "integrity": "sha512-V1c/WVw+NzH8vk7ZK/O8/nyBSCQimU8sfMsB/9qeSvdkGKNU7+mxy/bIF0gTgeBFmHpj30S4E9WHMSrxXGQuVQ==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.0.8.tgz",+ "integrity": "sha512-5+nkh8i3gt6lqS/d2jTZ1xAn6tdgtB4Lf1mW6T0Qm5/rXNwBuV1sAEyLEWan5o9gJPU/GuvHR3rvSeZ+FaGrbw==","cpu": ["arm64"],@@ -667,9 +667,9 @@}},"node_modules/@napi-rs/canvas-darwin-arm64": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.97.tgz",- "integrity": "sha512-ok+SCEF4YejcxuJ9Rm+WWunHHpf2HmiPxfz6z1a/NFQECGXtsY7A4B8XocK1LmT1D7P174MzwPF9Wy3AUAwEPw==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.0.8.tgz",+ "integrity": "sha512-7jQ47gi+fZ7KJmfc/5rNyy1CYw/cu4kZ0KPIYbo9UUgSdW0bKQJpt+WihEor6s4Lyp7+xc3a+3HeyXmAEbbnPg==","cpu": ["arm64"],@@ -687,9 +687,9 @@}},"node_modules/@napi-rs/canvas-darwin-x64": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.97.tgz",- "integrity": "sha512-PUP6e6/UGlclUvAQNnuXCcnkpdUou6VYZfQOQxExLp86epOylmiwLkqXIvpFmjoTEDmPmXrI+coL/9EFU1gKPA==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.0.8.tgz",+ "integrity": "sha512-rRjDMZs9pIRKGxgijwezplKc1RnJsqUokrA9h88bbTkqQ+7ePj0ZN4ZnZDy8Vu0tXs7KRlI2tQLaK4mx9QlxHg==","cpu": ["x64"],@@ -707,9 +707,9 @@}},"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.97.tgz",- "integrity": "sha512-XyXH2L/cic8eTNtbrXCcvqHtMX/nEOxN18+7rMrAM2XtLYC/EB5s0wnO1FsLMWmK+04ZSLN9FBGipo7kpIkcOw==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.0.8.tgz",+ "integrity": "sha512-jGcCd+8ra6Q61xKqZeiItujTpp9a9eRLcQ0jW6qYNku+WpupqOPFPY0SrsuSnXFviJwkpKYT9p7QrB4lsf3LNQ==","cpu": ["arm"],@@ -727,12 +727,15 @@}},"node_modules/@napi-rs/canvas-linux-arm64-gnu": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.97.tgz",- "integrity": "sha512-Kuq/M3djq0K8ktgz6nPlK7Ne5d4uWeDxPpyKWOjWDK2RIOhHVtLtyLiJw2fuldw7Vn4mhw05EZXCEr4Q76rs9w==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.0.8.tgz",+ "integrity": "sha512-od6I2Y7kU7i1SwZYG2EKW8rWz6JiedtPpko4WEe1DDsiikrfaotVBCRaUTM5/yeZKaZ92EatoAS+5xG+6uJlYA==","cpu": ["arm64"],+ "libc": [+ "glibc"+ ],"license": "MIT","optional": true,"os": [@@ -747,12 +750,15 @@}},"node_modules/@napi-rs/canvas-linux-arm64-musl": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.97.tgz",- "integrity": "sha512-kKmSkQVnWeqg7qdsiXvYxKhAFuHz3tkBjW/zyQv5YKUPhotpaVhpBGv5LqCngzyuRV85SXoe+OFj+Tv0a0QXkQ==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.0.8.tgz",+ "integrity": "sha512-yYkPbJDJiWj6N0gASA3CAvRypZmVpJnxU0DQg3aBhneLDQde9TPLKADsQkobNoJUtTT/lj46aWpzT48PDb3Qcg==","cpu": ["arm64"],+ "libc": [+ "musl"+ ],"license": "MIT","optional": true,"os": [@@ -767,12 +773,15 @@}},"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.97.tgz",- "integrity": "sha512-Jc7I3A51jnEOIAXeLsN/M/+Z28LUeakcsXs07FLq9prXc0eYOtVwsDEv913Gr+06IRo34gJJVgT0TXvmz+N2VA==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.0.8.tgz",+ "integrity": "sha512-PB00MSKAp4VwK/xwe6duKxRKmH8UH4GIl1pqHSbxng0jnU9Dr7FwaDypDiqwNFZ774N+8G7mJLGuLtg9NTcQsg==","cpu": ["riscv64"],+ "libc": [+ "glibc"+ ],"license": "MIT","optional": true,"os": [@@ -787,12 +796,15 @@}},"node_modules/@napi-rs/canvas-linux-x64-gnu": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.97.tgz",- "integrity": "sha512-iDUBe7AilfuBSRbSa8/IGX38Mf+iCSBqoVKLSQ5XaY2JLOaqz1TVyPFEyIck7wT6mRQhQt5sN6ogfjIDfi74tg==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.0.8.tgz",+ "integrity": "sha512-TWM2XWJoitLiIPCvgJh7SriC+L/T9qkYCVzC66AidsZy0QP1hkKzBzVwshCdcA3q6fIn3yE0ISbq4lMJSy8jFw==","cpu": ["x64"],+ "libc": [+ "glibc"+ ],"license": "MIT","optional": true,"os": [@@ -807,12 +819,15 @@}},"node_modules/@napi-rs/canvas-linux-x64-musl": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.97.tgz",- "integrity": "sha512-AKLFd/v0Z5fvgqBDqhvqtAdx+fHMJ5t9JcUNKq4FIZ5WH+iegGm8HPdj00NFlCSnm83Fp3Ln8I2f7uq1aIiWaA==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.0.8.tgz",+ "integrity": "sha512-hb20MxKXXb5IB7AAwN8UHz9WRsa2HmdZfjsDCzjElwJoeV1aotVEwFU4FrFQcYQVzsJQLeaCc/2Qdt/0Q72mMg==","cpu": ["x64"],+ "libc": [+ "musl"+ ],"license": "MIT","optional": true,"os": [@@ -827,9 +842,9 @@}},"node_modules/@napi-rs/canvas-win32-arm64-msvc": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-0.1.97.tgz",- "integrity": "sha512-u883Yr6A6fO7Vpsy9YE4FVCIxzzo5sO+7pIUjjoDLjS3vQaNMkVzx5bdIpEL+ob+gU88WDK4VcxYMZ6nmnoX9A==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.0.8.tgz",+ "integrity": "sha512-WwPN08IXE4SkL+FhJyPz/iFnycMAUkbphFIT4cmKLlvbSU0Zfn1R7BGJ3Hqky1S89QUYc0Q4IOScXb/42Re9wQ==","cpu": ["arm64"],@@ -847,9 +862,9 @@}},"node_modules/@napi-rs/canvas-win32-x64-msvc": {- "version": "0.1.97",- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.97.tgz",- "integrity": "sha512-sWtD2EE3fV0IzN+iiQUqr/Q1SwqWhs2O1FKItFlxtdDkikpEj5g7DKQpY3x55H/MAOnL8iomnlk3mcEeGiUMoQ==",+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.0.8.tgz",+ "integrity": "sha512-XkrVqKb+pxyba7kjy2LJvABFVBTE0DNpEl7MrG4OYUmaWarrXH+t54z/Czj2YxCKtizYTV4mg6phNm3x24qjhQ==","cpu": ["x64"],@@ -2237,16 +2252,16 @@}},"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {- "version": "5.0.6",- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",- "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",+ "version": "5.0.9",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",+ "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==","dev": true,"license": "MIT","dependencies": {"balanced-match": "^4.0.2"},"engines": {- "node": "18 || 20 || >=22"+ "node": "20 || >=22"}},"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {@@ -2650,9 +2665,9 @@"license": "MIT"},"node_modules/brace-expansion": {- "version": "1.1.13",- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz",- "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==",+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==","dev": true,"license": "MIT","dependencies": {@@ -3969,9 +3984,9 @@"license": "MIT"},"node_modules/js-yaml": {- "version": "4.2.0",- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz",- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==",+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",+ "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==","dev": true,"funding": [{@@ -5436,9 +5451,9 @@"license": "MIT"},"node_modules/nanoid": {- "version": "3.3.15",- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",- "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",+ "version": "3.3.18",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==","funding": [{"type": "github",@@ -5460,13 +5475,6 @@"dev": true,"license": "MIT"},- "node_modules/node-readable-to-web-readable-stream": {- "version": "0.4.2",- "resolved": "https://registry.npmjs.org/node-readable-to-web-readable-stream/-/node-readable-to-web-readable-stream-0.4.2.tgz",- "integrity": "sha512-/cMZNI34v//jUTrI+UIo4ieHAB5EZRY/+7OmXZgBxaWBMcW2tGdceIw06RFxWxrKZ5Jp3sI2i5TsRo+CBhtVLQ==",- "license": "MIT",- "optional": true- },"node_modules/node-releases": {"version": "2.0.48","resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.48.tgz",@@ -5636,16 +5644,15 @@"license": "MIT"},"node_modules/pdfjs-dist": {- "version": "5.6.205",- "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-5.6.205.tgz",- "integrity": "sha512-tlUj+2IDa7G1SbvBNN74UHRLJybZDWYom+k6p5KIZl7huBvsA4APi6mKL+zCxd3tLjN5hOOEE9Tv7VdzO88pfg==",+ "version": "6.3.289",+ "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.3.289.tgz",+ "integrity": "sha512-ZHjSVpDa3D6izMq8/04lvkhkATUmL9px6ChPaXc1k6nU2Mrhlg1/7F0bdUqCwUjw3NsPTfPZsMDUU6ZIcRaeQw==","license": "Apache-2.0","engines": {- "node": ">=20.19.0 || >=22.13.0 || >=24"+ "node": ">=22.13.0 || >=24"},"optionalDependencies": {- "@napi-rs/canvas": "^0.1.96",- "node-readable-to-web-readable-stream": "^0.4.2"+ "@napi-rs/canvas": "^1.0.0"}},"node_modules/picocolors": {@@ -5714,9 +5721,9 @@}},"node_modules/postcss": {- "version": "8.5.15",- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",- "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",+ "version": "8.5.26",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",+ "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==","funding": [{"type": "opencollective",@@ -5733,7 +5740,7 @@],"license": "MIT","dependencies": {- "nanoid": "^3.3.12",+ "nanoid": "^3.3.17","picocolors": "^1.1.1","source-map-js": "^1.2.1"},diff --git a/package.json b/package.jsonindex 8d343977..46854136 100644--- a/package.json+++ b/package.json@@ -49,7 +49,7 @@"katex": "^0.17.0","lucide-react": "^1.0.1","mammoth": "^1.12.0",- "pdfjs-dist": "^5.6.205",+ "pdfjs-dist": "^6.3.289","react": "^19.2.4","react-dom": "^19.2.4","react-markdown": "^10.1.0",diff --git a/scripts/build-llama.sh b/scripts/build-llama.shindex 92dec9be..81254783 100755--- a/scripts/build-llama.sh+++ b/scripts/build-llama.sh@@ -25,10 +25,23 @@set -euo pipefail# --- Pinned, reproducible llama.cpp revision --------------------------------# Bump deliberately and re-test; do not float. llama.cpp tags are build numbers-# and upstream SKIPS numbers whose CI failed — verify the tag exists first:+# LLAMA_COMMIT is the pin. A git tag is a mutable pointer: upstream can delete+# and recreate it, and whoever owns that repo (or anyone who takes it over) can+# point b9949 at different code tomorrow. This script builds the binary that+# ships inside the installer and is code-signed with the app, so "whatever the+# tag names on the day CI runs" is not a supply chain we can stand behind.+# LLAMA_TAG stays as the readable name and as the cross-check: the checkout is+# verified against LLAMA_COMMIT on every run, cache hit included, and the build+# stops if the two ever disagree.+#+# To bump, resolve the tag yourself and paste BOTH — llama.cpp tags are build+# numbers and upstream SKIPS numbers whose CI failed, so the tag must exist:# git ls-remote --tags https://github.com/ggml-org/llama.cpp.git 'refs/tags/<tag>'+# CI reuses a cached checkout keyed on hashFiles('scripts/build-llama.sh')+# (release.yml, sidecar-windows.yml), so both values below are inside the cache+# key by construction — bumping one cannot silently reuse the old source tree.LLAMA_TAG="${LLAMA_TAG:-b9949}"+LLAMA_COMMIT="${LLAMA_COMMIT:-049326a00025d00b08cc188ed716b681e984a3f8}"LLAMA_REPO="${LLAMA_REPO:-https://github.com/ggml-org/llama.cpp.git}"# --- Paths -----------------------------------------------------------------@@ -88,21 +101,52 @@ out_name_for() {esac}+# A 40-hex commit SHA and nothing else. A short SHA, a tag name or an empty+# override would all silently reduce the pin back to "whatever origin says".+assert_pinned_commit() {+ case "$LLAMA_COMMIT" in+ *[!0-9a-f]* | "") die "LLAMA_COMMIT must be a full 40-char lowercase commit SHA, got '$LLAMA_COMMIT'" ;;+ esac+ [ "${#LLAMA_COMMIT}" -eq 40 ] \+ || die "LLAMA_COMMIT must be a full 40-char lowercase commit SHA, got '$LLAMA_COMMIT'"+}+ensure_src() {command -v git >/dev/null 2>&1 || die "git not found"command -v cmake >/dev/null 2>&1 || die "cmake not found — install it (macOS: brew install cmake)"+ assert_pinned_commitmkdir -p "$CACHE_DIR"if [ ! -d "$SRC_DIR/.git" ]; then- log "cloning llama.cpp @ $LLAMA_TAG"- git clone --depth 1 --branch "$LLAMA_TAG" "$LLAMA_REPO" "$SRC_DIR"- else- local have- have="$(git -C "$SRC_DIR" describe --tags --exact-match 2>/dev/null || true)"- if [ "$have" != "$LLAMA_TAG" ]; then- log "updating llama.cpp checkout → $LLAMA_TAG"- git -C "$SRC_DIR" fetch --depth 1 origin "refs/tags/$LLAMA_TAG:refs/tags/$LLAMA_TAG"- git -C "$SRC_DIR" checkout -f "$LLAMA_TAG"- fi+ log "initialising llama.cpp checkout for $LLAMA_TAG ($LLAMA_COMMIT)"+ git init -q "$SRC_DIR"+ git -C "$SRC_DIR" remote add origin "$LLAMA_REPO"+ fi+ local have+ have="$(git -C "$SRC_DIR" rev-parse HEAD 2>/dev/null || true)"+ if [ "$have" != "$LLAMA_COMMIT" ]; then+ log "fetching llama.cpp $LLAMA_TAG ($LLAMA_COMMIT)"+ # Fetch the object by SHA — GitHub serves any commit reachable from a ref,+ # and a request for a SHA cannot be answered with different code. The tag+ # is only the fallback for a mirror that refuses SHA fetches; the check+ # below is what decides whether we got the right object either way.+ git -C "$SRC_DIR" fetch --depth 1 origin "$LLAMA_COMMIT" 2>/dev/null \+ || git -C "$SRC_DIR" fetch --depth 1 origin "refs/tags/$LLAMA_TAG"+ git -C "$SRC_DIR" checkout -f --detach FETCH_HEAD+ fi+ # Re-asserted on every run, cache hit included: a restored build cache is an+ # artifact from an earlier run, not evidence about what is in it now.+ have="$(git -C "$SRC_DIR" rev-parse HEAD)"+ [ "$have" = "$LLAMA_COMMIT" ] \+ || die "llama.cpp checkout is at $have, expected $LLAMA_COMMIT ($LLAMA_TAG) — upstream tag moved, or the build cache is stale"+}++# sha256 of a file, or "" where no hasher is on PATH. macOS ships `shasum`,+# Linux and Git-Bash ship `sha256sum`; neither is guaranteed on the other.+sha256_of() {+ if command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$1" | awk '{print $1}'+ elif command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$1" | awk '{print $1}'fi}@@ -126,7 +170,13 @@ build_triple() {local out="$BIN_DIR/$(out_name_for "$triple")"cp "$built" "$out"chmod +x "$out"- log "installed → $out"+ # Record what actually got produced. A from-source build is not bit-for-bit+ # reproducible across machines, so this cannot be pinned to a constant — but+ # it puts the digest of the binary that ships, next to the source revision it+ # came from, in the release log, which is what an "which binary was that?"+ # question after the fact needs.+ local digest; digest="$(sha256_of "$out")"+ log "installed → $out (llama.cpp $LLAMA_TAG @ ${LLAMA_COMMIT:0:12}, sha256 ${digest:-unavailable})"}# Boot the host binary and probe /health on an ephemeral port. Without adiff --git a/src/api/__tests__/build-llama-script.test.ts b/src/api/__tests__/build-llama-script.test.tsindex e9affaf7..bfa1fa2e 100644--- a/src/api/__tests__/build-llama-script.test.ts+++ b/src/api/__tests__/build-llama-script.test.ts@@ -1,11 +1,32 @@-import { describe, it, expect } from 'vitest'+import { describe, it, expect, afterAll } from 'vitest'import { execFileSync } from 'node:child_process'-import { resolve } from 'node:path'-import { existsSync, statSync } from 'node:fs'+import { resolve, join } from 'node:path'+import { existsSync, statSync, mkdtempSync, rmSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'// P0: unit-test the pure functions of scripts/build-llama.sh by sourcing it// (main() is guarded so sourcing does not build anything) and invoking helpers.const SCRIPT = resolve(__dirname, '../../../scripts/build-llama.sh')+const REPO_ROOT = resolve(__dirname, '../../..')++/** Run a snippet with the script sourced. Returns stdout+stderr, both wanted:+ * the pin guards report through die(), which writes to stderr. */+function runScript(+ snippet: string,+ env: NodeJS.ProcessEnv = {},+): { code: number; out: string } {+ try {+ const out = execFileSync('bash', ['-c', `source '${SCRIPT}'; ${snippet}`], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, ...env },+ })+ return { code: 0, out: out.trim() }+ } catch (err) {+ const e = err as { status?: number; stdout?: unknown; stderr?: unknown }+ return { code: e.status ?? 1, out: `${String(e.stdout ?? '')}${String(e.stderr ?? '')}`.trim() }+ }+}function callFn(fn: string, ...args: string[]): { code: number; out: string } {const argv = args.map((a) => `'${a}'`).join(' ')@@ -83,3 +104,143 @@ describe('build-llama.sh', () => {expect(out).toMatch(/-/)})})++/**+ * The sidecar pin.+ *+ * `llama-server` is compiled from upstream source, dropped into the installer+ * and code-signed with the app. Until this pin existed the build followed a+ * git TAG — a mutable pointer that upstream (or anyone who takes that repo+ * over) can move to different code without any local change, so the binary+ * users installed was in practice unpinned. The commit SHA is the pin now; the+ * tag stays as the readable name and is cross-checked against it.+ */+describe('build-llama.sh — the llama.cpp revision is pinned to a commit', () => {+ const temps: string[] = []+ const tmp = (prefix: string) => {+ const dir = mkdtempSync(join(tmpdir(), prefix))+ temps.push(dir)+ return dir.replace(/\\/g, '/')+ }+ afterAll(() => {+ for (const dir of temps) rmSync(dir, { recursive: true, force: true })+ })++ const git = (cwd: string, ...args: string[]) =>+ execFileSync('git', args, {+ cwd,+ encoding: 'utf8',+ env: { ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' },+ }).trim()++ /** A throwaway upstream with one commit and a tag on it. */+ function fakeUpstream(): { path: string; sha: string; tag: string } {+ const path = tmp('llama-upstream-')+ git(path, 'init', '-q', '-b', 'main', '.')+ writeFileSync(join(path, 'CMakeLists.txt'), 'project(fake)\n')+ git(path, 'add', '-A')+ git(path, 'commit', '-qm', 'init')+ git(path, 'tag', 'btest')+ // Local file:// transport refuses a fetch-by-SHA unless asked; the real+ // origin (GitHub) allows it, so allow it here too and exercise that path.+ git(path, 'config', 'uploadpack.allowAnySHA1InWant', 'true')+ return { path, sha: git(path, 'rev-parse', 'HEAD'), tag: 'btest' }+ }++ it('ships a full 40-hex commit SHA next to the readable tag', () => {+ const { out } = runScript('printf "%s %s" "$LLAMA_TAG" "$LLAMA_COMMIT"')+ const [tag, commit] = out.split(' ')+ expect(tag).toBeTruthy()+ expect(commit).toMatch(/^[0-9a-f]{40}$/)+ })++ it('refuses anything that is not a full commit SHA', () => {+ // Each of these would quietly hand the choice back to origin. An empty+ // LLAMA_COMMIT is assigned inside the shell, not through the environment,+ // because `${LLAMA_COMMIT:-<default>}` reads an empty env var as "no+ // override" — which is the intended reading of it.+ for (const bad of ['b9949', '049326a', '049326A00025D00B08CC188ED716B681E984A3F8', 'HEAD']) {+ const { code, out } = runScript('assert_pinned_commit', { LLAMA_COMMIT: bad })+ expect(code, `accepted LLAMA_COMMIT='${bad}'`).not.toBe(0)+ expect(out).toContain('40-char')+ }+ const empty = runScript('LLAMA_COMMIT=""; assert_pinned_commit')+ expect(empty.code).not.toBe(0)+ expect(empty.out).toContain('40-char')+ })++ it('checks out exactly the pinned commit', () => {+ const up = fakeUpstream()+ const cache = tmp('llama-cache-')+ const { code, out } = runScript('ensure_src; git -C "$SRC_DIR" rev-parse HEAD', {+ LLAMA_BUILD_CACHE: cache,+ LLAMA_REPO: up.path,+ LLAMA_TAG: up.tag,+ LLAMA_COMMIT: up.sha,+ })+ expect(code).toBe(0)+ expect(out).toContain(up.sha)+ })++ it('stops the build when the tag no longer names the pinned commit', () => {+ // The attack the pin exists for: upstream retags b9949 onto other code.+ // The fetch then brings back the wrong object and the build must refuse it+ // instead of compiling and signing it.+ const up = fakeUpstream()+ const cache = tmp('llama-cache-moved-')+ const { code, out } = runScript('ensure_src', {+ LLAMA_BUILD_CACHE: cache,+ LLAMA_REPO: up.path,+ LLAMA_TAG: up.tag,+ LLAMA_COMMIT: '0123456789012345678901234567890123456789',+ })+ expect(code).not.toBe(0)+ expect(out).toContain('expected 0123456789012345678901234567890123456789')+ })++ it('re-verifies a checkout it did not create, so a stale cache cannot slip through', () => {+ // CI restores .llama-build from a cache. A restored directory is an+ // artifact of an earlier run, not evidence about its contents.+ const up = fakeUpstream()+ const cache = tmp('llama-cache-stale-')+ const first = runScript('ensure_src', {+ LLAMA_BUILD_CACHE: cache,+ LLAMA_REPO: up.path,+ LLAMA_TAG: up.tag,+ LLAMA_COMMIT: up.sha,+ })+ expect(first.code).toBe(0)+ // Same on-disk checkout, different pin — the second run must not accept it.+ const second = runScript('ensure_src', {+ LLAMA_BUILD_CACHE: cache,+ LLAMA_REPO: up.path,+ LLAMA_TAG: up.tag,+ LLAMA_COMMIT: 'ffffffffffffffffffffffffffffffffffffffff',+ })+ expect(second.code).not.toBe(0)+ expect(second.out).toContain(`checkout is at ${up.sha}`)+ })++ it('hashes a digest of the binary it installed', () => {+ const probe = join(tmp('llama-digest-'), 'artifact')+ writeFileSync(probe, 'llama-server')+ const { code, out } = runScript(`sha256_of '${probe}'`)+ expect(code).toBe(0)+ expect(out).toMatch(/^[0-9a-f]{64}$/)+ })++ it('is inside the CI cache key, so bumping the pin cannot reuse the old source', () => {+ // Both lanes key the .llama-build cache on hashFiles() of this script, and+ // LLAMA_TAG/LLAMA_COMMIT live in it — so the pin is in the key by+ // construction. If a lane ever keys on something narrower, the pin can be+ // bumped while CI keeps building the cached old tree.+ for (const workflow of ['.github/workflows/release.yml', '.github/workflows/sidecar-windows.yml']) {+ const text = readFileSync(resolve(REPO_ROOT, workflow), 'utf8')+ const keys = text.match(/^\s*key:\s*.*llama.*$/gm) ?? []+ expect(keys.length, `${workflow} has no llama cache key`).toBeGreaterThan(0)+ for (const key of keys) {+ expect(key, workflow).toContain("hashFiles('scripts/build-llama.sh')")+ }+ }+ })+})diff --git a/src/api/__tests__/pdfjs-supply-chain.test.ts b/src/api/__tests__/pdfjs-supply-chain.test.tsnew file mode 100644index 00000000..40b330fe--- /dev/null+++ b/src/api/__tests__/pdfjs-supply-chain.test.ts@@ -0,0 +1,115 @@+/**+ * Supply-chain guard for the PDF parser.+ *+ * GHSA-hq66-cqwq-w95j affects pdfjs-dist >= 5.6.83 and < 6.2.108. 2.6.7+ * shipped 5.6.205. The behavioural proof that the sink is gone lives in+ * rag-pdf-eval.test.ts; this file guards the two ways it could quietly come+ * back — a lockfile that resolves into the window again, and a manifest range+ * that permits it.+ *+ * `npm audit` catches the same thing, but only when someone runs it. The suite+ * runs on every change.+ *+ * Run: npx vitest run src/api/__tests__/pdfjs-supply-chain.test.ts+ */+import { describe, it, expect, vi } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { extractText } from '../rag'++/**+ * Stand in for pdf.js so the options rag.ts passes are observable. The mock is+ * keyed on the legacy specifier: if rag.ts ever goes back to the default build,+ * this does not apply and the assertions below fail — which is the point, the+ * legacy build is what older WKWebView/WebKitGTK can run at all.+ */+const captured = vi.hoisted(() => [] as Record<string, unknown>[])+vi.mock('pdfjs-dist/legacy/build/pdf.mjs', () => ({+ GlobalWorkerOptions: { workerSrc: '' },+ getDocument: (params: Record<string, unknown>) => {+ captured.push(params)+ return {+ promise: Promise.resolve({+ numPages: 1,+ getPage: async () => ({ getTextContent: async () => ({ items: [{ str: 'ok' }] }) }),+ }),+ }+ },+}))++const REPO = resolve(__dirname, '../../..')+const read = (p: string) => readFileSync(resolve(REPO, p), 'utf8')+const json = (p: string) => JSON.parse(read(p))++/** First affected and first fixed version of GHSA-hq66-cqwq-w95j. */+const AFFECTED_FROM = '5.6.83'+const FIXED_IN = '6.2.108'++/** -1 / 0 / 1, on plain `x.y.z` releases — pdfjs never ships prereleases. */+function compare(a: string, b: string): number {+ const pa = a.split('.').map(Number)+ const pb = b.split('.').map(Number)+ for (let i = 0; i < 3; i++) {+ if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) < (pb[i] ?? 0) ? -1 : 1+ }+ return 0+}++const inAdvisoryWindow = (v: string) =>+ compare(v, AFFECTED_FROM) >= 0 && compare(v, FIXED_IN) < 0++describe('pdfjs-dist stays out of GHSA-hq66-cqwq-w95j', () => {+ it('the version on disk is at or past the fix', () => {+ const installed = json('node_modules/pdfjs-dist/package.json').version as string+ expect(inAdvisoryWindow(installed)).toBe(false)+ expect(compare(installed, FIXED_IN)).toBeGreaterThanOrEqual(0)+ })++ it('the declared range cannot resolve back into the window', () => {+ const range = json('package.json').dependencies['pdfjs-dist'] as string+ // A caret range on 6.x has 6.x as its floor and 7.0.0 as its ceiling, so+ // no resolution of it reaches 5.x or an early 6.x. Any other range shape+ // (a `>=`, a `*`, a downgrade to `^5`) needs re-reading, not a nod.+ const caret = /^\^(\d+\.\d+\.\d+)$/.exec(range)+ expect(caret, `unexpected range shape for pdfjs-dist: ${range}`).not.toBeNull()+ const floor = caret![1]+ expect(floor.startsWith('6.')).toBe(true)+ expect(compare(floor, FIXED_IN)).toBeGreaterThanOrEqual(0)+ })++ it('no shipped bundle still carries the eval switch', () => {+ // `isEvalSupported` was both the option name and the internal gate in front+ // of `new Function(<compiled PostScript>)`. 6.2.108 removed the compiler,+ // so the identifier disappears from the build entirely — its presence in+ // any bundle means the vulnerable code path is back on disk.+ for (const bundle of [+ 'node_modules/pdfjs-dist/build/pdf.mjs',+ 'node_modules/pdfjs-dist/build/pdf.worker.mjs',+ 'node_modules/pdfjs-dist/legacy/build/pdf.mjs',+ 'node_modules/pdfjs-dist/legacy/build/pdf.worker.mjs',+ 'node_modules/pdfjs-dist/legacy/build/pdf.worker.min.mjs',+ ]) {+ expect(read(bundle), bundle).not.toContain('isEvalSupported')+ }+ })+})++describe('getDocument is called with the document-driven features pinned off', () => {+ it('passes enableXfa: false and the file bytes, nothing else', async () => {+ captured.length = 0+ const file = new File([new Uint8Array([0x25, 0x50, 0x44, 0x46])], 'x.pdf')++ await expect(extractText(file)).resolves.toBe('ok')++ expect(captured).toHaveLength(1)+ // XFA carries its own scripting layer; it stays off no matter what pdf.js+ // decides to default to later.+ expect(captured[0].enableXfa).toBe(false)+ // No URL option: every one of them (cMapUrl, standardFontDataUrl, iccUrl,+ // wasmUrl, docBaseUrl) turns document content into a fetch, and a dropped+ // file is processed locally or not at all.+ for (const key of ['cMapUrl', 'standardFontDataUrl', 'iccUrl', 'wasmUrl', 'docBaseUrl', 'url']) {+ expect(captured[0]).not.toHaveProperty(key)+ }+ })+})diff --git a/src/api/__tests__/prod-licenses.test.ts b/src/api/__tests__/prod-licenses.test.tsnew file mode 100644index 00000000..be191133--- /dev/null+++ b/src/api/__tests__/prod-licenses.test.ts@@ -0,0 +1,80 @@+/**+ * The app ships under AGPL-3.0-only. That is a promise about what a user may+ * do with the binary, and it only holds if nothing in the production tree+ * carries terms that contradict it — a GPL-2.0-only dependency cannot be+ * relicensed forward into v3, and a source-available licence (SSPL, Commons+ * Clause, "UNLICENSED") is not free software at all.+ *+ * A dependency bump is exactly how such a licence arrives: nobody reads the+ * new transitive tree. This reads package-lock.json, which records a licence+ * per resolved package, so the check is offline and exact about the versions+ * that actually install.+ *+ * Run: npx vitest run src/api/__tests__/prod-licenses.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++type LockEntry = { version?: string; dev?: boolean; optional?: boolean; license?: string }++const lock = JSON.parse(+ readFileSync(resolve(__dirname, '../../../package-lock.json'), 'utf8'),+) as { packages: Record<string, LockEntry> }++/** Everything that can reach a user's machine: the root and devDependencies+ * are out, optional platform builds stay in — one of them ships per OS. */+const production = Object.entries(lock.packages).filter(([path, entry]) => path && !entry.dev)++/**+ * Terms that cannot travel inside an AGPL-3.0-only release.+ * GPL-2.0-**or-later** is fine (it upgrades into v3), GPL-3.0 and AGPL-3.0 are+ * fine (that is what we are), so only the version-locked v2 forms and the+ * non-free licences are listed.+ */+const INCOMPATIBLE = [+ /^GPL-2\.0(-only)?$/i,+ /^LGPL-2\.[01](-only)?$/i,+ /\bSSPL\b/i,+ /Commons\s*Clause/i,+ /^UNLICENSED$/,+ /\bCC-BY-NC/i,+ /^BUSL/i,+ /Elastic-2\.0/i,+]++describe('production dependency licences stay compatible with AGPL-3.0-only', () => {+ it('has a production tree to check at all', () => {+ // A refactor that renames the lock format would otherwise turn every+ // assertion below into a green no-op.+ expect(production.length).toBeGreaterThan(100)+ })++ it('carries no licence that an AGPL-3.0-only release cannot contain', () => {+ const bad = production+ .filter(([, e]) => e.license && INCOMPATIBLE.some((re) => re.test(e.license!)))+ .map(([p, e]) => `${p} -> ${e.license}`)+ expect(bad).toEqual([])+ })++ it('names every package that declares no licence at all', () => {+ // Both of these carry an MIT LICENSE file and an MIT header in the source;+ // only the package.json metadata is missing ([email protected] uses the retired+ // `licenses` array, [email protected] has no field). Checked by hand —+ // a third name appearing here has NOT been checked and must be.+ const undeclared = production.filter(([, e]) => !e.license).map(([p]) => p)+ expect(undeclared.sort()).toEqual(['node_modules/format', 'node_modules/webgl-constants'])+ })++ it('has exactly one unspecific licence string, and it is duck', () => {+ // npm reports [email protected] as "BSD*" because the package only says "BSD".+ // Its LICENSE file is the two-clause form — copyright notice, binary+ // notice, disclaimer, and no endorsement clause — which is BSD-2-Clause,+ // the same licence its sibling `lop` (same author) declares outright.+ // Permissive, so it travels into an AGPL release without a condition.+ const unspecific = production+ .filter(([, e]) => /^(BSD|MIT\*|Apache|GPL)$/i.test(e.license ?? ''))+ .map(([p, e]) => `${p} -> ${e.license}`)+ expect(unspecific).toEqual(['node_modules/duck -> BSD'])+ })+})diff --git a/src/api/__tests__/rag-pdf-eval.test.ts b/src/api/__tests__/rag-pdf-eval.test.tsnew file mode 100644index 00000000..25576ee6--- /dev/null+++ b/src/api/__tests__/rag-pdf-eval.test.ts@@ -0,0 +1,195 @@+/**+ * GHSA-hq66-cqwq-w95j — "arbitrary JavaScript execution upon opening a+ * malicious PDF". 2.6.7 shipped pdfjs-dist 5.6.205, squarely inside the+ * affected range (>= 5.6.83, < 6.2.108).+ *+ * The sink is concrete: a PDF may carry a PostScript calculator function+ * (`/FunctionType 4`). Up to 6.2.108 pdf.js translated that program into+ * JavaScript source and passed it to `new Function` whenever `isEvalSupported`+ * kept its default `true`. 6.2.108 replaced the compiler with a WebAssembly+ * one and deleted the option.+ *+ * So the regression guard is not "is the version string new enough" — it is+ * "does opening a document that carries such a program still construct a+ * function out of it". This file measures that directly, by trapping the+ * global `Function` constructor while a crafted PDF goes through the parser.+ *+ * How far the sink was from this app, measured on 5.6.205 with the probe+ * below: text extraction (getDocument → getPage → getTextContent, which is+ * all rag.ts does) compiles nothing; `getOperatorList` on the same file+ * compiles the document's own program and constructs it —+ * dest[destOffset + 0] = Math.max(0, (1 - (... src[srcOffset + 0] ... * 2)));+ * So the shipped RAG path did not run the payload, and the first feature to+ * render a page rather than read it would have. Both are asserted here, and a+ * downgrade under the pin fails the second one, not just `npm audit`.+ *+ * Run: npx vitest run src/api/__tests__/rag-pdf-eval.test.ts+ */+import { describe, it, expect, beforeAll } from 'vitest'+import { resolve } from 'node:path'+import { pathToFileURL } from 'node:url'+import { extractText } from '../rag'++/** Assemble a syntactically valid PDF with a real xref table. */+function buildPdf(objects: string[]): Uint8Array {+ let out = '%PDF-1.7\n'+ const offsets: number[] = []+ objects.forEach((body, i) => {+ offsets.push(out.length)+ out += `${i + 1} 0 obj\n${body}\nendobj\n`+ })+ const xref = out.length+ out += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`+ for (const off of offsets) out += `${String(off).padStart(10, '0')} 00000 n \n`+ out += `trailer\n<</Size ${objects.length + 1}/Root 1 0 R>>\nstartxref\n${xref}\n%%EOF\n`+ return new TextEncoder().encode(out)+}++function stream(dict: string, body: string): string {+ return `<<${dict}/Length ${body.length}>>\nstream\n${body}\nendstream`+}++/** A plain text document, one object per page content. */+function textPdf(pages: string[]): Uint8Array {+ const kids = pages.map((_, i) => `${4 + i * 2} 0 R`).join(' ')+ const objects = [+ '<</Type/Catalog/Pages 2 0 R>>',+ `<</Type/Pages/Kids[${kids}]/Count ${pages.length}>>`,+ '<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>',+ ]+ pages.forEach((text, i) => {+ const contentObj = 5 + i * 2+ objects.push(+ `<</Type/Page/Parent 2 0 R/MediaBox[0 0 300 300]/Contents ${contentObj} 0 R` ++ '/Resources<</Font<</F1 3 0 R>>>>>>',+ )+ objects.push(stream('', `BT /F1 12 Tf 20 200 Td (${text}) Tj ET`))+ })+ return buildPdf(objects)+}++/**+ * A document carrying the attack primitive: a `/FunctionType 4` PostScript+ * program, referenced by a shading the page actually paints, so the parser has+ * a reason to build the function rather than skip the object.+ */+function postScriptFunctionPdf(text: string): Uint8Array {+ const ps = '{ 2 mul 1 exch sub }'+ const content = `q /Sh0 sh Q BT /F1 12 Tf 20 200 Td (${text}) Tj ET`+ return buildPdf([+ '<</Type/Catalog/Pages 2 0 R>>',+ '<</Type/Pages/Kids[3 0 R]/Count 1>>',+ '<</Type/Page/Parent 2 0 R/MediaBox[0 0 300 300]/Contents 4 0 R' ++ '/Resources<</Font<</F1 5 0 R>>/Shading<</Sh0 7 0 R>>>>>>',+ stream('', content),+ '<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>',+ stream('/FunctionType 4/Domain[0 1]/Range[0 1]', ps),+ '<</ShadingType 2/ColorSpace/DeviceGray/Coords[0 0 300 0]/Function 6 0 R/Extend[true true]>>',+ ])+}++const asFile = (bytes: Uint8Array, name = 'probe.pdf') =>+ new File([bytes as unknown as BlobPart], name, { type: 'application/pdf' })++/**+ * Record every dynamic function construction. `new Function(...)` and+ * `Function(...)` both resolve `Function` off the global object from inside a+ * module, so a Proxy in that slot sees the compiled body pdf.js would hand it.+ * Behaviour is unchanged — every trap forwards to the real intrinsic.+ */+async function recordFunctionSources<T>(run: () => Promise<T>): Promise<{ result: T; sources: string[] }> {+ const real = globalThis.Function+ const sources: string[] = []+ const note = (args: ArrayLike<unknown>) => sources.push(String(args[args.length - 1] ?? ''))+ globalThis.Function = new Proxy(real, {+ construct(target, args, newTarget) {+ note(args)+ return Reflect.construct(target, args, newTarget)+ },+ apply(target, thisArg, args) {+ note(args)+ return Reflect.apply(target, thisArg, args)+ },+ })+ try {+ return { result: await run(), sources }+ } finally {+ globalThis.Function = real+ }+}++/** What rag.ts asked pdf.js to load its worker from. */+let requestedWorkerSrc = ''++beforeAll(async () => {+ // rag.ts loads pdf.js lazily. Import it once up front so module evaluation —+ // which legitimately builds functions — happens outside the trap below.+ const pdfjsLib = await import('pdfjs-dist/legacy/build/pdf.mjs')++ // Vite rewrites `new URL(<bare specifier>, import.meta.url)` into an emitted+ // asset URL for the client build only. Vitest runs the node module graph, so+ // rag.ts's worker URL resolves next to src/api/ and points at nothing. Keep+ // what it asked for — that string is the privacy and compatibility+ // invariant — and hand pdf.js the copy that is actually on disk.+ const onDisk = pathToFileURL(+ resolve(__dirname, '../../../node_modules/pdfjs-dist/legacy/build/pdf.worker.min.mjs'),+ ).href+ Object.defineProperty(pdfjsLib.GlobalWorkerOptions, 'workerSrc', {+ configurable: true,+ get: () => onDisk,+ set: (value: string) => { requestedWorkerSrc = value },+ })+})++describe('the PDF worker is bundled, not fetched', () => {+ it('points at the local legacy worker and never at a remote origin', async () => {+ await extractText(asFile(textPdf(['worker source probe'])))+ expect(requestedWorkerSrc).toMatch(/pdfjs-dist\/legacy\/build\/pdf\.worker\.min\.mjs$/)+ expect(requestedWorkerSrc).not.toMatch(/^https?:/)+ })+})++describe('PDF text extraction still works after the pdfjs 6 jump', () => {+ it('reads the text out of a real single-page PDF', async () => {+ const text = await extractText(asFile(textPdf(['Locally Uncensored RAG probe'])))+ expect(text).toContain('Locally Uncensored RAG probe')+ })++ it('keeps every page, separated by a blank line', async () => {+ const text = await extractText(asFile(textPdf(['first page marker', 'second page marker'])))+ expect(text).toContain('first page marker')+ expect(text).toContain('second page marker')+ expect(text.split('\n\n')).toHaveLength(2)+ })++ it('reports which file failed instead of a bare parser error', async () => {+ const notAPdf = asFile(new TextEncoder().encode('this is not a PDF at all'), 'broken.pdf')+ await expect(extractText(notAPdf)).rejects.toThrow(/broken\.pdf/)+ })+})++describe('GHSA-hq66-cqwq-w95j — a PDF cannot get its own code executed', () => {+ it('builds no function while extracting text from a PostScript-function PDF', async () => {+ const { result, sources } = await recordFunctionSources(() =>+ extractText(asFile(postScriptFunctionPdf('carrier document'))),+ )+ expect(result).toContain('carrier document')+ expect(sources).toEqual([])+ })++ it('builds no function even on the path that used to compile the program', async () => {+ // Text extraction never asks for an operator list, so this is the sink the+ // advisory describes reached deliberately: on 5.6.205 it hands the+ // document's own compiled program to `new Function`, here it must not.+ const pdfjsLib = await import('pdfjs-dist/legacy/build/pdf.mjs')+ const { sources } = await recordFunctionSources(async () => {+ const doc = await pdfjsLib.getDocument({+ data: postScriptFunctionPdf('carrier document'),+ enableXfa: false,+ }).promise+ const page = await doc.getPage(1)+ await page.getOperatorList()+ })+ expect(sources).toEqual([])+ })+})diff --git a/src/api/rag.ts b/src/api/rag.tsindex 7162a953..ac016b85 100644--- a/src/api/rag.ts+++ b/src/api/rag.ts@@ -16,12 +16,52 @@ export async function extractText(file: File): Promise<string> {}}+/**+ * A dropped PDF is attacker-controlled input, and only the packaged app has a+ * CSP behind it — the browser and from-source lanes run this with nothing else+ * in the way.+ *+ * GHSA-hq66-cqwq-w95j (pdfjs-dist >= 5.6.83, < 6.2.108, which is what 2.6.7+ * shipped): a PostScript calculator function (`/FunctionType 4`) inside a+ * document was compiled to JavaScript source and handed to `new Function`+ * whenever the `getDocument` option `isEvalSupported` kept its default `true`.+ *+ * That sink sat one call away, not zero: measured on 5.6.205, the sequence+ * below — getDocument, getPage, getTextContent — compiles nothing, while+ * `getOperatorList` on the same file hands the document's own program to+ * `new Function`. Text extraction never renders, so this path did not execute+ * the payload; the next person to reach for a thumbnail or a page preview+ * would have. 6.2.108 replaced the compiler with a WebAssembly one and DELETED+ * the option, so the floor in package.json is the fix and there is no flag+ * left to pass. rag-pdf-eval.test.ts holds the sink shut by measurement,+ * pdfjs-supply-chain.test.ts holds the floor.+ *+ * `enableScripting` is not a `getDocument` option in any 5.x or 6.x; it gates+ * the AnnotationLayer, which text extraction never constructs, so a document's+ * own /JavaScript actions have nothing to run in.+ */async function extractTextFromPDF(file: File): Promise<string> {- const pdfjsLib = await import("pdfjs-dist")+ // The `legacy` build, not the default one. pdfjs 6's modern bundle calls+ // Uint8Array.prototype.toHex / Uint8Array.fromBase64 while parsing, and those+ // shipped only in Safari 18.2, Firefox 133 and Chrome 140 — every older+ // WKWebView, WebKitGTK and WebView2 dies with "toHex is not a function", and+ // so does Node (measured on 24.15), which is what the tests run in. `legacy`+ // carries the polyfills for exactly this.+ const pdfjsLib = await import("pdfjs-dist/legacy/build/pdf.mjs")// Use local worker — never load from CDN to protect privacy- pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).href+ pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/legacy/build/pdf.worker.min.mjs', import.meta.url).hrefconst arrayBuffer = await file.arrayBuffer()- const doc = await pdfjsLib.getDocument({ data: arrayBuffer }).promise+ const doc = await pdfjsLib.getDocument({+ data: arrayBuffer,+ // XFA is a second, script-carrying document format that pdf.js only parses+ // on request. Pinned off so a future change of the default cannot reopen+ // it under us.+ enableXfa: false,+ // CMap / standard-font / wasm URLs stay unset on purpose: each one is a+ // fetch whose path comes out of the document, and this app promises that a+ // dropped file is processed locally. Absence is the property, not an+ // oversight — the legacy build carries what it needs inline.+ }).promiseconst pages: string[] = []for (let i = 1; i <= doc.numPages; i++) {const page = await doc.getPage(i)