From 5556530826aa7ded68eb143c3af39f5e404ec96b Mon Sep 17 00:00:00 2001 From: maruson08 Date: Wed, 7 Oct 2026 19:28:11 +0900 Subject: [PATCH 01/12] =?UTF-8?q?=F0=9F=94=A7[Config]=20Bootstrap=20v2.3?= =?UTF-8?q?=20development=20cycle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 2 +- AGENTS.md | 12 +- docs/development-workflow.md | 18 +-- docs/v2.3-bootstrap.md | 179 +++++++++++++++++++++++++++++ scripts/validate-branch-policy.mjs | 4 +- tests/branch-policy.test.mjs | 29 +++-- tests/ci-foundation.test.mjs | 2 +- 7 files changed, 215 insertions(+), 31 deletions(-) create mode 100644 docs/v2.3-bootstrap.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e278d6b..90bb253 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,7 @@ on: branches: - main - v2 - - v2.2 + - v2.3 permissions: contents: read diff --git a/AGENTS.md b/AGENTS.md index c1e8df3..af82669 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,13 +2,13 @@ ## Protected branches -- `main` is production-only. `v2.2` is the active integration branch for the v2.2.0 development cycle. -- Never commit feature, fix, test, or chore work directly to `main` or `v2.2`. +- `main` is production-only. `v2.3` is the active integration branch for the v2.3.0 development cycle. +- Never commit feature, fix, test, or chore work directly to `main` or `v2.3`. ## Development work -- Create short-lived `feat/*`, `fix/*`, `test/*`, or `chore/*` branches from `v2.2`. -- Sprint and routine development pull requests target `v2.2`, not `main`. +- Create short-lived `feat/*`, `fix/*`, `test/*`, or `chore/*` branches from `v2.3`. +- Sprint and routine development pull requests target `v2.3`, not `main`. - After a successful merge, delete only the merged short-lived branch when cleanup is authorized. ## Commit messages @@ -30,8 +30,8 @@ ## Production promotion -- Normal development reaches `main` only through a dedicated release or hardening pull request from `v2.2`. -- Creating the v2.2.0 tag or release requires separate explicit authorization after final verification. +- Normal development reaches `main` only through a dedicated release or hardening pull request from `v2.3`. +- Creating the v2.3.0 tag or release requires separate explicit authorization after final verification. ## Hotfixes diff --git a/docs/development-workflow.md b/docs/development-workflow.md index a8df0e6..f93a1f0 100644 --- a/docs/development-workflow.md +++ b/docs/development-workflow.md @@ -5,16 +5,16 @@ Secure Tools separates product versions from Sprint numbers. A Sprint is a bound ## Branch roles - `main` is the production branch. Routine development does not target it. -- `v2.2` is the active integration branch for the v2.2.0 cycle. -- Short-lived `feat/*`, `fix/*`, `test/*`, and `chore/*` branches start from `v2.2` and return through pull requests into `v2.2`. -- Direct feature or fix commits to `main` or `v2.2` are prohibited. +- `v2.3` is the active integration branch for the v2.3.0 cycle. +- Short-lived `feat/*`, `fix/*`, `test/*`, and `chore/*` branches start from `v2.3` and return through pull requests into `v2.3`. +- Direct feature or fix commits to `main` or `v2.3` are prohibited. ```text main (production) ↑ -release PR after v2.2 hardening +release PR after v2.3 hardening ↑ -v2.2 (active integration) +v2.3 (active integration) ↑ Sprint PRs ↑ @@ -23,10 +23,10 @@ feat/* fix/* test/* chore/* ## Sprint delivery -1. Update local `v2.2` from `origin/v2.2`. +1. Update local `v2.3` from `origin/v2.3`. 2. Create a short-lived branch from that exact integration state. 3. Commit and validate only the Sprint’s intended changes. -4. Open a pull request into `v2.2` and wait for required CI. +4. Open a pull request into `v2.3` and wait for required CI. 5. Treat review and merge as a separate step. An agent does not merge its own pull request or enable auto-merge unless the user explicitly authorizes that specific action. 6. After a successful merge and verification, remove the merged short-lived branch when branch cleanup is authorized. @@ -40,7 +40,7 @@ CI validates non-merge commits introduced by the pull request’s actual base-to ## Production release -The v2.1.0 cycle is released. The v2.2.0 cycle is active development. After the v2.2.0 scope is integrated, complete release hardening and final verification on `v2.2`. Promote it through a dedicated `v2.2` → `main` pull request. Only after that pull request is explicitly reviewed and merged may a separately authorized task create the v2.2.0 tag and release. +The v2.2.0 cycle is released. The v2.3.0 cycle is active development. After the v2.3.0 scope is integrated, complete release hardening and final verification on `v2.3`. Promote it through a dedicated `v2.3` → `main` pull request. Only after that pull request is explicitly reviewed and merged may a separately authorized task create the v2.3.0 tag and release. ## Hotfixes @@ -48,4 +48,4 @@ Urgent production fixes use a dedicated `hotfix/*` branch and pull request into ## Enforced pull request policy -CI permits routine `feat/*`, `fix/*`, `test/*`, and `chore/*` pull requests into `v2.2`. Pull requests into `main` pass the branch-policy gate only when the head is exactly `v2.2` or a dedicated `hotfix/*` branch. The repository protects both long-lived branches with required pull requests, the existing `Validate static tools` check, resolved review conversations, blocked force pushes, and blocked deletion. Because the repository currently has one maintainer, an approving-review count is not required; explicit merge authorization remains mandatory. +CI permits routine `feat/*`, `fix/*`, `test/*`, and `chore/*` pull requests into `v2.3`. Pull requests into `main` pass the branch-policy gate only when the head is exactly `v2.3` or a dedicated `hotfix/*` branch. The repository protects both long-lived branches with required pull requests, the existing `Validate static tools` check, resolved review conversations, blocked force pushes, and blocked deletion. Because the repository currently has one maintainer, an approving-review count is not required; explicit merge authorization remains mandatory. diff --git a/docs/v2.3-bootstrap.md b/docs/v2.3-bootstrap.md new file mode 100644 index 0000000..263f64b --- /dev/null +++ b/docs/v2.3-bootstrap.md @@ -0,0 +1,179 @@ +# v2.3 bootstrap and security audit delta + +Verified 2026-10-07 against production v2.2.0. This review reconciles the supplied +2026-09-28 finding list, not an unavailable full audit report. Historical CVE IDs +and most historical dependency versions were not supplied; absence of a current +advisory match is not evidence that a historical vulnerability was fixed. + +## Baseline + +- Repository: `SecureToolsProject/Secure_Tools`. +- Production `main`, `origin/main`, release tag `v2.2.0`, and new `v2.3` start at + `4b07f2962e524f4cfa5736de35e0f31ad52aaa15`. +- Toolchain observed locally: Node `24.16.0`, npm `11.13.0`; production workflows + select Node 24, use `npm ci --ignore-scripts`, TypeScript `7.0.2`, Playwright + `1.63.0`. Workflow runner/Node patch versions are not fixed reproducibility inputs. +- `main` remains production-only. Short-lived `feat/*`, `fix/*`, `test/*`, and + `chore/*` branches start from and target `v2.3`. Production promotion uses a + dedicated `v2.3 -> main` release PR. No automatic merges or release publication. +- `v2.3` protection mirrors existing `main`: strict `Validate static tools` check, + PR required, conversation resolution, admins enforced, no force push/deletion. + Required approving-review count remains the existing value of zero; explicit + human merge authorization remains repository policy. +- This bootstrap PR rolls AGENTS/workflow documentation, CI integration trigger, + and branch-policy tests forward. Unknown/retired PR bases now fail closed. + The policy rollover takes effect on integration after the PR is reviewed/merged. + +The three workflows are `.github/workflows/ci.yml` (PR/static/type/build/OCR gates), +`deploy-cloudflare-bridge.yml` (main-only isolated Cloudflare Pages deployment and +GitHub deployment status), and `production-smoke.yml` (manual verification of +canonical and immutable production origins, with retained evidence). + +Production is `https://tools.securetools.app`; verified immutable deployment is +`https://94144189.secure-tools-web-bridge.pages.dev`. Successful deployment +[run 37576953311](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/37576953311) +links GitHub deployment `6902567301`, source SHA above, and Cloudflare deployment +`94144189-f211-43ec-b031-fe7935418a5c`. Successful clean-runner production verification +[run 37577312702](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/37577312702) +reported no third-party requests, analytics, or CSP violations on either origin. +No deployment, Hub, DNS, analytics settings, dependencies, or runtime code change +is part of this bootstrap. + +## Audit delta matrix + +Paths/lines below refer to the baseline unless explicitly identified as bootstrap. +The exact classifications apply to current evidence, not assumptions about the +historical code. + +| Finding | Current status | Evidence | Necessary next action | Priority / issue | +| --- | --- | --- | --- | --- | +| F-06 Artifact/source provenance | PARTIALLY RESOLVED | Deployment workflow lines 26, 130–135 checks out the triggering commit and supplies its SHA to Pages; GitHub/Cloudflare deployment IDs and release above agree. `tests/production/smoke.mjs:55–64` compares hashes of 15 selected assets across origins. `scripts/build-site.mjs:11–64` does not emit a source/build manifest. | Add compact SHA/toolchain/file-digest manifest, retain deployment artifact identity, verify deployed bytes. Existing selected-asset checks are not complete reproducibility proof. | P1 / [#112](https://github.com/SecureToolsProject/Secure_Tools/issues/112) | +| F-02 Mutable Actions | PARTIALLY RESOLVED | Two deployment Actions already use full SHAs. Six other uses are mutable across all three workflows; details below. No `dependabot.yml`; repository SHA-pinning requirement is disabled. | Pin six references to verified intended releases; update contract tests; maintain pins with targeted Dependabot configuration and review. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | +| F-01 PDF admission | OPEN | `tools/shared/pdf.js:22–33` accepts MIME/name hints then calls `PDFDocument.load`; `pdf-ocr.ts:215–216` returns unchecked bytes; `pdf-renderer.js:18–27` passes bytes to PDF.js. No required `%PDF-` pre-validation. Parser failures are caught, and renderer evaluation/worker fetching/WASM are disabled. | Shared byte validator before original-source parser entry, with documented header-offset compatibility policy and negative fixtures; preserve existing limits/fail-closed parsing. | P2 / [#114](https://github.com/SecureToolsProject/Secure_Tools/issues/114) | +| F-03 Disclosure | OPEN | Root `SECURITY.md` absent; GitHub private vulnerability reporting API reports `enabled: false`. | Document supported versions, verified private reporting route, coordinated disclosure, scope/non-goals, and warning against attaching sensitive files; enable route where permitted. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | +| F-04 Independent scanning | OPEN | CI runs custom `security-hardening.test.mjs` and `release-gate.test.mjs`, but no CodeQL, Dependency Review, OSV/npm-audit job, or Dependabot configuration. GitHub reports security updates/secret scanning disabled and no code-scanning analysis. | Small complementary JS/TS SAST and vendor-aware advisory monitoring; use lockfile audit for its actual coverage, without duplicating scanners. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | +| F-05 HTTP headers | PARTIALLY RESOLVED | Root/Image-to-Text/PDF-to-Text HTML and JS checked on both production origins: `nosniff` and `strict-origin-when-cross-origin` present; HTTP CSP and Permissions-Policy absent. Meta CSP in `index.html:10` and OCR pages line 4 contains `connect-src 'none'`, but no HTTP `frame-ancestors`. Generated deployment `_headers` covers alias noindex only (workflow lines 77–86). | Hosting-level CSP with `frame-ancestors 'none'` and appropriate Permissions-Policy; preserve same-origin worker/WASM/font/Blob flows and existing Referrer-Policy/nosniff. | P1 / [#117](https://github.com/SecureToolsProject/Secure_Tools/issues/117) | + +### Provenance scope + +The release tag is lightweight/unsigned; a signed merge commit is not a signed +release artifact. Neither deployment nor verification workflow emits artifact +attestations or a complete durable file manifest. A reproducible byte-for-byte +build has not been demonstrated. The smallest useful follow-up is the manifest +and deployment verification above, accounting explicitly for Cloudflare HTML +rewrites. No heavyweight attestation platform is required by this review. + +### Verified Action releases + +Upstream tag objects were resolved to commit SHAs through GitHub on the review +date. Reconfirm before implementing; preserve intended major versions. + +| Action / intended release | Verified commit SHA | Current uses | +| --- | --- | --- | +| `actions/checkout` v4.4.0 | `11d5960a326750d5838078e36cf38b85af677262` | Mutable `@v4`: CI line 22; production smoke line 37 | +| `actions/setup-node` v4.4.0 | `49933ea5288caeca8642d1e84afbd3f7d6820020` | Mutable `@v4`: CI line 27; deployment line 31; production smoke line 40 | +| `actions/upload-artifact` v4.6.2 | `ea165f8d65b6e75b540449e92b4886f43607fa02` | Mutable `@v4`: production smoke line 52 | +| `actions/checkout` v6.0.2 | `de0fac2e4500dabe0009e67214ff5f5447ce83dd` | Already pinned: deployment line 26 | +| `cloudflare/wrangler-action` v4.0.0 | `ebbaa1584979971c8614a24965b4405ff95890e0` | Already pinned: deployment line 130 | + +[Dependabot supports maintaining Action references, including commit pins](https://docs.github.com/en/code-security/how-tos/secure-your-supply-chain/secure-your-dependencies/auto-update-actions). +Use a configuration targeting the active integration branch and explicit review; +do not enable auto-merge. Existing tests expecting mutable `@v4` must be updated +with the separate pinning change, not disabled. + +### PDF boundary and regression scope + +Filename/MIME remain hints; bytes must pass admission before parser entry, with +parser errors remaining the final rejection layer. Cover valid PDFs, non-PDF +`.pdf` files, invalid `application/pdf` content, empty files, truncated files, +and malformed corpus samples. Assert that invalid signatures never reach either +parser, and that malformed content with a valid header still fails parsing. +Preserve `pdf-ocr.ts:8–10,132–135` bounds (16,384 dimension, 50 million pixels, +large-page warning) and cancellation/resource cleanup. A signature is not a +guarantee of safe or well-formed content. + +### Monitoring limitations + +`npm audit` completed successfully with zero reported vulnerabilities for the +lockfile. It does not cover every directly vendored browser library. Exact-version +OSV queries returned no matching advisories for the packages below. GitHub +Dependabot-alert API returned 403 with alerts explicitly disabled; this is not an +empty clean alert list. No access-scope escalation was attempted. Code-scanning +API reported no analysis. These are monitoring gaps, not verified exploits. + +## Dependency delta + +The supplied historical snapshot explicitly identifies only JSZip 3.10.1 and its +3.10.2 follow-up; do not invent other historical versions or CVE fixes. All listed +browser assets are local and hash-gated: `tests/release-gate.test.mjs:20–80` covers +the direct vendored libraries/secure-metadata; `tests/ocr-foundation.test.mjs:182–219` +covers the OCR manifest; searchable-PDF asset preparation/tests cover fontkit/fonts. + +Each dependency/CVE follow-up remains **PARTIALLY RESOLVED**: pinned versions, +hash gates, and the current advisory check are verified, but historical CVE +identity and comprehensive continuous vendor monitoring are absent (issue #116). +This classification does not imply an active known vulnerability or mandate an +upgrade. Maintenance and patch-lag findings are separately classified below. + +| Runtime input | Current pin | Registry latest observed | CVE follow-up status / decision | +| --- | --- | --- | --- | +| `pdfjs-dist` | 6.2.108 | 6.4.299 | PARTIALLY RESOLVED; no OSV match for pin; newer alone does not justify update | +| `jspdf` | 4.2.1 | 4.2.1 | PARTIALLY RESOLVED; no OSV match; retain | +| `jszip` | 3.10.1 | 3.10.2 | PARTIALLY RESOLVED; no OSV match; assess compatibility changes below | +| `pdf-lib` | 1.17.1 | 1.17.1 | PARTIALLY RESOLVED; no OSV match; maintenance assessment needed | +| `tesseract.js` | 7.0.0 | 7.0.0 | PARTIALLY RESOLVED; no OSV match; retain | +| `tesseract.js-core` | 7.0.0 | 6.1.2 dist-tag | PARTIALLY RESOLVED; published 7.0.0 exists and matches existing Tesseract inputs; do not infer downgrade from dist-tag | +| `secure-metadata` | 0.1.1 | GitHub v0.1.1 | PARTIALLY RESOLVED; upstream release verified; npm registry returns 404, OSV name query is insufficient coverage; monitor GitHub source | +| `@pdf-lib/fontkit` | 1.1.1 | 1.1.1 | PARTIALLY RESOLVED; no OSV match; retain | +| `@fontsource/noto-sans-kr` | 5.3.0 | 5.3.0 | PARTIALLY RESOLVED; no OSV match; retain | +| `@tesseract.js-data/eng` | 1.0.0 | 1.0.0 | PARTIALLY RESOLVED; no OSV match; retain | +| `@tesseract.js-data/kor` | 1.0.0 | 1.0.0 | PARTIALLY RESOLVED; no OSV match; retain | + +- **pdf-lib maintenance: OPEN, P2.** Latest npm release 1.17.1 dates to 2021; + upstream is not archived, but last observed push was 2024-07-17. Merge, split, + organize, metadata editing, and searchable-PDF composition depend on its + parser/manipulation behavior (`tools/shared/pdf.js` and searchable-PDF modules). + Local processing still exposes untrusted PDF parsing. Investigate a maintained + compatible fork first; browser-local qpdf/MuPDF WASM alternatives require + feature, size, performance, licensing, privacy, and malformed-input evaluation. + Scope the investigation to v2.3; replacing it requires separate justified work. + [Upstream releases](https://github.com/Hopding/pdf-lib/releases). +- **JSZip patch lag: OPEN, P2.** The official + [3.10.2 changelog](https://raw.githubusercontent.com/Stuk/jszip/v3.10.2/CHANGES.md) + lists cross-realm binary type detection, missing type defaults, and Node >=18 + Blob support; it does not state a security fix. Secure Tools creates browser + ZIPs from local generated inputs. Demonstrate a relevant compatibility benefit + before upgrading; no automatic dependency refresh is warranted. +- These two maintenance assessments share [#118](https://github.com/SecureToolsProject/Secure_Tools/issues/118). + Any justified update must regenerate vendor assets, update SHA-256 and release + gates, verify license metadata, and pass relevant regressions in a separate PR. + +## v2.3 security gate + +- **P0:** No active Critical/High advisory or broken privacy invariant identified + in this review. This is a bounded assessment, not a claim that scanners cover + all vendor/transitive code. Any newly confirmed P0 blocks feature work. +- **P1:** Artifact provenance (#112), remaining Action pins (#113), HTTP CSP and + embedding/permissions boundary (#117). Use dedicated reviewed hardening PRs. +- **P2:** PDF admission (#114), disclosure (#115), independent monitoring (#116), + dependency maintenance/compatibility assessment (#118). + +> v2.3 feature development may begin after the bootstrap branch is established and all P0 findings are cleared. P1/P2 findings may proceed as dedicated hardening PRs unless they block the safety of new feature work. + +Bootstrap tracking: [#111](https://github.com/SecureToolsProject/Secure_Tools/issues/111). +Recommended first implementation: #112, a compact source/file-hash manifest and +deployed-artifact verification extending the existing v2.2 evidence. + +## Verification and preserved invariants + +Required bootstrap checks: clean pinned install, full `npm test` (includes custom +security/release gates), production `npm run build`, `scripts/validate-build.mjs`, +and real local OCR smoke. Record actual results in the bootstrap PR. + +Generic/GitHub Pages output intentionally retains the pre-existing root `CNAME`; +deployment strips it only from the isolated Cloudflare bridge copy +(`deploy-cloudflare-bridge.yml:62–88`, tested by `tests/cloudflare-bridge.test.mjs`). +Do not mistake preserving this tested separation for introducing a legacy CNAME +into Cloudflare. No CNAME, deployed header, analytics/RUM, runtime network API, +file-upload, CDN, or local-processing behavior changes in this PR. Tests retain +fail-closed privacy/security checks. Production remains at the verified baseline. diff --git a/scripts/validate-branch-policy.mjs b/scripts/validate-branch-policy.mjs index 039de60..e3ff75f 100644 --- a/scripts/validate-branch-policy.mjs +++ b/scripts/validate-branch-policy.mjs @@ -1,7 +1,7 @@ import { fileURLToPath } from "node:url"; import { execFileSync } from "node:child_process"; -export const ACTIVE_INTEGRATION_BRANCH = "v2.2"; +export const ACTIVE_INTEGRATION_BRANCH = "v2.3"; const routineBranch = /^(?:feat|fix|test|chore)\/.+$/; const hotfixBranch = /^hotfix\/.+$/; @@ -76,7 +76,7 @@ export function validateBranchPolicy(baseRef, headRef) { }; } - return { valid: true, reason: null }; + return { valid: false, reason: `Unsupported pull request base ${baseRef}; use ${ACTIVE_INTEGRATION_BRANCH} or an authorized main promotion/hotfix.` }; } export function run([baseRef, headRef] = process.argv.slice(2)) { diff --git a/tests/branch-policy.test.mjs b/tests/branch-policy.test.mjs index d6d3aed..e355573 100644 --- a/tests/branch-policy.test.mjs +++ b/tests/branch-policy.test.mjs @@ -9,14 +9,14 @@ import { validateProductionVerificationLock, } from "../scripts/validate-branch-policy.mjs"; -assert.equal(ACTIVE_INTEGRATION_BRANCH, "v2.2"); +assert.equal(ACTIVE_INTEGRATION_BRANCH, "v2.3"); for (const [headRef, baseRef] of [ - ["feat/example", "v2.2"], - ["fix/example", "v2.2"], - ["test/example", "v2.2"], - ["chore/example", "v2.2"], - ["v2.2", "main"], + ["feat/example", "v2.3"], + ["fix/example", "v2.3"], + ["test/example", "v2.3"], + ["chore/example", "v2.3"], + ["v2.3", "main"], ["hotfix/example", "main"], ]) { assert.deepEqual(validateBranchPolicy(baseRef, headRef), { valid: true, reason: null }, `${headRef} → ${baseRef}`); @@ -29,19 +29,24 @@ for (const [headRef, baseRef] of [ ["test/example", "main"], ["chore/example", "main"], ["v2.1", "main"], + ["v2.2", "main"], ]) { const result = validateBranchPolicy(baseRef, headRef); assert.equal(result.valid, false, `${headRef} → ${baseRef}`); - assert.match(result.reason, /Only v2\.2 release promotion or an explicit hotfix/); - assert.throws(() => run([baseRef, headRef]), /Only v2\.2 release promotion or an explicit hotfix/); + assert.match(result.reason, /Only v2\.3 release promotion or an explicit hotfix/); + assert.throws(() => run([baseRef, headRef]), /Only v2\.3 release promotion or an explicit hotfix/); } for (const headRef of ["v2.1", "main", "hotfix/example", "feature/example"]) { - const result = validateBranchPolicy("v2.2", headRef); - assert.equal(result.valid, false, `${headRef} → v2.2`); - assert.match(result.reason, /Pull requests into v2\.2 must come from feat\/\*, fix\/\*, test\/\*, or chore\/\*/); + const result = validateBranchPolicy("v2.3", headRef); + assert.equal(result.valid, false, `${headRef} → v2.3`); + assert.match(result.reason, /Pull requests into v2\.3 must come from feat\/\*, fix\/\*, test\/\*, or chore\/\*/); } +for (const base of ["v2.2", "v2.1", "unknown"]) { + assert.equal(validateBranchPolicy(base, "feat/example").valid, false); + assert.throws(() => run([base, "feat/example"]), /Unsupported pull request base/); +} assert.throws(() => run([]), /Usage:/); assert.equal(validateBranchPolicy("main", "fix/production-deploy-workflow").valid, true); assert.equal(validateBranchPolicy("main", "fix/production-deploy-workflow-other").valid, false); @@ -78,4 +83,4 @@ assert.throws(() => validateProductionVerificationLock(originalLock, changedLock const leakedRuntime = structuredClone(verificationLock); leakedRuntime.packages["node_modules/playwright"].dev = false; assert.throws(() => validateProductionVerificationLock(originalLock, leakedRuntime), /test-only Playwright/); -console.log("v2.2 integration, production promotion, hotfix, and rejection branch-policy checks passed."); +console.log("v2.3 integration, production promotion, hotfix, and rejection branch-policy checks passed."); diff --git a/tests/ci-foundation.test.mjs b/tests/ci-foundation.test.mjs index f4631b9..aec7ba6 100644 --- a/tests/ci-foundation.test.mjs +++ b/tests/ci-foundation.test.mjs @@ -4,7 +4,7 @@ import fs from "node:fs"; const workflow = fs.readFileSync(".github/workflows/ci.yml", "utf8"); assert.match(workflow, /^name: CI$/m); assert.match(workflow, /^\s{2}pull_request:$/m); -assert.match(workflow, /^\s{2}push:\s*$[\s\S]*?^\s{6}- main$[\s\S]*?^\s{6}- v2$[\s\S]*?^\s{6}- v2\.2$/m); +assert.match(workflow, /^\s{2}push:\s*$[\s\S]*?^\s{6}- main$[\s\S]*?^\s{6}- v2$[\s\S]*?^\s{6}- v2\.3$/m); assert.match(workflow, /uses: actions\/checkout@v4/); assert.match(workflow, /uses: actions\/setup-node@v4/); assert.match(workflow, /node-version: 24/); From 60fdd5576533f97d5dfd53b6ed0adfcf870bf0b5 Mon Sep 17 00:00:00 2001 From: maruson08 Date: Wed, 7 Oct 2026 20:00:00 +0900 Subject: [PATCH 02/12] =?UTF-8?q?=F0=9F=94=A7[Config]=20Add=20production?= =?UTF-8?q?=20artifact=20provenance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 3 + .../workflows/deploy-cloudflare-bridge.yml | 7 +- .github/workflows/production-smoke.yml | 11 + docs/production-verification.md | 13 +- docs/v2.3-bootstrap.md | 229 ++++++++++++++++++ scripts/build-provenance.mjs | 50 ++++ scripts/build-site.mjs | 4 + scripts/validate-build.mjs | 2 + scripts/verify-build-provenance.mjs | 19 ++ tests/build-provenance.test.mjs | 102 ++++++++ tests/cloudflare-bridge.test.mjs | 2 + tests/production/smoke.mjs | 7 + tests/run-all.mjs | 1 + 13 files changed, 448 insertions(+), 2 deletions(-) create mode 100644 docs/v2.3-bootstrap.md create mode 100644 scripts/build-provenance.mjs create mode 100644 scripts/verify-build-provenance.mjs create mode 100644 tests/build-provenance.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e278d6b..021f852 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,6 +70,9 @@ jobs: - name: Verify prepared production OCR assets run: npm run build + - name: Validate generated artifact and source provenance + run: node scripts/validate-build.mjs + - name: Run static tool validation run: npm test diff --git a/.github/workflows/deploy-cloudflare-bridge.yml b/.github/workflows/deploy-cloudflare-bridge.yml index 36b3404..f4ad388 100644 --- a/.github/workflows/deploy-cloudflare-bridge.yml +++ b/.github/workflows/deploy-cloudflare-bridge.yml @@ -139,6 +139,11 @@ jobs: DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }} run: node tests/deployment-smoke.mjs "$DEPLOYMENT_URL" noindex + - name: Verify deployed source provenance + env: + DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }} + run: node scripts/verify-build-provenance.mjs "$DEPLOYMENT_URL" "$GITHUB_SHA" + - name: Validate stable deployment aliases shell: bash run: | @@ -147,7 +152,7 @@ jobs: local indexing="$2" for attempt in 1 2 3 4 5 6; do - if node tests/deployment-smoke.mjs "$url" "$indexing"; then + if node tests/deployment-smoke.mjs "$url" "$indexing" && node scripts/verify-build-provenance.mjs "$url" "$GITHUB_SHA"; then return 0 fi [[ "$attempt" -lt 6 ]] || return 1 diff --git a/.github/workflows/production-smoke.yml b/.github/workflows/production-smoke.yml index c009812..28b9aee 100644 --- a/.github/workflows/production-smoke.yml +++ b/.github/workflows/production-smoke.yml @@ -12,6 +12,10 @@ on: description: Immutable deployment origin to compare required: true type: string + source_commit: + description: Full source SHA of the deployment being verified + required: true + type: string # Bootstrap this new workflow before its explicitly authorized merge. # Ordinary development PRs do not run the production browser gate. pull_request: @@ -33,15 +37,22 @@ jobs: env: PRODUCTION_ORIGIN: ${{ inputs.production_origin || 'https://tools.securetools.app' }} IMMUTABLE_ORIGIN: ${{ inputs.immutable_origin || 'https://b9802e7e.secure-tools-web-bridge.pages.dev' }} + EXPECTED_PRODUCTION_SHA: ${{ inputs.source_commit || github.sha }} steps: - uses: actions/checkout@v4 with: persist-credentials: false + # Read canonical version and verification code from the expected deployment. + ref: ${{ inputs.source_commit || github.sha }} - uses: actions/setup-node@v4 with: node-version: 24 cache: npm - run: npm ci --ignore-scripts + - name: Require deployment source provenance + run: | + node scripts/verify-build-provenance.mjs "$PRODUCTION_ORIGIN" "$EXPECTED_PRODUCTION_SHA" + node scripts/verify-build-provenance.mjs "$IMMUTABLE_ORIGIN" "$EXPECTED_PRODUCTION_SHA" - run: npx playwright install --with-deps chromium - run: npm run test:production - name: Publish technical result diff --git a/docs/production-verification.md b/docs/production-verification.md index cb26925..82a2272 100644 --- a/docs/production-verification.md +++ b/docs/production-verification.md @@ -2,7 +2,18 @@ Run `npm ci --ignore-scripts`, `npx playwright install --with-deps chromium`, then `npm run test:production` with `PRODUCTION_ORIGIN` and `IMMUTABLE_ORIGIN` set to -the canonical and deployment-specific HTTPS origins. Node 24 is required. +the canonical and deployment-specific HTTPS origins and `EXPECTED_PRODUCTION_SHA` +set to the full lowercase source commit SHA. Check out that source commit so its +canonical package version matches the deployment. Node 24 is required. + +The manual workflow requires `source_commit`, checks out that exact commit, and +checks `/build-info.json` on both origins before browser gates. The strict public +record must match the expected SHA, the checked-out `package.json` version, schema +1, and the GitHub Actions build marker. Missing JSON, redirects, fallback HTML, +unsupported fields, or mismatches fail signoff. The deployment workflow also +checks this record on the immutable URL and both stable aliases, with existing +alias propagation retries. A small record binds declared source identity; it is +not a signed attestation, full artifact digest, or proof of reproducible builds. Use the **Production smoke** workflow's manual dispatch inputs for release signoff. The initial infrastructure PR has a narrowly scoped bootstrap trigger; diff --git a/docs/v2.3-bootstrap.md b/docs/v2.3-bootstrap.md new file mode 100644 index 0000000..bf9a144 --- /dev/null +++ b/docs/v2.3-bootstrap.md @@ -0,0 +1,229 @@ +# v2.3 bootstrap and security audit delta + +Verified 2026-10-07 against production v2.2.0. This review reconciles the supplied +2026-09-28 finding list, not an unavailable full audit report. Historical CVE IDs +and most historical dependency versions were not supplied; absence of a current +advisory match is not evidence that a historical vulnerability was fixed. + +## Baseline + +- Repository: `SecureToolsProject/Secure_Tools`. +- Production `main`, `origin/main`, release tag `v2.2.0`, and new `v2.3` start at + `4b07f2962e524f4cfa5736de35e0f31ad52aaa15`. +- Toolchain observed locally: Node `24.16.0`, npm `11.13.0`; production workflows + select Node 24, use `npm ci --ignore-scripts`, TypeScript `7.0.2`, Playwright + `1.63.0`. Workflow runner/Node patch versions are not fixed reproducibility inputs. +- `main` remains production-only. Short-lived `feat/*`, `fix/*`, `test/*`, and + `chore/*` branches start from and target `v2.3`. Production promotion uses a + dedicated `v2.3 -> main` release PR. No automatic merges or release publication. +- `v2.3` protection mirrors existing `main`: strict `Validate static tools` check, + PR required, conversation resolution, admins enforced, no force push/deletion. + Required approving-review count remains the existing value of zero; explicit + human merge authorization remains repository policy. +- This bootstrap PR rolls AGENTS/workflow documentation, CI integration trigger, + and branch-policy tests forward. Unknown/retired PR bases now fail closed. + The policy rollover takes effect on integration after the PR is reviewed/merged. + +The three workflows are `.github/workflows/ci.yml` (PR/static/type/build/OCR gates), +`deploy-cloudflare-bridge.yml` (main-only isolated Cloudflare Pages deployment and +GitHub deployment status), and `production-smoke.yml` (manual verification of +canonical and immutable production origins, with retained evidence). + +Production is `https://tools.securetools.app`; verified immutable deployment is +`https://94144189.secure-tools-web-bridge.pages.dev`. Successful deployment +[run 37576953311](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/37576953311) +links GitHub deployment `6902567301`, source SHA above, and Cloudflare deployment +`94144189-f211-43ec-b031-fe7935418a5c`. Successful clean-runner production verification +[run 37577312702](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/37577312702) +reported no third-party requests, analytics, or CSP violations on either origin. +No deployment, Hub, DNS, analytics settings, dependencies, or runtime code change +is part of this bootstrap. + +## Audit delta matrix + +Paths/lines below refer to the baseline unless explicitly identified as bootstrap. +The exact classifications apply to current evidence, not assumptions about the +historical code. + +| Finding | Current status | Evidence | Necessary next action | Priority / issue | +| --- | --- | --- | --- | --- | +| F-06 Artifact/source provenance | PARTIALLY RESOLVED | Deployment workflow lines 26, 130–135 checks out the triggering commit and supplies its SHA to Pages; GitHub/Cloudflare deployment IDs and release above agree. `tests/production/smoke.mjs:55–64` compares hashes of 15 selected assets across origins. `scripts/build-site.mjs:11–64` does not emit a source/build manifest. | Issue #112 implementation generates and verifies a compact public source record; see the addendum below. Production promotion/live confirmation remains pending, and this is not a complete digest/reproducibility proof. | P1 / [#112](https://github.com/SecureToolsProject/Secure_Tools/issues/112) | +| F-02 Mutable Actions | PARTIALLY RESOLVED | Two deployment Actions already use full SHAs. Six other uses are mutable across all three workflows; details below. No `dependabot.yml`; repository SHA-pinning requirement is disabled. | Pin six references to verified intended releases; update contract tests; maintain pins with targeted Dependabot configuration and review. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | +| F-01 PDF admission | OPEN | `tools/shared/pdf.js:22–33` accepts MIME/name hints then calls `PDFDocument.load`; `pdf-ocr.ts:215–216` returns unchecked bytes; `pdf-renderer.js:18–27` passes bytes to PDF.js. No required `%PDF-` pre-validation. Parser failures are caught, and renderer evaluation/worker fetching/WASM are disabled. | Shared byte validator before original-source parser entry, with documented header-offset compatibility policy and negative fixtures; preserve existing limits/fail-closed parsing. | P2 / [#114](https://github.com/SecureToolsProject/Secure_Tools/issues/114) | +| F-03 Disclosure | OPEN | Root `SECURITY.md` absent; GitHub private vulnerability reporting API reports `enabled: false`. | Document supported versions, verified private reporting route, coordinated disclosure, scope/non-goals, and warning against attaching sensitive files; enable route where permitted. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | +| F-04 Independent scanning | OPEN | CI runs custom `security-hardening.test.mjs` and `release-gate.test.mjs`, but no CodeQL, Dependency Review, OSV/npm-audit job, or Dependabot configuration. GitHub reports security updates/secret scanning disabled and no code-scanning analysis. | Small complementary JS/TS SAST and vendor-aware advisory monitoring; use lockfile audit for its actual coverage, without duplicating scanners. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | +| F-05 HTTP headers | PARTIALLY RESOLVED | Root/Image-to-Text/PDF-to-Text HTML and JS checked on both production origins: `nosniff` and `strict-origin-when-cross-origin` present; HTTP CSP and Permissions-Policy absent. Meta CSP in `index.html:10` and OCR pages line 4 contains `connect-src 'none'`, but no HTTP `frame-ancestors`. Generated deployment `_headers` covers alias noindex only (workflow lines 77–86). | Hosting-level CSP with `frame-ancestors 'none'` and appropriate Permissions-Policy; preserve same-origin worker/WASM/font/Blob flows and existing Referrer-Policy/nosniff. | P1 / [#117](https://github.com/SecureToolsProject/Secure_Tools/issues/117) | + +### Provenance scope + +The release tag is lightweight/unsigned; a signed merge commit is not a signed +release artifact. Neither deployment nor verification workflow emits artifact +attestations or a complete durable file manifest. A reproducible byte-for-byte +build has not been demonstrated. The smallest useful follow-up is the manifest +and deployment verification above, accounting explicitly for Cloudflare HTML +rewrites. No heavyweight attestation platform is required by this review. + +### Verified Action releases + +Upstream tag objects were resolved to commit SHAs through GitHub on the review +date. Reconfirm before implementing; preserve intended major versions. + +| Action / intended release | Verified commit SHA | Current uses | +| --- | --- | --- | +| `actions/checkout` v4.4.0 | `11d5960a326750d5838078e36cf38b85af677262` | Mutable `@v4`: CI line 22; production smoke line 37 | +| `actions/setup-node` v4.4.0 | `49933ea5288caeca8642d1e84afbd3f7d6820020` | Mutable `@v4`: CI line 27; deployment line 31; production smoke line 40 | +| `actions/upload-artifact` v4.6.2 | `ea165f8d65b6e75b540449e92b4886f43607fa02` | Mutable `@v4`: production smoke line 52 | +| `actions/checkout` v6.0.2 | `de0fac2e4500dabe0009e67214ff5f5447ce83dd` | Already pinned: deployment line 26 | +| `cloudflare/wrangler-action` v4.0.0 | `ebbaa1584979971c8614a24965b4405ff95890e0` | Already pinned: deployment line 130 | + +[Dependabot supports maintaining Action references, including commit pins](https://docs.github.com/en/code-security/how-tos/secure-your-supply-chain/secure-your-dependencies/auto-update-actions). +Use a configuration targeting the active integration branch and explicit review; +do not enable auto-merge. Existing tests expecting mutable `@v4` must be updated +with the separate pinning change, not disabled. + +### PDF boundary and regression scope + +Filename/MIME remain hints; bytes must pass admission before parser entry, with +parser errors remaining the final rejection layer. Cover valid PDFs, non-PDF +`.pdf` files, invalid `application/pdf` content, empty files, truncated files, +and malformed corpus samples. Assert that invalid signatures never reach either +parser, and that malformed content with a valid header still fails parsing. +Preserve `pdf-ocr.ts:8–10,132–135` bounds (16,384 dimension, 50 million pixels, +large-page warning) and cancellation/resource cleanup. A signature is not a +guarantee of safe or well-formed content. + +### Monitoring limitations + +`npm audit` completed successfully with zero reported vulnerabilities for the +lockfile. It does not cover every directly vendored browser library. Exact-version +OSV queries returned no matching advisories for the packages below. GitHub +Dependabot-alert API returned 403 with alerts explicitly disabled; this is not an +empty clean alert list. No access-scope escalation was attempted. Code-scanning +API reported no analysis. These are monitoring gaps, not verified exploits. + +## Dependency delta + +The supplied historical snapshot explicitly identifies only JSZip 3.10.1 and its +3.10.2 follow-up; do not invent other historical versions or CVE fixes. All listed +browser assets are local and hash-gated: `tests/release-gate.test.mjs:20–80` covers +the direct vendored libraries/secure-metadata; `tests/ocr-foundation.test.mjs:182–219` +covers the OCR manifest; searchable-PDF asset preparation/tests cover fontkit/fonts. + +Each dependency/CVE follow-up remains **PARTIALLY RESOLVED**: pinned versions, +hash gates, and the current advisory check are verified, but historical CVE +identity and comprehensive continuous vendor monitoring are absent (issue #116). +This classification does not imply an active known vulnerability or mandate an +upgrade. Maintenance and patch-lag findings are separately classified below. + +| Runtime input | Current pin | Registry latest observed | CVE follow-up status / decision | +| --- | --- | --- | --- | +| `pdfjs-dist` | 6.2.108 | 6.4.299 | PARTIALLY RESOLVED; no OSV match for pin; newer alone does not justify update | +| `jspdf` | 4.2.1 | 4.2.1 | PARTIALLY RESOLVED; no OSV match; retain | +| `jszip` | 3.10.1 | 3.10.2 | PARTIALLY RESOLVED; no OSV match; assess compatibility changes below | +| `pdf-lib` | 1.17.1 | 1.17.1 | PARTIALLY RESOLVED; no OSV match; maintenance assessment needed | +| `tesseract.js` | 7.0.0 | 7.0.0 | PARTIALLY RESOLVED; no OSV match; retain | +| `tesseract.js-core` | 7.0.0 | 6.1.2 dist-tag | PARTIALLY RESOLVED; published 7.0.0 exists and matches existing Tesseract inputs; do not infer downgrade from dist-tag | +| `secure-metadata` | 0.1.1 | GitHub v0.1.1 | PARTIALLY RESOLVED; upstream release verified; npm registry returns 404, OSV name query is insufficient coverage; monitor GitHub source | +| `@pdf-lib/fontkit` | 1.1.1 | 1.1.1 | PARTIALLY RESOLVED; no OSV match; retain | +| `@fontsource/noto-sans-kr` | 5.3.0 | 5.3.0 | PARTIALLY RESOLVED; no OSV match; retain | +| `@tesseract.js-data/eng` | 1.0.0 | 1.0.0 | PARTIALLY RESOLVED; no OSV match; retain | +| `@tesseract.js-data/kor` | 1.0.0 | 1.0.0 | PARTIALLY RESOLVED; no OSV match; retain | + +- **pdf-lib maintenance: OPEN, P2.** Latest npm release 1.17.1 dates to 2021; + upstream is not archived, but last observed push was 2024-07-17. Merge, split, + organize, metadata editing, and searchable-PDF composition depend on its + parser/manipulation behavior (`tools/shared/pdf.js` and searchable-PDF modules). + Local processing still exposes untrusted PDF parsing. Investigate a maintained + compatible fork first; browser-local qpdf/MuPDF WASM alternatives require + feature, size, performance, licensing, privacy, and malformed-input evaluation. + Scope the investigation to v2.3; replacing it requires separate justified work. + [Upstream releases](https://github.com/Hopding/pdf-lib/releases). +- **JSZip patch lag: OPEN, P2.** The official + [3.10.2 changelog](https://raw.githubusercontent.com/Stuk/jszip/v3.10.2/CHANGES.md) + lists cross-realm binary type detection, missing type defaults, and Node >=18 + Blob support; it does not state a security fix. Secure Tools creates browser + ZIPs from local generated inputs. Demonstrate a relevant compatibility benefit + before upgrading; no automatic dependency refresh is warranted. +- These two maintenance assessments share [#118](https://github.com/SecureToolsProject/Secure_Tools/issues/118). + Any justified update must regenerate vendor assets, update SHA-256 and release + gates, verify license metadata, and pass relevant regressions in a separate PR. + +## v2.3 security gate + +- **P0:** No active Critical/High advisory or broken privacy invariant identified + in this review. This is a bounded assessment, not a claim that scanners cover + all vendor/transitive code. Any newly confirmed P0 blocks feature work. +- **P1:** Artifact provenance (#112), remaining Action pins (#113), HTTP CSP and + embedding/permissions boundary (#117). Use dedicated reviewed hardening PRs. +- **P2:** PDF admission (#114), disclosure (#115), independent monitoring (#116), + dependency maintenance/compatibility assessment (#118). + +> v2.3 feature development may begin after the bootstrap branch is established and all P0 findings are cleared. P1/P2 findings may proceed as dedicated hardening PRs unless they block the safety of new feature work. + +Bootstrap tracking: [#111](https://github.com/SecureToolsProject/Secure_Tools/issues/111). +Recommended first implementation: #112, a compact source/file-hash manifest and +deployed-artifact verification extending the existing v2.2 evidence. + +## Verification and preserved invariants + +Required bootstrap checks: clean pinned install, full `npm test` (includes custom +security/release gates), production `npm run build`, `scripts/validate-build.mjs`, +and real local OCR smoke. Record actual results in the bootstrap PR. + +Generic/GitHub Pages output intentionally retains the pre-existing root `CNAME`; +deployment strips it only from the isolated Cloudflare bridge copy +(`deploy-cloudflare-bridge.yml:62–88`, tested by `tests/cloudflare-bridge.test.mjs`). +Do not mistake preserving this tested separation for introducing a legacy CNAME +into Cloudflare. No CNAME, deployed header, analytics/RUM, runtime network API, +file-upload, CDN, or local-processing behavior changes in this PR. Tests retain +fail-closed privacy/security checks. Production remains at the verified baseline. + +## Issue #112 provenance implementation (pending integration/promotion) + +PR #119 is still open. This branch starts at actual `origin/v2.3`, not the +unmerged bootstrap head. Only this audit document was copied from #119 to retain +its matrix; its policy/code changes are not imported. Review #119 first and +reconcile this shared document when refreshing the provenance PR after integration. + +F-06 remains **PARTIALLY RESOLVED**. The implementation is verified locally/in CI, +but is not yet deployed on production. No end-to-end production claim is made. + +The canonical generated endpoint is `/build-info.json`. Schema 1 contains exactly +`schemaVersion`, `commit`, `version`, and `build: { source }`. The source marker is +`github-actions` in GitHub Actions, otherwise `local`; no timestamps, usernames, +paths, runner IDs, secrets, branches, or deployment URLs are exposed. It is generated +in `dist`, not tracked in source. Identical inputs produce identical record bytes. + +The build takes full lowercase 40-character `GITHUB_SHA` directly. CI rejects +missing/invalid input and never falls back to Git. Local builds without that input +use Git HEAD and are explicitly marked local; local working-tree content is not +certified by that record. Existing build tooling uses Node `.mjs`, which is reused. +`version` reads the existing `package.json` version, currently `0.0.0`; it is not +relabelled as v2.2.0 and no second manual version constant is introduced. + +`scripts/validate-build.mjs` requires the record and compares its strict schema, +SHA, version, and marker to the build context. CI invokes it after the production +build. Isolated bridge packaging preserves the exact JSON while removing CNAME; +tests execute the actual packaging block. The same directory is handed to Wrangler. +Production push/dispatch checkout uses the workflow source commit and automatic +`GITHUB_SHA`; PR CI uses its GitHub-generated test merge SHA, never presented as a +production release. + +`scripts/verify-build-provenance.mjs` requires HTTP 200 JSON without redirects and +checks the deployed record against the explicit expected SHA and canonical package +version. Deployment runs it on the immutable URL and both stable aliases with +the existing alias retries. The manual production smoke accepts `source_commit`, +checks out that exact source/version, and checks both origins, recording the result +in its report. Use verification workflow code from this implementation or later; +old releases do not contain the new gate. + +The current v2.2.0 production deployment lacks this generated record and was not +redeployed for this issue. A 2026-10-07 read of `/build-info.json` returned HTTP 404 +HTML on both canonical and immutable production origins. Future release signoff must verify the newly promoted +source SHA on both origins before considering F-06 resolved within this bounded +model. Remaining trust: GitHub builds/checkouts and Cloudflare serving are trusted; +a record is not a signature or proof that every served byte came from that commit. +This change adds no full file-hash manifest, reproducibility proof, SLSA claim, +account-compromise protection, runtime fetch, UI, or telemetry. Existing sampled +asset equivalence checks remain in place. Full digest/attestation work is a +separate decision rather than an implicit guarantee of this compact record. diff --git a/scripts/build-provenance.mjs b/scripts/build-provenance.mjs new file mode 100644 index 0000000..91da128 --- /dev/null +++ b/scripts/build-provenance.mjs @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +export const provenanceFile = "build-info.json"; +export const canonicalVersion = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version; + +export function requireCommit(commit) { + assert.equal(typeof commit, "string", "Source commit is required"); + assert.match(commit, /^[0-9a-f]{40}$/, "Source commit must be a full lowercase Git SHA"); + return commit; +} + +export function buildIdentity(env = process.env, gitCommit = () => execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim()) { + const ci = env.GITHUB_ACTIONS === "true" || (Boolean(env.CI) && env.CI !== "false"); + if (ci) assert.ok(env.GITHUB_SHA, "CI requires an explicit GITHUB_SHA; Git fallback is local-only"); + return { + commit: requireCommit(env.GITHUB_SHA ?? gitCommit()), + version: canonicalVersion, + source: env.GITHUB_ACTIONS === "true" ? "github-actions" : "local", + }; +} + +export function validateBuildInfo(info, expected) { + assert.ok(info && typeof info === "object" && !Array.isArray(info), "Provenance must be an object"); + assert.deepEqual(Object.keys(info).sort(), ["build", "commit", "schemaVersion", "version"], "Unexpected provenance fields"); + assert.equal(info.schemaVersion, 1, "Unsupported provenance schema"); + requireCommit(info.commit); + assert.equal(info.commit, requireCommit(expected.commit), "Provenance source SHA mismatch"); + assert.equal(info.version, expected.version, "Provenance canonical version mismatch"); + assert.ok(typeof info.version === "string" && info.version.length > 0, "Canonical version is required"); + assert.ok(info.build && typeof info.build === "object" && !Array.isArray(info.build), "Build source is required"); + assert.deepEqual(Object.keys(info.build), ["source"], "Unexpected build metadata fields"); + assert.ok(["local", "github-actions"].includes(info.build.source), "Unsupported build source"); + assert.equal(info.build.source, expected.source, "Provenance build source mismatch"); + return info; +} + +export function writeBuildInfo(directory, identity = buildIdentity()) { + const info = validateBuildInfo({ schemaVersion: 1, commit: identity.commit, version: identity.version, build: { source: identity.source } }, identity); + fs.writeFileSync(path.join(directory, provenanceFile), `${JSON.stringify(info, null, 2)}\n`); + return info; +} + +export function validateBuildProvenance(directory, identity = buildIdentity()) { + return validateBuildInfo(JSON.parse(fs.readFileSync(path.join(directory, provenanceFile), "utf8")), identity); +} diff --git a/scripts/build-site.mjs b/scripts/build-site.mjs index 052be08..333475a 100644 --- a/scripts/build-site.mjs +++ b/scripts/build-site.mjs @@ -4,9 +4,12 @@ import { fileURLToPath } from "node:url"; import { canonicalPages, legacyRedirects, redirectStatus } from "./site-routes.mjs"; import { compiledBrowserModules } from "./typescript-modules.mjs"; +import { buildIdentity, writeBuildInfo } from "./build-provenance.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const output = path.join(root, "dist"); +// Resolve before replacing output; production CI cannot fall back to a local SHA. +const identity = buildIdentity(); fs.rmSync(output, { recursive: true, force: true }); fs.mkdirSync(output, { recursive: true }); @@ -50,5 +53,6 @@ for (const file of ["404.html", "robots.txt", "sitemap.xml"]) { const redirectFile = `${legacyRedirects.map(({ from, to }) => `${from} ${to} ${redirectStatus}`).join("\n")}\n`; fs.writeFileSync(path.join(output, "_redirects"), redirectFile); +writeBuildInfo(output, identity); console.log(`Built ${canonicalPages.length} canonical pages and ${legacyRedirects.length} permanent redirects in dist/.`); diff --git a/scripts/validate-build.mjs b/scripts/validate-build.mjs index 5526432..e1dd40d 100644 --- a/scripts/validate-build.mjs +++ b/scripts/validate-build.mjs @@ -5,9 +5,11 @@ import { fileURLToPath } from "node:url"; import { canonicalPages, legacyRedirects, redirectStatus } from "./site-routes.mjs"; import { compiledBrowserModules } from "./typescript-modules.mjs"; +import { validateBuildProvenance } from "./build-provenance.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const output = path.resolve(root, process.argv[2] || "dist"); +validateBuildProvenance(output); const htmlFiles = []; const outputFiles = []; diff --git a/scripts/verify-build-provenance.mjs b/scripts/verify-build-provenance.mjs new file mode 100644 index 0000000..91f540e --- /dev/null +++ b/scripts/verify-build-provenance.mjs @@ -0,0 +1,19 @@ +import assert from "node:assert/strict"; +import { pathToFileURL } from "node:url"; +import { canonicalVersion, provenanceFile, requireCommit, validateBuildInfo } from "./build-provenance.mjs"; + +export async function verifyDeployedBuildInfo(origin, commit, request = fetch) { + requireCommit(commit); + const base = new URL(origin); + assert.ok(base.protocol === "https:" || (base.protocol === "http:" && ["localhost", "127.0.0.1"].includes(base.hostname)), "Provenance verification requires HTTPS or local test HTTP"); + assert.ok(base.pathname === "/" && !base.username && !base.password && !base.search && !base.hash, "Expected a plain origin"); + const response = await request(new URL(provenanceFile, base), { redirect: "manual", cache: "no-store", signal: AbortSignal.timeout(30000) }); + assert.equal(response.status, 200, "Provenance endpoint must return HTTP 200 without redirects"); + assert.match(response.headers.get("content-type") || "", /^application\/json(?:\s*;|$)/i, "Provenance must be JSON, not a fallback HTML page"); + return validateBuildInfo(await response.json(), { commit, version: canonicalVersion, source: "github-actions" }); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await verifyDeployedBuildInfo(process.argv[2], process.argv[3] ?? process.env.GITHUB_SHA); + console.log("Deployed provenance matches expected source SHA, canonical version, and strict public schema."); +} diff --git a/tests/build-provenance.test.mjs b/tests/build-provenance.test.mjs new file mode 100644 index 0000000..1c9c3cf --- /dev/null +++ b/tests/build-provenance.test.mjs @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import http from "node:http"; +import { execFileSync } from "node:child_process"; +import { buildIdentity, canonicalVersion, provenanceFile, validateBuildInfo, validateBuildProvenance, writeBuildInfo } from "../scripts/build-provenance.mjs"; +import { verifyDeployedBuildInfo } from "../scripts/verify-build-provenance.mjs"; + +const sha = "1234567890abcdef1234567890abcdef12345678"; +const env = { ...process.env, CI: "true", GITHUB_ACTIONS: "true", GITHUB_SHA: sha }; +const identity = buildIdentity(env, () => { throw new Error("CI must never consult Git fallback"); }); +assert.deepEqual(identity, { commit: sha, version: JSON.parse(fs.readFileSync("package.json", "utf8")).version, source: "github-actions" }); +assert.equal(buildIdentity({}, () => sha).commit, sha); +assert.equal(buildIdentity({}, () => sha).source, "local"); +for (const input of [undefined, "", "1234567", "local", sha.toUpperCase(), "g".repeat(40)]) { + assert.throws(() => buildIdentity({ CI: "true", GITHUB_SHA: input }, () => sha)); + assert.throws(() => buildIdentity({ GITHUB_ACTIONS: "true", GITHUB_SHA: input }, () => sha)); +} +assert.throws(() => buildIdentity({ GITHUB_SHA: "bad" }, () => sha)); + +const staging = path.resolve(".ts-build"); +fs.mkdirSync(staging, { recursive: true }); +const directory = fs.mkdtempSync(path.join(staging, "provenance-test-")); +let info; +try { + assert.throws(() => validateBuildProvenance(directory, identity)); + info = writeBuildInfo(directory, identity); + const first = fs.readFileSync(path.join(directory, provenanceFile), "utf8"); + writeBuildInfo(directory, identity); + assert.equal(fs.readFileSync(path.join(directory, provenanceFile), "utf8"), first, "Generation is byte deterministic"); + assert.deepEqual(JSON.parse(first), { schemaVersion: 1, commit: sha, version: canonicalVersion, build: { source: "github-actions" } }); + assert.equal(validateBuildProvenance(directory, identity).commit, sha); + for (const change of [ + value => { delete value.commit; }, + value => { value.commit = "1234567"; }, + value => { value.commit = "f".repeat(40); }, + value => { value.schemaVersion = 2; }, + value => { value.version = "unexpected"; }, + value => { value.timestamp = "2026-10-07"; }, + value => { value.build.runner = "private-runner"; }, + value => { value.build.source = "local"; }, + value => { value.build = null; }, + ]) { + const corrupt = structuredClone(info); change(corrupt); + fs.writeFileSync(path.join(directory, provenanceFile), JSON.stringify(corrupt)); + assert.throws(() => validateBuildProvenance(directory, identity)); + } + assert.throws(() => validateBuildInfo(null, identity)); + assert.throws(() => validateBuildInfo([], identity)); + // Exercise the real generator and complete production validator with an explicit + // CI SHA deliberately different from local HEAD; the supplied source must win. + execFileSync(process.execPath, ["scripts/build-site.mjs"], { env, stdio: "pipe" }); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join("dist", provenanceFile), "utf8")), info); + execFileSync(process.execPath, ["scripts/validate-build.mjs"], { env, stdio: "pipe" }); + fs.unlinkSync(path.join("dist", provenanceFile)); + assert.throws(() => execFileSync(process.execPath, ["scripts/validate-build.mjs"], { env, stdio: "pipe" })); + writeBuildInfo("dist", identity); +} finally { + assert.equal(path.dirname(directory), staging); + fs.rmSync(directory, { recursive: true, force: true }); +} + +// Use a real HTTP server to cover the live verifier's transport and schema gates. +let status = 200; +let contentType = "application/json"; +let body = info; +const server = http.createServer((request, response) => { + assert.equal(request.url, `/${provenanceFile}`); + response.writeHead(status, { "content-type": contentType, location: "/" }); + response.end(JSON.stringify(body)); +}); +await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); +const origin = `http://127.0.0.1:${server.address().port}`; +try { + assert.deepEqual(await verifyDeployedBuildInfo(origin, sha), info); + await assert.rejects(verifyDeployedBuildInfo(origin, "f".repeat(40))); + for (const code of [404, 302, 500]) { + status = code; await assert.rejects(verifyDeployedBuildInfo(origin, sha)); + } + status = 200; contentType = "text/html"; + await assert.rejects(verifyDeployedBuildInfo(origin, sha)); + contentType = "application/json"; body = { ...info, version: "unexpected" }; + await assert.rejects(verifyDeployedBuildInfo(origin, sha)); + body = { ...info, token: "must-not-leak" }; + await assert.rejects(verifyDeployedBuildInfo(origin, sha)); + await assert.rejects(verifyDeployedBuildInfo(origin, undefined)); +} finally { + await new Promise(resolve => server.close(resolve)); +} + +const deployment = fs.readFileSync(".github/workflows/deploy-cloudflare-bridge.yml", "utf8"); +assert.match(deployment, /verify-build-provenance\.mjs "\$DEPLOYMENT_URL" "\$GITHUB_SHA"/); +assert.match(deployment, /verify-build-provenance\.mjs "\$url" "\$GITHUB_SHA"/); +assert.ok(deployment.indexOf('node scripts/validate-build.mjs "$BRIDGE_DIRECTORY"') < deployment.indexOf("command: pages deploy")); +const smokeWorkflow = fs.readFileSync(".github/workflows/production-smoke.yml", "utf8"); +assert.match(smokeWorkflow, /source_commit:[\s\S]*?required: true/); +assert.match(smokeWorkflow, /ref: \$\{\{ inputs\.source_commit \|\| github\.sha \}\}/); +assert.match(smokeWorkflow, /EXPECTED_PRODUCTION_SHA: \$\{\{ inputs\.source_commit \|\| github\.sha \}\}/); +assert.match(smokeWorkflow, /verify-build-provenance\.mjs "\$PRODUCTION_ORIGIN" "\$EXPECTED_PRODUCTION_SHA"/); +assert.match(smokeWorkflow, /verify-build-provenance\.mjs "\$IMMUTABLE_ORIGIN" "\$EXPECTED_PRODUCTION_SHA"/); +assert.match(fs.readFileSync(".github/workflows/ci.yml", "utf8"), /run: node scripts\/validate-build\.mjs/); +console.log("Provenance generator, strict artifact schema, CI identity and live HTTP failure checks passed."); diff --git a/tests/cloudflare-bridge.test.mjs b/tests/cloudflare-bridge.test.mjs index 344b584..c701857 100644 --- a/tests/cloudflare-bridge.test.mjs +++ b/tests/cloudflare-bridge.test.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import fs from "node:fs"; import path from "node:path"; import { spawnSync } from "node:child_process"; +import { validateBuildProvenance } from "../scripts/build-provenance.mjs"; const workflow = fs.readFileSync(".github/workflows/deploy-cloudflare-bridge.yml", "utf8"); @@ -81,6 +82,7 @@ try { assert.equal(fs.readFileSync("CNAME", "utf8").trim(), "securetools.app"); assert.equal(fs.readFileSync("dist/CNAME", "utf8").trim(), "securetools.app", "Generic build retains hosting ownership file"); assert.ok(!fs.existsSync(path.join(artifact, "CNAME")), "Isolated Cloudflare artifact excludes CNAME"); + assert.deepEqual(validateBuildProvenance(artifact), validateBuildProvenance("dist"), "Exact provenance survives isolated deployment packaging"); assert.ok(!fs.existsSync(path.join(artifact, "_worker.js")) && !fs.existsSync(path.join(artifact, "functions"))); assert.match(fs.readFileSync(path.join(artifact, "_headers"), "utf8"), /X-Robots-Tag: noindex, nofollow/); } finally { diff --git a/tests/production/smoke.mjs b/tests/production/smoke.mjs index 2b1ddf7..dacaa6b 100644 --- a/tests/production/smoke.mjs +++ b/tests/production/smoke.mjs @@ -8,6 +8,7 @@ import { pdfToTextLocales } from "../../js/locales/pdf-to-text.js"; import { createFixtures } from "./fixtures.mjs"; import { auditContext } from "./audit.mjs"; import { verifyPdf } from "./pdf-artifact.mjs"; +import { verifyDeployedBuildInfo } from "../../scripts/verify-build-provenance.mjs"; function origin(value, name) { assert.ok(value, `${name} is required`); @@ -182,6 +183,12 @@ async function writerFlow(page, fixtures, downloads) { return { cancellation: "zero downloads; retry passed", staleReplacement: "zero A; one B", existingText: "exactly once per page", ...inspected }; } try { + await gate("Production source provenance", async () => { + const commit = process.env.EXPECTED_PRODUCTION_SHA; + const results = await Promise.all([canonical, immutable].map(o => verifyDeployedBuildInfo(o, commit))); + assert.deepEqual(results[0], results[1], "Production origins must expose identical provenance"); + return results[0]; + }); await gate("HTTP routes and SEO", httpSmoke); await gate("Release asset equivalence", assetComparison); browser = await chromium.launch({ headless: true, args: ["--disable-extensions"] }); report.browser = browser.version(); diff --git a/tests/run-all.mjs b/tests/run-all.mjs index 9fc9196..c042852 100644 --- a/tests/run-all.mjs +++ b/tests/run-all.mjs @@ -55,6 +55,7 @@ for (const test of [ "tests/branch-policy.test.mjs", "tests/ci-foundation.test.mjs", "tests/commit-message.test.mjs", + "tests/build-provenance.test.mjs", "tests/cloudflare-bridge.test.mjs", "tests/release-hardening-http.test.mjs", "tests/verify-browser-export-artifacts.mjs", From 7fbdfa94a98d8d049bac9fc04ba3c9d918961e1a Mon Sep 17 00:00:00 2001 From: maruson08 Date: Fri, 9 Oct 2026 11:58:27 +0900 Subject: [PATCH 03/12] =?UTF-8?q?=F0=9F=94=A7[Config]=20Pin=20GitHub=20Act?= =?UTF-8?q?ions=20to=20verified=20SHAs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/dependabot.yml | 12 ++++++ .github/workflows/ci.yml | 4 +- .../workflows/deploy-cloudflare-bridge.yml | 8 ++-- .github/workflows/production-smoke.yml | 6 +-- docs/v2.3-bootstrap.md | 43 +++++++++++++------ scripts/validate-action-pins.mjs | 40 +++++++++++++++++ tests/action-pins.test.mjs | 31 +++++++++++++ tests/ci-foundation.test.mjs | 4 +- tests/run-all.mjs | 1 + tests/security-hardening.test.mjs | 2 + 10 files changed, 125 insertions(+), 26 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 scripts/validate-action-pins.mjs create mode 100644 tests/action-pins.test.mjs diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..4d23f8f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + target-branch: "v2.3" + schedule: + interval: "weekly" + pull-request-branch-name: + prefix: "chore/dependabot" + commit-message: + # Trailing space prevents Dependabot from inserting a colon after [Config]. + prefix: "🔧[Config] " diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 686c028..95ba0f2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,12 +19,12 @@ jobs: steps: - name: Check out repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 - name: Set up Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 24 diff --git a/.github/workflows/deploy-cloudflare-bridge.yml b/.github/workflows/deploy-cloudflare-bridge.yml index f4ad388..2fd1433 100644 --- a/.github/workflows/deploy-cloudflare-bridge.yml +++ b/.github/workflows/deploy-cloudflare-bridge.yml @@ -22,13 +22,12 @@ jobs: steps: - name: Check out repository - # actions/checkout v6.0.2 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false - name: Set up Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 24 @@ -126,8 +125,7 @@ jobs: - name: Deploy to Cloudflare Pages id: deploy - # cloudflare/wrangler-action v4.0.0 - uses: cloudflare/wrangler-action@ebbaa1584979971c8614a24965b4405ff95890e0 + uses: cloudflare/wrangler-action@ebbaa1584979971c8614a24965b4405ff95890e0 # v4.0.0 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} diff --git a/.github/workflows/production-smoke.yml b/.github/workflows/production-smoke.yml index 28b9aee..cec6ebf 100644 --- a/.github/workflows/production-smoke.yml +++ b/.github/workflows/production-smoke.yml @@ -39,12 +39,12 @@ jobs: IMMUTABLE_ORIGIN: ${{ inputs.immutable_origin || 'https://b9802e7e.secure-tools-web-bridge.pages.dev' }} EXPECTED_PRODUCTION_SHA: ${{ inputs.source_commit || github.sha }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false # Read canonical version and verification code from the expected deployment. ref: ${{ inputs.source_commit || github.sha }} - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 24 cache: npm @@ -60,7 +60,7 @@ jobs: run: cat .ts-build/production-smoke/summary.md >> "$GITHUB_STEP_SUMMARY" - name: Retain failure diagnostics (synthetic fixtures only) if: failure() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: production-smoke-diagnostics path: .ts-build/production-smoke diff --git a/docs/v2.3-bootstrap.md b/docs/v2.3-bootstrap.md index f02364c..5067e59 100644 --- a/docs/v2.3-bootstrap.md +++ b/docs/v2.3-bootstrap.md @@ -48,10 +48,10 @@ historical code. | Finding | Current status | Evidence | Necessary next action | Priority / issue | | --- | --- | --- | --- | --- | | F-06 Artifact/source provenance | PARTIALLY RESOLVED | Production baseline has deployment SHA linkage and sampled asset equivalence. The Issue #112 implementation generates `dist/build-info.json` (`scripts/build-site.mjs`, `scripts/build-provenance.mjs`) and strictly checks SHA/version/schema/sensitive fields (`scripts/validate-build.mjs`, `scripts/verify-build-provenance.mjs`). The public path will be `/build-info.json`; current production has not received this code. | Preserve CI/generated/deployed-record checks; keep Issue #112 open until promotion and actual live production equality verification. This record is not a full digest or reproducibility proof. | P1 / [#112](https://github.com/SecureToolsProject/Secure_Tools/issues/112) | -| F-02 Mutable Actions | PARTIALLY RESOLVED | Two deployment Actions already use full SHAs. Six other uses are mutable across all three workflows; details below. No `dependabot.yml`; repository SHA-pinning requirement is disabled. | Pin six references to verified intended releases; update contract tests; maintain pins with targeted Dependabot configuration and review. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | +| F-02 Mutable Actions | PARTIALLY RESOLVED | The #113 implementation pins all eight external Action uses to verified full SHAs with release comments; `scripts/validate-action-pins.mjs` and the security gate reject mutable/abbreviated/dynamic refs. `.github/dependabot.yml` configures weekly reviewed Actions updates targeting v2.3. | Pinning is complete on this branch. Maintenance automation is not yet active: GitHub requires this configuration on the default branch (main), which is unchanged. Activate only through a separately authorized production promotion, then verify scheduled updates before marking fully resolved. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | | F-01 PDF admission | OPEN | `tools/shared/pdf.js:22–33` accepts MIME/name hints then calls `PDFDocument.load`; `pdf-ocr.ts:215–216` returns unchecked bytes; `pdf-renderer.js:18–27` passes bytes to PDF.js. No required `%PDF-` pre-validation. Parser failures are caught, and renderer evaluation/worker fetching/WASM are disabled. | Shared byte validator before original-source parser entry, with documented header-offset compatibility policy and negative fixtures; preserve existing limits/fail-closed parsing. | P2 / [#114](https://github.com/SecureToolsProject/Secure_Tools/issues/114) | | F-03 Disclosure | OPEN | Root `SECURITY.md` absent; GitHub private vulnerability reporting API reports `enabled: false`. | Document supported versions, verified private reporting route, coordinated disclosure, scope/non-goals, and warning against attaching sensitive files; enable route where permitted. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | -| F-04 Independent scanning | OPEN | CI runs custom `security-hardening.test.mjs` and `release-gate.test.mjs`, but no CodeQL, Dependency Review, OSV/npm-audit job, or Dependabot configuration. GitHub reports security updates/secret scanning disabled and no code-scanning analysis. | Small complementary JS/TS SAST and vendor-aware advisory monitoring; use lockfile audit for its actual coverage, without duplicating scanners. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | +| F-04 Independent scanning | OPEN | CI runs custom `security-hardening.test.mjs` and `release-gate.test.mjs`, but no CodeQL, Dependency Review, OSV/npm-audit job, or runtime-dependency monitoring. #113 prepares Actions version updates only. GitHub reports security updates/secret scanning disabled and no code-scanning analysis. | Small complementary JS/TS SAST and vendor-aware advisory monitoring; use lockfile audit for its actual coverage, without duplicating scanners. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | | F-05 HTTP headers | PARTIALLY RESOLVED | Root/Image-to-Text/PDF-to-Text HTML and JS checked on both production origins: `nosniff` and `strict-origin-when-cross-origin` present; HTTP CSP and Permissions-Policy absent. Meta CSP in `index.html:10` and OCR pages line 4 contains `connect-src 'none'`, but no HTTP `frame-ancestors`. Generated deployment `_headers` covers alias noindex only (workflow lines 77–86). | Hosting-level CSP with `frame-ancestors 'none'` and appropriate Permissions-Policy; preserve same-origin worker/WASM/font/Blob flows and existing Referrer-Policy/nosniff. | P1 / [#117](https://github.com/SecureToolsProject/Secure_Tools/issues/117) | ### Provenance scope @@ -65,21 +65,34 @@ rewrites. No heavyweight attestation platform is required by this review. ### Verified Action releases -Upstream tag objects were resolved to commit SHAs through GitHub on the review -date. Reconfirm before implementing; preserve intended major versions. +Upstream v4 major tags and intended release tag objects were reconfirmed through +GitHub on 2026-10-09 and resolve to the same commits. Six mutable references are +now pinned without changing their current major/minor release. Two existing SHA +pins retain their commits, with inline comments for Dependabot maintenance. | Action / intended release | Verified commit SHA | Current uses | | --- | --- | --- | -| `actions/checkout` v4.4.0 | `11d5960a326750d5838078e36cf38b85af677262` | Mutable `@v4`: CI line 22; production smoke line 37 | -| `actions/setup-node` v4.4.0 | `49933ea5288caeca8642d1e84afbd3f7d6820020` | Mutable `@v4`: CI line 27; deployment line 31; production smoke line 40 | -| `actions/upload-artifact` v4.6.2 | `ea165f8d65b6e75b540449e92b4886f43607fa02` | Mutable `@v4`: production smoke line 52 | -| `actions/checkout` v6.0.2 | `de0fac2e4500dabe0009e67214ff5f5447ce83dd` | Already pinned: deployment line 26 | -| `cloudflare/wrangler-action` v4.0.0 | `ebbaa1584979971c8614a24965b4405ff95890e0` | Already pinned: deployment line 130 | +| `actions/checkout` v4.4.0 | `11d5960a326750d5838078e36cf38b85af677262` | Pinned: CI line 22; production smoke line 42 | +| `actions/setup-node` v4.4.0 | `49933ea5288caeca8642d1e84afbd3f7d6820020` | Pinned: CI line 27; deployment line 30; production smoke line 47 | +| `actions/upload-artifact` v4.6.2 | `ea165f8d65b6e75b540449e92b4886f43607fa02` | Pinned: production smoke line 63 | +| `actions/checkout` v6.0.2 | `de0fac2e4500dabe0009e67214ff5f5447ce83dd` | Existing pin retained: deployment line 25 | +| `cloudflare/wrangler-action` v4.0.0 | `ebbaa1584979971c8614a24965b4405ff95890e0` | Existing pin retained: deployment line 128 | [Dependabot supports maintaining Action references, including commit pins](https://docs.github.com/en/code-security/how-tos/secure-your-supply-chain/secure-your-dependencies/auto-update-actions). -Use a configuration targeting the active integration branch and explicit review; -do not enable auto-merge. Existing tests expecting mutable `@v4` must be updated -with the separate pinning change, not disabled. +The new configuration targets v2.3 weekly and retains explicit review; no +auto-merge is enabled. Generated branches use `chore/dependabot` to satisfy branch +policy. The `🔧[Config] ` commit prefix includes a trailing space so Dependabot +does not add a colon; CI contract tests now require SHA pins while retaining the +intended v4 major. Existing production provenance and privacy checks are unchanged. + +[GitHub reads Dependabot configuration from the default branch](https://docs.github.com/en/code-security/concepts/supply-chain-security/about-the-dependabot-yml-file). +Main remains production-only and has no configuration, so weekly maintenance is +prepared but not active. This is the remaining F-02 gap; no default-branch change +is made by this task. Configuration placement, target-branch, commit/branch prefixes +follow the [official options reference](https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference). +The pin gate supports literal block-style `uses` entries, quoted or unquoted; +unsupported inline/dynamic entries fail closed. It classifies local Actions without +requiring an external SHA. YAML parsing is a separate verification check. ### PDF boundary and regression scope @@ -162,8 +175,10 @@ upgrade. Maintenance and patch-lag findings are separately classified below. Bootstrap tracking: [#111](https://github.com/SecureToolsProject/Secure_Tools/issues/111). Issue #112 implementation is documented below; live confirmation remains pending. -After the bootstrap and provenance PRs are integrated and verified, the next -implementation task is #113, remaining GitHub Actions pins. +Bootstrap and provenance are integrated into v2.3. Issue #113 implements the +remaining Action pins on its review branch; maintenance activation is pending +production promotion. Recommended next independent hardening task: #114, shared +PDF byte-signature admission. Do not start it as part of #113. ## Verification and preserved invariants diff --git a/scripts/validate-action-pins.mjs b/scripts/validate-action-pins.mjs new file mode 100644 index 0000000..1815349 --- /dev/null +++ b/scripts/validate-action-pins.mjs @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +export function classifyActionReference(reference, comment = "") { + if (/^\.\/[A-Za-z0-9_./-]+$/.test(reference)) return "repository-local"; + assert.match(reference, /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_./-]+@[0-9a-f]{40}$/, "External Actions require a full lowercase 40-character commit SHA"); + assert.match(comment, /^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\s*$/, "External Action pin requires an inline upstream release comment"); + return "external-sha"; +} + +export function auditWorkflowUses(contents, file = "workflow") { + const references = []; + for (const [index, line] of contents.split(/\r?\n/).entries()) { + if (/^\s*#/.test(line) || !/\buses\s*:/.test(line)) continue; + // Require a literal block-style uses entry; unsupported inline/dynamic forms + // fail closed rather than evade this deliberately small workflow policy. + const entry = line.match(/^\s*(?:-\s*)?uses:\s*(?:"([^"]+)"|'([^']+)'|([^#\s]+))\s*(?:#\s*(.*))?$/); + assert.ok(entry, `${file}:${index + 1}: Unsupported uses entry`); + const reference = entry[1] || entry[2] || entry[3]; + references.push({ file, line: index + 1, reference, release: entry[4], classification: classifyActionReference(reference, entry[4]) }); + } + return references; +} + +export function auditActionPins() { + const directory = path.join(root, ".github/workflows"); + const files = fs.readdirSync(directory).filter(file => /\.ya?ml$/.test(file)); + assert.ok(files.length > 0, "No workflow files found"); + const references = files.flatMap(file => auditWorkflowUses(fs.readFileSync(path.join(directory, file), "utf8"), `.github/workflows/${file}`)); + assert.ok(references.length > 0, "No Action references found"); + return references; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + console.log(JSON.stringify(auditActionPins(), null, 2)); +} diff --git a/tests/action-pins.test.mjs b/tests/action-pins.test.mjs new file mode 100644 index 0000000..1f073bd --- /dev/null +++ b/tests/action-pins.test.mjs @@ -0,0 +1,31 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import { auditActionPins, auditWorkflowUses, classifyActionReference } from "../scripts/validate-action-pins.mjs"; +import { validateBranchPolicy } from "../scripts/validate-branch-policy.mjs"; + +const pin = `actions/example@${"a".repeat(40)}`; +assert.equal(classifyActionReference(pin, "v4.4.0"), "external-sha"); +assert.equal(classifyActionReference("./.github/actions/local"), "repository-local"); +for (const ref of ["actions/example@v4", "actions/example@main", "actions/example@abcdef0", `actions/example@${"a".repeat(39)}`, `actions/example@${"A".repeat(40)}`, "docker://example:latest", "${{ inputs.action }}"]) { + assert.throws(() => classifyActionReference(ref, "v4.4.0")); +} +for (const comment of ["", "v4", "some arbitrary commit"]) assert.throws(() => classifyActionReference(pin, comment)); +assert.equal(auditWorkflowUses(`- uses: '${pin}' # v4.4.0`)[0].reference, pin); +assert.equal(auditWorkflowUses(` uses: ${pin} # v4.4.0`)[0].classification, "external-sha", "Reusable workflow entries are also audited"); +assert.equal(auditWorkflowUses("# uses: actions/example@v4").length, 0); +assert.throws(() => auditWorkflowUses("- { uses: actions/example@v4 }")); +assert.throws(() => auditWorkflowUses("- uses: actions/example@v4")); +const references = auditActionPins(); +assert.ok(references.every(ref => ref.classification === "external-sha" || ref.classification === "repository-local")); + +const dependabot = fs.readFileSync(".github/dependabot.yml", "utf8"); +assert.match(dependabot, /^version: 2$/m); +assert.match(dependabot, /package-ecosystem: "github-actions"/); +assert.match(dependabot, /directory: "\/"/); +assert.match(dependabot, /target-branch: "v2\.3"/); +assert.match(dependabot, /interval: "weekly"/); +assert.match(dependabot, /pull-request-branch-name:\s*\n\s+prefix: "chore\/dependabot"/); +assert.match(dependabot, /commit-message:[\s\S]*?prefix: "🔧\[Config\] "/); +assert.equal(validateBranchPolicy("v2.3", "chore/dependabot/github_actions/actions/checkout-4.4.0").valid, true); +assert.doesNotMatch(dependabot, /auto-merge|enable-pull-request-automerge/); +console.log(`Action supply-chain gate passed: ${references.length} references classified; mutable/abbreviated/dynamic refs rejected; reviewed weekly update configuration checked.`); diff --git a/tests/ci-foundation.test.mjs b/tests/ci-foundation.test.mjs index aec7ba6..113a020 100644 --- a/tests/ci-foundation.test.mjs +++ b/tests/ci-foundation.test.mjs @@ -5,8 +5,8 @@ const workflow = fs.readFileSync(".github/workflows/ci.yml", "utf8"); assert.match(workflow, /^name: CI$/m); assert.match(workflow, /^\s{2}pull_request:$/m); assert.match(workflow, /^\s{2}push:\s*$[\s\S]*?^\s{6}- main$[\s\S]*?^\s{6}- v2$[\s\S]*?^\s{6}- v2\.3$/m); -assert.match(workflow, /uses: actions\/checkout@v4/); -assert.match(workflow, /uses: actions\/setup-node@v4/); +assert.match(workflow, /uses: actions\/checkout@[0-9a-f]{40} # v4\.\d+\.\d+/); +assert.match(workflow, /uses: actions\/setup-node@[0-9a-f]{40} # v4\.\d+\.\d+/); assert.match(workflow, /node-version: 24/); assert.match(workflow, /permissions:\s*\n\s+contents: read/); assert.match(workflow, /name: Enforce pull request branch policy/); diff --git a/tests/run-all.mjs b/tests/run-all.mjs index c042852..d8177e3 100644 --- a/tests/run-all.mjs +++ b/tests/run-all.mjs @@ -54,6 +54,7 @@ for (const test of [ "tests/job-focus.test.mjs", "tests/branch-policy.test.mjs", "tests/ci-foundation.test.mjs", + "tests/action-pins.test.mjs", "tests/commit-message.test.mjs", "tests/build-provenance.test.mjs", "tests/cloudflare-bridge.test.mjs", diff --git a/tests/security-hardening.test.mjs b/tests/security-hardening.test.mjs index 07a49bf..fd43f9f 100644 --- a/tests/security-hardening.test.mjs +++ b/tests/security-hardening.test.mjs @@ -89,4 +89,6 @@ const firstParty = ["js", "tools"].flatMap((directory) => { const networkApi = /\bfetch\s*\(|\bXMLHttpRequest\b|\bsendBeacon\s*\(|\bWebSocket\b|\bEventSource\b/; for (const source of firstParty) assert.doesNotMatch(fs.readFileSync(source, "utf8"), networkApi, `Unexpected network API: ${path.relative(root, source)}`); +const { auditActionPins } = await import("../scripts/validate-action-pins.mjs"); +auditActionPins(); console.log("Security hardening checks passed."); From 34e83ed121f67ae3136285b87dffe0bf6b6f3d45 Mon Sep 17 00:00:00 2001 From: maruson08 Date: Fri, 9 Oct 2026 12:16:43 +0900 Subject: [PATCH 04/12] =?UTF-8?q?=F0=9F=90=9B[Fix]=20Validate=20PDF=20sign?= =?UTF-8?q?atures=20before=20parsing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/v2.3-bootstrap.md | 54 ++++++++++++---- tests/pdf-metadata.test.mjs | 2 +- tests/pdf-ocr-foundation.test.mjs | 22 +++---- tests/pdf-signature.test.mjs | 104 ++++++++++++++++++++++++++++++ tests/pdf-to-text.test.mjs | 6 +- tests/run-all.mjs | 1 + tests/searchable-pdf.test.mjs | 2 +- tools/pdf/merge/app.js | 6 +- tools/pdf/metadata/app.js | 3 +- tools/pdf/metadata/pdf.js | 5 +- tools/pdf/organize/app.js | 2 - tools/pdf/organize/pdf.js | 5 +- tools/pdf/split/app.js | 6 +- tools/pdf/to-images/app.js | 5 +- tools/shared/pdf-ocr.ts | 10 +-- tools/shared/pdf-renderer.js | 2 + tools/shared/pdf.d.ts | 2 + tools/shared/pdf.js | 34 +++++++++- tools/shared/searchable-pdf.ts | 2 + 19 files changed, 220 insertions(+), 53 deletions(-) create mode 100644 tests/pdf-signature.test.mjs diff --git a/docs/v2.3-bootstrap.md b/docs/v2.3-bootstrap.md index 5067e59..1dbdb51 100644 --- a/docs/v2.3-bootstrap.md +++ b/docs/v2.3-bootstrap.md @@ -49,7 +49,7 @@ historical code. | --- | --- | --- | --- | --- | | F-06 Artifact/source provenance | PARTIALLY RESOLVED | Production baseline has deployment SHA linkage and sampled asset equivalence. The Issue #112 implementation generates `dist/build-info.json` (`scripts/build-site.mjs`, `scripts/build-provenance.mjs`) and strictly checks SHA/version/schema/sensitive fields (`scripts/validate-build.mjs`, `scripts/verify-build-provenance.mjs`). The public path will be `/build-info.json`; current production has not received this code. | Preserve CI/generated/deployed-record checks; keep Issue #112 open until promotion and actual live production equality verification. This record is not a full digest or reproducibility proof. | P1 / [#112](https://github.com/SecureToolsProject/Secure_Tools/issues/112) | | F-02 Mutable Actions | PARTIALLY RESOLVED | The #113 implementation pins all eight external Action uses to verified full SHAs with release comments; `scripts/validate-action-pins.mjs` and the security gate reject mutable/abbreviated/dynamic refs. `.github/dependabot.yml` configures weekly reviewed Actions updates targeting v2.3. | Pinning is complete on this branch. Maintenance automation is not yet active: GitHub requires this configuration on the default branch (main), which is unchanged. Activate only through a separately authorized production promotion, then verify scheduled updates before marking fully resolved. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | -| F-01 PDF admission | OPEN | `tools/shared/pdf.js:22–33` accepts MIME/name hints then calls `PDFDocument.load`; `pdf-ocr.ts:215–216` returns unchecked bytes; `pdf-renderer.js:18–27` passes bytes to PDF.js. No required `%PDF-` pre-validation. Parser failures are caught, and renderer evaluation/worker fetching/WASM are disabled. | Shared byte validator before original-source parser entry, with documented header-offset compatibility policy and negative fixtures; preserve existing limits/fail-closed parsing. | P2 / [#114](https://github.com/SecureToolsProject/Secure_Tools/issues/114) | +| F-01 PDF admission | RESOLVED | Shared `tools/shared/pdf.js` signature admission checks five bytes before full file reads; all original-source pdf-lib/PDF.js entry points use it, including cached-byte helpers. MIME/extension cannot authorize or veto valid bytes. | Issue #114 implementation; strict byte-zero header policy and parser failure regression coverage described below. Structural validation remains with the parsers. | P2 / [#114](https://github.com/SecureToolsProject/Secure_Tools/issues/114) | | F-03 Disclosure | OPEN | Root `SECURITY.md` absent; GitHub private vulnerability reporting API reports `enabled: false`. | Document supported versions, verified private reporting route, coordinated disclosure, scope/non-goals, and warning against attaching sensitive files; enable route where permitted. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | | F-04 Independent scanning | OPEN | CI runs custom `security-hardening.test.mjs` and `release-gate.test.mjs`, but no CodeQL, Dependency Review, OSV/npm-audit job, or runtime-dependency monitoring. #113 prepares Actions version updates only. GitHub reports security updates/secret scanning disabled and no code-scanning analysis. | Small complementary JS/TS SAST and vendor-aware advisory monitoring; use lockfile audit for its actual coverage, without duplicating scanners. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | | F-05 HTTP headers | PARTIALLY RESOLVED | Root/Image-to-Text/PDF-to-Text HTML and JS checked on both production origins: `nosniff` and `strict-origin-when-cross-origin` present; HTTP CSP and Permissions-Policy absent. Meta CSP in `index.html:10` and OCR pages line 4 contains `connect-src 'none'`, but no HTTP `frame-ancestors`. Generated deployment `_headers` covers alias noindex only (workflow lines 77–86). | Hosting-level CSP with `frame-ancestors 'none'` and appropriate Permissions-Policy; preserve same-origin worker/WASM/font/Blob flows and existing Referrer-Policy/nosniff. | P1 / [#117](https://github.com/SecureToolsProject/Secure_Tools/issues/117) | @@ -96,14 +96,43 @@ requiring an external SHA. YAML parsing is a separate verification check. ### PDF boundary and regression scope -Filename/MIME remain hints; bytes must pass admission before parser entry, with -parser errors remaining the final rejection layer. Cover valid PDFs, non-PDF -`.pdf` files, invalid `application/pdf` content, empty files, truncated files, -and malformed corpus samples. Assert that invalid signatures never reach either -parser, and that malformed content with a valid header still fails parsing. -Preserve `pdf-ocr.ts:8–10,132–135` bounds (16,384 dimension, 50 million pixels, -large-page warning) and cancellation/resource cleanup. A signature is not a -guarantee of safe or well-formed content. +MIME type and extension are advisory only; valid `%PDF-` bytes are required before parser processing. + +Issue #114 implements `requirePdfSignature` and `readPdfSourceBytes` in +`tools/shared/pdf.js`. File admission reads only `slice(0, 5)` before a full +read, then checks the returned buffer too. Cached-byte parser entry points use +the same primitive. The retained `isSupportedPdf` helper chooses an error +message only; file-picker accept attributes remain advisory UX hints. + +The header must begin at byte zero, matching the first-line header specified in +[Adobe PDF Reference 1.7, section 3.4.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.7old.pdf). +Generated minimal fixtures and the existing real PDF corpus start there. BOMs, +junk preambles, empty files and incomplete prefixes are rejected; there is no +scan for a later header, even if a repair-tolerant parser could accept one. +A complete five-byte header passes admission only. It does not prove full PDF +validity: parser loading/page inspection remains the deeper rejection layer. + +Audited original-source paths: + +- Merge and Split use `loadPdfSource`; inspection uses the same loader. +- Organizer and Metadata use the loader and bounded reader; their exported + cached-byte processing helpers explicitly require the signature again. +- PDF to Images uses inspection/bounded reading and `LocalPdfRenderer.load`. +- Organizer thumbnails also use `LocalPdfRenderer.load`, guarded before PDF.js. +- PDF to Text/Searchable PDF use `readPdfOcrSource`, the OCR service gate, + the guarded renderer, and `createSearchablePdf` before pdf-lib loading. +- Metadata's second load verifies bytes freshly serialized by pdf-lib, rather + than accepting another user input; original-source admission already ran. + +`tests/pdf-signature.test.mjs` covers real PDF admission/merge/split with normal, +empty and misleading MIME/name metadata; spoofed bytes, empty/truncated prefixes, +BOM/preambles, typed-array offsets, bounded reads, swapped adapter bytes, +cached-byte/OCR/renderer rejection before parsing, and malformed complete headers +rejected by pdf-lib. Existing OCR/cancellation fixtures now contain complete +headers so those tests still reach their intended paths. Existing render bounds +(16,384 dimension, 50 million pixels), large-page warning, cancellation and +resource cleanup are unchanged. F-01 is resolved by this implementation; its PR +still requires review and integration before release. ### Monitoring limitations @@ -176,9 +205,10 @@ upgrade. Maintenance and patch-lag findings are separately classified below. Bootstrap tracking: [#111](https://github.com/SecureToolsProject/Secure_Tools/issues/111). Issue #112 implementation is documented below; live confirmation remains pending. Bootstrap and provenance are integrated into v2.3. Issue #113 implements the -remaining Action pins on its review branch; maintenance activation is pending -production promotion. Recommended next independent hardening task: #114, shared -PDF byte-signature admission. Do not start it as part of #113. +remaining Action pins, now integrated through PR #121; maintenance activation is +pending production promotion. Issue #114 implements shared PDF byte-signature +admission on its review branch. Recommended next independent hardening task: +#117, hosting-layer security headers (P1); do not combine it with #114. ## Verification and preserved invariants diff --git a/tests/pdf-metadata.test.mjs b/tests/pdf-metadata.test.mjs index 90c0e25..1fde118 100644 --- a/tests/pdf-metadata.test.mjs +++ b/tests/pdf-metadata.test.mjs @@ -112,7 +112,7 @@ async function testFailuresAndNames() { await assert.rejects(readPdfMetadata(new File(["not pdf"], "broken.pdf", { type: "application/pdf" }), PDFDocument), (error) => error.code === "UNREADABLE_PDF"); await assert.rejects(readPdfMetadata(new File(["text"], "notes.txt", { type: "text/plain" }), PDFDocument), (error) => error.code === "UNSUPPORTED_PDF"); const encryptedLibrary = { create: PDFDocument.create, load: async () => { throw new Error("password encrypted"); } }; - await assert.rejects(readPdfMetadata(new File(["%PDF"], "locked.pdf", { type: "application/pdf" }), encryptedLibrary), (error) => error.code === "ENCRYPTED_PDF"); + await assert.rejects(readPdfMetadata(new File(["%PDF-1.7"], "locked.pdf", { type: "application/pdf" }), encryptedLibrary), (error) => error.code === "ENCRYPTED_PDF"); assert.equal(metadataFilename("report.pdf"), "report_clean.pdf"); assert.equal(metadataFilename("report.PDF"), "report_clean.pdf"); assert.equal(metadataFilename("report.pdf", "client/private"), "client_private.pdf"); diff --git a/tests/pdf-ocr-foundation.test.mjs b/tests/pdf-ocr-foundation.test.mjs index 88ffd09..e629c89 100644 --- a/tests/pdf-ocr-foundation.test.mjs +++ b/tests/pdf-ocr-foundation.test.mjs @@ -110,7 +110,7 @@ assert.equal(new TextDecoder().decode(await readPdfOcrSource(acceptedPdf)), "%PD canvasFactory() { const canvas = canvasHarness(renderer.events); canvases.push(canvas); return canvas; }, }); const result = await service.recognizeDocument({ - sourceBytes: Uint8Array.of(1, 2, 3).buffer, + sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng+kor", selection: { mode: "selected", pageNumbers: [3, 1] }, onProgress(value) { progress.push(value); }, @@ -144,7 +144,7 @@ assert.equal(new TextDecoder().decode(await readPdfOcrSource(acceptedPdf)), "%PD return { text: "layout", lines: [{ text: "layout", confidence: 54, bbox: { x0: 2, y0: 4, x1: 20, y1: 14 } }] }; }); const service = createPdfOcrService({ rendererFactory: async () => renderer.renderer, ocrService: ocr.service, canvasFactory: () => canvasHarness([]) }); - const result = await service.recognizeDocument({ sourceBytes: new ArrayBuffer(1), language: "eng", includeLayout: true, inspectExistingText: true }); + const result = await service.recognizeDocument({ sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng", includeLayout: true, inspectExistingText: true }); assert.deepEqual(result.pages[0].lines, [{ text: "layout", confidence: 54, bbox: { x0: 2, y0: 4, x1: 20, y1: 14 } }]); assert.deepEqual(result.pages[0].rasterToPdfTransform.map((value) => Object.is(value, -0) ? 0 : value), [0.5, 0, 0, -0.5, 0, 50]); assert.equal(result.pages[0].hasMeaningfulText, false); @@ -160,7 +160,7 @@ assert.equal(new TextDecoder().decode(await readPdfOcrSource(acceptedPdf)), "%PD canvasFactory: () => canvasHarness([]), }); for (const language of ["eng", "kor", "eng+kor"]) { - const result = await service.recognizeDocument({ sourceBytes: new ArrayBuffer(1), language }); + const result = await service.recognizeDocument({ sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language }); assert.equal(result.pages[0].text, language); } assert.deepEqual(languages, ["eng", "kor", "eng+kor"]); @@ -186,7 +186,7 @@ assert.equal(new TextDecoder().decode(await readPdfOcrSource(acceptedPdf)), "%PD canvasFactory: () => canvasHarness([]), }); const task = service.recognizeDocument({ - sourceBytes: new ArrayBuffer(2), language: "eng", + sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng", onProgress(value) { emitted.push(value); }, onPageResult(value) { appended.push(value); }, }); @@ -199,7 +199,7 @@ assert.equal(new TextDecoder().decode(await readPdfOcrSource(acceptedPdf)), "%PD assert.deepEqual(appended, [], "no stale page result is appended"); const replacementResult = await service.recognizeDocument({ - sourceBytes: Uint8Array.of(9).buffer, + sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng", selection: { mode: "selected", pageNumbers: [2] }, }); @@ -215,7 +215,7 @@ assert.equal(new TextDecoder().decode(await readPdfOcrSource(acceptedPdf)), "%PD ocrService: ocr.service, canvasFactory: () => canvasHarness(renderer.events), }); - const task = service.recognizeDocument({ sourceBytes: new ArrayBuffer(1), language: "eng" }); + const task = service.recognizeDocument({ sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng" }); await waitTurn(); const started = performance.now(); assert.equal(await service.cancel(), true); @@ -237,17 +237,17 @@ assert.equal(new TextDecoder().decode(await readPdfOcrSource(acceptedPdf)), "%PD ocrService: ocr.service, canvasFactory: () => canvasHarness([]), }); - await assert.rejects(service.recognizeDocument({ sourceBytes: new ArrayBuffer(1), language: "eng" }), (error) => error.code === "PDF_OCR_FAILED"); - assert.equal((await service.recognizeDocument({ sourceBytes: new ArrayBuffer(1), language: "eng" })).pages[0].text, "retry succeeded"); + await assert.rejects(service.recognizeDocument({ sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng" }), (error) => error.code === "PDF_OCR_FAILED"); + assert.equal((await service.recognizeDocument({ sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng" })).pages[0].text, "retry succeeded"); await service.dispose(); - await assert.rejects(service.recognizeDocument({ sourceBytes: new ArrayBuffer(1), language: "eng" }), (error) => error.code === "PDF_OCR_DISPOSED"); + await assert.rejects(service.recognizeDocument({ sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng" }), (error) => error.code === "PDF_OCR_DISPOSED"); } { const renderer = rendererHarness({ loadError: new Error("FormatError: Invalid PDF structure") }); const ocr = ocrHarness(); const service = createPdfOcrService({ rendererFactory: async () => renderer.renderer, ocrService: ocr.service, canvasFactory: () => canvasHarness([]) }); - await assert.rejects(service.recognizeDocument({ sourceBytes: new ArrayBuffer(1), language: "eng" }), (error) => error.code === "UNREADABLE_PDF"); + await assert.rejects(service.recognizeDocument({ sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng" }), (error) => error.code === "UNREADABLE_PDF"); assert.equal(renderer.events.filter((event) => event === "destroy").length, 1); await service.dispose(); } @@ -257,7 +257,7 @@ assert.equal(new TextDecoder().decode(await readPdfOcrSource(acceptedPdf)), "%PD const ocr = ocrHarness(); const service = createPdfOcrService({ rendererFactory: async () => renderer.renderer, ocrService: ocr.service, canvasFactory: () => canvasHarness([]) }); const result = await service.recognizeDocument({ - sourceBytes: new ArrayBuffer(1), language: "eng", selection: { mode: "selected", pageNumbers: [1] }, + sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, language: "eng", selection: { mode: "selected", pageNumbers: [1] }, }); assert.equal(result.largeDocument, true, "large documents surface a warning signal without an arbitrary hard limit"); await service.dispose(); diff --git a/tests/pdf-signature.test.mjs b/tests/pdf-signature.test.mjs new file mode 100644 index 0000000..b2a0eb8 --- /dev/null +++ b/tests/pdf-signature.test.mjs @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { File } from "node:buffer"; +import { createRequire } from "node:module"; +import { inspectPdf, loadPdfSource, readPdfSourceBytes, requirePdfSignature } from "../tools/shared/pdf.js"; +import { mergePdfFiles } from "../tools/pdf/merge/pdf.js"; +import { splitPdfFile } from "../tools/pdf/split/pdf.js"; +import { organizePdf, readOrganizerSource } from "../tools/pdf/organize/pdf.js"; +import { cleanPdfMetadata, readPdfMetadata } from "../tools/pdf/metadata/pdf.js"; +import { createSearchablePdf } from "../.ts-build/tools/shared/searchable-pdf.js"; +import { createPdfOcrService, readPdfOcrSource } from "../.ts-build/tools/shared/pdf-ocr.js"; + +const PDFLib = createRequire(import.meta.url)("../assets/vendor/pdf-lib/pdf-lib.min.js"); +const { PDFDocument } = PDFLib; +const source = await PDFDocument.create(); +source.addPage([200, 300]); +const validBytes = await source.save(); +const buffer = (text) => new TextEncoder().encode(text).buffer; +const unreadable = (error) => ["UNREADABLE_PDF", "UNSUPPORTED_PDF"].includes(error.code); + +// Actual PDF fixtures, including valid bytes with misleading metadata. +for (const [name, type] of [["minimal.pdf", "application/pdf"], ["empty-mime.pdf", ""], ["no-extension", ""], ["image.png", "image/png"]]) { + const file = new File([validBytes], name, { type }); + assert.deepEqual(await inspectPdf(file, PDFDocument), { pageCount: 1 }); + assert.equal((await readPdfOcrSource(file)).byteLength, validBytes.byteLength); + const merged = await mergePdfFiles({ files: [file, file], PDFDocument }); + assert.equal((await PDFDocument.load(await merged.blob.arrayBuffer())).getPageCount(), 2); + const split = await splitPdfFile({ file, mode: "extract", selection: "1", PDFDocument }); + assert.equal((await PDFDocument.load(await split.blob.arrayBuffer())).getPageCount(), 1); +} + +let loads = 0; +const parser = { create: PDFDocument.create.bind(PDFDocument), async load(...args) { loads += 1; return PDFDocument.load(...args); } }; +const invalidFiles = [ + new File(["plain text"], "spoof.pdf"), + new File(["not a PDF"], "spoof.bin", { type: "application/pdf" }), + new File([], "empty.pdf", { type: "application/pdf" }), + ...["%", "%P", "%PD", "%PDF"].map((prefix) => new File([prefix], "truncated.pdf", { type: "application/pdf" })), + new File(["\uFEFF%PDF-1.7"], "bom.pdf", { type: "application/pdf" }), + new File(["junk\n%PDF-1.7"], "preamble.pdf", { type: "application/pdf" }), +]; +for (const file of invalidFiles) { + await assert.rejects(loadPdfSource(file, parser), unreadable); + await assert.rejects(mergePdfFiles({ files: [file], PDFDocument: parser }), unreadable); + await assert.rejects(splitPdfFile({ file, mode: "extract", selection: "1", PDFDocument: parser }), unreadable); + await assert.rejects(readOrganizerSource(file, parser), unreadable); + await assert.rejects(readPdfMetadata(file, parser), unreadable); + await assert.rejects(readPdfOcrSource(file), unreadable); +} +assert.equal(loads, 0, "spoofed or truncated input never enters the parser"); + +// Five complete header bytes are admission, not proof of a valid document. +for (const text of ["%PDF-", "%PDF-1.7\n1 0 obj\n<< /Type /Catalog"]) { + const file = new File([text], "malformed.pdf", { type: "application/pdf" }); + await assert.rejects(loadPdfSource(file, parser), (error) => error.code === "UNREADABLE_PDF" && Boolean(error.cause)); +} +assert.equal(loads, 2, "valid headers reach the deep parser, which rejects malformed structure"); + +// A spoofed file adapter must be rejected after a bounded read, without a full read. +let fullReads = 0; +const boundedFile = { + name: "large.pdf", type: "application/pdf", + slice(start, end) { assert.equal(start, 0); assert.equal(end, 5); return new Blob(["wrong"]); }, + async arrayBuffer() { fullReads += 1; throw new Error("must not read the whole spoofed file"); }, +}; +await assert.rejects(readPdfSourceBytes(boundedFile), unreadable); +assert.equal(fullReads, 0); +// Also validate the full returned buffer so a non-Blob adapter cannot swap bytes. +await assert.rejects(readPdfSourceBytes({ ...boundedFile, slice() { return new Blob(["%PDF-"]); }, async arrayBuffer() { return buffer("wrong"); } }), unreadable); + +const offsetBytes = new Uint8Array(buffer("junk%PDF-1.7")); +assert.doesNotThrow(() => requirePdfSignature(offsetBytes.subarray(4))); +assert.doesNotThrow(() => requirePdfSignature(new DataView(offsetBytes.buffer, 4))); +assert.throws(() => requirePdfSignature(offsetBytes), unreadable); +assert.throws(() => requirePdfSignature(new ArrayBuffer(0)), unreadable); + +// Exported cached-byte entry points cannot bypass admission. +const invalid = buffer("not a PDF"); +loads = 0; +await assert.rejects(organizePdf({ sourceBytes: invalid, pages: [{ originalIndex: 0, removed: false, rotation: 0 }], PDFDocument: parser, degrees: PDFLib.degrees }), unreadable); +await assert.rejects(cleanPdfMetadata({ sourceBytes: invalid, selectedKeys: ["title"], PDFDocument: parser, PDFName: PDFLib.PDFName }), unreadable); +await assert.rejects(createSearchablePdf({ sourceBytes: invalid, pages: [], PDFLib: { PDFDocument: parser }, fontkit: {}, fontBytes: new ArrayBuffer(0) }), unreadable); +assert.equal(loads, 0); +let renderers = 0; +const service = createPdfOcrService({ rendererFactory() { renderers += 1; throw new Error("must not create renderer"); } }); +await assert.rejects(service.recognizeDocument({ sourceBytes: invalid, language: "eng" }), unreadable); +assert.equal(renderers, 0); +await service.dispose(); + +globalThis.DOMMatrix ||= class DOMMatrix {}; +globalThis.ImageData ||= class ImageData {}; +globalThis.Path2D ||= class Path2D {}; +// Match the existing searchable-PDF test's Node-only browser API shims. +Uint8Array.prototype.toHex ||= function toHex() { return Array.from(this, (value) => value.toString(16).padStart(2, "0")).join(""); }; +Math.sumPrecise ||= (values) => Array.from(values).reduce((sum, value) => sum + value, 0); +const { LocalPdfRenderer } = await import("../tools/shared/pdf-renderer.js"); +const validRenderer = new LocalPdfRenderer(validBytes.buffer.slice(validBytes.byteOffset, validBytes.byteOffset + validBytes.byteLength)); +assert.equal(await validRenderer.load(), 1, "a real PDF also passes PDF.js admission"); +await validRenderer.destroy(); +const renderer = new LocalPdfRenderer(invalid); +await assert.rejects(renderer.load(), unreadable); +assert.equal(renderer.loadingTask, null, "PDF.js is never started for invalid signatures"); +await renderer.destroy(); + +console.log("PDF signature admission passed: real merge/split, bounded reads, spoofed metadata, strict byte-zero headers, parser failure, and cached/OCR/renderer entry points."); diff --git a/tests/pdf-to-text.test.mjs b/tests/pdf-to-text.test.mjs index 42ede4f..b15cfc7 100644 --- a/tests/pdf-to-text.test.mjs +++ b/tests/pdf-to-text.test.mjs @@ -42,7 +42,7 @@ const service = { async dispose() {}, }; const controller = createPdfToTextController({ service, inspect: async () => ({ pageCount: 2 }), onChange: (state) => states.push(state.phase) }); -const file = Object.assign(new Blob(["%PDF"], { type: "application/pdf" }), { name: "sample.pdf", lastModified: 0 }); +const file = Object.assign(new Blob(["%PDF-1.7"], { type: "application/pdf" }), { name: "sample.pdf", lastModified: 0 }); await controller.select(file); const running = controller.recognize("eng", { mode: "all" }); await controller.cancel(); @@ -92,8 +92,8 @@ const replacementController = createPdfToTextController({ service: { async recognizeDocument() { throw new Error("unused"); }, async cancel() { return false; }, async dispose() {} }, inspect: async (source) => source.name === "old.pdf" ? new Promise((resolve) => { releaseOld = () => resolve({ pageCount: 9 }); }) : { pageCount: 2 }, }); -const oldFile = Object.assign(new Blob(["%PDF"], { type: "application/pdf" }), { name: "old.pdf", lastModified: 0 }); -const newFile = Object.assign(new Blob(["%PDF"], { type: "application/pdf" }), { name: "new.pdf", lastModified: 0 }); +const oldFile = Object.assign(new Blob(["%PDF-1.7"], { type: "application/pdf" }), { name: "old.pdf", lastModified: 0 }); +const newFile = Object.assign(new Blob(["%PDF-1.7"], { type: "application/pdf" }), { name: "new.pdf", lastModified: 0 }); const oldSelection = replacementController.select(oldFile); await replacementController.select(newFile); releaseOld(); await oldSelection; diff --git a/tests/run-all.mjs b/tests/run-all.mjs index d8177e3..3038dc7 100644 --- a/tests/run-all.mjs +++ b/tests/run-all.mjs @@ -40,6 +40,7 @@ for (const test of [ "tests/pdf-merge-and-categories.test.mjs", "tests/file-input-queue-state.test.mjs", "tests/pdf-split.test.mjs", + "tests/pdf-signature.test.mjs", "tests/security-hardening.test.mjs", "tests/release-gate.test.mjs", "tests/seo-foundation.test.mjs", diff --git a/tests/searchable-pdf.test.mjs b/tests/searchable-pdf.test.mjs index d82c316..0f42324 100644 --- a/tests/searchable-pdf.test.mjs +++ b/tests/searchable-pdf.test.mjs @@ -107,7 +107,7 @@ await assert.rejects(createSearchablePdf({ sourceBytes: new ArrayBuffer(1), page const midBuild = new AbortController(); const fakePage = { drawText() {}, pushOperators() {} }; const fakeLibrary = { degrees: (angle) => angle, pushGraphicsState() {}, popGraphicsState() {}, setCharacterSqueeze() {}, PDFDocument: { async load() { return { registerFontkit() {}, async embedFont() { return { widthOfTextAtSize: () => 10 }; }, getPages: () => [fakePage, fakePage], async save() { return Uint8Array.of(1); } }; } } }; -await assert.rejects(createSearchablePdf({ sourceBytes: new ArrayBuffer(1), pages: [pages[0], { ...pages[0], pageNumber: 2 }], PDFLib: fakeLibrary, fontkit: {}, fontBytes: new ArrayBuffer(1), signal: midBuild.signal, onProgress(value) { if (value.phase === "building-pdf" && value.pageIndex === 1) midBuild.abort(); } }), (error) => error.code === "SEARCHABLE_PDF_CANCELLED"); +await assert.rejects(createSearchablePdf({ sourceBytes: new TextEncoder().encode("%PDF-1.7").buffer, pages: [pages[0], { ...pages[0], pageNumber: 2 }], PDFLib: fakeLibrary, fontkit: {}, fontBytes: new ArrayBuffer(1), signal: midBuild.signal, onProgress(value) { if (value.phase === "building-pdf" && value.pageIndex === 1) midBuild.abort(); } }), (error) => error.code === "SEARCHABLE_PDF_CANCELLED"); const sourceCode = fs.readFileSync(path.join(root, "tools/shared/searchable-pdf.ts"), "utf8"); assert.doesNotMatch(sourceCode, /fetch\s*\(|XMLHttpRequest|sendBeacon|WebSocket|EventSource|https?:\/\//); assert.match(sourceCode, /opacity: 0/); diff --git a/tools/pdf/merge/app.js b/tools/pdf/merge/app.js index 326d8e8..b317eee 100644 --- a/tools/pdf/merge/app.js +++ b/tools/pdf/merge/app.js @@ -1,7 +1,7 @@ import { t } from "../../../js/i18n.js"; import { formatBytes, moveArrayItem, sanitizePdfFilename } from "../../shared/file.js"; import { downloadBlob, requestPdfSaveHandle, writeBlobToHandle } from "../../shared/save.js"; -import { inspectPdf, isSupportedPdf, mergePdfFiles } from "./pdf.js"; +import { inspectPdf, mergePdfFiles } from "./pdf.js"; const elements = { input: document.querySelector("#file-input"), dropZone: document.querySelector("#drop-zone"), @@ -79,8 +79,8 @@ function errorMessage(error) { async function addFiles(files) { if (state.busy || !files.length) return; - const candidates = files.filter(isSupportedPdf); - let rejected = files.length - candidates.length; + const candidates = files; + let rejected = 0; let added = 0; let lastError = null; state.busy = true; diff --git a/tools/pdf/metadata/app.js b/tools/pdf/metadata/app.js index 9764838..bd4137c 100644 --- a/tools/pdf/metadata/app.js +++ b/tools/pdf/metadata/app.js @@ -1,7 +1,6 @@ import { t } from "../../../js/i18n.js"; import { formatBytes } from "../../shared/file.js"; import { downloadBlob, requestPdfSaveHandle, writeBlobToHandle } from "../../shared/save.js"; -import { isSupportedPdf } from "../../shared/pdf.js"; import { clearMetadataSelection, selectedMetadataKeys, selectAllPresentMetadata, setMetadataSelected } from "./model.js"; import { cleanPdfMetadata, metadataFilename, readPdfMetadata } from "./pdf.js"; @@ -108,7 +107,7 @@ function errorKey(error) { async function addSource(files) { if (state.busy || !files.length) return; if (files.length !== 1) { setStatus("pdfMetadata.errors.oneFile", {}, "error"); return; } - const file = files[0]; if (!isSupportedPdf(file)) { setStatus("pdfMetadata.errors.unsupported", {}, "error"); return; } + const file = files[0]; state.busy = true; state.source = null; state.fields = []; state.comparison = null; elements.filename.value = ""; elements.inspectionDetails.open = false; elements.customizeCleaning.open = false; render(); setStatus("pdfMetadata.status.reading"); try { diff --git a/tools/pdf/metadata/pdf.js b/tools/pdf/metadata/pdf.js index 9d883f1..de78f73 100644 --- a/tools/pdf/metadata/pdf.js +++ b/tools/pdf/metadata/pdf.js @@ -1,5 +1,5 @@ import { sanitizePdfFilename } from "../../shared/file.js"; -import { createPdfError, loadPdfSource, requirePdfDocument } from "../../shared/pdf.js"; +import { createPdfError, loadPdfSource, readPdfSourceBytes, requirePdfDocument, requirePdfSignature } from "../../shared/pdf.js"; import { extractMetadata, isSupportedMetadataKey, SUPPORTED_METADATA_FIELDS } from "./model.js"; function pageSnapshot(document) { @@ -40,7 +40,7 @@ export async function readPdfMetadata(file, PDFDocument) { requirePdfDocument(PDFDocument); const document = await loadPdfSource(file, PDFDocument); return { - bytes: await file.arrayBuffer(), + bytes: await readPdfSourceBytes(file), fields: extractMetadata(document), pages: pageSnapshot(document), }; @@ -57,6 +57,7 @@ export async function cleanPdfMetadata({ sourceBytes, selectedKeys, PDFDocument, } try { + requirePdfSignature(sourceBytes); const source = await PDFDocument.load(sourceBytes, { ignoreEncryption: false, updateMetadata: false }); const before = extractMetadata(source); const beforePages = pageSnapshot(source); diff --git a/tools/pdf/organize/app.js b/tools/pdf/organize/app.js index 7e8d733..d367577 100644 --- a/tools/pdf/organize/app.js +++ b/tools/pdf/organize/app.js @@ -1,7 +1,6 @@ import { t } from "../../../js/i18n.js"; import { formatBytes } from "../../shared/file.js"; import { downloadBlob, requestPdfSaveHandle, writeBlobToHandle } from "../../shared/save.js"; -import { isSupportedPdf } from "../../shared/pdf.js"; import { createPageState, isDirty, movePage, removePage, resetPages, rotatePage, visiblePages } from "./model.js"; import { organizePdf, organizerFilename, readOrganizerSource } from "./pdf.js"; import { PdfThumbnailRenderer, runRenderQueue } from "./renderer.js"; @@ -135,7 +134,6 @@ async function addSource(files) { if (state.busy || !files.length) return; if (files.length !== 1) { setStatus("organizePdf.errors.oneFile", {}, "error"); return; } const file = files[0]; - if (!isSupportedPdf(file)) { setStatus("organizePdf.errors.unsupported", {}, "error"); return; } state.busy = true; renderState(); setStatus("organizePdf.status.loading"); diff --git a/tools/pdf/organize/pdf.js b/tools/pdf/organize/pdf.js index 6691448..0badbf2 100644 --- a/tools/pdf/organize/pdf.js +++ b/tools/pdf/organize/pdf.js @@ -1,5 +1,5 @@ import { sanitizePdfFilename } from "../../shared/file.js"; -import { createPdfError, loadPdfSource, requirePdfDocument } from "../../shared/pdf.js"; +import { createPdfError, loadPdfSource, readPdfSourceBytes, requirePdfDocument, requirePdfSignature } from "../../shared/pdf.js"; import { visiblePages } from "./model.js"; export function organizerFilename(sourceName, customValue = "") { @@ -12,7 +12,7 @@ export async function readOrganizerSource(file, PDFDocument) { requirePdfDocument(PDFDocument); const document = await loadPdfSource(file, PDFDocument); return { - bytes: await file.arrayBuffer(), + bytes: await readPdfSourceBytes(file), pageCount: document.getPageCount(), rotations: document.getPages().map((page) => page.getRotation().angle), }; @@ -23,6 +23,7 @@ export async function organizePdf({ sourceBytes, pages, PDFDocument, degrees }) const active = visiblePages(pages); if (!active.length) throw createPdfError("NO_PAGES_REMAIN"); try { + requirePdfSignature(sourceBytes); const source = await PDFDocument.load(sourceBytes, { ignoreEncryption: false, updateMetadata: false }); const output = await PDFDocument.create(); const copied = await output.copyPages(source, active.map((page) => page.originalIndex)); diff --git a/tools/pdf/split/app.js b/tools/pdf/split/app.js index 9651cba..d08da2e 100644 --- a/tools/pdf/split/app.js +++ b/tools/pdf/split/app.js @@ -1,6 +1,6 @@ import { t } from "../../../js/i18n.js"; import { formatBytes, sanitizePdfFilename } from "../../shared/file.js"; -import { inspectPdf, isSupportedPdf } from "../../shared/pdf.js"; +import { inspectPdf } from "../../shared/pdf.js"; import { downloadBlob, requestSaveHandle, writeBlobToHandle } from "../../shared/save.js"; import { createPageGroups, createSplitNames, splitPdfFile } from "./pdf.js"; @@ -97,10 +97,6 @@ async function addSource(files) { return; } const file = files[0]; - if (!isSupportedPdf(file)) { - setStatus("splitPdf.errors.unsupported", {}, "error"); - return; - } state.busy = true; setStatus("splitPdf.status.reading", {}, "neutral"); renderSource(); diff --git a/tools/pdf/to-images/app.js b/tools/pdf/to-images/app.js index 167427d..983b953 100644 --- a/tools/pdf/to-images/app.js +++ b/tools/pdf/to-images/app.js @@ -1,6 +1,6 @@ import { t } from "../../../js/i18n.js"; import { formatBytes, sanitizePdfFilename } from "../../shared/file.js"; -import { inspectPdf, isSupportedPdf } from "../../shared/pdf.js"; +import { inspectPdf, readPdfSourceBytes } from "../../shared/pdf.js"; import { downloadBlob, requestSaveHandle, writeBlobToHandle } from "../../shared/save.js"; import { createConversionPlan, convertPdfToImages, IMAGE_FORMATS } from "./converter.js"; @@ -90,13 +90,12 @@ async function addSource(files) { await stopActiveJob(); if (files.length !== 1) { setStatus("pdfToImages.errors.oneFile", {}, "error"); return; } const file = files[0]; - if (!isSupportedPdf(file)) { setStatus("pdfToImages.errors.unsupported", {}, "error"); return; } const session = ++state.session; state.loading = true; renderState(); setStatus("pdfToImages.status.reading"); try { - const [{ pageCount }, bytes] = await Promise.all([inspectPdf(file, window.PDFLib?.PDFDocument), file.arrayBuffer()]); + const [{ pageCount }, bytes] = await Promise.all([inspectPdf(file, window.PDFLib?.PDFDocument), readPdfSourceBytes(file)]); if (session !== state.session) return; state.source = { file, pageCount, bytes }; elements.filename.value = sourceBaseName(file.name); diff --git a/tools/shared/pdf-ocr.ts b/tools/shared/pdf-ocr.ts index 6ac225e..8d417a5 100644 --- a/tools/shared/pdf-ocr.ts +++ b/tools/shared/pdf-ocr.ts @@ -1,6 +1,6 @@ import { createOcrService, resolveOcrLanguage } from "./ocr.js"; import type { OcrLanguage, OcrProgress, OcrService } from "./ocr.js"; -import { isSupportedPdf } from "./pdf.js"; +import { readPdfSourceBytes, requirePdfSignature } from "./pdf.js"; import type { PdfFileLike } from "./pdf.js"; import type { LocalPdfRenderer, PdfPageProxy, PdfRenderContext } from "./pdf-renderer.js"; @@ -115,6 +115,7 @@ function throwIfAborted(signal: AbortSignal): void { function normalizePipelineError(error: unknown, signal: AbortSignal): ErrorWithCode { if (signal.aborted || errorCode(error) === "OCR_CANCELLED") return pdfOcrError("PDF_OCR_CANCELLED", error); if (hasErrorCode(error) && error.code.startsWith("PDF_OCR_")) return error; + if (hasErrorCode(error) && error.code === "UNREADABLE_PDF") return error; const detail = errorDetail(error); if (detail.includes("password") || detail.includes("encrypt")) return pdfOcrError("ENCRYPTED_PDF", error); if (detail.includes("invalid pdf") || detail.includes("missing pdf") || detail.includes("formaterror")) { @@ -212,8 +213,7 @@ export function resolvePdfOcrPages(selection: PdfOcrPageSelection | undefined, p } export async function readPdfOcrSource(file: PdfFileLike): Promise { - if (!isSupportedPdf(file)) throw pdfOcrError("UNSUPPORTED_PDF"); - return file.arrayBuffer(); + return readPdfSourceBytes(file); } async function defaultRendererFactory(sourceBytes: ArrayBuffer): Promise { @@ -235,7 +235,7 @@ export function createPdfOcrService(configuration: PdfOcrServiceConfiguration = async function run(request: PdfOcrRequest, jobGeneration: number, signal: AbortSignal): Promise { const language = resolveOcrLanguage(request.language); - let sourceBytes = request.sourceBytes.slice(0); + let sourceBytes = request.sourceBytes; let renderer: PdfOcrRenderer | null = null; let destroying: Promise | null = null; const destroyRenderer = (): Promise => { @@ -253,6 +253,8 @@ export function createPdfOcrService(configuration: PdfOcrServiceConfiguration = signal.addEventListener("abort", abortRenderer, { once: true }); try { throwIfAborted(signal); + requirePdfSignature(sourceBytes); + sourceBytes = sourceBytes.slice(0); emit({ phase: "loading-document", pageNumber: null, pageIndex: 0, pageCount: 0, documentPageCount: null, pageProgress: null, overallProgress: 0, ocrStage: null }); renderer = await rendererFactory(sourceBytes); const documentPageCount = await renderer.load(); diff --git a/tools/shared/pdf-renderer.js b/tools/shared/pdf-renderer.js index 75d173c..d6fdaf5 100644 --- a/tools/shared/pdf-renderer.js +++ b/tools/shared/pdf-renderer.js @@ -1,4 +1,5 @@ import * as pdfjsLib from "../../assets/vendor/pdfjs/pdf.min.mjs"; +import { requirePdfSignature } from "./pdf.js"; export const PDFJS_VERSION = pdfjsLib.version; export const PDFJS_WORKER_URL = new URL("../../assets/vendor/pdfjs/pdf.worker.min.mjs", import.meta.url).href; @@ -17,6 +18,7 @@ export class LocalPdfRenderer { async load() { if (this.destroyed) throw new Error("RENDERER_UNAVAILABLE"); + requirePdfSignature(this.sourceBytes); this.loadingTask = pdfjsLib.getDocument({ data: new Uint8Array(this.sourceBytes.slice(0)), isEvalSupported: false, diff --git a/tools/shared/pdf.d.ts b/tools/shared/pdf.d.ts index 4ca016b..aa34b7e 100644 --- a/tools/shared/pdf.d.ts +++ b/tools/shared/pdf.d.ts @@ -3,4 +3,6 @@ export interface PdfFileLike extends Blob { } export function isSupportedPdf(file: unknown): boolean; +export function requirePdfSignature(sourceBytes: ArrayBuffer | ArrayBufferView, fileName?: string): void; +export function readPdfSourceBytes(file: PdfFileLike): Promise; export function inspectPdf(file: PdfFileLike, PDFDocument: unknown): Promise<{ pageCount: number }>; diff --git a/tools/shared/pdf.js b/tools/shared/pdf.js index 38b2efa..821c820 100644 --- a/tools/shared/pdf.js +++ b/tools/shared/pdf.js @@ -20,16 +20,46 @@ export function requirePdfDocument(PDFDocument) { } export function isSupportedPdf(file) { + // Advisory hint for error messaging only; never authorizes parser entry. if (!file) return false; const type = String(file.type || "").toLowerCase(); if (type === "application/pdf") return true; return type === "" && /\.pdf$/i.test(String(file.name || "")); } +// Require the header at byte zero. Do not scan for a header in arbitrary content. +// This is admission only: the parser must still validate the PDF structure. +export function requirePdfSignature(sourceBytes, fileName) { + const signature = [0x25, 0x50, 0x44, 0x46, 0x2d]; + const view = ArrayBuffer.isView(sourceBytes) + ? new Uint8Array(sourceBytes.buffer, sourceBytes.byteOffset, Math.min(5, sourceBytes.byteLength)) + : sourceBytes instanceof ArrayBuffer ? new Uint8Array(sourceBytes, 0, Math.min(5, sourceBytes.byteLength)) : null; + if (!view || view.length !== 5 || signature.some((byte, index) => view[index] !== byte)) { + throw createPdfError("UNREADABLE_PDF", fileName); + } +} + +export async function readPdfSourceBytes(file) { + if (typeof file?.slice !== "function" || typeof file?.arrayBuffer !== "function") { + throw createPdfError("UNSUPPORTED_PDF", file?.name); + } + try { + // Reject before reading the complete file or starting any parser/worker. + requirePdfSignature(await file.slice(0, 5).arrayBuffer(), file.name); + } catch (error) { + if (error?.code === "UNREADABLE_PDF" && !isSupportedPdf(file)) { + throw createPdfError("UNSUPPORTED_PDF", file.name, error); + } + throw error; + } + const bytes = await file.arrayBuffer(); + requirePdfSignature(bytes, file.name); + return bytes; +} + export async function loadPdfSource(file, PDFDocument) { - if (!isSupportedPdf(file)) throw createPdfError("UNSUPPORTED_PDF", file?.name); try { - const bytes = await file.arrayBuffer(); + const bytes = await readPdfSourceBytes(file); return await PDFDocument.load(bytes, { ignoreEncryption: false, updateMetadata: false }); } catch (error) { if (error?.code) throw error; diff --git a/tools/shared/searchable-pdf.ts b/tools/shared/searchable-pdf.ts index 3546a7e..78a50ab 100644 --- a/tools/shared/searchable-pdf.ts +++ b/tools/shared/searchable-pdf.ts @@ -1,4 +1,5 @@ import type { PdfOcrPageResult } from "./pdf-ocr.js"; +import { requirePdfSignature } from "./pdf.js"; type Matrix = readonly [number, number, number, number, number, number]; interface PdfFontLike { widthOfTextAtSize(text: string, size: number): number } @@ -26,6 +27,7 @@ export function searchablePdfFilename(name = "document.pdf"): string { export async function createSearchablePdf(request: SearchablePdfRequest): Promise { abort(request.signal); + requirePdfSignature(request.sourceBytes); const document = await request.PDFLib.PDFDocument.load(request.sourceBytes.slice(0), { updateMetadata: false }); const needsFont = request.pages.some((page) => !page.hasMeaningfulText && Boolean(page.lines?.some((line) => line.text.trim()))); let font: PdfFontLike | null = null; From b6c02ba21978f9c80d927afc88a3db125fcaff96 Mon Sep 17 00:00:00 2001 From: maruson08 Date: Fri, 9 Oct 2026 12:32:30 +0900 Subject: [PATCH 05/12] =?UTF-8?q?=F0=9F=94=A7[Config]=20Enforce=20producti?= =?UTF-8?q?on=20HTTP=20security=20headers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 14 +++ .../workflows/deploy-cloudflare-bridge.yml | 8 +- config/cloudflare/_headers | 18 ++++ docs/v2.3-bootstrap.md | 74 +++++++++++++- scripts/build-site.mjs | 1 + scripts/http-security-headers.mjs | 96 +++++++++++++++++++ scripts/validate-build.mjs | 2 + tests/ci-foundation.test.mjs | 3 + tests/cloudflare-bridge.test.mjs | 11 ++- tests/deployment-smoke.mjs | 6 ++ tests/production/local-smoke.mjs | 24 +++++ tests/production/smoke.mjs | 29 ++++-- tests/release-hardening-http.test.mjs | 11 +++ tests/security-hardening.test.mjs | 33 +++++++ tests/serve-ocr-smoke.mjs | 8 ++ 15 files changed, 317 insertions(+), 21 deletions(-) create mode 100644 config/cloudflare/_headers create mode 100644 scripts/http-security-headers.mjs create mode 100644 tests/production/local-smoke.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 95ba0f2..bab5edf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -78,3 +78,17 @@ jobs: - name: Run real local OCR smoke test run: node tests/ocr-smoke.test.mjs + + - name: Install pinned browser for artifact security verification + run: npx playwright install --with-deps chromium + + - name: Verify HTTP headers, browser OCR and downloads on built artifact + run: node tests/production/local-smoke.mjs + + - name: Retain artifact browser diagnostics + if: failure() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: artifact-browser-diagnostics + path: .ts-build/production-smoke + retention-days: 7 diff --git a/.github/workflows/deploy-cloudflare-bridge.yml b/.github/workflows/deploy-cloudflare-bridge.yml index 2fd1433..a9c3401 100644 --- a/.github/workflows/deploy-cloudflare-bridge.yml +++ b/.github/workflows/deploy-cloudflare-bridge.yml @@ -76,13 +76,7 @@ jobs: # Keep the generic/GitHub Pages CNAME; strip only the isolated Pages copy. rm -f "$BRIDGE_DIRECTORY/CNAME" - printf '%s\n' \ - 'https://secure-tools-web-bridge.pages.dev/*' \ - ' X-Robots-Tag: noindex, nofollow' \ - '' \ - 'https://:version.secure-tools-web-bridge.pages.dev/*' \ - ' X-Robots-Tag: noindex, nofollow' \ - > "$BRIDGE_DIRECTORY/_headers" + # _headers is copied from the reviewed config by build-site, not overwritten. [[ ! -e "$BRIDGE_DIRECTORY/CNAME" ]] [[ ! -e "$BRIDGE_DIRECTORY/_worker.js" ]] diff --git a/config/cloudflare/_headers b/config/cloudflare/_headers new file mode 100644 index 0000000..34f2296 --- /dev/null +++ b/config/cloudflare/_headers @@ -0,0 +1,18 @@ +# Static Pages policy. Keep MIME types and caching under Pages' control. +/* + Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; connect-src 'none'; object-src 'none'; frame-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self' + Referrer-Policy: no-referrer + Permissions-Policy: camera=(), microphone=(), geolocation=() + X-Content-Type-Options: nosniff + +# Preserve the existing dedicated worker context: it fetches same-origin +# core/WASM/language assets. Document connect-src remains none; workerBlobURL=false. +# Do not inherit the document policy on this one worker response. +/assets/vendor/tesseract/worker/worker.min.js + ! Content-Security-Policy + +https://secure-tools-web-bridge.pages.dev/* + X-Robots-Tag: noindex, nofollow + +https://:version.secure-tools-web-bridge.pages.dev/* + X-Robots-Tag: noindex, nofollow diff --git a/docs/v2.3-bootstrap.md b/docs/v2.3-bootstrap.md index 1dbdb51..5397ba8 100644 --- a/docs/v2.3-bootstrap.md +++ b/docs/v2.3-bootstrap.md @@ -48,11 +48,11 @@ historical code. | Finding | Current status | Evidence | Necessary next action | Priority / issue | | --- | --- | --- | --- | --- | | F-06 Artifact/source provenance | PARTIALLY RESOLVED | Production baseline has deployment SHA linkage and sampled asset equivalence. The Issue #112 implementation generates `dist/build-info.json` (`scripts/build-site.mjs`, `scripts/build-provenance.mjs`) and strictly checks SHA/version/schema/sensitive fields (`scripts/validate-build.mjs`, `scripts/verify-build-provenance.mjs`). The public path will be `/build-info.json`; current production has not received this code. | Preserve CI/generated/deployed-record checks; keep Issue #112 open until promotion and actual live production equality verification. This record is not a full digest or reproducibility proof. | P1 / [#112](https://github.com/SecureToolsProject/Secure_Tools/issues/112) | -| F-02 Mutable Actions | PARTIALLY RESOLVED | The #113 implementation pins all eight external Action uses to verified full SHAs with release comments; `scripts/validate-action-pins.mjs` and the security gate reject mutable/abbreviated/dynamic refs. `.github/dependabot.yml` configures weekly reviewed Actions updates targeting v2.3. | Pinning is complete on this branch. Maintenance automation is not yet active: GitHub requires this configuration on the default branch (main), which is unchanged. Activate only through a separately authorized production promotion, then verify scheduled updates before marking fully resolved. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | +| F-02 Mutable Actions | PARTIALLY RESOLVED | The #113 implementation pins all external Action uses (now nine, including #117 diagnostics) to verified full SHAs with release comments; `scripts/validate-action-pins.mjs` and the security gate reject mutable/abbreviated/dynamic refs. `.github/dependabot.yml` configures weekly reviewed Actions updates targeting v2.3. | Pinning is complete on this branch. Maintenance automation is not yet active: GitHub requires this configuration on the default branch (main), which is unchanged. Activate only through a separately authorized production promotion, then verify scheduled updates before marking fully resolved. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | | F-01 PDF admission | RESOLVED | Shared `tools/shared/pdf.js` signature admission checks five bytes before full file reads; all original-source pdf-lib/PDF.js entry points use it, including cached-byte helpers. MIME/extension cannot authorize or veto valid bytes. | Issue #114 implementation; strict byte-zero header policy and parser failure regression coverage described below. Structural validation remains with the parsers. | P2 / [#114](https://github.com/SecureToolsProject/Secure_Tools/issues/114) | | F-03 Disclosure | OPEN | Root `SECURITY.md` absent; GitHub private vulnerability reporting API reports `enabled: false`. | Document supported versions, verified private reporting route, coordinated disclosure, scope/non-goals, and warning against attaching sensitive files; enable route where permitted. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | | F-04 Independent scanning | OPEN | CI runs custom `security-hardening.test.mjs` and `release-gate.test.mjs`, but no CodeQL, Dependency Review, OSV/npm-audit job, or runtime-dependency monitoring. #113 prepares Actions version updates only. GitHub reports security updates/secret scanning disabled and no code-scanning analysis. | Small complementary JS/TS SAST and vendor-aware advisory monitoring; use lockfile audit for its actual coverage, without duplicating scanners. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | -| F-05 HTTP headers | PARTIALLY RESOLVED | Root/Image-to-Text/PDF-to-Text HTML and JS checked on both production origins: `nosniff` and `strict-origin-when-cross-origin` present; HTTP CSP and Permissions-Policy absent. Meta CSP in `index.html:10` and OCR pages line 4 contains `connect-src 'none'`, but no HTTP `frame-ancestors`. Generated deployment `_headers` covers alias noindex only (workflow lines 77–86). | Hosting-level CSP with `frame-ancestors 'none'` and appropriate Permissions-Policy; preserve same-origin worker/WASM/font/Blob flows and existing Referrer-Policy/nosniff. | P1 / [#117](https://github.com/SecureToolsProject/Secure_Tools/issues/117) | +| F-05 HTTP headers | PARTIALLY RESOLVED | Issue #117 implements `config/cloudflare/_headers`, copied unchanged into the artifact and validated before deployment. HTTP CSP adds frame-ancestors none; no-referrer, sensitive capability denials, and nosniff apply globally. A narrowly scoped Tesseract worker exception preserves existing local OCR loading. | Branch implementation complete; canonical/immutable production header and clean browser signoff remain pending a separately authorized promotion/deployment. Meta CSP is not an embedding defense. | P1 / [#117](https://github.com/SecureToolsProject/Secure_Tools/issues/117) | ### Provenance scope @@ -134,6 +134,71 @@ headers so those tests still reach their intended paths. Existing render bounds resource cleanup are unchanged. F-01 is resolved by this implementation; its PR still requires review and integration before release. +### Hosting-layer HTTP headers — Issue #117 + +The source of truth is `config/cloudflare/_headers`. `build-site.mjs` copies +it into `dist/_headers`; the isolated Cloudflare bridge copies it unchanged and +removes only that artifact's legacy CNAME. Generic/GitHub Pages ownership remains +unchanged. The workflow no longer overwrites the policy with alias-only headers. +[Cloudflare Pages header rules](https://developers.cloudflare.com/pages/configuration/headers/) +apply to static responses; matching rules combine headers, and redirects execute +first. No Functions/advanced Worker is introduced. + +The global policy enforces: + +- CSP: `default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; connect-src 'none'; object-src 'none'; frame-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'`. +- `Referrer-Policy: no-referrer`. +- `Permissions-Policy: camera=(), microphone=(), geolocation=()` (unused sensitive capabilities). +- `X-Content-Type-Options: nosniff`. + +The original HTML meta policies remain. Image Blob/data sources support local +previews; fonts and worker entry points remain same-origin. HTTP +`frame-ancestors 'none'` provides the embedding boundary that meta CSP cannot. +No inline/eval exception, external origin, cache/MIME override, reporting endpoint, +analytics or telemetry is added. Alias-only noindex rules remain separate, so +`tools.securetools.app` stays indexable. + +Only `/assets/vendor/tesseract/worker/worker.min.js` detaches the global CSP. +This preserves the existing dedicated worker context: its vendored code loads +same-origin core/WASM/traineddata, and `workerBlobURL: false` remains in place. +[Workers use their script response policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy#csp_in_workers); +applying document connect-src none and script-src self there would break existing +OCR asset fetching/WASM compilation. This exception does not remove any previous +worker CSP (there was none) or relax the document's connection policy. The worker's +own network boundary remains trusted pinned vendor code plus browser request +verification, not a new restrictive worker CSP. PDF.js retains the global policy +and its disabled evaluation/worker fetching/WASM settings. This task does not +redesign the application/worker CSP model. + +`scripts/http-security-headers.mjs` validates the reviewed policy, its exact +worker exception, alias isolation and isolated CNAME absence. `validate-build.mjs` +requires it for every build. Security regressions reject missing/weak CSP, +connections, embedding protection, inline/eval/external origins, privacy headers, +and widened exceptions. The artifact HTTP server reads this same configuration; +release tests verify all canonical HTML/linked assets and JSON/WASM/worker/lang +MIME types. Live response validation permits extra capability denials, but requires +camera/microphone/geolocation to be denied; the source policy remains exactly the +reviewed three denials. + +Deployment smoke and the full production smoke now check real response headers +on representative canonical/immutable routes, worker scripts and build-info.json. +CI runs the existing complete OCR/searchable-PDF/native-download/privacy browser +gate against the local built artifact in a clean GitHub environment. This is +artifact compatibility evidence, not proof of Cloudflare serving behavior. + +Read-only baseline on 2026-10-09: canonical root/PDF-to-Text and immutable root +still have no HTTP CSP/Permissions-Policy; Referrer-Policy is +strict-origin-when-cross-origin and nosniff is present. Canonical build-info.json +still returns 404 HTML. No production deployment or dashboard change occurred. +A local browser run exercised OCR/PDF workers/WASM/fonts, native downloads and +cancellation successfully; its clean privacy signoff failed because this computer's +AdGuard injected external scripts and rewrote HTTP CSP. Local full HTTP tests +therefore fail closed on the transformed policy. The strict gate remains intact; clean hosted +CI evidence is required. F-05 remains PARTIALLY RESOLVED until an authorized +release verifies actual canonical/immutable responses and clean browser behavior. +Cloudflare static delivery/project configuration is still a trust boundary; +Functions, hosting transformations or future path changes require renewed checks. + ### Monitoring limitations `npm audit` completed successfully with zero reported vulnerabilities for the @@ -207,8 +272,9 @@ Issue #112 implementation is documented below; live confirmation remains pending Bootstrap and provenance are integrated into v2.3. Issue #113 implements the remaining Action pins, now integrated through PR #121; maintenance activation is pending production promotion. Issue #114 implements shared PDF byte-signature -admission on its review branch. Recommended next independent hardening task: -#117, hosting-layer security headers (P1); do not combine it with #114. +admission, now integrated through PR #122. Issue #117 implements hosting headers +on its review branch, with production verification pending. Recommended next +independent hardening task: #115, private vulnerability disclosure. ## Verification and preserved invariants diff --git a/scripts/build-site.mjs b/scripts/build-site.mjs index 333475a..1462174 100644 --- a/scripts/build-site.mjs +++ b/scripts/build-site.mjs @@ -54,5 +54,6 @@ for (const file of ["404.html", "robots.txt", "sitemap.xml"]) { const redirectFile = `${legacyRedirects.map(({ from, to }) => `${from} ${to} ${redirectStatus}`).join("\n")}\n`; fs.writeFileSync(path.join(output, "_redirects"), redirectFile); writeBuildInfo(output, identity); +fs.copyFileSync(path.join(root, "config", "cloudflare", "_headers"), path.join(output, "_headers")); console.log(`Built ${canonicalPages.length} canonical pages and ${legacyRedirects.length} permanent redirects in dist/.`); diff --git a/scripts/http-security-headers.mjs b/scripts/http-security-headers.mjs new file mode 100644 index 0000000..6790078 --- /dev/null +++ b/scripts/http-security-headers.mjs @@ -0,0 +1,96 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; + +export const OCR_WORKER_PATH = "/assets/vendor/tesseract/worker/worker.min.js"; +const requiredCsp = new Map([ + ["default-src", "'self'"], ["script-src", "'self'"], ["style-src", "'self'"], + ["img-src", "'self' blob: data:"], ["font-src", "'self'"], ["worker-src", "'self'"], + ["connect-src", "'none'"], ["object-src", "'none'"], ["frame-src", "'none'"], + ["frame-ancestors", "'none'"], ["base-uri", "'self'"], ["form-action", "'self'"], +]); + +// This intentionally supports only the small literal/splat policy used here. +// Unsupported syntax fails rather than silently simulating Pages incorrectly. +export function parsePagesHeaders(text) { + const rules = []; + let current; + for (const raw of text.split(/\r?\n/)) { + if (!raw.trim() || raw.trimStart().startsWith("#")) continue; + if (!/^\s/.test(raw)) { + assert.ok(raw === "/*" || raw === OCR_WORKER_PATH || /^https:\/\/(?:secure-tools-web-bridge|:version\.secure-tools-web-bridge)\.pages\.dev\/\*$/.test(raw), `Unsupported Pages rule: ${raw}`); + current = { pattern: raw, headers: new Map(), remove: [] }; + rules.push(current); + } else { + assert.ok(current, "Header requires a rule"); + const line = raw.trim(); + if (line === "! Content-Security-Policy") { current.remove.push("content-security-policy"); continue; } + const match = line.match(/^([\w-]+):\s+(.+)$/); + assert.ok(match, `Invalid header: ${line}`); + const name = match[1].toLowerCase(); + assert.ok(!current.headers.has(name), `Duplicate header: ${name}`); + current.headers.set(name, match[2]); + } + } + return rules; +} + +export function headersForUrl(rules, value) { + const url = new URL(value); + const headers = new Headers(); + for (const rule of rules) { + const matches = rule.pattern === "/*" || rule.pattern === url.pathname + || (rule.pattern === "https://secure-tools-web-bridge.pages.dev/*" && url.hostname === "secure-tools-web-bridge.pages.dev") + || (rule.pattern === "https://:version.secure-tools-web-bridge.pages.dev/*" && /^[^.]+\.secure-tools-web-bridge\.pages\.dev$/.test(url.hostname)); + if (!matches) continue; + for (const [name, value] of rule.headers) headers.append(name, value); + for (const name of rule.remove) headers.delete(name); + } + return headers; +} + +export function assertSecurityHeaders(headers, { ocrWorker = false } = {}) { + assert.equal(headers.get("referrer-policy"), "no-referrer", "HTTP Referrer-Policy"); + const permissions = new Map(); + for (const part of (headers.get("permissions-policy") || "").split(",")) { + const match = part.trim().match(/^([a-z-]+)=\(\)$/); + assert.ok(match, "HTTP Permissions-Policy may contain only capability denials"); + assert.ok(!permissions.has(match[1]), "Duplicate permission directive"); + permissions.set(match[1], true); + } + for (const capability of ["camera", "microphone", "geolocation"]) assert.ok(permissions.has(capability), `HTTP Permissions-Policy must deny ${capability}`); + assert.equal(headers.get("x-content-type-options"), "nosniff", "HTTP nosniff"); + const csp = headers.get("content-security-policy"); + if (ocrWorker) { assert.equal(csp, null, "Only Tesseract's entry preserves its existing worker policy"); return; } + assert.ok(csp, "HTTP CSP is required"); + const directives = new Map(); + for (const part of csp.split(";").map(value => value.trim()).filter(Boolean)) { + const [name, ...values] = part.split(/\s+/); + assert.ok(!directives.has(name), `Duplicate CSP directive ${name}`); + directives.set(name, values.join(" ")); + } + assert.deepEqual(directives, requiredCsp, "HTTP CSP must preserve the reviewed local-only policy"); +} + +export function validateHostingHeaders(directory, { isolated = false } = {}) { + const rules = parsePagesHeaders(fs.readFileSync(path.join(directory, "_headers"), "utf8")); + assert.deepEqual(rules.map(rule => rule.pattern), ["/*", OCR_WORKER_PATH, "https://secure-tools-web-bridge.pages.dev/*", "https://:version.secure-tools-web-bridge.pages.dev/*"]); + assert.deepEqual([...rules[0].headers.keys()], ["content-security-policy", "referrer-policy", "permissions-policy", "x-content-type-options"]); + assert.deepEqual(rules[0].remove, []); + assert.equal(rules[0].headers.get("permissions-policy"), "camera=(), microphone=(), geolocation=()"); + assert.equal(rules[1].headers.size, 0); + assert.deepEqual(rules[1].remove, ["content-security-policy"]); + for (const rule of rules.slice(2)) { + assert.deepEqual([...rule.headers], [["x-robots-tag", "noindex, nofollow"]]); + assert.deepEqual(rule.remove, []); + } + for (const origin of ["https://tools.securetools.app", "https://secure-tools-web-bridge.pages.dev", "https://test.secure-tools-web-bridge.pages.dev"]) { + for (const route of ["/", "/pdf/to-text/", "/build-info.json", "/assets/vendor/pdfjs/pdf.worker.min.mjs", OCR_WORKER_PATH]) { + const headers = headersForUrl(rules, origin + route); + assertSecurityHeaders(headers, { ocrWorker: route === OCR_WORKER_PATH }); + assert.equal(headers.get("x-robots-tag"), origin.includes("pages.dev") ? "noindex, nofollow" : null); + } + } + if (isolated) assert.ok(!fs.existsSync(path.join(directory, "CNAME")), "Isolated Pages artifact must exclude CNAME"); + return rules; +} diff --git a/scripts/validate-build.mjs b/scripts/validate-build.mjs index e1dd40d..f6ee1e9 100644 --- a/scripts/validate-build.mjs +++ b/scripts/validate-build.mjs @@ -6,10 +6,12 @@ import { fileURLToPath } from "node:url"; import { canonicalPages, legacyRedirects, redirectStatus } from "./site-routes.mjs"; import { compiledBrowserModules } from "./typescript-modules.mjs"; import { validateBuildProvenance } from "./build-provenance.mjs"; +import { validateHostingHeaders } from "./http-security-headers.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const output = path.resolve(root, process.argv[2] || "dist"); validateBuildProvenance(output); +validateHostingHeaders(output, { isolated: Boolean(process.argv[2]) }); const htmlFiles = []; const outputFiles = []; diff --git a/tests/ci-foundation.test.mjs b/tests/ci-foundation.test.mjs index 113a020..58b41c5 100644 --- a/tests/ci-foundation.test.mjs +++ b/tests/ci-foundation.test.mjs @@ -27,5 +27,8 @@ assert.match(workflow, /run: npm ci --ignore-scripts/); assert.match(workflow, /run: npm run build/); assert.match(workflow, /run: npm test/); assert.match(workflow, /run: node tests\/ocr-smoke\.test\.mjs/); +assert.match(workflow, /run: npx playwright install --with-deps chromium/); +assert.match(workflow, /run: node tests\/production\/local-smoke\.mjs/); +assert.ok(workflow.indexOf("run: npm test") < workflow.indexOf("run: node tests/production/local-smoke.mjs")); console.log("CI workflow contract checks passed."); diff --git a/tests/cloudflare-bridge.test.mjs b/tests/cloudflare-bridge.test.mjs index c701857..e9af6b0 100644 --- a/tests/cloudflare-bridge.test.mjs +++ b/tests/cloudflare-bridge.test.mjs @@ -3,8 +3,10 @@ import fs from "node:fs"; import path from "node:path"; import { spawnSync } from "node:child_process"; import { validateBuildProvenance } from "../scripts/build-provenance.mjs"; +import { validateHostingHeaders } from "../scripts/http-security-headers.mjs"; const workflow = fs.readFileSync(".github/workflows/deploy-cloudflare-bridge.yml", "utf8"); +const headerPolicy = fs.readFileSync("config/cloudflare/_headers", "utf8"); assert.match(workflow, /^name: Deploy Cloudflare bridge$/m); assert.match(workflow, /^\s{2}push:\s*$[\s\S]*?^\s{6}- main$/m); @@ -24,9 +26,10 @@ assert.match(workflow, /secrets\.CLOUDFLARE_ACCOUNT_ID/); assert.match(workflow, /secure-tools-web-bridge/); assert.match(workflow, /pages deploy .* --project-name=secure-tools-web-bridge --branch=main --commit-hash=\$\{\{ github\.sha \}\}/); assert.match(workflow, /gitHubToken: \$\{\{ secrets\.GITHUB_TOKEN \}\}/); -assert.match(workflow, /X-Robots-Tag: noindex, nofollow/); -assert.match(workflow, /https:\/\/secure-tools-web-bridge\.pages\.dev\/\*/); -assert.match(workflow, /https:\/\/:version\.secure-tools-web-bridge\.pages\.dev\/\*/); +assert.match(headerPolicy, /X-Robots-Tag: noindex, nofollow/); +assert.match(headerPolicy, /https:\/\/secure-tools-web-bridge\.pages\.dev\/\*/); +assert.match(headerPolicy, /https:\/\/:version\.secure-tools-web-bridge\.pages\.dev\/\*/); +assert.doesNotMatch(workflow, />\s*"\$BRIDGE_DIRECTORY\/_headers"/, "Deployment cannot overwrite the validated header policy"); assert.doesNotMatch(workflow, /printf '\/\*\\n X-Robots-Tag/); assert.match(workflow, /steps\.deploy\.outputs\.deployment-url/); assert.match(workflow, /api\.cloudflare\.com\/client\/v4\/accounts\/\$\{CLOUDFLARE_ACCOUNT_ID\}\/pages\/projects\/secure-tools-web-bridge/); @@ -85,6 +88,8 @@ try { assert.deepEqual(validateBuildProvenance(artifact), validateBuildProvenance("dist"), "Exact provenance survives isolated deployment packaging"); assert.ok(!fs.existsSync(path.join(artifact, "_worker.js")) && !fs.existsSync(path.join(artifact, "functions"))); assert.match(fs.readFileSync(path.join(artifact, "_headers"), "utf8"), /X-Robots-Tag: noindex, nofollow/); + assert.equal(fs.readFileSync(path.join(artifact, "_headers"), "utf8"), headerPolicy); + validateHostingHeaders(artifact, { isolated: true }); } finally { assert.equal(path.dirname(artifact), staging); fs.rmSync(artifact, { recursive: true, force: true }); diff --git a/tests/deployment-smoke.mjs b/tests/deployment-smoke.mjs index a6c1d06..62d0a20 100644 --- a/tests/deployment-smoke.mjs +++ b/tests/deployment-smoke.mjs @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { canonicalPages, legacyRedirects, productionOrigin, redirectStatus } from "../scripts/site-routes.mjs"; +import { assertSecurityHeaders, OCR_WORKER_PATH } from "../scripts/http-security-headers.mjs"; const assets = [ "/css/base.css", @@ -38,6 +39,7 @@ async function request(pathname, options = {}) { if (options.status) assert.equal(response.status, options.status, `${url.href} status`); else { assert.equal(response.status, 200, `${url.href} must return HTTP 200 without a redirect`); + assertSecurityHeaders(response.headers, { ocrWorker: pathname === OCR_WORKER_PATH }); assert.equal( response.headers.get("x-robots-tag"), indexing === "noindex" ? "noindex, nofollow" : null, @@ -68,5 +70,9 @@ for (const asset of assets) { const response = await request(asset); await response.arrayBuffer(); } +for (const asset of ["/build-info.json", OCR_WORKER_PATH, "/assets/vendor/pdfjs/pdf.worker.min.mjs"]) { + const response = await request(asset); + await response.body.cancel(); +} console.log(`Deployment smoke checks passed for ${base.origin}: indexing=${indexing}, ${canonicalPages.length} canonical routes, ${legacyRedirects.length} permanent redirects, and ${assets.length} assets.`); diff --git a/tests/production/local-smoke.mjs b/tests/production/local-smoke.mjs new file mode 100644 index 0000000..c133aa6 --- /dev/null +++ b/tests/production/local-smoke.mjs @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; + +// Run the existing complete browser gate against the built artifact, not production. +// CI-produced provenance remains required; do not relax the deployed schema. +assert.equal(process.env.GITHUB_ACTIONS, "true", "Clean artifact browser gate runs on GitHub CI"); +assert.match(process.env.GITHUB_SHA || "", /^[0-9a-f]{40}$/); +const port = 43000 + Math.floor(Math.random() * 10000); +const origin = `http://127.0.0.1:${port}`; +const server = spawn(process.execPath, ["tests/serve-ocr-smoke.mjs", String(port)], { stdio: ["ignore", "pipe", "inherit"] }); +try { + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("Artifact server startup timed out")), 10000); + server.stdout.once("data", () => { clearTimeout(timer); resolve(); }); + server.once("error", error => { clearTimeout(timer); reject(error); }); + server.once("exit", code => { clearTimeout(timer); reject(new Error(`Artifact server exited: ${code}`)); }); + }); + const runner = spawn(process.execPath, ["tests/production/smoke.mjs"], { + stdio: "inherit", + env: { ...process.env, PRODUCTION_ORIGIN: origin, IMMUTABLE_ORIGIN: origin, EXPECTED_PRODUCTION_SHA: process.env.GITHUB_SHA }, + }); + const code = await new Promise((resolve, reject) => { runner.once("error", reject); runner.once("exit", resolve); }); + assert.equal(code, 0, "Clean artifact HTTP/CSP/OCR/download browser gate"); +} finally { server.kill(); } diff --git a/tests/production/smoke.mjs b/tests/production/smoke.mjs index dacaa6b..a289e20 100644 --- a/tests/production/smoke.mjs +++ b/tests/production/smoke.mjs @@ -3,12 +3,13 @@ import fs from "node:fs/promises"; import path from "node:path"; import { createHash } from "node:crypto"; import { chromium } from "playwright"; -import { canonicalPages, legacyRedirects } from "../../scripts/site-routes.mjs"; +import { canonicalPages, legacyRedirects, productionOrigin } from "../../scripts/site-routes.mjs"; import { pdfToTextLocales } from "../../js/locales/pdf-to-text.js"; import { createFixtures } from "./fixtures.mjs"; import { auditContext } from "./audit.mjs"; import { verifyPdf } from "./pdf-artifact.mjs"; import { verifyDeployedBuildInfo } from "../../scripts/verify-build-provenance.mjs"; +import { assertSecurityHeaders, OCR_WORKER_PATH } from "../../scripts/http-security-headers.mjs"; function origin(value, name) { assert.ok(value, `${name} is required`); @@ -19,9 +20,10 @@ function origin(value, name) { } const canonical = origin(process.env.PRODUCTION_ORIGIN, "PRODUCTION_ORIGIN"); const immutable = origin(process.env.IMMUTABLE_ORIGIN, "IMMUTABLE_ORIGIN"); +const targetLabel = canonical.startsWith("http:") && immutable.startsWith("http:") ? "Artifact smoke" : "Production smoke"; const directory = path.resolve(".ts-build/production-smoke"); await fs.mkdir(directory, { recursive: true }); -const report = { checkedAt: new Date().toISOString(), runner: process.env.GITHUB_ACTIONS ? "GitHub-hosted Ubuntu" : "local validation", canonical, immutable, gates: [], surfaces: {}, artifacts: [], status: "NO-GO" }; +const report = { checkedAt: new Date().toISOString(), target: targetLabel, runner: process.env.GITHUB_ACTIONS ? "GitHub-hosted Ubuntu" : "local validation", canonical, immutable, gates: [], surfaces: {}, artifacts: [], status: "NO-GO" }; let browser; const diagnosticError = error => String(error.stack || error).replaceAll(process.cwd(), "").replaceAll(process.cwd().replaceAll("\\", "/"), ""); async function gate(name, action, page) { @@ -40,8 +42,8 @@ async function get(url) { const r = await fetch(url, { redirect: "manual", signa async function httpSmoke() { for (const { route } of canonicalPages) { const text = await (await get(canonical + route)).text(); - assert.ok(text.includes(`href="${canonical}${route}"`), `canonical ${route}`); - assert.ok(text.includes(`content="${canonical}${route}"`), `OG ${route}`); + assert.ok(text.includes(`href="${productionOrigin}${route}"`), `canonical ${route}`); + assert.ok(text.includes(`content="${productionOrigin}${route}"`), `OG ${route}`); } for (const { from, to } of legacyRedirects) { const query = "?release=2.2&text=hello%20world"; @@ -49,10 +51,22 @@ async function httpSmoke() { assert.equal(r.status, 308); assert.equal(r.headers.get("location"), to + query); await get(canonical + to + query); } const sitemap = await (await get(canonical + "/sitemap.xml")).text(); - assert.deepEqual([...sitemap.matchAll(/(.*?)<\/loc>/g)].map(m => m[1]).sort(), canonicalPages.map(p => canonical + p.route).sort()); - assert.ok((await (await get(canonical + "/robots.txt")).text()).includes(canonical + "/sitemap.xml")); + assert.deepEqual([...sitemap.matchAll(/(.*?)<\/loc>/g)].map(m => m[1]).sort(), canonicalPages.map(p => productionOrigin + p.route).sort()); + assert.ok((await (await get(canonical + "/robots.txt")).text()).includes(productionOrigin + "/sitemap.xml")); return { routes: canonicalPages.length, redirects: legacyRedirects.length, sitemap: canonicalPages.length, robots: true }; } +async function httpHeaders() { + const results = []; + for (const o of [canonical, immutable]) { + for (const route of ["/", "/pdf/to-text/", "/image/to-text/", "/build-info.json", "/assets/vendor/pdfjs/pdf.worker.min.mjs", OCR_WORKER_PATH]) { + const response = await get(o + route); + assertSecurityHeaders(response.headers, { ocrWorker: route === OCR_WORKER_PATH }); + results.push({ url: o + route, headers: Object.fromEntries(response.headers) }); + await response.body.cancel(); + } + } + return results; +} async function assetComparison() { const routes = ["/js/main.js", "/js/i18n.js", "/pdf/to-text/app.js", "/image/to-text/app.js", "/shared/pdf-ocr.js", "/css/base.css", "/js/locales/pdf-to-text.js", "/assets/vendor/pdfjs/pdf.min.mjs", "/assets/vendor/pdfjs/pdf.worker.min.mjs", "/assets/vendor/tesseract/engine/tesseract.min.js", "/assets/vendor/tesseract/worker/worker.min.js", "/assets/vendor/tesseract/core/tesseract-core.wasm", "/assets/vendor/tesseract/lang/eng.traineddata.gz", "/assets/vendor/tesseract/lang/kor.traineddata.gz", "/assets/vendor/searchable-pdf/NotoSansKR-400.js"]; const assets = []; @@ -190,6 +204,7 @@ try { return results[0]; }); await gate("HTTP routes and SEO", httpSmoke); + await gate("Production HTTP security headers", httpHeaders); await gate("Release asset equivalence", assetComparison); browser = await chromium.launch({ headless: true, args: ["--disable-extensions"] }); report.browser = browser.version(); const fixtures = await createFixtures(browser); @@ -218,7 +233,7 @@ try { finally { await browser?.close(); await fs.writeFile(path.join(directory, "report.json"), JSON.stringify(report, null, 2)); - const summary = `# Production smoke: ${report.status}\n\nCanonical: ${canonical}\n\nImmutable: ${immutable}\n\n${report.gates.map(g => `- ${g.passed ? "PASS" : "FAIL"} ${g.name}${g.passed ? `: ${JSON.stringify(g.value)}` : `: ${g.error?.split("\n")[0]}`}`).join("\n")}\n`; + const summary = `# ${targetLabel}: ${report.status}\n\nCanonical: ${canonical}\n\nImmutable: ${immutable}\n\n${report.gates.map(g => `- ${g.passed ? "PASS" : "FAIL"} ${g.name}${g.passed ? `: ${JSON.stringify(g.value)}` : `: ${g.error?.split("\n")[0]}`}`).join("\n")}\n`; await fs.writeFile(path.join(directory, "summary.md"), summary); console.log(summary); } if (report.status !== "GO") process.exitCode = 1; diff --git a/tests/release-hardening-http.test.mjs b/tests/release-hardening-http.test.mjs index dcae1d4..628e6ba 100644 --- a/tests/release-hardening-http.test.mjs +++ b/tests/release-hardening-http.test.mjs @@ -4,6 +4,7 @@ import path from "node:path"; import { spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; import { canonicalPages, legacyRedirects, productionOrigin } from "../scripts/site-routes.mjs"; +import { assertSecurityHeaders, OCR_WORKER_PATH } from "../scripts/http-security-headers.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); // CI runs npm test without requiring a production build. Build-site only stages @@ -23,6 +24,7 @@ try { for (const { route } of canonicalPages) { const response = await fetch(`${origin}${route}`, { redirect: "manual" }); assert.equal(response.status, 200, `Direct route: ${route}`); + assertSecurityHeaders(response.headers); const html = await response.text(); assert.match(html, /[^<]+<\/title>/, `Title: ${route}`); assert.match(html, /<meta name="description" content="[^"]+"/, `Description: ${route}`); @@ -36,6 +38,7 @@ try { // Canonical links name the production origin and are not static assets. if (checkedAssets.has(url.href)) continue; const asset = await fetch(url); assert.equal(asset.status, 200, `Asset ${url.href}`); + assertSecurityHeaders(asset.headers); checkedAssets.add(url.href); } } @@ -47,6 +50,14 @@ try { assert.equal((await fetch(new URL(response.headers.get("location"), origin), { redirect: "manual" })).status, 200, `One hop: ${from}`); } const sitemap = await (await fetch(`${origin}/sitemap.xml`)).text(); + for (const [route, type] of [["/build-info.json", "application/json"], ["/assets/vendor/tesseract/core/tesseract-core.wasm", "application/wasm"], [OCR_WORKER_PATH, "text/javascript"], ["/assets/vendor/pdfjs/pdf.worker.min.mjs", "text/javascript"], ["/assets/vendor/tesseract/lang/eng.traineddata.gz", "application/gzip"]]) { + const response = await fetch(origin + route); + assert.equal(response.status, 200); + assert.ok(response.headers.get("content-type").startsWith(type), `${route} retains correct MIME`); + assertSecurityHeaders(response.headers, { ocrWorker: route === OCR_WORKER_PATH }); + if (route === "/build-info.json") assert.ok((await response.json()).commit); + else await response.body.cancel(); + } const locations = [...sitemap.matchAll(/<loc>(.*?)<\/loc>/g)].map((match) => match[1]).sort(); assert.deepEqual(locations, canonicalPages.map(({ route }) => `${productionOrigin}${route}`).sort()); const robots = await (await fetch(`${origin}/robots.txt`)).text(); diff --git a/tests/security-hardening.test.mjs b/tests/security-hardening.test.mjs index fd43f9f..c441226 100644 --- a/tests/security-hardening.test.mjs +++ b/tests/security-hardening.test.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { assertSecurityHeaders, headersForUrl, parsePagesHeaders, validateHostingHeaders } from "../scripts/http-security-headers.mjs"; import { MAX_DIMENSION, MAX_FILE_SIZE, MAX_PIXELS, MAX_QUEUE_BYTES, MAX_QUEUE_FILES, detectImageFormat, selectImageQueueFiles, validateImageDimensions, validateImageSignature, @@ -91,4 +92,36 @@ for (const source of firstParty) assert.doesNotMatch(fs.readFileSync(source, "ut const { auditActionPins } = await import("../scripts/validate-action-pins.mjs"); auditActionPins(); +const policy = read("config/cloudflare/_headers"); +validateHostingHeaders(path.join(root, "config/cloudflare")); +const policyDirectory = fs.mkdtempSync(path.join(root, ".ts-build/header-policy-")); +try { + for (const mutation of [ + policy.replace(/ Content-Security-Policy:.*\r?\n/, ""), + policy.replace("connect-src 'none'", "connect-src 'self'"), + policy.replace("frame-ancestors 'none'", "frame-ancestors 'self'"), + policy.replace("script-src 'self'", "script-src 'self' 'unsafe-inline'"), + policy.replace("script-src 'self'", "script-src 'self' 'unsafe-eval'"), + policy.replace("script-src 'self'", "script-src 'self' https://cdn.example"), + policy.replace("Referrer-Policy: no-referrer", "Referrer-Policy: unsafe-url"), + policy.replace("camera=()", "camera=*"), + policy.replace("X-Content-Type-Options: nosniff", "X-Content-Type-Options: other"), + policy.replace("/assets/vendor/tesseract/worker/worker.min.js", "/*"), + ]) { + fs.writeFileSync(path.join(policyDirectory, "_headers"), mutation); + assert.throws(() => validateHostingHeaders(policyDirectory), "Missing/weakened policy must fail artifact validation"); + } + fs.writeFileSync(path.join(policyDirectory, "_headers"), policy); + fs.writeFileSync(path.join(policyDirectory, "CNAME"), "securetools.app"); + assert.throws(() => validateHostingHeaders(policyDirectory, { isolated: true }), /CNAME/); + const headers = headersForUrl(parsePagesHeaders(policy), "https://tools.securetools.app/"); + assertSecurityHeaders(headers); + headers.set("permissions-policy", headers.get("permissions-policy") + ", browsing-topics=()"); + assertSecurityHeaders(headers); // Extra denials preserve required capability restrictions. + headers.set("permissions-policy", "camera=(*), microphone=(), geolocation=()"); + assert.throws(() => assertSecurityHeaders(headers), /capability denials/); + headers.set("permissions-policy", "camera=(), microphone=(), geolocation=()"); + headers.delete("content-security-policy"); + assert.throws(() => assertSecurityHeaders(headers), /HTTP CSP/); +} finally { fs.rmSync(policyDirectory, { recursive: true, force: true }); } console.log("Security hardening checks passed."); diff --git a/tests/serve-ocr-smoke.mjs b/tests/serve-ocr-smoke.mjs index a292699..68d2571 100644 --- a/tests/serve-ocr-smoke.mjs +++ b/tests/serve-ocr-smoke.mjs @@ -4,9 +4,11 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { legacyRedirects, redirectStatus } from "../scripts/site-routes.mjs"; +import { headersForUrl, parsePagesHeaders } from "../scripts/http-security-headers.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const siteRoot = path.join(root, "dist"); +const headerRules = parsePagesHeaders(fs.readFileSync(path.join(siteRoot, "_headers"), "utf8")); const port = Number.parseInt(process.argv[2] || "4173", 10); const audit = process.argv.includes("--audit"); const gates = process.argv.includes("--gates"); @@ -21,6 +23,11 @@ const contentTypes = new Map([ [".pdf", "application/pdf"], [".ico", "image/x-icon"], [".wasm", "application/wasm"], + [".svg", "image/svg+xml"], + [".woff", "font/woff"], + [".woff2", "font/woff2"], + [".jpg", "image/jpeg"], + [".webp", "image/webp"], ]); const server = http.createServer((request, response) => { @@ -45,6 +52,7 @@ const server = http.createServer((request, response) => { return; } response.writeHead(200, { + ...Object.fromEntries(headersForUrl(headerRules, `http://127.0.0.1${pathname}`)), "Cache-Control": "no-store", "Content-Type": contentTypes.get(path.extname(target)) || "application/octet-stream", }); From 8e052d68b44f1ca4a5770d04c85c118100348f5c Mon Sep 17 00:00:00 2001 From: maruson08 <maruson08@naver.com> Date: Thu, 15 Oct 2026 18:39:58 +0900 Subject: [PATCH 06/12] =?UTF-8?q?=F0=9F=93=84[Docs]=20Add=20vulnerability?= =?UTF-8?q?=20disclosure=20policy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SECURITY.md | 41 +++++++++++++++++++++++++++++++++++++++++ docs/v2.3-bootstrap.md | 40 +++++++++++++++++++++++++++++++++++++--- 2 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c0888be --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,41 @@ +# Security Policy + +## Supported Versions + +| Version | Security support | +| --- | --- | +| Latest stable GitHub release (currently `v2.2.0`) | Security fixes target the latest stable release; upgrade when a fix is released. | +| Current integration branch (`v2.3`) | Pre-release development and triage only; not a supported production release. | +| Older releases | No maintained security backports; upgrade to the latest stable release. | + +The published [GitHub releases](https://github.com/SecureToolsProject/Secure_Tools/releases) identify the stable version. Update this policy when promoting a new release. + +## Reporting a Vulnerability + +Use [GitHub Private Vulnerability Reporting](https://github.com/SecureToolsProject/Secure_Tools/security/advisories/new), or open this repository's **Security → Advisories → Report a vulnerability** flow. A GitHub account is required. Reports go privately to repository maintainers. + +**Do not open public issues or pull requests for undisclosed vulnerabilities.** Do not include sensitive user files, real personal/confidential documents, credentials, or private keys, even in a private report. Treat input bytes as potentially malicious; use a minimal, synthetic, non-sensitive reproduction and explain any risk before attaching a sample. + +Include: + +- The affected release, commit, tool and deployment URL, when known. +- Expected and observed behavior, impact, and minimal reproduction steps. +- Relevant browser/version details and redacted diagnostics. + +If the private reporting form is unavailable, do not guess an email address or publish exploit details. Repository owners must restore and verify the private route; wait for it before sharing the report. + +## Scope + +Security-relevant reports include privacy-invariant bypasses; unexpected network requests or file uploads; XSS/CSP bypasses; malicious-file handling, parser or resource-exhaustion bugs; dependency/supply-chain issues; and deployment/provenance failures. + +Local processing does not eliminate browser, dependency or hosting trust boundaries. Successful parsing does not prove that a file is safe or fully sanitized. See the [privacy model](docs/privacy-model.md) for bounded guarantees. + +## Non-goals and Limits + +The project does not claim formal security certification. Reporting a vulnerability does not imply a bounty or other payment. General feature requests and unsupported-format bugs without a security impact belong in normal issues; uncertain security reports should use the private route first. + +## Disclosure Process + +Maintainers aim to acknowledge receipt, reproduce and triage the issue, coordinate a fix and verification with the reporter, and publish an advisory or release notes when appropriate. Please coordinate public disclosure so users can receive a fix or mitigation first. + +No fixed response or remediation timeline is promised. Keep discussion and reproduction details private until disclosure is coordinated. diff --git a/docs/v2.3-bootstrap.md b/docs/v2.3-bootstrap.md index 5397ba8..f725d21 100644 --- a/docs/v2.3-bootstrap.md +++ b/docs/v2.3-bootstrap.md @@ -50,7 +50,7 @@ historical code. | F-06 Artifact/source provenance | PARTIALLY RESOLVED | Production baseline has deployment SHA linkage and sampled asset equivalence. The Issue #112 implementation generates `dist/build-info.json` (`scripts/build-site.mjs`, `scripts/build-provenance.mjs`) and strictly checks SHA/version/schema/sensitive fields (`scripts/validate-build.mjs`, `scripts/verify-build-provenance.mjs`). The public path will be `/build-info.json`; current production has not received this code. | Preserve CI/generated/deployed-record checks; keep Issue #112 open until promotion and actual live production equality verification. This record is not a full digest or reproducibility proof. | P1 / [#112](https://github.com/SecureToolsProject/Secure_Tools/issues/112) | | F-02 Mutable Actions | PARTIALLY RESOLVED | The #113 implementation pins all external Action uses (now nine, including #117 diagnostics) to verified full SHAs with release comments; `scripts/validate-action-pins.mjs` and the security gate reject mutable/abbreviated/dynamic refs. `.github/dependabot.yml` configures weekly reviewed Actions updates targeting v2.3. | Pinning is complete on this branch. Maintenance automation is not yet active: GitHub requires this configuration on the default branch (main), which is unchanged. Activate only through a separately authorized production promotion, then verify scheduled updates before marking fully resolved. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | | F-01 PDF admission | RESOLVED | Shared `tools/shared/pdf.js` signature admission checks five bytes before full file reads; all original-source pdf-lib/PDF.js entry points use it, including cached-byte helpers. MIME/extension cannot authorize or veto valid bytes. | Issue #114 implementation; strict byte-zero header policy and parser failure regression coverage described below. Structural validation remains with the parsers. | P2 / [#114](https://github.com/SecureToolsProject/Secure_Tools/issues/114) | -| F-03 Disclosure | OPEN | Root `SECURITY.md` absent; GitHub private vulnerability reporting API reports `enabled: false`. | Document supported versions, verified private reporting route, coordinated disclosure, scope/non-goals, and warning against attaching sensitive files; enable route where permitted. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | +| F-03 Disclosure | RESOLVED | Root `SECURITY.md` defines latest-stable support, private reporting, synthetic samples, scope, limits and coordinated disclosure. GitHub Private Vulnerability Reporting was enabled and independently confirmed on 2026-10-15. | Policy exists on the #115 review branch; default-branch Security-policy discovery waits for an authorized promotion. The private reporting route is already active repository-wide. No production deployment occurred. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | | F-04 Independent scanning | OPEN | CI runs custom `security-hardening.test.mjs` and `release-gate.test.mjs`, but no CodeQL, Dependency Review, OSV/npm-audit job, or runtime-dependency monitoring. #113 prepares Actions version updates only. GitHub reports security updates/secret scanning disabled and no code-scanning analysis. | Small complementary JS/TS SAST and vendor-aware advisory monitoring; use lockfile audit for its actual coverage, without duplicating scanners. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | | F-05 HTTP headers | PARTIALLY RESOLVED | Issue #117 implements `config/cloudflare/_headers`, copied unchanged into the artifact and validated before deployment. HTTP CSP adds frame-ancestors none; no-referrer, sensitive capability denials, and nosniff apply globally. A narrowly scoped Tesseract worker exception preserves existing local OCR loading. | Branch implementation complete; canonical/immutable production header and clean browser signoff remain pending a separately authorized promotion/deployment. Meta CSP is not an embedding defense. | P1 / [#117](https://github.com/SecureToolsProject/Secure_Tools/issues/117) | @@ -199,6 +199,38 @@ release verifies actual canonical/immutable responses and clean browser behavior Cloudflare static delivery/project configuration is still a trust boundary; Functions, hosting transformations or future path changes require renewed checks. +### Private disclosure — Issue #115 + +Root [SECURITY.md](../SECURITY.md) defines bounded security support: the latest +stable GitHub release (currently v2.2.0), pre-release triage only on v2.3, and no +maintained backports to older releases. It documents private reporting, affected +version/commit and reproduction details, synthetic non-sensitive samples, +security scope, coordinated disclosure, no formal certification/bounty claim, +and no fixed response-time promise. Terminology was reviewed against the sibling +Secure_Metadata security policy: input bytes are untrusted and privacy claims +remain bounded, without copying that library's no-filesystem/network guarantees +into this browser application. No separate contribution/security policy or issue +templates existed under the repository root/.github before this task. + +GitHub's reporting setting was false before this task. With confirmed repository +admin permission, `PUT /repos/SecureToolsProject/Secure_Tools/private-vulnerability-reporting` +returned HTTP 204; an independent GET returned `{"enabled":true}` on 2026-10-15. +The public [Advisories page](https://github.com/SecureToolsProject/Secure_Tools/security/advisories) +returned HTTP 200 with the Report a vulnerability button and the +[private report link](https://github.com/SecureToolsProject/Secure_Tools/security/advisories/new). +Anonymous access to the report link redirects to GitHub sign-in, as expected; +no report/advisory was submitted. This is the single verified private route; no +email address or other private contact was invented. If it becomes unavailable, +reporters must wait for owners to restore/verify it rather than post details. +See [GitHub's reporting instructions](https://docs.github.com/en/code-security/how-tos/report-and-fix-vulnerabilities/report-privately). + +F-03 is resolved by the branch policy plus the confirmed active reporting route. +The Markdown is not yet on main: GitHub's default-branch Security-policy discovery +will require a separately authorized promotion. Reporting activation is an actual +repository setting change, independent of the unmerged documentation PR. It does +not deploy the app or change runtime handling. F-02, F-05 and F-06 keep their +existing production/activation limitations. + ### Monitoring limitations `npm audit` completed successfully with zero reported vulnerabilities for the @@ -273,8 +305,10 @@ Bootstrap and provenance are integrated into v2.3. Issue #113 implements the remaining Action pins, now integrated through PR #121; maintenance activation is pending production promotion. Issue #114 implements shared PDF byte-signature admission, now integrated through PR #122. Issue #117 implements hosting headers -on its review branch, with production verification pending. Recommended next -independent hardening task: #115, private vulnerability disclosure. +now integrated through PR #123, with production verification pending. Recommended next +independent hardening task: #116, complementary security/advisory monitoring. +Issue #115 adds the disclosure policy on its review branch and activates the +verified private reporting route. ## Verification and preserved invariants From d6115f964c6ca536d7bb186be79d4f27b3908b62 Mon Sep 17 00:00:00 2001 From: maruson08 <maruson08@naver.com> Date: Thu, 15 Oct 2026 19:08:56 +0900 Subject: [PATCH 07/12] =?UTF-8?q?=F0=9F=94=A7[Config]=20Add=20SAST=20and?= =?UTF-8?q?=20dependency=20monitoring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/codeql/config.yml | 7 ++ .github/dependabot.yml | 10 ++ .github/workflows/security-monitoring.yml | 60 +++++++++++ config/security/vendor-dependencies.json | 20 ++++ config/security/vendor-release-pins.json | 74 +++++++++++++ docs/v2.3-bootstrap.md | 126 +++++++++++++++++++--- scripts/check-security-advisories.mjs | 126 ++++++++++++++++++++++ scripts/security-inventory.mjs | 82 ++++++++++++++ tests/release-gate.test.mjs | 50 +-------- tests/run-all.mjs | 1 + tests/security-hardening.test.mjs | 2 + tests/security-monitoring.test.mjs | 103 ++++++++++++++++++ 12 files changed, 597 insertions(+), 64 deletions(-) create mode 100644 .github/codeql/config.yml create mode 100644 .github/workflows/security-monitoring.yml create mode 100644 config/security/vendor-dependencies.json create mode 100644 config/security/vendor-release-pins.json create mode 100644 scripts/check-security-advisories.mjs create mode 100644 scripts/security-inventory.mjs create mode 100644 tests/security-monitoring.test.mjs diff --git a/.github/codeql/config.yml b/.github/codeql/config.yml new file mode 100644 index 0000000..c61f493 --- /dev/null +++ b/.github/codeql/config.yml @@ -0,0 +1,7 @@ +name: First-party JavaScript and TypeScript +paths-ignore: + - assets/vendor/** + - node_modules/** + - dist/** + - .ts-build/** + - tests/fixtures/** diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 4d23f8f..7c60bf9 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -10,3 +10,13 @@ updates: commit-message: # Trailing space prevents Dependabot from inserting a colon after [Config]. prefix: "🔧[Config] " + - package-ecosystem: "npm" + directory: "/" + target-branch: "v2.3" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 + pull-request-branch-name: + prefix: "chore/dependabot" + commit-message: + prefix: "🔧[Config] " diff --git a/.github/workflows/security-monitoring.yml b/.github/workflows/security-monitoring.yml new file mode 100644 index 0000000..5850615 --- /dev/null +++ b/.github/workflows/security-monitoring.yml @@ -0,0 +1,60 @@ +name: Security monitoring + +on: + pull_request: + branches: [v2.3, main] + push: + branches: [v2.3, main] + schedule: + - cron: '29 3 * * 3' + workflow_dispatch: + +permissions: + contents: read + +jobs: + codeql: + name: CodeQL JavaScript and TypeScript + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + security-events: write + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Initialize JS/TS analysis + uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + with: + languages: javascript-typescript + build-mode: none + config-file: .github/codeql/config.yml + - name: Analyze and upload results + uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + with: + category: /language:javascript-typescript + + advisories: + name: Lockfile and vendor advisories + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24 + - name: Install locked inputs without scripts + run: npm ci --ignore-scripts + - name: Check inventory and scanner failure regressions + run: node tests/security-monitoring.test.mjs + - name: Query lockfile advisories (all severities, including dev inputs) + run: | + mkdir -p .ts-build + npm audit --json --audit-level=low > .ts-build/npm-audit.json + - name: Query exact vendored versions and project release advisories + env: + GITHUB_TOKEN: ${{ github.token }} + run: node scripts/check-security-advisories.mjs .ts-build/npm-audit.json diff --git a/config/security/vendor-dependencies.json b/config/security/vendor-dependencies.json new file mode 100644 index 0000000..2a5b136 --- /dev/null +++ b/config/security/vendor-dependencies.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 1, + "dependencies": [ + { "name": "pdfjs-dist", "source": "npm" }, + { "name": "jspdf", "source": "npm" }, + { "name": "jszip", "source": "npm" }, + { "name": "pdf-lib", "source": "npm" }, + { "name": "tesseract.js", "source": "npm" }, + { "name": "tesseract.js-core", "source": "npm" }, + { "name": "@tesseract.js-data/eng", "source": "npm" }, + { "name": "@tesseract.js-data/kor", "source": "npm" }, + { "name": "@pdf-lib/fontkit", "source": "npm" }, + { "name": "@fontsource/noto-sans-kr", "source": "npm" }, + { + "name": "secure-metadata", + "source": "github", + "repository": "SecureToolsProject/Secure_Metadata" + } + ] +} diff --git a/config/security/vendor-release-pins.json b/config/security/vendor-release-pins.json new file mode 100644 index 0000000..f70a1c8 --- /dev/null +++ b/config/security/vendor-release-pins.json @@ -0,0 +1,74 @@ +{ + "jspdf": { + "name": "jspdf", + "version": "4.2.1", + "license": "MIT", + "files": [ + "LICENSE.txt", + "README.md", + "jspdf.umd.min.js", + "package.json" + ], + "runtimes": { + "jspdf.umd.min.js": "e6551fcdc32f09d6853b2c5126d18d01d9447e0da618a41a11ebeee0f6c20d54" + } + }, + "jszip": { + "name": "jszip", + "version": "3.10.1", + "license": "(MIT OR GPL-3.0-or-later)", + "files": [ + "LICENSE.markdown", + "README.md", + "jszip.min.js", + "package.json" + ], + "runtimes": { + "jszip.min.js": "acc7e41455a80765b5fd9c7ee1b8078a6d160bbbca455aeae854de65c947d59e" + } + }, + "pdf-lib": { + "name": "pdf-lib", + "version": "1.17.1", + "license": "MIT", + "files": [ + "LICENSE.md", + "README.md", + "package.json", + "pdf-lib.min.js" + ], + "runtimes": { + "pdf-lib.min.js": "0f9a5cad07941f0826586c94e089d89b918c46e5c17cf2d5a3c6f666e3bc694f" + } + }, + "pdfjs": { + "name": "pdfjs-dist", + "version": "6.2.108", + "license": "Apache-2.0", + "files": [ + "LICENSE", + "README.md", + "package.json", + "pdf.min.mjs", + "pdf.worker.min.mjs" + ], + "runtimes": { + "pdf.min.mjs": "e0be3863c23c8af2305b16548febd58e7f8874a460253317d7771cddbc1c0f6d", + "pdf.worker.min.mjs": "0613f41490dd6aaceed7a93fbbd38c85e6d6aa60474b6588c6e7709cfbe18cb3" + } + }, + "secure-metadata": { + "name": "secure-metadata", + "version": "0.1.1", + "license": "MIT", + "files": [ + "LICENSE", + "README.md", + "package.json", + "secure-metadata-0.1.1.browser.js" + ], + "runtimes": { + "secure-metadata-0.1.1.browser.js": "4bfcc9e0e484db12192e46f076c19cf69cd36c496c7cfbb5a71c1057cbcccba1" + } + } +} diff --git a/docs/v2.3-bootstrap.md b/docs/v2.3-bootstrap.md index f725d21..a251842 100644 --- a/docs/v2.3-bootstrap.md +++ b/docs/v2.3-bootstrap.md @@ -48,10 +48,10 @@ historical code. | Finding | Current status | Evidence | Necessary next action | Priority / issue | | --- | --- | --- | --- | --- | | F-06 Artifact/source provenance | PARTIALLY RESOLVED | Production baseline has deployment SHA linkage and sampled asset equivalence. The Issue #112 implementation generates `dist/build-info.json` (`scripts/build-site.mjs`, `scripts/build-provenance.mjs`) and strictly checks SHA/version/schema/sensitive fields (`scripts/validate-build.mjs`, `scripts/verify-build-provenance.mjs`). The public path will be `/build-info.json`; current production has not received this code. | Preserve CI/generated/deployed-record checks; keep Issue #112 open until promotion and actual live production equality verification. This record is not a full digest or reproducibility proof. | P1 / [#112](https://github.com/SecureToolsProject/Secure_Tools/issues/112) | -| F-02 Mutable Actions | PARTIALLY RESOLVED | The #113 implementation pins all external Action uses (now nine, including #117 diagnostics) to verified full SHAs with release comments; `scripts/validate-action-pins.mjs` and the security gate reject mutable/abbreviated/dynamic refs. `.github/dependabot.yml` configures weekly reviewed Actions updates targeting v2.3. | Pinning is complete on this branch. Maintenance automation is not yet active: GitHub requires this configuration on the default branch (main), which is unchanged. Activate only through a separately authorized production promotion, then verify scheduled updates before marking fully resolved. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | +| F-02 Mutable Actions | PARTIALLY RESOLVED | The #113 implementation pins all external Action uses (now fourteen, including #116 monitoring) to verified full SHAs with release comments; `scripts/validate-action-pins.mjs` and the security gate reject mutable/abbreviated/dynamic refs. `.github/dependabot.yml` configures weekly reviewed Actions updates targeting v2.3. | Pinning is complete on this branch. Maintenance automation is not yet active: GitHub requires this configuration on the default branch (main), which is unchanged. Activate only through a separately authorized production promotion, then verify scheduled updates before marking fully resolved. | P1 / [#113](https://github.com/SecureToolsProject/Secure_Tools/issues/113) | | F-01 PDF admission | RESOLVED | Shared `tools/shared/pdf.js` signature admission checks five bytes before full file reads; all original-source pdf-lib/PDF.js entry points use it, including cached-byte helpers. MIME/extension cannot authorize or veto valid bytes. | Issue #114 implementation; strict byte-zero header policy and parser failure regression coverage described below. Structural validation remains with the parsers. | P2 / [#114](https://github.com/SecureToolsProject/Secure_Tools/issues/114) | -| F-03 Disclosure | RESOLVED | Root `SECURITY.md` defines latest-stable support, private reporting, synthetic samples, scope, limits and coordinated disclosure. GitHub Private Vulnerability Reporting was enabled and independently confirmed on 2026-10-15. | Policy exists on the #115 review branch; default-branch Security-policy discovery waits for an authorized promotion. The private reporting route is already active repository-wide. No production deployment occurred. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | -| F-04 Independent scanning | OPEN | CI runs custom `security-hardening.test.mjs` and `release-gate.test.mjs`, but no CodeQL, Dependency Review, OSV/npm-audit job, or runtime-dependency monitoring. #113 prepares Actions version updates only. GitHub reports security updates/secret scanning disabled and no code-scanning analysis. | Small complementary JS/TS SAST and vendor-aware advisory monitoring; use lockfile audit for its actual coverage, without duplicating scanners. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | +| F-03 Disclosure | RESOLVED | Root `SECURITY.md` defines latest-stable support, private reporting, synthetic samples, scope, limits and coordinated disclosure. GitHub Private Vulnerability Reporting was enabled and independently confirmed on 2026-10-15. | Policy is integrated into v2.3 through PR #124; default-branch Security-policy discovery waits for an authorized promotion. The private reporting route is already active repository-wide. No production deployment occurred. | P2 / [#115](https://github.com/SecureToolsProject/Secure_Tools/issues/115) | +| F-04 Independent scanning | PARTIALLY RESOLVED | Issue #116 adds JS/TS-only CodeQL, full-lockfile npm audit, canonical vendor inventory plus exact-input OSV/repository advisory checks, and reviewed npm updates. Offline scanner failure/drift tests enforce coverage and fail-closed behavior. | Actual CodeQL/CI execution evidence is recorded in the review PR. Default-branch Dependabot/weekly triggers remain pending promotion. Direct vendor coverage does not resolve all nested bundle/native-code provenance; Dependency Review API returned 403 for the current token. | P2 / [#116](https://github.com/SecureToolsProject/Secure_Tools/issues/116) | | F-05 HTTP headers | PARTIALLY RESOLVED | Issue #117 implements `config/cloudflare/_headers`, copied unchanged into the artifact and validated before deployment. HTTP CSP adds frame-ancestors none; no-referrer, sensitive capability denials, and nosniff apply globally. A narrowly scoped Tesseract worker exception preserves existing local OCR loading. | Branch implementation complete; canonical/immutable production header and clean browser signoff remain pending a separately authorized promotion/deployment. Meta CSP is not an embedding defense. | P1 / [#117](https://github.com/SecureToolsProject/Secure_Tools/issues/117) | ### Provenance scope @@ -231,14 +231,109 @@ repository setting change, independent of the unmerged documentation PR. It does not deploy the app or change runtime handling. F-02, F-05 and F-06 keep their existing production/activation limitations. -### Monitoring limitations - -`npm audit` completed successfully with zero reported vulnerabilities for the -lockfile. It does not cover every directly vendored browser library. Exact-version -OSV queries returned no matching advisories for the packages below. GitHub -Dependabot-alert API returned 403 with alerts explicitly disabled; this is not an -empty clean alert list. No access-scope escalation was attempted. Code-scanning -API reported no analysis. These are monitoring gaps, not verified exploits. +### Complementary scanning — Issue #116 + +`.github/workflows/security-monitoring.yml` runs JS/TS CodeQL and a separate +read-only advisory job for PRs to v2.3/main and pushes to those branches. CodeQL +uses verified v4.38.3 commit `24c54180a607b1449ed407dd24f251e4e9147c8d`, +build mode none, and the default JS/TS security queries. Only its analysis job +receives security-events write; all jobs otherwise have contents read. Generated +output, node_modules, vendored bundles and binary fixtures are excluded by +`.github/codeql/config.yml`. It analyzes first-party app/scripts/tests, not +vendored/minified code, WASM or fonts. Successful uploaded analysis must be +confirmed through GitHub before calling SAST operational; the review PR records +that actual execution evidence. A successful analysis job is not a proof of +absence of vulnerabilities or a replacement for alert triage. + +The advisory job installs the unchanged lockfile with scripts disabled, runs +`npm audit --json --audit-level=low` including dev/build inputs, then runs +`node scripts/check-security-advisories.mjs .ts-build/npm-audit.json`. Any audit +nonzero exit stops the job; independent JSON validation rejects missing/malformed +reports, service errors and any advisory count. No fixes or dependency upgrades +are performed. Audit files older than one hour or implausibly future-dated are +rejected. There is no committed clean-result cache; old vendor evidence is +removed before scanning. A fresh successful report is written only under +`.ts-build/security-advisories.json` with a verification timestamp. + +`config/security/vendor-dependencies.json` enumerates all eleven runtime +identities. Versions are deliberately **not copied** there: the inventory reads +vendor package.json and prepared OCR/font manifests. The former release test's +unchanged approved pin/license/hash object now lives in +`config/security/vendor-release-pins.json`, shared with the existing release +gate. Hash verification is still performed once by that gate, not reimplemented +by the scanner. Name/version drift, missing/duplicate/unknown inventory records, +untracked runtime inputs, package-lock mismatches, and malformed canonical pins +fail the offline gate. The following inputs are monitored: + +| Identity | Resolved version | Advisory/identity coverage | +| --- | --- | --- | +| pdfjs-dist | 6.2.108 | Vendored npm coordinate + OSV | +| jspdf | 4.2.1 | Vendored npm coordinate + OSV | +| jszip | 3.10.1 | Vendored npm coordinate + OSV | +| pdf-lib | 1.17.1 | Vendored npm coordinate + OSV | +| tesseract.js | 7.0.0 | Lockfile + prepared runtime + OSV | +| tesseract.js-core | 7.0.0 | Lockfile + prepared runtime + OSV | +| @tesseract.js-data/eng | 1.0.0 | Lockfile + prepared language artifact + OSV | +| @tesseract.js-data/kor | 1.0.0 | Lockfile + prepared language artifact + OSV | +| @pdf-lib/fontkit | 1.1.1 | Lockfile + prepared bundle + OSV | +| @fontsource/noto-sans-kr | 5.3.0 | Lockfile + prepared font + OSV | +| secure-metadata | 0.1.1 | SecureToolsProject/Secure_Metadata release/tag/commit + public advisories; no npm query | + +For each npm vendor, a registry lookup first proves the exact name/version exists +(otherwise PACKAGE_NOT_REPRESENTED fails the scan). The +[OSV package/version API](https://google.github.io/osv.dev/post-v1-query/) +is queried with that complete package identity and canonical version; response +records must match the package ecosystem/name. All active matches block for +review, without a custom semver/range database. OSV documents version matching as +fuzzy: we supply complete npm versions and conservatively block any returned +active record rather than claiming independent proof of affectedness. Pagination, +HTTP/JSON errors, missing fields, mismatched identities, repeated/excessive pages, +network timeout and stale HTTP Age over one day fail closed. Empty documented +OSV output means no known advisory returned, not that a package is safe or that +all upstream databases are complete/current. Local live checks on 2026-10-15 +returned no known advisories for these exact inputs at verification time. + +Secure_Metadata is **not** submitted as an npm package. Its npm version URL still +returned 404 on 2026-10-15. Monitoring resolves the GitHub release tag (including +annotated tags), requires pinned commit `cdcd138e48d30618b6d76f7c6538cd43ad660b53`, +checks the published stable release/runtime asset identity, and checks every page +of public repository advisories. Any active public advisory blocks for manual +pinned-release applicability review; private/unpublished reports and advisories +not associated with the repository are not covered. The release had no active +public repository advisories at verification time. Existing artifact hashes and +release identity assertions remain unchanged. + +**Remaining limits:** npm audit covers the installed lockfile, not all browser +bundles. JSZip/pdf-lib/jsPDF metadata declares nested dependencies by ranges; +those ranges do not establish the exact nested code bundled into the checked-in +artifact. OSV parent-package checks and lockfile transitive coverage must not be +misrepresented as a full vendored bundle/native-library SBOM or a compiler/font +safety audit. Binary Tesseract/Leptonica components and unpublished ecosystem +advisories can remain unrepresented. These coverage limits keep F-04 PARTIALLY +RESOLVED; no dependency upgrade or replacement is included. + +Dependency Review was evaluated: the repository dependency-graph comparison API +returned HTTP 403 for the current token. The available evidence does not establish +whether the reason is settings, plan or token scope; no scope escalation or +fabricated successful dependency review was performed. It is not added as a +second scanner with duplicate full-lockfile advisory coverage. CodeQL default +setup was initially not configured, and analysis listing initially returned +404/no analysis; actual advanced-workflow results are separate evidence. + +Dependabot preserves reviewed weekly Actions updates and adds reviewed weekly +npm PRs targeting v2.3, using the approved chore branch/config commit prefix, +without auto-merge or grouping. GitHub requires default-branch configuration +before these updates and the new weekly workflow trigger can activate: main is +unchanged, so these portions remain pending promotion. PR/push scans are verified +separately. Existing disabled Dependabot security-update/alert settings and secret +scanning were not silently changed or counted as active checks. + +Offline tests cover inventory/approved-pin/lock drift, positive and negative npm +reports, actual OSV empty schema, advisories, malformed/stale/network failures, +pagination and GitHub release/advisory identity. CI additionally queries live +services. Scanning network access is confined to repository/CI scripts; no +application fetch, backend, CDN fallback, telemetry or runtime asset change is +introduced. No-known-advisory observations are time-bound and do not prove safety. ## Dependency delta @@ -250,7 +345,7 @@ covers the OCR manifest; searchable-PDF asset preparation/tests cover fontkit/fo Each dependency/CVE follow-up remains **PARTIALLY RESOLVED**: pinned versions, hash gates, and the current advisory check are verified, but historical CVE -identity and comprehensive continuous vendor monitoring are absent (issue #116). +identity and complete nested-bundle coverage remain unresolved (issue #116). This classification does not imply an active known vulnerability or mandate an upgrade. Maintenance and patch-lag findings are separately classified below. @@ -306,9 +401,10 @@ remaining Action pins, now integrated through PR #121; maintenance activation is pending production promotion. Issue #114 implements shared PDF byte-signature admission, now integrated through PR #122. Issue #117 implements hosting headers now integrated through PR #123, with production verification pending. Recommended next -independent hardening task: #116, complementary security/advisory monitoring. -Issue #115 adds the disclosure policy on its review branch and activates the -verified private reporting route. +independent hardening task: #118, a bounded pdf-lib/JSZip maintenance assessment +without automatic upgrades. Issue #115 is integrated through PR #124 and its +private reporting route is active. Issue #116 adds monitoring on its review branch; +default-branch activation and nested-bundle coverage remain explicit limits. ## Verification and preserved invariants diff --git a/scripts/check-security-advisories.mjs b/scripts/check-security-advisories.mjs new file mode 100644 index 0000000..bcfd3b2 --- /dev/null +++ b/scripts/check-security-advisories.mjs @@ -0,0 +1,126 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { loadInventory } from "./security-inventory.mjs"; + +export function validateNpmAudit(report) { + assert.equal(report?.auditReportVersion, 2, "Unsupported/missing npm audit schema"); + assert.ok(!Object.hasOwn(report, "error"), "npm audit service failed"); + assert.ok(report.vulnerabilities && typeof report.vulnerabilities === "object" && !Array.isArray(report.vulnerabilities)); + const counts = report.metadata?.vulnerabilities; + for (const key of ["info", "low", "moderate", "high", "critical", "total"]) { + assert.ok(Number.isSafeInteger(counts?.[key]) && counts[key] >= 0, `Invalid audit count: ${key}`); + } + assert.equal(Object.keys(report.vulnerabilities).length, 0, "npm audit returned known advisories; review without auto-fixing"); + assert.ok(Object.values(counts).every(value => value === 0), "npm audit returned known advisories"); +} + +export function readNpmAudit(file, now = Date.now()) { + const age = now - fs.statSync(file).mtimeMs; + assert.ok(age >= -300000 && age <= 3600000, "Stale/future npm audit input; regenerate the report"); + const report = JSON.parse(fs.readFileSync(file, "utf8")); + validateNpmAudit(report); + return report; +} + +export async function fetchJson(url, options = {}, request = fetch) { + const response = await request(url, { ...options, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(30000) }); + if (response.status === 404 && url.startsWith("https://registry.npmjs.org/")) throw new Error(`PACKAGE_NOT_REPRESENTED: ${url}; no clean result inferred`); + assert.equal(response.status, 200, `SCAN_FAILED HTTP ${response.status}: ${url}`); + const age = response.headers.get("age"); + if (age !== null) assert.ok(/^\d+$/.test(age) && Number(age) <= 86400, `SCAN_FAILED stale advisory response: ${url}`); + assert.match(response.headers.get("content-type") || "", /\bapplication\/(?:[\w.+-]*\+)?json\b/i, `SCAN_FAILED non-JSON: ${url}`); + return { value: await response.json(), headers: response.headers }; +} + +export function parseOsv(response, name) { + assert.ok(response && typeof response === "object" && !Array.isArray(response), "Malformed OSV response"); + assert.ok(Object.keys(response).every(key => ["vulns", "next_page_token"].includes(key)), "Unexpected OSV response/error"); + if (response.next_page_token !== undefined) assert.ok(typeof response.next_page_token === "string" && response.next_page_token.length > 0); + const vulnerabilities = Object.hasOwn(response, "vulns") ? response.vulns : []; + assert.ok(Array.isArray(vulnerabilities)); + for (const vulnerability of vulnerabilities) { + assert.ok(typeof vulnerability.id === "string" && vulnerability.id.length > 0); + assert.ok(Number.isFinite(Date.parse(vulnerability.modified)), "Missing OSV modification timestamp"); + assert.ok(Array.isArray(vulnerability.affected) && vulnerability.affected.some(affected => affected.package?.ecosystem === "npm" && affected.package.name === name), "OSV package identity mismatch"); + if (vulnerability.withdrawn !== undefined) assert.ok(Number.isFinite(Date.parse(vulnerability.withdrawn))); + } + return { active: vulnerabilities.filter(vulnerability => !vulnerability.withdrawn).map(vulnerability => vulnerability.id), next: response.next_page_token }; +} + +export async function scanNpmVendor(record, request = fetch) { + // OSV empty output does not prove registry representation. Confirm exact identity. + const registryUrl = `https://registry.npmjs.org/${encodeURIComponent(record.name)}/${encodeURIComponent(record.version)}`; + const { value: metadata } = await fetchJson(registryUrl, {}, request); + assert.equal(metadata.name, record.name, "PACKAGE_NOT_REPRESENTED: npm name mismatch"); + assert.equal(metadata.version, record.version, "PACKAGE_NOT_REPRESENTED: npm version mismatch"); + const visited = new Set(); + const ids = []; + let token; + do { + assert.ok(visited.size < 10 && !visited.has(token), "OSV pagination exceeded/repeated; scan incomplete"); + visited.add(token); + const { value } = await fetchJson("https://api.osv.dev/v1/query", { + method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ package: { ecosystem: "npm", name: record.name }, version: record.version, ...(token ? { page_token: token } : {}) }), + }, request); + const page = parseOsv(value, record.name); + ids.push(...page.active); token = page.next; + } while (token); + assert.equal(ids.length, 0, `${record.name}@${record.version}: known OSV advisories ${ids.join(", ")}; review required`); + return { name: record.name, version: record.version, source: "npm/OSV", result: "no-known-advisories" }; +} + +export async function scanGithubVendor(record, request = fetch, token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN) { + const headers = { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", ...(token ? { Authorization: `Bearer ${token}` } : {}) }; + const api = `https://api.github.com/repos/${record.repository}`; + const get = async suffix => fetchJson(api + suffix, { headers }, request); + let { value: reference } = await get(`/git/ref/tags/${record.tag}`); + let object = reference.object; + for (let depth = 0; object?.type === "tag" && depth < 3; depth++) ({ value: { object } } = await get(`/git/tags/${object.sha}`)); + assert.equal(object?.type, "commit", "Unresolved project release tag"); + assert.equal(object.sha, record.commit, "Project release tag/commit drift"); + const { value: release } = await get(`/releases/tags/${record.tag}`); + assert.equal(release.tag_name, record.tag); + assert.equal(release.draft, false); assert.equal(release.prerelease, false); + assert.ok(Number.isFinite(Date.parse(release.published_at))); + assert.ok(Array.isArray(release.assets) && release.assets.some(asset => asset.name === `secure-metadata-${record.version}.browser.js`), "Project runtime asset missing from release"); + let page = 1; + let more; + do { + assert.ok(page <= 10, "Repository advisories pagination exceeded; scan incomplete"); + const { value: advisories, headers: responseHeaders } = await get(`/security-advisories?per_page=100&page=${page++}`); + assert.ok(Array.isArray(advisories), "Malformed repository advisory response"); + for (const advisory of advisories) { + assert.match(advisory.ghsa_id || "", /^GHSA-[\w-]+$/); + assert.equal(advisory.state, "published"); + assert.ok(Number.isFinite(Date.parse(advisory.published_at))); + if (advisory.withdrawn_at) assert.ok(Number.isFinite(Date.parse(advisory.withdrawn_at))); + // Conservatively require review of any active public repository advisory; + // do not invent an npm identity or hand-roll advisory semver evaluation. + assert.ok(advisory.withdrawn_at, `Project public advisory ${advisory.ghsa_id}: pinned release applicability needs review`); + } + more = /rel="next"/.test(responseHeaders.get("link") || ""); + } while (more); + return { name: record.name, version: record.version, source: record.repository, commit: record.commit, result: "no-active-public-repository-advisories", npm: "not-represented/not-queried" }; +} + +export async function scanVendors(records, request = fetch) { + const results = await Promise.allSettled(records.map(record => record.source === "npm" ? scanNpmVendor(record, request) : scanGithubVendor(record, request))); + const failures = results.flatMap((result, index) => result.status === "rejected" ? [`${records[index].name}: ${result.reason.message}`] : []); + assert.equal(failures.length, 0, `SCAN_FAILED or advisory review required:\n${failures.join("\n")}`); + return results.map(result => result.value); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + fs.rmSync(path.join(".ts-build", "security-advisories.json"), { force: true }); + readNpmAudit(process.argv[2] || ".ts-build/npm-audit.json"); + const results = await scanVendors(loadInventory()); + fs.mkdirSync(".ts-build", { recursive: true }); + fs.writeFileSync(path.join(".ts-build", "security-advisories.json"), JSON.stringify({ checkedAt: new Date().toISOString(), results }, null, 2) + "\n"); + console.log("Lockfile and exact vendor queries completed. No known advisories returned at verification time; not proof of safety."); + console.log(JSON.stringify(results, null, 2)); + } catch (error) { console.error(`SCAN_FAILED: ${error.message}`); process.exitCode = 1; } +} diff --git a/scripts/security-inventory.mjs b/scripts/security-inventory.mjs new file mode 100644 index 0000000..6121e94 --- /dev/null +++ b/scripts/security-inventory.mjs @@ -0,0 +1,82 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +export const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const json = file => JSON.parse(fs.readFileSync(file, "utf8")); +export const exactVersion = value => typeof value === "string" && /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(value); + +export function validateInventory(manifest, canonical, dependencies, lock) { + assert.deepEqual(Object.keys(manifest).sort(), ["dependencies", "schemaVersion"]); + assert.equal(manifest.schemaVersion, 1); + assert.ok(Array.isArray(manifest.dependencies)); + const seen = new Set(); + const records = manifest.dependencies.map(entry => { + assert.ok(entry && typeof entry.name === "string"); + assert.ok(!seen.has(entry.name), `Duplicate security inventory entry: ${entry.name}`); + seen.add(entry.name); + const vendor = canonical.get(entry.name); + assert.ok(vendor, `Unknown/stale security inventory entry: ${entry.name}`); + assert.ok(exactVersion(vendor.version), `Non-exact canonical version: ${entry.name}`); + if (vendor.approvedVersion) assert.equal(vendor.version, vendor.approvedVersion, `Release-gate/vendor version drift: ${entry.name}`); + const github = entry.name === "secure-metadata"; + assert.deepEqual(Object.keys(entry).sort(), github ? ["name", "repository", "source"] : ["name", "source"]); + assert.equal(entry.source, github ? "github" : "npm"); + if (github) { + assert.equal(entry.repository, "SecureToolsProject/Secure_Metadata"); + assert.equal(vendor.repository, entry.repository); + assert.equal(vendor.tag, `v${vendor.version}`); + assert.match(vendor.commit, /^[0-9a-f]{40}$/); + } + if (Object.hasOwn(dependencies, entry.name)) { + assert.equal(dependencies[entry.name], vendor.version, `Runtime/manifest version drift: ${entry.name}`); + assert.equal(lock.packages[`node_modules/${entry.name}`]?.version, vendor.version, `Lockfile/vendor drift: ${entry.name}`); + } + return { ...entry, ...vendor }; + }); + assert.deepEqual([...seen].sort(), [...canonical.keys()].sort(), "Every vendored runtime must be monitored"); + for (const name of Object.keys(dependencies)) assert.ok(seen.has(name), `Untracked runtime build input: ${name}`); + return records; +} + +export function loadInventory(root = repositoryRoot) { + const canonical = new Map(); + const releasePins = json(path.join(root, "config/security/vendor-release-pins.json")); + const vendorRoot = path.join(root, "assets/vendor"); + const add = (name, record) => { + assert.ok(!canonical.has(name), `Duplicate canonical vendor ${name}`); + canonical.set(name, record); + }; + for (const directory of fs.readdirSync(vendorRoot, { withFileTypes: true })) { + assert.ok(directory.isDirectory(), "Unexpected vendor root file"); + const base = path.join(vendorRoot, directory.name); + const metadataFile = path.join(base, "package.json"); + const manifestFile = path.join(base, "manifest.json"); + if (fs.existsSync(metadataFile)) { + const metadata = json(metadataFile); + const approved = releasePins[directory.name]; + assert.ok(approved, `Vendor has no approved release pin: ${directory.name}`); + assert.equal(metadata.name, approved.name, "Release-gate/vendor name drift"); + const record = { version: metadata.version, approvedVersion: approved.version, versionSource: path.relative(root, metadataFile).replaceAll("\\", "/") }; + if (metadata.name === "secure-metadata") { + const provenance = fs.readFileSync(path.join(base, "README.md"), "utf8"); + record.repository = provenance.match(/Source repository: `([^`]+)`/)?.[1]; + record.tag = provenance.match(/Release tag: `([^`]+)`/)?.[1]; + record.commit = provenance.match(/Release commit: `([^`]+)`/)?.[1]; + } + add(metadata.name, record); + } else { + assert.ok(fs.existsSync(manifestFile), `Vendor has no canonical package/manifest: ${directory.name}`); + const aggregate = json(manifestFile); + assert.ok(aggregate.packages && Object.keys(aggregate.packages).length > 0); + for (const [name, version] of Object.entries(aggregate.packages)) { + add(name, { version, versionSource: path.relative(root, manifestFile).replaceAll("\\", "/") }); + } + } + } + // Versions are dereferenced, never copied into a second security version source. + // Existing release/prepared-asset gates independently enforce approved pins/hashes. + const manifest = json(path.join(root, "config/security/vendor-dependencies.json")); + return validateInventory(manifest, canonical, json(path.join(root, "package.json")).dependencies, json(path.join(root, "package-lock.json"))); +} diff --git a/tests/release-gate.test.mjs b/tests/release-gate.test.mjs index 5213b2f..bad66c3 100644 --- a/tests/release-gate.test.mjs +++ b/tests/release-gate.test.mjs @@ -14,55 +14,7 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const read = (relative) => fs.readFileSync(path.join(root, relative), "utf8"); const sha256 = (relative) => createHash("sha256").update(fs.readFileSync(path.join(root, relative))).digest("hex"); -const vendors = { - jspdf: { - name: "jspdf", - version: "4.2.1", - license: "MIT", - files: ["LICENSE.txt", "README.md", "jspdf.umd.min.js", "package.json"], - runtimes: { - "jspdf.umd.min.js": "e6551fcdc32f09d6853b2c5126d18d01d9447e0da618a41a11ebeee0f6c20d54", - }, - }, - jszip: { - name: "jszip", - version: "3.10.1", - license: "(MIT OR GPL-3.0-or-later)", - files: ["LICENSE.markdown", "README.md", "jszip.min.js", "package.json"], - runtimes: { - "jszip.min.js": "acc7e41455a80765b5fd9c7ee1b8078a6d160bbbca455aeae854de65c947d59e", - }, - }, - "pdf-lib": { - name: "pdf-lib", - version: "1.17.1", - license: "MIT", - files: ["LICENSE.md", "README.md", "package.json", "pdf-lib.min.js"], - runtimes: { - "pdf-lib.min.js": "0f9a5cad07941f0826586c94e089d89b918c46e5c17cf2d5a3c6f666e3bc694f", - }, - }, - pdfjs: { - name: "pdfjs-dist", - version: "6.2.108", - license: "Apache-2.0", - files: ["LICENSE", "README.md", "package.json", "pdf.min.mjs", "pdf.worker.min.mjs"], - runtimes: { - "pdf.min.mjs": "e0be3863c23c8af2305b16548febd58e7f8874a460253317d7771cddbc1c0f6d", - "pdf.worker.min.mjs": "0613f41490dd6aaceed7a93fbbd38c85e6d6aa60474b6588c6e7709cfbe18cb3", - }, - }, - "secure-metadata": { - name: "secure-metadata", - version: "0.1.1", - license: "MIT", - files: ["LICENSE", "README.md", "package.json", "secure-metadata-0.1.1.browser.js"], - runtimes: { - "secure-metadata-0.1.1.browser.js": "4bfcc9e0e484db12192e46f076c19cf69cd36c496c7cfbb5a71c1057cbcccba1", - }, - }, - -}; +const vendors = JSON.parse(read("config/security/vendor-release-pins.json")); assert.deepEqual(fs.readdirSync(path.join(root, "assets/vendor")).sort(), [...Object.keys(vendors), "searchable-pdf", "tesseract"].sort()); for (const [directory, expected] of Object.entries(vendors)) { diff --git a/tests/run-all.mjs b/tests/run-all.mjs index 3038dc7..e5034be 100644 --- a/tests/run-all.mjs +++ b/tests/run-all.mjs @@ -42,6 +42,7 @@ for (const test of [ "tests/pdf-split.test.mjs", "tests/pdf-signature.test.mjs", "tests/security-hardening.test.mjs", + "tests/security-monitoring.test.mjs", "tests/release-gate.test.mjs", "tests/seo-foundation.test.mjs", "tests/url-namespace.test.mjs", diff --git a/tests/security-hardening.test.mjs b/tests/security-hardening.test.mjs index c441226..4d39921 100644 --- a/tests/security-hardening.test.mjs +++ b/tests/security-hardening.test.mjs @@ -92,6 +92,8 @@ for (const source of firstParty) assert.doesNotMatch(fs.readFileSync(source, "ut const { auditActionPins } = await import("../scripts/validate-action-pins.mjs"); auditActionPins(); +const { loadInventory } = await import("../scripts/security-inventory.mjs"); +loadInventory(); const policy = read("config/cloudflare/_headers"); validateHostingHeaders(path.join(root, "config/cloudflare")); const policyDirectory = fs.mkdtempSync(path.join(root, ".ts-build/header-policy-")); diff --git a/tests/security-monitoring.test.mjs b/tests/security-monitoring.test.mjs new file mode 100644 index 0000000..9d0a0ab --- /dev/null +++ b/tests/security-monitoring.test.mjs @@ -0,0 +1,103 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { loadInventory, validateInventory } from "../scripts/security-inventory.mjs"; +import { fetchJson, parseOsv, readNpmAudit, scanGithubVendor, scanNpmVendor, scanVendors, validateNpmAudit } from "../scripts/check-security-advisories.mjs"; +import { auditActionPins } from "../scripts/validate-action-pins.mjs"; + +const json = file => JSON.parse(fs.readFileSync(file, "utf8")); +const records = loadInventory(); +assert.equal(records.length, 11); +const manifest = json("config/security/vendor-dependencies.json"); +const canonical = new Map(records.map(record => [record.name, record])); +const dependencies = json("package.json").dependencies; +const lock = json("package-lock.json"); +const validate = (input = manifest, pins = canonical, runtime = dependencies, locked = lock) => validateInventory(input, pins, runtime, locked); +assert.throws(() => validate({ ...manifest, dependencies: manifest.dependencies.slice(1) }), /Every vendored/); +assert.throws(() => validate({ ...manifest, dependencies: [...manifest.dependencies, manifest.dependencies[0]] }), /Duplicate/); +assert.throws(() => validate({ ...manifest, dependencies: [...manifest.dependencies, { name: "unknown", source: "npm" }] }), /Unknown/); +assert.throws(() => validate({ ...manifest, dependencies: manifest.dependencies.map(entry => ({ ...entry, version: "1.0.0" })) }), /deep-equal/); +const drift = new Map(canonical); drift.set("jszip", { ...drift.get("jszip"), version: "3.10.2" }); +assert.throws(() => validate(manifest, drift), /Release-gate\/vendor version drift/); +assert.throws(() => validate(manifest, canonical, { ...dependencies, "tesseract.js": "7.0.1" }), /version drift/); +const staleLock = structuredClone(lock); staleLock.packages["node_modules/tesseract.js"].version = "0.0.1"; +assert.throws(() => validate(manifest, canonical, dependencies, staleLock), /Lockfile\/vendor drift/); +assert.throws(() => validate(manifest, canonical, { ...dependencies, "new-runtime": "1.0.0" }), /Untracked/); +const fakeNpm = structuredClone(manifest); fakeNpm.dependencies.find(entry => entry.name === "secure-metadata").source = "npm"; +assert.throws(() => validate(fakeNpm)); + +const audit = { auditReportVersion: 2, vulnerabilities: {}, metadata: { vulnerabilities: { info: 0, low: 0, moderate: 0, high: 0, critical: 0, total: 0 } } }; +validateNpmAudit(audit); +fs.mkdirSync(".ts-build", { recursive: true }); +const temporary = fs.mkdtempSync(".ts-build/advisory-test-"); +try { + const input = path.join(temporary, "audit.json"); + fs.writeFileSync(input, JSON.stringify(audit)); + readNpmAudit(input); + const old = new Date(Date.now() - 7200000); fs.utimesSync(input, old, old); + assert.throws(() => readNpmAudit(input), /Stale/); +} finally { fs.rmSync(temporary, { recursive: true, force: true }); } +for (const bad of [{}, { ...audit, error: { code: "ENETUNREACH" } }, { ...audit, vulnerabilities: [] }, { ...audit, metadata: {} }, { ...audit, vulnerabilities: { example: {} } }, { ...audit, metadata: { vulnerabilities: { ...audit.metadata.vulnerabilities, low: 1, total: 1 } } }]) assert.throws(() => validateNpmAudit(bad)); + +const response = (value, status = 200, headers = {}) => new Response(JSON.stringify(value), { status, headers: { "Content-Type": "application/json", ...headers } }); +const npm = records.find(record => record.name === "jszip"); +const vulnerability = { id: "GHSA-test-test-test", modified: "2026-10-01T00:00:00Z", affected: [{ package: { name: npm.name, ecosystem: "npm" } }] }; +const npmRequest = (osv = {}, registry = { name: npm.name, version: npm.version }) => async (url, options) => { + assert.equal(options.cache, "no-store"); + assert.ok(options.signal instanceof AbortSignal); + if (url.startsWith("https://registry.npmjs.org/")) return response(registry); + assert.equal(url, "https://api.osv.dev/v1/query"); + const query = JSON.parse(options.body); + assert.deepEqual(query.package, { ecosystem: "npm", name: npm.name }); + assert.equal(query.version, npm.version); + return response(osv); +}; +assert.equal((await scanNpmVendor(npm, npmRequest())).result, "no-known-advisories"); +assert.deepEqual(parseOsv({}, npm.name).active, []); // OSV's documented empty result. +for (const bad of [[], null, { error: "unavailable" }, { vulns: null }, { vulns: {} }, { vulns: [{}] }, { next_page_token: "" }, { vulns: [{ ...vulnerability, affected: [{ package: { name: "wrong", ecosystem: "npm" } }] }] }]) assert.throws(() => parseOsv(bad, npm.name)); +await assert.rejects(scanNpmVendor(npm, npmRequest({ vulns: [vulnerability] })), /known OSV advisories/); +await assert.rejects(scanNpmVendor(npm, npmRequest({}, { name: npm.name, version: "99.0.0" })), /PACKAGE_NOT_REPRESENTED/); +await assert.rejects(scanNpmVendor(npm, npmRequest({ next_page_token: "repeat" })), /pagination/); +let pages = 0; +const paginated = npmRequest(); +assert.equal((await scanNpmVendor(npm, async (url, options) => { + if (url.startsWith("https://registry")) return paginated(url, options); + pages++; + return response(pages === 1 ? { next_page_token: "second" } : {}); +})).result, "no-known-advisories"); +assert.equal(pages, 2); +await assert.rejects(fetchJson("https://registry.npmjs.org/missing/1.0.0", {}, async () => response({}, 404)), /PACKAGE_NOT_REPRESENTED/); +await assert.rejects(fetchJson("https://api.osv.dev/v1/query", {}, async () => response({}, 503)), /SCAN_FAILED HTTP 503/); +await assert.rejects(fetchJson("https://api.osv.dev/v1/query", {}, async () => response({}, 200, { Age: "86401" })), /stale/); +await assert.rejects(fetchJson("https://api.osv.dev/v1/query", {}, async () => new Response("oops", { headers: { "Content-Type": "text/html" } })), /non-JSON/); +await assert.rejects(fetchJson("https://api.osv.dev/v1/query", {}, async () => new Response("{", { headers: { "Content-Type": "application/json" } }))); +await assert.rejects(scanVendors([npm], async () => { throw new Error("offline"); }), /SCAN_FAILED.*|offline/s); + +const github = records.find(record => record.source === "github"); +const projectRequest = ({ commit = github.commit, draft = false, advisories = [], secondPage = false } = {}) => async url => { + assert.ok(url.startsWith(`https://api.github.com/repos/${github.repository}/`), "No fake npm or other repository query"); + if (url.includes("/git/ref/")) return response({ object: { type: "commit", sha: commit } }); + if (url.includes("/releases/")) return response({ tag_name: github.tag, draft, prerelease: false, published_at: "2026-08-27T04:12:48Z", assets: [{ name: `secure-metadata-${github.version}.browser.js` }] }); + return response(secondPage && url.endsWith("page=1") ? [] : advisories, 200, secondPage && url.endsWith("page=1") ? { Link: '<https://api.github.com/next>; rel="next"' } : {}); +}; +assert.equal((await scanGithubVendor(github, projectRequest())).result, "no-active-public-repository-advisories"); +await assert.rejects(scanGithubVendor(github, projectRequest({ commit: "a".repeat(40) })), /commit drift/); +await assert.rejects(scanGithubVendor(github, projectRequest({ draft: true }))); +await assert.rejects(scanGithubVendor(github, projectRequest({ advisories: {} })), /Malformed/); +await assert.rejects(scanGithubVendor(github, projectRequest({ secondPage: true, advisories: [{ ghsa_id: "GHSA-test-test-test", state: "published", published_at: "2026-10-01T00:00:00Z", withdrawn_at: null }] })), /applicability needs review/); + +const workflow = fs.readFileSync(".github/workflows/security-monitoring.yml", "utf8"); +assert.match(workflow, /branches: \[v2\.3, main\]/); +assert.match(workflow, /languages: javascript-typescript\n\s+build-mode: none/); +assert.match(workflow, /security-events: write/); +assert.doesNotMatch(workflow, /contents: write|pull-requests: write|continue-on-error|\|\| true|pull_request_target/); +assert.match(workflow, /npm ci --ignore-scripts/); +assert.match(workflow, /npm audit --json --audit-level=low/); +assert.match(workflow, /node scripts\/check-security-advisories\.mjs/); +assert.match(fs.readFileSync(".github/codeql/config.yml", "utf8"), /assets\/vendor\/\*\*/); +const dependabot = fs.readFileSync(".github/dependabot.yml", "utf8"); +assert.match(dependabot, /package-ecosystem: "npm"[\s\S]*?target-branch: "v2\.3"/); +assert.match(dependabot, /package-ecosystem: "github-actions"/); +assert.doesNotMatch(dependabot, /auto-merge/); +auditActionPins(); +console.log("Security monitoring: inventory/pin/lock drift, malformed/offline/stale responses, pagination, advisory failures, project release identity, and workflow enforcement passed."); From 626e2898e3e1c1a069f5dfb12cd3cf22139f472d Mon Sep 17 00:00:00 2001 From: maruson08 <maruson08@naver.com> Date: Thu, 15 Oct 2026 19:50:56 +0900 Subject: [PATCH 08/12] =?UTF-8?q?=F0=9F=93=84[Docs]=20Document=20dependenc?= =?UTF-8?q?y=20maintenance=20assessment?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/v2.3-bootstrap.md | 54 +++-- .../v2.3-dependency-maintenance-assessment.md | 206 ++++++++++++++++++ 2 files changed, 236 insertions(+), 24 deletions(-) create mode 100644 docs/v2.3-dependency-maintenance-assessment.md diff --git a/docs/v2.3-bootstrap.md b/docs/v2.3-bootstrap.md index a251842..aa399ae 100644 --- a/docs/v2.3-bootstrap.md +++ b/docs/v2.3-bootstrap.md @@ -353,8 +353,8 @@ upgrade. Maintenance and patch-lag findings are separately classified below. | --- | --- | --- | --- | | `pdfjs-dist` | 6.2.108 | 6.4.299 | PARTIALLY RESOLVED; no OSV match for pin; newer alone does not justify update | | `jspdf` | 4.2.1 | 4.2.1 | PARTIALLY RESOLVED; no OSV match; retain | -| `jszip` | 3.10.1 | 3.10.2 | PARTIALLY RESOLVED; no OSV match; assess compatibility changes below | -| `pdf-lib` | 1.17.1 | 1.17.1 | PARTIALLY RESOLVED; no OSV match; maintenance assessment needed | +| `jszip` | 3.10.1 | 3.10.2 | PARTIALLY RESOLVED coverage; assessment complete: DEFER compatibility refresh | +| `pdf-lib` | 1.17.1 | 1.17.1 | PARTIALLY RESOLVED coverage; retain for v2.3, investigate replacement in v2.4 | | `tesseract.js` | 7.0.0 | 7.0.0 | PARTIALLY RESOLVED; no OSV match; retain | | `tesseract.js-core` | 7.0.0 | 6.1.2 dist-tag | PARTIALLY RESOLVED; published 7.0.0 exists and matches existing Tesseract inputs; do not infer downgrade from dist-tag | | `secure-metadata` | 0.1.1 | GitHub v0.1.1 | PARTIALLY RESOLVED; upstream release verified; npm registry returns 404, OSV name query is insufficient coverage; monitor GitHub source | @@ -363,24 +363,30 @@ upgrade. Maintenance and patch-lag findings are separately classified below. | `@tesseract.js-data/eng` | 1.0.0 | 1.0.0 | PARTIALLY RESOLVED; no OSV match; retain | | `@tesseract.js-data/kor` | 1.0.0 | 1.0.0 | PARTIALLY RESOLVED; no OSV match; retain | -- **pdf-lib maintenance: OPEN, P2.** Latest npm release 1.17.1 dates to 2021; - upstream is not archived, but last observed push was 2024-07-17. Merge, split, - organize, metadata editing, and searchable-PDF composition depend on its - parser/manipulation behavior (`tools/shared/pdf.js` and searchable-PDF modules). - Local processing still exposes untrusted PDF parsing. Investigate a maintained - compatible fork first; browser-local qpdf/MuPDF WASM alternatives require - feature, size, performance, licensing, privacy, and malformed-input evaluation. - Scope the investigation to v2.3; replacing it requires separate justified work. - [Upstream releases](https://github.com/Hopding/pdf-lib/releases). -- **JSZip patch lag: OPEN, P2.** The official - [3.10.2 changelog](https://raw.githubusercontent.com/Stuk/jszip/v3.10.2/CHANGES.md) - lists cross-realm binary type detection, missing type defaults, and Node >=18 - Blob support; it does not state a security fix. Secure Tools creates browser - ZIPs from local generated inputs. Demonstrate a relevant compatibility benefit - before upgrading; no automatic dependency refresh is warranted. -- These two maintenance assessments share [#118](https://github.com/SecureToolsProject/Secure_Tools/issues/118). - Any justified update must regenerate vendor assets, update SHA-256 and release - gates, verify license metadata, and pass relevant regressions in a separate PR. +### Dependency maintenance decision — Issue #118 + +Assessment completed on 2026-10-15; see the +[exposure matrix, primary evidence, alternatives and change plan](./v2.3-dependency-maintenance-assessment.md). + +- **pdf-lib: INVESTIGATE_REPLACEMENT_IN_V2.4.** Keep pinned 1.17.1 for v2.3 + under monitoring. The original is not archived, but its last release/default- + branch commit dates to 2021 and repository push metadata to 2024. Community + reports/PRs are not proof of maintainer response or a confirmed active exploit. + [#126](https://github.com/SecureToolsProject/Secure_Tools/issues/126) scopes an + auditable, bounded prototype; no replacement or fork adoption is approved here. +- **JSZip: DEFER.** 3.10.2 addresses foreign-realm input detection, defaults + typings and direct Node Blob input. Current writers use local typed arrays; + no relevant current failure or specific security fix was established. Keep + 3.10.1; do not add a root lockfile dependency just to perform a patch refresh. +- Signature admission, parser errors, local-only behavior, rendering limits and + hash/advisory gates reduce particular risks but do not eliminate parser bugs. + There is no universal pdf-lib parse byte/page/time/memory cap or hard abort. +- Review before promotion and on a relevant advisory/reproducible failure, + archival, unresolved parser issues with inactivity, unsupported requirements, + or an auditable maintained successor. No dependency/runtime bytes changed. +- The assessment supports beginning separately authorized v2.3 UX/mobile work; + it is not production GO. F-02/F-04/F-05/F-06 activation/coverage/live-evidence + limitations remain. Any newly confirmed P0 blocks feature work. ## v2.3 security gate @@ -401,10 +407,10 @@ remaining Action pins, now integrated through PR #121; maintenance activation is pending production promotion. Issue #114 implements shared PDF byte-signature admission, now integrated through PR #122. Issue #117 implements hosting headers now integrated through PR #123, with production verification pending. Recommended next -independent hardening task: #118, a bounded pdf-lib/JSZip maintenance assessment -without automatic upgrades. Issue #115 is integrated through PR #124 and its -private reporting route is active. Issue #116 adds monitoring on its review branch; -default-branch activation and nested-bundle coverage remain explicit limits. +work: review the #118 assessment, then a separately authorized v2.3 UX/mobile pass. +Issue #115 is integrated through PR #124 and its private reporting route is active. +Issue #116 monitoring is integrated through PR #125; default-branch activation +and nested-bundle coverage remain explicit limits. A v2.4 prototype is tracked in #126. ## Verification and preserved invariants diff --git a/docs/v2.3-dependency-maintenance-assessment.md b/docs/v2.3-dependency-maintenance-assessment.md new file mode 100644 index 0000000..bd70140 --- /dev/null +++ b/docs/v2.3-dependency-maintenance-assessment.md @@ -0,0 +1,206 @@ +# Dependency maintenance assessment — Issue #118 + +Evidence checked on 2026-10-15 against v2.3 integration commit +`e728eacb4683d42d8c5b1d8a7edf419159096b41`, after merging PR #125. +This is an assessment, not approval to upgrade, patch or replace dependencies. + +## Decisions + +- **pdf-lib: `INVESTIGATE_REPLACEMENT_IN_V2.4`.** Retain the pinned 1.17.1 for + v2.3 under current monitoring. The long release gap and uncertain upstream + response justify a bounded prototype, tracked in [#126](https://github.com/SecureToolsProject/Secure_Tools/issues/126). + Evidence here does not establish an active exploit requiring replacement + before v2.3. This is a provisional maintenance decision, not a safety guarantee. +- **JSZip: `DEFER`.** Keep vendored 3.10.1. The 3.10.2 compatibility fixes do not + justify a patch refresh for the application's current byte-array ZIP writers. + Revisit if the input boundary, typing needs or advisory evidence changes. + +## pdf-lib exposure matrix + +All production pdf-lib input loads require `%PDF-` at byte zero. The signature +does not validate structure or constrain the cost of a signature-valid PDF. + +| First-party path/tool | Operation and classification | Untrusted PDF parsing? | Security significance | +| --- | --- | --- | --- | +| [Merge](../tools/pdf/merge/pdf.js), its app inspection | Load each source; create destination; copy/reassemble pages | Yes, during inspection and merge | New output does not make copied source objects trusted | +| [Split](../tools/pdf/split/pdf.js), its app inspection | Load source; create/copy selected pages; package generated outputs | Yes | Selection and ZIP generation happen after original parsing | +| [Organizer](../tools/pdf/organize/pdf.js) | Load for page state, reload cached bytes, copy/reorder/rotate retained pages | Yes, including cached reload | Cached bytes remain user input; PDF.js thumbnails are a separate parser | +| [Metadata](../tools/pdf/metadata/pdf.js) | Read Info fields/pages; reload source, delete selected Info entries, save and reparse output | Yes; verification parses a serialized derivative | Metadata-only intent still requires a full PDF parser; this is not arbitrary-content sanitization | +| [PDF to Images](../tools/pdf/to-images/app.js) | `inspectPdf` calls pdf-lib before PDF.js rendering | Yes, despite PDF.js providing the rendering | A replacement assessment must include this preflight dependency | +| [PDF to Text](../tools/pdf/to-text/app.ts), [controller](../tools/pdf/to-text/controller.ts) | `inspectPdf` admission/page count; PDF.js/Tesseract then handle rendering/OCR | Yes in preflight | Plain-text export still exposes pdf-lib even without searchable generation | +| [Searchable PDF](../tools/shared/searchable-pdf.ts) | Load original; embed font; add invisible OCR text; preserve existing pages and save | Yes, then modification of an existing user PDF | Must preserve layout, existing selectable text, annotations and original content | +| [Shared PDF helpers](../tools/shared/pdf.js) | Bounded header read, full read, `PDFDocument.load`, page-count inspection | Yes; common boundary | Catches loading errors/encryption, but does not provide a general parser resource budget | + +`PDFDocument.create()` in Merge/Split/Organizer creates a new destination, but its +page sources are untrusted. There is no separate production pdf-lib-only path +creating a PDF solely from trusted generated data. Images to PDF uses **jsPDF**, +not pdf-lib. PDF.js rendering and Tesseract recognition are separate dependencies. + +Tests invoke pdf-lib to make synthetic fixtures, reload outputs and inspect +regressions: `pdf-merge-and-categories`, `pdf-split`, `pdf-organizer`, `pdf-metadata`, +`pdf-signature`, and `searchable-pdf` tests; browser `gate-fixtures`, `pdf-ocr-smoke` +and `release-hardening`; production `fixtures.mjs` and `pdf-artifact.mjs`; and the +`verify-browser-export-artifacts`/`verify-hardening-download` diagnostic scripts. +These are testing/operator parsing surfaces, not additional public app routes. +Build/deployment scripts copy or check assets; `prepare-searchable-pdf-assets.mjs` +prepares **fontkit/fonts**, not a pdf-lib parsing job. A deployment smoke asset +reference by itself is not a parser invocation. + +## Upstream maintenance and security evidence + +The [npm registry](https://registry.npmjs.org/pdf-lib) and +[GitHub release](https://github.com/Hopding/pdf-lib/releases/tag/v1.17.1) still +identify 1.17.1, published 2021-11-06, as the latest original release. The +[repository API](https://api.github.com/repos/Hopding/pdf-lib) reports not archived +and last push 2024-07-17. Its [default-branch commits](https://github.com/Hopding/pdf-lib/commits/master/) +still end at `93dd36e85aa659a3bca09867d2d8fac172501fbe` (2021-11-12). +Repository `updated_at`, new issue comments and recent community PR submissions +do not establish recent maintainer code/release activity. + +The contributor API shows historical concentration: Hopding has 358 commits +versus 13 for the next listed contributor (a bot). This does not establish current +permissions, staffing or a response guarantee. The original +[maintainership guide](https://github.com/Hopding/pdf-lib/blob/master/docs/MAINTAINERSHIP.md) +describes an unpaid principal maintainer and stale-issue closure; it is historical +policy, not evidence that its old response targets are met today. Describe the +original project as **low release/code activity with uncertain response**, rather +than asserting abandonment or treating it as merely stable because no release is new. + +Exact-input OSV checks for pdf-lib 1.17.1 returned no known advisories at this +verification time. Its [public repository advisories](https://github.com/Hopding/pdf-lib/security/advisories) +were empty. This is not a comprehensive CVE search or proof of parser safety. +Public [report #1776](https://github.com/Hopding/pdf-lib/issues/1776) and +[PR #1781](https://github.com/Hopding/pdf-lib/pull/1781) concern XRef parsing. +The report was closed by the stale bot, not by a verified fix; the PR is open with +no reviews. Its impact claims were **not independently reproduced or accepted as +a confirmed vulnerability** here. Do not equate its closure with remediation, or +repeat its native-memory-corruption claims as established JavaScript behavior. +This is a concrete triage/response uncertainty, not a release-blocking exploit finding. + +### What existing defenses do and do not cover + +| Control | Material benefit | Remaining boundary | +| --- | --- | --- | +| Five-byte admission | Rejects empty, spoofed and incomplete-header input before full read/parser entry | Any signature-valid malicious structure still reaches the parser | +| Parser errors and encrypted-input rejection | Stops supported failures from producing successful results | Cannot catch an allocation spike or work that never completes; parsers can repair/tolerate some malformed input | +| Render limits, sequential OCR and cleanup | Bounds raster dimensions/pixels and some concurrent work; cancellation suppresses obsolete results | These are **not** universal pdf-lib file/page/time/memory caps or a hard abort of every `load()`; loading currently occurs in the page context | +| Browser-local processing, no backend | No service-side parser/file-upload attack surface | Browser CPU/memory and origin trust still matter; local-only is not parser isolation | +| Strict document CSP | Restricts code/resource/network behavior | Not a parser correctness or resource-consumption proof; integrated HTTP header delivery still awaits release verification | +| Hash pins, corpus and CodeQL/advisory checks | Detects changed approved bytes, regressions and known/pattern-based issues | Pins retain old bugs; CodeQL excludes vendored bundles; nested/native dependency coverage remains incomplete | + +No universal parser budget is claimed. A future prototype must evaluate hard +termination/resource controls, not assume an async API or a newer engine supplies them. + +## Browser-local fallback comparison + +The byte counts below were measured from current vendored files or npm package +archives whose SHA-512 matched registry integrity. Candidate archives were read +in memory, **not installed or executed**. Gzip uses level 6. Figures exclude +separate fonts/fontkit, runtime initialization and other app assets, and are not +whole-app download or memory benchmarks. + +| Candidate | Browser-local / features | Measured bundle cost | WASM/native complexity | Maintenance / migration risk | +| --- | --- | --- | --- | --- | +| Retain pdf-lib 1.17.1 temporarily | Existing complete editor/generator integration | 525,099 B JS; 206,639 B gzip | None | Lowest immediate regression risk; poor original release cadence, current parser exposure remains | +| [Cantoo fork](https://github.com/cantoo-scribe/pdf-lib), npm `@cantoo/pdf-lib` 2.11.1 | Publisher claims original APIs plus editing/font/form features; closest adapter candidate | 616,746 B minified JS; 251,781 B gzip, before fontkit/fonts | None for base library | Recent default-branch work/tag v2.11.0 on 2026-09-11; product-focused support, broader behavior must be tested; provenance discrepancy below blocks blind adoption | +| [PDF.js](https://mozilla.github.io/pdf.js/) | Already used for parse/render/text extraction; possible reuse for renderer-backed preflight | Already vendored: 454,669 B JS + 1,262,398 B worker; 505,270 B combined gzip | Existing JS worker | Maintained renderer; **not a drop-in page-copy/Info-cleaning/font-writing editor**. Save/annotation support does not prove required editing coverage | +| [MuPDF.js](https://github.com/ArtifexSoftware/mupdf/blob/master/platform/wasm/README.md), npm mupdf 1.28.1 | Official browser-capable bindings; page manipulation/editing/rendering | 10,409,826 B WASM + 132,111 B JS; about 4.74 MB combined gzip | High: WASM lifecycle, memory, workers and native dependencies | Active native project; major API/behavior migration. Declared AGPL/commercial licensing needs an explicit project decision, not assumed equivalence to MIT | +| [qpdf WASM wrapper](https://github.com/jsscheller/qpdf-wasm), `@jspawn/qpdf-wasm` 0.0.2 | Browser-local CLI build; structural page selection/reassembly, not a complete OCR-text/font authoring replacement | 1,274,647 B WASM + 52,796 B JS; 440,904 B combined gzip | High: virtual filesystem, compiled engine and worker wrapper | Core [qpdf](https://qpdf.readthedocs.io/en/stable/cli.html#page-selection) is active, but this npm wrapper was published 2022-07-26; core activity does not update the shipped binary. Apache-2.0 is the package's declared license | + +Cantoo's [publisher README](https://github.com/cantoo-scribe/pdf-lib#readme) claims +API continuity and additional repair/format behavior; that is not Secure Tools +compatibility evidence. Registry latest is 2.11.1 (2026-09-15), while observed +repository tags/default branch end at v2.11.0. The registry's 2.11.1 gitHead +`c8c88e84dcd5510ec35921123bb5140fe02a7115` could not be resolved in its declared +repository (HTTP 422); the v2.11.1 ref returned 404. Reconcile that provenance or +select another auditable exact version before prototyping. This discrepancy does +not itself establish compromise. Its inherited maintainership guide also must +not be mistaken for a verified current staffing/SLA statement. + +Custom byte rewriting is not a serious general PDF editing replacement. Keep the +existing narrow signature check; do not invent a second PDF parser for metadata +removal or page copying. No candidate has been demonstrated to eliminate current +risks. A small adapter/corpus prototype is preferable to replacing all paths at once. + +## JSZip 3.10.2 relevance + +The [tag comparison](https://github.com/Stuk/jszip/compare/v3.10.1...v3.10.2) +contains eight commits, including the three compatibility changes described by +the [changelog](https://github.com/Stuk/jszip/blob/v3.10.2/CHANGES.md). The registry +published 3.10.2 on 2026-09-08 UTC; the changelog dates it September 9. The tag +exists, but the repository release-by-tag API returned 404: absence of a GitHub +Release object is not absence of the npm/tagged version. + +| Change | Actual Secure Tools boundary | Decision | +| --- | --- | --- | +| Cross-realm Array/ArrayBuffer/Uint8Array detection | Three writers: [image-output](../tools/shared/image-output.js) for Converter/Resize/Compressor, [PDF Split](../tools/pdf/split/pdf.js), and [PDF to Images](../tools/pdf/to-images/converter.js). They insert local Uint8Arrays; Blob-based images are converted via `arrayBuffer()` and a new local typed array. No foreign-window/iframe archive input was found | Binary detection is exercised, but not the foreign-realm case fixed by the patch | +| Missing `JSZip.defaults` TypeScript declarations | ZIP helpers are JS, no defaults API use or JSZip TS import was found | No current type-check benefit demonstrated | +| Node 18+ Blob input | Production creates browser ZIPs. Node verification reads generated bytes/ArrayBuffers; app helpers convert input Blobs to typed arrays before `.file()` | Could help a future direct Node Blob tool; does not repair current app behavior | + +One-off Node 24 checks confirmed current 3.10.1 round-trips local typed-array input, +while direct Node Blob insertion fails. That unsupported test-only boundary is +not used by today's helpers. Existing Split/To-Images ZIP regressions passed. +Production writes archives; `loadAsync` usage is test verification, not a user ZIP +import feature. No JSZip advisory fixed specifically by 3.10.2 was identified in +the inspected changelog/public advisories, and current exact-input OSV returned +no known advisory. Do not infer that no undisclosed vulnerability exists. + +## Future change plan — not implemented + +For a separately approved JSZip update: acquire the exact registry artifact; +verify package integrity and the selected MIT license; replace vendored JS, +package metadata and README provenance; update approved version/hash in +`config/security/vendor-release-pins.json`; rerun inventory consistency, release +and ZIP tests (including version-specific expectations), then full browser/native +download checks. JSZip is **not currently a root npm/lockfile dependency**: do not +invent a lockfile bump or add it solely for this assessment. If future vendoring +automation introduces it as a build input, update package.json/lockfile together +in that reviewed task. The security manifest resolves metadata versions; it has +no duplicate version field to bump. Add foreign-realm/Node Blob cases only if +those boundaries become supported requirements. + +For the v2.4 pdf-lib prototype in #126: + +1. Reconcile candidate release/tag/commit/artifact/license and nested-dependency + provenance; compare against current behavior through an adapter. +2. Consider reusing PDF.js inspection first only on already renderer-backed + Images/Text paths; then test Merge/Split/Organizer, Info metadata, and finally + Searchable PDF separately. Avoid adding redundant parsers to every tool. +3. Use classic/object-stream PDFs, rotations/crop boxes, forms, annotations, + bookmarks, empty/encrypted/truncated/malformed cases, large/deep structures, + and bounded isolated evaluation of public parser reports. Preserve error + categories and intentional rejection behavior; don't silently accept more + repair-tolerated content. +4. Compare page count/order/geometry, metadata field semantics, links/forms, + extraction and original rendered pixels. Test Korean/English font subsetting, + OCR line geometry, and no duplicated existing selectable text. Serialized byte + equality is not required because IDs/compression/serialization can change. +5. Measure input size/page budgets, mobile latency, peak memory, cancellation and + hard parser termination in an isolated worker/process, with no network/file + upload or CSP weakening. Benchmark rather than assume better performance. +6. Only after a review decision, update tool adapters, vendoring/provenance, + canonical pins/licenses/security inventory, regressions and complete browser + gates in a focused implementation PR. No such implementation is authorized here. + +## Review triggers and release/UX boundary + +Reassess immediately on a relevant advisory or reproducible security failure, +upstream archival, a required feature that cannot be maintained, or stronger +evidence of parser bugs without a response. Recheck before v2.3 promotion. +Current prolonged inactivity and unresolved-report triage already justify #126; +an auditable, compatible maintained successor is another selection trigger. + +The audit backlog is sufficiently addressed to **begin a separately authorized +v2.3 UX/mobile pass**, under the existing policy permitting nonblocking P1/P2 work. +This is not production GO or a declaration that the audit is fully closed: +F-02 default-branch automation, F-04 nested/native coverage, and F-05/F-06 live +delivery/provenance evidence remain outstanding. Any newly confirmed P0 overrides +that development readiness. No UX work starts in this assessment. + +## Verification + +Relevant Merge, Split, Organizer, Metadata, To-Images and Image Converter tests +passed. Package/lockfile/runtime bytes and release pins were unchanged. Primary +links and local source links were checked; normal CI evidence is recorded in the +assessment PR. No candidate was installed, no malformed resource-exhaustion sample +was executed, and no production/dependency implementation changed. From f4a549cf72b62b8c1336c735ae61afd119d926be Mon Sep 17 00:00:00 2001 From: maruson08 <maruson08@naver.com> Date: Thu, 15 Oct 2026 21:21:37 +0900 Subject: [PATCH 09/12] =?UTF-8?q?=E2=9C=A8[Feat]=20Improve=20responsive=20?= =?UTF-8?q?navigation=20and=20tool=20layouts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 7 +- 404.html | 4 +- about/index.html | 14 +-- css/base.css | 4 +- css/categories.css | 5 + css/components.css | 45 +++++++- docs/v2.3-mobile-ux.md | 87 +++++++++++++++ index.html | 14 +-- js/locales/de.js | 1 + js/locales/en.js | 1 + js/locales/es.js | 1 + js/locales/fr.js | 1 + js/locales/ja.js | 1 + js/locales/ko.js | 1 + js/main.js | 2 + js/navigation.js | 29 +++++ privacy/index.html | 14 +-- tests/browser/responsive.mjs | 149 ++++++++++++++++++++++++++ tests/i18n-quality.test.mjs | 2 +- tests/typography-i18n-layout.test.mjs | 5 +- tools/image/compress/index.html | 4 +- tools/image/converter/index.html | 12 +-- tools/image/index.html | 14 +-- tools/image/metadata/index.html | 7 +- tools/image/metadata/tool.css | 10 +- tools/image/resize/index.html | 4 +- tools/image/to-text/index.html | 4 +- tools/media/index.html | 4 +- tools/pdf/images-to-pdf/index.html | 14 +-- tools/pdf/index.html | 4 +- tools/pdf/merge/index.html | 4 +- tools/pdf/metadata/index.html | 7 +- tools/pdf/metadata/tool.css | 8 +- tools/pdf/organize/index.html | 4 +- tools/pdf/split/index.html | 4 +- tools/pdf/to-images/index.html | 4 +- tools/pdf/to-text/index.html | 4 +- tools/scan/index.html | 4 +- tools/shared/tool.css | 16 ++- 39 files changed, 430 insertions(+), 89 deletions(-) create mode 100644 docs/v2.3-mobile-ux.md create mode 100644 js/navigation.js create mode 100644 tests/browser/responsive.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bab5edf..399a160 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -85,10 +85,15 @@ jobs: - name: Verify HTTP headers, browser OCR and downloads on built artifact run: node tests/production/local-smoke.mjs + - name: Verify responsive navigation, metadata layouts and accessibility + run: node tests/browser/responsive.mjs + - name: Retain artifact browser diagnostics if: failure() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: artifact-browser-diagnostics - path: .ts-build/production-smoke + path: | + .ts-build/production-smoke + .ts-build/responsive retention-days: 7 diff --git a/404.html b/404.html index f8b9386..afdc408 100644 --- a/404.html +++ b/404.html @@ -21,7 +21,9 @@ </head> <body class="page-shell" data-page="notFound"> <a class="skip-link" href="#main" data-i18n="common.skip">Skip to main content</a> - <header class="site-header"><div class="container header-inner"><a class="brand" href="./" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"><span class="brand-mark" aria-hidden="true"></span><span>Secure Tools</span></a><div class="header-controls"><label class="control-label"><span data-i18n="common.language">Language</span><select class="control" data-language-select><option value="en">English</option><option value="ko">한국어</option><option value="ja">日本語</option><option value="es">Español</option><option value="de">Deutsch</option><option value="fr">Français</option></select></label><label class="control-label"><span data-i18n="common.theme">Theme</span><select class="control" data-theme-select><option value="system" data-i18n="common.themes.system">System</option><option value="light" data-i18n="common.themes.light">Light</option><option value="dark" data-i18n="common.themes.dark">Dark</option></select></label></div></div></header> + <header class="site-header"><div class="container header-inner"><a class="brand" href="./" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"><span class="brand-mark" aria-hidden="true"></span><span>Secure Tools</span></a> +<details class="header-menu"><summary data-i18n="common.menu">Menu</summary><div class="header-menu__content"><nav class="site-nav" aria-label="Primary navigation" data-i18n-aria-label="common.aria.primaryNavigation"><a href="./#tools" data-i18n="common.nav.tools">Tools</a><a href="./privacy/" data-i18n="common.nav.privacy">Privacy</a><a href="./about/" data-i18n="common.nav.about">About</a><a href="https://github.com/SecureToolsProject/Secure_Tools" data-repository-link target="_blank" rel="noreferrer" data-i18n="common.nav.source">Source</a></nav><div class="header-controls"><label class="control-label"><span data-i18n="common.language">Language</span><select class="control" data-language-select><option value="en">English</option><option value="ko">한국어</option><option value="ja">日本語</option><option value="es">Español</option><option value="de">Deutsch</option><option value="fr">Français</option></select></label><label class="control-label"><span data-i18n="common.theme">Theme</span><select class="control" data-theme-select><option value="system" data-i18n="common.themes.system">System</option><option value="light" data-i18n="common.themes.light">Light</option><option value="dark" data-i18n="common.themes.dark">Dark</option></select></label></div></div></details> +</div></header> <main id="main" class="page-main not-found"><div class="container prose"><p class="eyebrow" data-i18n="notFound.eyebrow">404</p><h1 data-i18n="notFound.title">This page is not here.</h1><p data-i18n="notFound.description">The address may be outdated or mistyped.</p><a class="button button--primary" href="./" data-i18n="notFound.action">Return home</a></div></main> <footer class="site-footer"><div class="container footer-inner"><div><a class="brand" href="./" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"><span class="brand-mark" aria-hidden="true"></span><span>Secure Tools</span></a><p data-i18n="common.footerStatement">Your files stay on your device.</p></div><nav aria-label="Footer navigation" data-i18n-aria-label="common.aria.footerNavigation"><a href="./#tools" data-i18n="common.nav.tools">Tools</a><a href="./privacy/" data-i18n="common.nav.privacy">Privacy</a><a href="./about/" data-i18n="common.nav.about">About</a><a href="https://github.com/SecureToolsProject/Secure_Tools" data-repository-link target="_blank" rel="noreferrer" data-i18n="common.nav.source">Source</a></nav></div></footer> <script type="module" src="./js/main.js"></script> diff --git a/about/index.html b/about/index.html index a1d4607..47f146e 100644 --- a/about/index.html +++ b/about/index.html @@ -34,21 +34,17 @@ </head> <body class="page-shell" data-page="about"> <a class="skip-link" href="#main" data-i18n="common.skip">Skip to main content</a> - <header class="site-header"> - <div class="container header-inner"> - <a class="brand" href="../" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"><span class="brand-mark" aria-hidden="true"></span><span>Secure Tools</span></a> - <nav class="site-nav" aria-label="Primary navigation" data-i18n-aria-label="common.aria.primaryNavigation"> + <header class="site-header"><div class="container header-inner"><a class="brand" href="../" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"><span class="brand-mark" aria-hidden="true"></span><span>Secure Tools</span></a> +<details class="header-menu"><summary data-i18n="common.menu">Menu</summary><div class="header-menu__content"><nav class="site-nav" aria-label="Primary navigation" data-i18n-aria-label="common.aria.primaryNavigation"> <a href="../#tools" data-i18n="common.nav.tools">Tools</a> <a href="../privacy/" data-i18n="common.nav.privacy">Privacy</a> <a href="./" aria-current="page" data-i18n="common.nav.about">About</a> <a href="https://github.com/SecureToolsProject/Secure_Tools" data-repository-link target="_blank" rel="noreferrer" data-i18n="common.nav.source">Source</a> - </nav> - <div class="header-controls"> + </nav><div class="header-controls"> <label class="control-label"><span data-i18n="common.language">Language</span><select class="control" data-language-select><option value="en">English</option><option value="ko">한국어</option><option value="ja">日本語</option><option value="es">Español</option><option value="de">Deutsch</option><option value="fr">Français</option></select></label> <label class="control-label"><span data-i18n="common.theme">Theme</span><select class="control" data-theme-select><option value="system" data-i18n="common.themes.system">System</option><option value="light" data-i18n="common.themes.light">Light</option><option value="dark" data-i18n="common.themes.dark">Dark</option></select></label> - </div> - </div> - </header> + </div></div></details> +</div></header> <main id="main" class="page-main subpage-main"> <article class="container prose"> <p class="eyebrow" data-i18n="about.eyebrow">About</p> diff --git a/css/base.css b/css/base.css index e3f4b1b..14cfca5 100644 --- a/css/base.css +++ b/css/base.css @@ -68,11 +68,11 @@ } *, *::before, *::after { box-sizing: border-box; } -html { scroll-behavior: smooth; scroll-padding-top: 6rem; } +html { font-family: var(--font-sans); scroll-behavior: smooth; scroll-padding-top: 6rem; } body { margin: 0; - min-width: 20rem; + min-width: 0; min-height: 100vh; background: var(--bg-primary); color: var(--text-primary); diff --git a/css/categories.css b/css/categories.css index 29f8db0..8993a12 100644 --- a/css/categories.css +++ b/css/categories.css @@ -24,3 +24,8 @@ a.category-tool:hover { border-color: var(--border-strong); transform: translate .category-tool { min-height: 10rem; } } @media (prefers-reduced-motion: reduce) { a.category-tool:hover { transform: none; } } + +@media (max-width: 38rem) { + .category-nav__inner { flex-wrap: nowrap; padding-block: var(--space-1); gap: var(--space-1); } + .category-nav a { white-space: nowrap; padding-inline: var(--space-3); } +} diff --git a/css/components.css b/css/components.css index 745d046..170516f 100644 --- a/css/components.css +++ b/css/components.css @@ -25,7 +25,7 @@ .button:disabled { border-color: var(--border); background: var(--bg-subtle); color: var(--status-muted); cursor: not-allowed; } .control { - min-height: 2.5rem; + min-height: 2.75rem; min-width: 0; max-width: 7.5rem; padding: 0.4rem 1.8rem 0.4rem 0.65rem; @@ -59,6 +59,41 @@ .header-inner > *, .header-controls > *, .control-label > span { min-width: 0; } .header-controls { display: flex; min-width: 0; flex: 0 1 auto; align-items: center; gap: var(--space-3); } +.header-menu { min-width: 0; flex: 1; margin: 0; } +.header-menu > summary { width: fit-content; min-height: 2.75rem; margin-left: auto; padding: var(--space-2) var(--space-3); border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--bg-secondary); font-weight: var(--font-weight-semibold); cursor: pointer; } +.header-menu__content { display: flex; align-items: center; gap: var(--space-5); } +.header-menu[data-desktop] > summary { display: none; } + +/* Keep native form semantics and mobile pickers; inherit the resolved theme. */ +select.control, .field select { + appearance: none; + padding-inline-end: var(--space-7); + background-image: linear-gradient(45deg, transparent 50%, var(--text-secondary) 50%), linear-gradient(135deg, var(--text-secondary) 50%, transparent 50%); + background-position: right 1rem center, right .7rem center; + background-size: .3rem .3rem; + background-repeat: no-repeat; + color-scheme: inherit; + text-overflow: ellipsis; +} +select option, select optgroup { background: var(--bg-secondary); color: var(--text-primary); } +.field select { max-width: 100%; padding-inline-start: .7rem; } +.field select:disabled { background-color: var(--bg-subtle); color: var(--status-muted); cursor: not-allowed; } +select:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; } + +/* Enhance only fine-pointer desktop pickers where the browser supports it. */ +@supports (appearance: base-select) { + @media (min-width: 38.001rem) and (pointer: fine) { + select.control, .field select, ::picker(select) { appearance: base-select; } + select.control, .field select { background-image: none; padding-inline-end: var(--space-3); } + ::picker(select) { padding: var(--space-1); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); background: var(--bg-secondary); color: var(--text-primary); box-shadow: var(--shadow-sm); } + select::picker-icon { color: var(--text-secondary); } + select option { min-height: 2.75rem; padding: var(--space-2) var(--space-3); border-radius: var(--radius-sm); overflow-wrap: anywhere; } + select option:checked { background: var(--accent-soft); color: var(--text-primary); } + select option:hover, select option:focus { background: var(--bg-subtle); outline: 2px solid var(--focus); outline-offset: -2px; } + } +} +@media (forced-colors: active) { select.control, .field select { appearance: auto; background-image: none; } } + .site-footer { padding-block: var(--space-7); border-top: 1px solid var(--border); } .footer-inner { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-6); } .footer-inner p { margin: var(--space-3) 0 0; color: var(--text-secondary); font-size: var(--font-size-sm); } @@ -66,15 +101,21 @@ @media (max-width: 68rem) { .header-inner { flex-wrap: wrap; padding-block: var(--space-3); gap: var(--space-3) var(--space-5); } + .header-menu__content { flex-wrap: wrap; gap: var(--space-3); } .site-nav { order: 3; width: 100%; padding-top: var(--space-3); border-top: 1px solid var(--border); } .header-controls { margin-left: auto; } } @media (max-width: 38rem) { + .header-inner { position: relative; min-height: 4.25rem; gap: var(--space-3); } + .header-menu { flex: 0 0 auto; margin-left: auto; } + .header-menu[open] { flex-basis: 100%; } + .header-menu[open] > summary { position: absolute; top: var(--space-3); right: 0; } + .header-menu__content { flex-direction: column; align-items: stretch; padding-block: var(--space-4); gap: var(--space-5); } .header-controls { width: 100%; align-items: stretch; flex-direction: column; margin-left: 0; } .control-label { width: 100%; justify-content: space-between; } .control, .control[data-language-select] { width: min(100%, 12rem); max-width: none; } - .site-nav { justify-content: flex-start; gap: var(--space-2) var(--space-4); } + .site-nav { order: 0; justify-content: flex-start; gap: var(--space-2) var(--space-4); } .site-nav a { font-size: 0.8rem; } .footer-inner { flex-direction: column; } } diff --git a/docs/v2.3-mobile-ux.md b/docs/v2.3-mobile-ux.md new file mode 100644 index 0000000..aee4277 --- /dev/null +++ b/docs/v2.3-mobile-ux.md @@ -0,0 +1,87 @@ +# Mobile UX pass — Issue #128 + +This development pass follows the PR #127 normal merge into `v2.3` at +`91e89a70fe37452b3e2b767135a387f400f04436`. It does not promote production +or close the security audit's outstanding activation/coverage/live-delivery limits. + +## Shared UI inventory and decisions + +- The 19 canonical pages and 404 page repeat one header structure. Navigation + and language/theme controls now share one native `details` disclosure, with + a translated Menu summary in all six catalogs. No duplicate controls or IDs. + Without JavaScript it remains a working disclosure at every width. With JS, + desktop/tablet navigation is open and the summary hidden above 38rem; mobile + starts closed. Enter/Space and expanded semantics are native, Escape returns + focus to the summary, and there is no modal or focus trap. Crossing the + breakpoint resets the disclosure and preserves a visible keyboard focus. +- All category/tool pages use `.category-nav__inner`. Mobile reduces padding + to `--space-1`, keeps a single scrollable row and 44px link targets, and + retains `aria-current`. Neither header nor categories become sticky. +- Inspected `base`, `components`, `pages`, `categories`, shared tool CSS and all + eleven per-tool stylesheets. Existing layout breakpoints span 24, 30, 38, + 42, 44, 46, 48, 52, 54, 56 and 68rem; this pass retains existing desktop and + tool grid breakpoints. Shared mobile workspace/section gaps use `--space-6` + instead of scattered child margins. Metadata cards/results/limitations and + status spacing use the same tokens; desktop gaps remain unchanged. +- Both metadata scope asides move in actual document order after the cleaning + result/comparison and before the existing polite live status. All scope text, + localized keys, heading IDs and supported/unsupported claims are retained. + Shared typography/padding removes the large heading/accent-bar treatment; + limitations remain visible, without an extra disclosure. +- The inherited font reset previously reset body/controls to the root's browser + default. Root font-family now establishes the existing intended system font. + Removing the body's 320px minimum avoids overflow when a classic scrollbar + reduces the available content width at a 320px viewport. + +### Select inventory + +Every production header has language and theme selects. Tool-specific selects: + +| Tool | Native selects | +| --- | --- | +| Image Converter, Resize, Compressor | Output format | +| Image to Text, PDF to Text | OCR language | +| Images to PDF | Page size, orientation, fit, quality | +| PDF to Images | Image format, render scale | +| Metadata, PDF Merge/Split/Organizer | Global preference selects only | + +Resize dimensions/compression quality use existing inputs/radio/range controls; +these do not need dropdown adapters. The retired `/tools/privacy/` source is +not a canonical built page; its URL is a permanent redirect to `/privacy/`. + +**Strategy: enhanced native selects.** Shared appearance, CSS arrow, option +palette, resolved `color-scheme`, focus and disabled treatment cover all selects. +Fine-pointer desktop browsers supporting `appearance: base-select` also receive +a themed native picker with selected/hover/focus states. Other browsers retain +native options and apply supported colors; mobile keeps its platform picker. +Forced-colors restores the native appearance. No custom ARIA listbox, library, +portal, script-based option rendering or new runtime dependency is introduced. + +This deliberately preserves platform keyboard, typeahead, touch and assistive +technology behavior. Complete identical OS popup rendering is not promised. +See [MDN's native select customization](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Forms/Customizable_select) +and [option styling limits](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/option). + +## Reproducible verification + +`node tests/browser/responsive.mjs` uses the real built artifact/server and +strict hosting-header validation. It covers 441 combinations: seven viewports +(320×568, 360×800, 375×812, 390×844, 430×932, 768×1024, 1280×900), seven routes +(home, Image category, Converter, Image OCR, PDF Merge, both Metadata tools), +EN/KO/JA, and System/Light/Dark. It checks compact height, native disclosure tab +order/Escape, current/single-row categories, overflow/control bounds, heading/skip +targets, scope order, long CJK PDF metadata and real metadata-clean downloads. +It also checks system theme changes, native select keyboard selection, and no-JS +navigation. Existing full i18n checks cover all six catalogs. Diagnostics and +screenshots are written under `.ts-build/responsive` and retained on CI failure. + +Local pinned install, build/artifact validation, real English/Korean/combined OCR, +fresh lockfile/vendor advisories and structural tests passed. Local full tests +reach the strict HTTP gate and fail closed because installed AdGuard rewrites +CSP to allow `local.adguard.org`, changes `connect-src`, and injects scripts. +No expected policy, network assertion or app CSP is relaxed for that environment. +Clean GitHub CI is required for the complete HTTP/browser/security result. + +The review PR records final CI evidence. A physical iOS/Android picker and a +screen reader on each OS remain useful manual follow-up; browser emulation and +semantic/keyboard checks do not claim to replace those device/AT combinations. diff --git a/index.html b/index.html index 1040b0e..b5ec6da 100644 --- a/index.html +++ b/index.html @@ -34,19 +34,16 @@ <body class="page-shell" data-page="home"> <a class="skip-link" href="#main" data-i18n="common.skip">Skip to main content</a> - <header class="site-header"> - <div class="container header-inner"> - <a class="brand" href="./" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"> + <header class="site-header"><div class="container header-inner"><a class="brand" href="./" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"> <span class="brand-mark" aria-hidden="true"></span> <span>Secure Tools</span> </a> - <nav class="site-nav" aria-label="Primary navigation" data-i18n-aria-label="common.aria.primaryNavigation"> +<details class="header-menu"><summary data-i18n="common.menu">Menu</summary><div class="header-menu__content"><nav class="site-nav" aria-label="Primary navigation" data-i18n-aria-label="common.aria.primaryNavigation"> <a href="#tools" data-i18n="common.nav.tools">Tools</a> <a href="./privacy/" data-i18n="common.nav.privacy">Privacy</a> <a href="./about/" data-i18n="common.nav.about">About</a> <a href="https://github.com/SecureToolsProject/Secure_Tools" data-repository-link target="_blank" rel="noreferrer" data-i18n="common.nav.source">Source</a> - </nav> - <div class="header-controls"> + </nav><div class="header-controls"> <label class="control-label"> <span data-i18n="common.language">Language</span> <select class="control" data-language-select> @@ -62,9 +59,8 @@ <option value="dark" data-i18n="common.themes.dark">Dark</option> </select> </label> - </div> - </div> - </header> + </div></div></details> +</div></header> <main id="main" class="page-main"> <section class="hero container"> diff --git a/js/locales/de.js b/js/locales/de.js index 5570cb2..0653091 100644 --- a/js/locales/de.js +++ b/js/locales/de.js @@ -66,6 +66,7 @@ export const de = { } }, "common": { + "menu": "Menü", "skip": "Zum Hauptinhalt springen", "brandTagline": "Private Dateitools, direkt auf Ihrem Gerät", "nav": { diff --git a/js/locales/en.js b/js/locales/en.js index a1930b8..0a6dd6e 100644 --- a/js/locales/en.js +++ b/js/locales/en.js @@ -18,6 +18,7 @@ export const en = { mediaCategory: { title: "Media tools — Secure Tools", description: "Local audio and video utilities from Secure Tools." }, }, common: { + menu: "Menu", skip: "Skip to main content", brandTagline: "Private utilities, processed on your device", nav: { tools: "Tools", privacy: "Privacy", source: "Source", about: "About" }, aria: { home: "Secure Tools home", primaryNavigation: "Primary navigation", footerNavigation: "Footer navigation", toolCategories: "Tool categories", localProcessingSummary: "Local processing summary" }, diff --git a/js/locales/es.js b/js/locales/es.js index 41ef690..e9b8424 100644 --- a/js/locales/es.js +++ b/js/locales/es.js @@ -66,6 +66,7 @@ export const es = { } }, "common": { + "menu": "Menú", "skip": "Saltar al contenido principal", "brandTagline": "Herramientas privadas, procesadas en tu dispositivo", "nav": { diff --git a/js/locales/fr.js b/js/locales/fr.js index ca311ac..cdf1421 100644 --- a/js/locales/fr.js +++ b/js/locales/fr.js @@ -66,6 +66,7 @@ export const fr = { } }, "common": { + "menu": "Menu", "skip": "Passer au contenu principal", "brandTagline": "Outils privés, traités sur votre appareil", "nav": { diff --git a/js/locales/ja.js b/js/locales/ja.js index 2c1ed66..52a8ea1 100644 --- a/js/locales/ja.js +++ b/js/locales/ja.js @@ -66,6 +66,7 @@ export const ja = { } }, "common": { + "menu": "メニュー", "skip": "メインコンテンツへ移動", "brandTagline": "端末内で処理するプライバシーツール", "nav": { diff --git a/js/locales/ko.js b/js/locales/ko.js index 39074b5..1f29d5c 100644 --- a/js/locales/ko.js +++ b/js/locales/ko.js @@ -18,6 +18,7 @@ export const ko = { mediaCategory: { title: "미디어 도구 — Secure Tools", description: "Secure Tools의 로컬 오디오 및 비디오 유틸리티입니다." }, }, common: { + menu: "메뉴", skip: "본문으로 바로가기", brandTagline: "기기에서 바로 처리하는 프라이버시 중심 도구", nav: { tools: "도구", privacy: "개인정보 보호", source: "소스", about: "소개" }, aria: { home: "Secure Tools 홈", primaryNavigation: "주 탐색", footerNavigation: "바닥글 탐색", toolCategories: "도구 카테고리", localProcessingSummary: "로컬 처리 요약" }, diff --git a/js/main.js b/js/main.js index 7371d64..014db95 100644 --- a/js/main.js +++ b/js/main.js @@ -1,10 +1,12 @@ import { REPOSITORY_URL } from "./config.js"; import { initializeI18n } from "./i18n.js"; import { initializeTheme } from "./theme.js"; +import { initializeNavigation } from "./navigation.js"; document.querySelectorAll("[data-repository-link]").forEach((link) => { link.href = REPOSITORY_URL; }); +initializeNavigation(); initializeTheme(); initializeI18n(); diff --git a/js/navigation.js b/js/navigation.js new file mode 100644 index 0000000..3d8cbc0 --- /dev/null +++ b/js/navigation.js @@ -0,0 +1,29 @@ +// The native disclosure remains usable when scripts or preference storage fail. +export function initializeNavigation() { + const desktop = window.matchMedia('(min-width: 38.001rem)'); + document.querySelectorAll('.header-menu').forEach((menu) => { + const summary = menu.querySelector('summary'); + const update = () => { + const focusInside = menu.contains(document.activeElement); + menu.open = desktop.matches; + menu.toggleAttribute('data-desktop', desktop.matches); + if (!desktop.matches && focusInside) summary.focus(); + }; + update(); + desktop.addEventListener('change', update); + menu.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && !desktop.matches && menu.open) { + event.preventDefault(); + menu.open = false; + summary.focus(); + } + }); + menu.querySelectorAll('nav a').forEach((link) => link.addEventListener('click', () => { + if (!desktop.matches) { + menu.open = false; + summary.focus(); + } + })); + menu.dataset.navigationReady = 'true'; + }); +} diff --git a/privacy/index.html b/privacy/index.html index 0d3504f..e6b573f 100644 --- a/privacy/index.html +++ b/privacy/index.html @@ -35,21 +35,17 @@ </head> <body class="page-shell" data-page="privacy"> <a class="skip-link" href="#main" data-i18n="common.skip">Skip to main content</a> - <header class="site-header"> - <div class="container header-inner"> - <a class="brand" href="../" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"><span class="brand-mark" aria-hidden="true"></span><span>Secure Tools</span></a> - <nav class="site-nav" aria-label="Primary navigation" data-i18n-aria-label="common.aria.primaryNavigation"> + <header class="site-header"><div class="container header-inner"><a class="brand" href="../" aria-label="Secure Tools home" data-i18n-aria-label="common.aria.home"><span class="brand-mark" aria-hidden="true"></span><span>Secure Tools</span></a> +<details class="header-menu"><summary data-i18n="common.menu">Menu</summary><div class="header-menu__content"><nav class="site-nav" aria-label="Primary navigation" data-i18n-aria-label="common.aria.primaryNavigation"> <a href="../#tools" data-i18n="common.nav.tools">Tools</a> <a href="./" aria-current="page" data-i18n="common.nav.privacy">Privacy</a> <a href="../about/" data-i18n="common.nav.about">About</a> <a href="https://github.com/SecureToolsProject/Secure_Tools" data-repository-link target="_blank" rel="noreferrer" data-i18n="common.nav.source">Source</a> - </nav> - <div class="header-controls"> + </nav><div class="header-controls"> <label class="control-label"><span data-i18n="common.language">Language</span><select class="control" data-language-select><option value="en">English</option><option value="ko">한국어</option><option value="ja">日本語</option><option value="es">Español</option><option value="de">Deutsch</option><option value="fr">Français</option></select></label> <label class="control-label"><span data-i18n="common.theme">Theme</span><select class="control" data-theme-select><option value="system" data-i18n="common.themes.system">System</option><option value="light" data-i18n="common.themes.light">Light</option><option value="dark" data-i18n="common.themes.dark">Dark</option></select></label> - </div> - </div> - </header> + </div></div></details> +</div></header> <main id="main" class="page-main subpage-main"> <article class="container prose"> <p class="eyebrow" data-i18n="privacy.eyebrow">Privacy model</p> diff --git a/tests/browser/responsive.mjs b/tests/browser/responsive.mjs new file mode 100644 index 0000000..c5f35e0 --- /dev/null +++ b/tests/browser/responsive.mjs @@ -0,0 +1,149 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { chromium } from 'playwright'; +import { translations } from '../../js/i18n.js'; +import { createFixtures, PDFLib } from '../production/fixtures.mjs'; +import { assertSecurityHeaders } from '../../scripts/http-security-headers.mjs'; + +// Exercise the real built pages and native controls; never substitute app code/CSP. +const viewports = [[320,568],[360,800],[375,812],[390,844],[430,932],[768,1024],[1280,900]]; +const routes = ['/', '/image/', '/image/converter/', '/image/to-text/', '/pdf/merge/', '/pdf/metadata/', '/image/metadata/']; +const directory = '.ts-build/responsive'; +await fs.mkdir(directory, { recursive: true }); +const report = { cases: [], errors: [], headerErrors: [], external: [], status: 'FAIL' }; +const port = 44000 + Math.floor(Math.random() * 9000); +const origin = `http://127.0.0.1:${port}`; +const server = spawn(process.execPath, ['tests/serve-ocr-smoke.mjs', String(port)], { stdio: ['ignore','pipe','inherit'] }); +let browser; +try { + await new Promise((resolve,reject) => { + const timer = setTimeout(() => reject(new Error('Responsive server timed out')),10000); + server.stdout.once('data', () => { clearTimeout(timer); resolve(); }); + server.once('error', reject); + server.once('exit', code => reject(new Error(`Server exited ${code}`))); + }); + browser = await chromium.launch(); + const fixtures = await createFixtures(browser); + const pdf = await PDFLib.PDFDocument.load(fixtures.replacement.buffer); + pdf.setTitle('Mobile metadata — 한국어 日本語 '.repeat(12)); + const pdfFile = { name: '모바일-メタデータ.pdf', mimeType: 'application/pdf', buffer: Buffer.from(await pdf.save()) }; + for (const language of ['en','ko','ja']) for (const theme of ['system','light','dark']) { + const context = await browser.newContext({ locale: language, colorScheme: theme === 'light' ? 'light' : 'dark', acceptDownloads: true }); + await context.addInitScript(({language,theme}) => { + // Exercise the browser download fallback without opening an OS save dialog. + delete window.showSaveFilePicker; + localStorage.setItem('secure-tools-language', language); + localStorage.setItem('secure-tools-theme', theme); + document.addEventListener('securitypolicyviolation', event => console.error(`CSP: ${event.effectiveDirective} ${event.blockedURI}`)); + }, {language,theme}); + context.on('request', request => { + if (!request.url().startsWith(origin + '/') && !/^(blob:|data:|about:)/.test(request.url())) report.external.push(request.url()); + }); + const page = await context.newPage(); + page.on('pageerror', error => report.errors.push(error.message)); + page.on('console', message => { if (message.type() === 'error') report.errors.push(message.text()); }); + for (const [width,height] of viewports) { + await page.setViewportSize({width,height}); + for (const route of routes) { + report.active = {language,theme,width,height,route}; + const response = await page.goto(origin + route); + if (!report.headerErrors.length) { + try { assertSecurityHeaders(new Headers(response.headers())); } + catch (error) { report.headerErrors.push(error.message); } + } + await page.waitForFunction(({language,theme}) => document.documentElement.lang === language && document.documentElement.dataset.theme === theme && document.querySelector('.header-menu')?.dataset.navigationReady === 'true', {language,theme}); + const menu = page.locator('.header-menu'); + const summary = menu.locator(':scope > summary'); + const mobile = width <= 608; + assert.equal(await menu.evaluate(el => el.open), !mobile); + if (mobile) { + assert.ok((await page.locator('.site-header').boundingBox()).height <= 80, 'Collapsed mobile header stays compact'); + assert.equal(await page.locator('.site-nav').isVisible(), false); + await summary.focus(); await page.keyboard.press('Enter'); + assert.equal(await menu.evaluate(el => el.open), true); + assert.equal(await page.locator('.site-nav a').count(), 4); + assert.ok(await page.locator('[data-language-select]').isVisible()); + assert.ok(await page.locator('[data-theme-select]').isVisible()); + assert.equal(await summary.innerText(), translations[language].common.menu); + await page.keyboard.press('Tab'); + assert.ok(await page.locator('.site-nav a').first().evaluate(el => el === document.activeElement), 'Links follow disclosure in tab order'); + await page.keyboard.press('Escape'); + assert.equal(await menu.evaluate(el => el.open), false); + assert.ok(await summary.evaluate(el => el === document.activeElement)); + } + const category = page.locator('.category-nav__inner'); + if (await category.count()) { + const rects = await category.locator('a').evaluateAll(links => links.map(link => { const r = link.getBoundingClientRect(); return {top:r.top,height:r.height}; })); + assert.ok(rects.every(r => Math.abs(r.top - rects[0].top) < 1 && r.height >= 44), 'Single-row category navigation retains touch targets'); + assert.equal(await page.locator('.category-nav [aria-current="page"]').count(), 1); + if (mobile) assert.ok((await page.locator('.category-nav').boundingBox()).height <= 64); + await category.evaluate(el => { el.scrollLeft = el.scrollWidth; }); + } + const scope = page.locator('.scope-note'); + if (await scope.count()) { + assert.ok(await scope.evaluate(el => { + const result = document.querySelector('.clean-result, .metadata-comparison'); + return !!(result.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING); + }), 'Scope follows results in source order at every viewport'); + } + const overflow = await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1); + assert.equal(overflow, false, `${language}/${theme}/${width} ${route}: page overflow`); + const clipped = await page.locator('select:visible').evaluateAll(selects => selects.filter(el => {const r=el.getBoundingClientRect(); return r.left < -1 || r.right > innerWidth + 1 || r.width < 40;}).map(el => el.id)); + assert.deepEqual(clipped, [], 'Visible selects stay inside viewport'); + assert.equal(await page.locator('h1').count(), 1); + assert.equal(await page.locator('.skip-link[href="#main"]').count(), 1); + // Populate metadata and settings pages at each width, including long CJK metadata. + if (theme === 'dark' && route.includes('/metadata/')) { + await page.locator('#file-input').setInputFiles(route.startsWith('/pdf') ? pdfFile : fixtures.english); + const clean = page.locator(route.startsWith('/pdf') ? '#clean-pdf' : '#clean-image'); + await clean.waitFor({state:'visible'}); + await page.waitForFunction(selector => !document.querySelector(selector).disabled, route.startsWith('/pdf') ? '#clean-pdf' : '#clean-image'); + const download = page.waitForEvent('download'); await clean.click(); await download; + await page.locator(route.startsWith('/pdf') ? '.metadata-comparison' : '.clean-result').waitFor({state:'visible'}); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false, 'Populated metadata has no page overflow'); + assert.ok((await scope.boundingBox()).y > (await page.locator('.metadata-workspace').boundingBox()).y); + } + if (language === 'ko' && theme === 'dark' && [320,390,768,1280].includes(width)) { + await page.screenshot({path:`${directory}/${width}-${route.replaceAll('/','_') || 'home'}.png`,fullPage:true}); + } + report.cases.push({language,theme,width,height,route,passed:true}); + } + } + // Native select keyboard and resolved system theme remain functional. + await page.setViewportSize({width:1280,height:900}); + await page.goto(origin + '/'); + await page.locator('[data-theme-select]').selectOption('light'); + await page.waitForFunction(() => document.documentElement.dataset.resolvedTheme === 'light'); + await page.locator('[data-theme-select]').selectOption('system'); + await page.emulateMedia({colorScheme:'dark',reducedMotion:'reduce'}); + await page.waitForFunction(() => document.documentElement.dataset.resolvedTheme === 'dark'); + await page.locator('[data-language-select]').selectOption(language); + if (language === 'en' && theme === 'system') { + const select = page.locator('[data-language-select]'); + await select.selectOption('en'); await select.focus(); + await page.keyboard.press('Space'); await page.keyboard.press('End'); await page.keyboard.press('Enter'); + assert.equal(await select.inputValue(), 'fr', 'Native popup supports keyboard selection'); + await select.selectOption('en'); + await page.keyboard.press('Space'); await page.keyboard.press('Escape'); + assert.equal(await select.inputValue(), 'en', 'Escape leaves selection unchanged'); + } + await context.close(); + console.log(`Responsive matrix: ${language}/${theme} complete (${report.cases.length} cases)`); + } + // All six localized menu names and no-JS semantic navigation fallback. + const context = await browser.newContext({javaScriptEnabled:false,viewport:{width:320,height:568}}); + const page = await context.newPage(); await page.goto(origin + '/'); + await page.locator('.header-menu > summary').click(); + assert.ok(await page.locator('.site-nav').isVisible()); + await context.close(); + for (const language of ['en','ko','ja','es','de','fr']) assert.ok(translations[language].common.menu); + assert.deepEqual(report.headerErrors, [], 'Served headers must preserve strict CSP'); + assert.deepEqual(report.external, [], 'No external requests or telemetry'); + assert.deepEqual(report.errors, [], 'No page/console/CSP errors'); + report.status = 'PASS'; + console.log(`Responsive/accessibility matrix passed: ${report.cases.length} cases, populated metadata, themes, keyboard and no-JS navigation.`); +} finally { + await fs.writeFile(`${directory}/report.json`, JSON.stringify(report,null,2)); + await browser?.close(); server.kill(); +} diff --git a/tests/i18n-quality.test.mjs b/tests/i18n-quality.test.mjs index 7ce23a2..36e5e46 100644 --- a/tests/i18n-quality.test.mjs +++ b/tests/i18n-quality.test.mjs @@ -46,7 +46,7 @@ function placeholders(value) { function testCatalogParityAndQuality() { assert.deepEqual([...Object.keys(translations)], [...languageNames.keys()]); const english = flatten(translations.en); - assert.equal(english.size, 896); + assert.equal(english.size, 897); for (const [language, catalog] of Object.entries(translations)) { const flattened = flatten(catalog); diff --git a/tests/typography-i18n-layout.test.mjs b/tests/typography-i18n-layout.test.mjs index 9871be8..c26ff54 100644 --- a/tests/typography-i18n-layout.test.mjs +++ b/tests/typography-i18n-layout.test.mjs @@ -43,7 +43,7 @@ function testLocaleWrappingPolicy() { const nowrapRules = [...css.matchAll(/([^{}]+)\{[^{}]*white-space:\s*nowrap/g)].map((match) => match[1].trim()); for (const selector of nowrapRules) { - assert.match(selector, /brand|visually-hidden|source-name|queue-name|metadata-table thead/, `Unexpected nowrap rule: ${selector}`); + assert.match(selector, /brand|visually-hidden|source-name|queue-name|metadata-table thead|category-nav a/, `Unexpected nowrap rule: ${selector}`); } } @@ -58,7 +58,8 @@ function testControlAndLongCopyLayout() { assert.match(tools, /\.tool-layout > \*[^}]*min-width:\s*0/); assert.match(tools, /\.mode-option strong, \.mode-option span\s*\{[^}]*overflow-wrap:\s*anywhere/); assert.match(metadata, /\.metadata-value\s*\{[^}]*overflow-wrap:\s*anywhere[^}]*white-space:\s*pre-wrap/); - assert.match(base, /body\s*\{[^}]*min-width:\s*20rem/); + assert.match(base, /html\s*\{[^}]*font-family:\s*var\(--font-sans\)/); + assert.match(base, /body\s*\{[^}]*min-width:\s*0/); } function testNoRemoteFontResources() { diff --git a/tools/image/compress/index.html b/tools/image/compress/index.html index 18576d1..699da4f 100644 --- a/tools/image/compress/index.html +++ b/tools/image/compress/index.html @@ -22,7 +22,9 @@ <title>Image Compressor — Secure Tools - +

Image tool

Image Compressor

Re-encode JPEG, PNG, and WebP images locally and compare the resulting file sizes.

Add your images

Drop files here or use the picker. JPEG, PNG, and WebP can be mixed.

Processed locally. Your images never leave this device. How privacy works

diff --git a/tools/image/converter/index.html b/tools/image/converter/index.html index 55654f8..cbd2d31 100644 --- a/tools/image/converter/index.html +++ b/tools/image/converter/index.html @@ -38,16 +38,12 @@ -
diff --git a/tools/image/index.html b/tools/image/index.html index 0fd9349..0a7d603 100644 --- a/tools/image/index.html +++ b/tools/image/index.html @@ -37,20 +37,17 @@ -
+