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 new file mode 100644 index 0000000..7c60bf9 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,22 @@ +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] " + - 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/ci.yml b/.github/workflows/ci.yml index e278d6b..8aeab54 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 @@ -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 @@ -70,8 +70,41 @@ 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 - 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: Verify responsive navigation, metadata layouts and accessibility + run: node tests/browser/responsive.mjs + + - name: Inspect isolated release review artifact + run: node scripts/inspect-release-artifact.mjs + + - name: Retain inspected release review artifact + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: release-review-${{ github.sha }} + path: .ts-build/release-review + if-no-files-found: error + retention-days: 7 + + - 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 + .ts-build/responsive + retention-days: 7 diff --git a/.github/workflows/deploy-cloudflare-bridge.yml b/.github/workflows/deploy-cloudflare-bridge.yml index 36b3404..a9c3401 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 @@ -77,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" ]] @@ -126,8 +119,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 }} @@ -139,6 +131,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 +144,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..cec6ebf 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 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false - - uses: actions/setup-node@v4 + # Read canonical version and verification code from the expected deployment. + ref: ${{ inputs.source_commit || github.sha }} + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 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 @@ -49,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/.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/404.html b/404.html index f8b9386..afdc408 100644 --- a/404.html +++ b/404.html @@ -21,7 +21,9 @@ - +

404

This page is not here.

The address may be outdated or mistyped.

Return home
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/CHANGELOG.md b/CHANGELOG.md index ad6b466..7e54d3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,43 @@ # Changelog -## Unreleased +## 2.3.0 — Release candidate, unpublished + +### Security and reliability + +- Bind CI artifacts to the source commit and canonical package version through + `/build-info.json`; live production equality remains a release-time gate. +- Pin all external GitHub Actions to reviewed full SHAs; prepare reviewed weekly + Actions/npm maintenance, whose default-branch activation is still pending. +- Require `%PDF-` at byte zero before original-source PDF parsing. Signature + admission is not a parser safety or resource-budget guarantee. +- Add root SECURITY.md, supported-version boundaries and verified GitHub private + vulnerability reporting. +- Deliver the reviewed HTTP CSP, no-referrer, Permissions-Policy and nosniff policy + in the isolated Pages artifact. Live delivery is not yet signed off. +- Add JS/TS CodeQL and exact lockfile/vendor advisory monitoring. Nested/native + dependency coverage remains incomplete; no-known-advisory results are bounded. +- Retain pdf-lib 1.17.1 and JSZip 3.10.1 following the maintenance assessment; + investigate a pdf-lib successor separately in v2.4, without an automatic upgrade. +- Exclude repository instructions, package manifests and build configs from the + public artifact root; retain license metadata and isolate Cloudflare CNAME removal. + +### UX + +- Compact mobile navigation, language and theme into a native disclosure, with + keyboard/Escape support and usable navigation without JavaScript. +- Reduce category-bar padding, keep one scrollable row and retain touch targets. +- Improve mobile workspace spacing, intended system-font inheritance and narrow + viewport fit without changing the brand or adding a component framework. +- Move both metadata scope cards after results on desktop/mobile, preserving all + supported-scope limitations. +- Theme native selects and supported desktop pickers while retaining mobile + platform pickers and existing form/accessibility behavior. + +Image OCR, PDF OCR/TXT and searchable PDF export are existing v2.2 capabilities, +not newly introduced v2.3 tools. Release notes are a candidate record, not +production GO, audit closure, release publication or deployment authorization. + +## Earlier development history ### Added diff --git a/README.md b/README.md index 3f5be16..685215a 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ See the [privacy model](./docs/privacy-model.md) for exact guarantees and bounda - [PDF Organizer](https://tools.securetools.app/pdf/organize/) — preview, reorder, rotate, remove, and export pages. - [PDF to Images](https://tools.securetools.app/pdf/to-images/) — render pages to PNG, JPEG, or WebP. - [PDF Metadata Inspector & Cleaner](https://tools.securetools.app/pdf/metadata/) — inspect and remove supported document-info fields. +- [PDF to Text OCR](https://tools.securetools.app/pdf/to-text/) — recognize selected pages locally and save text or a searchable PDF. ### Image @@ -32,10 +33,11 @@ See the [privacy model](./docs/privacy-model.md) for exact guarantees and bounda - [Image Resize](https://tools.securetools.app/image/resize/) — resize batches by pixels or percentage. - [Image Compressor](https://tools.securetools.app/image/compress/) — quality-compress images and compare byte results. - [Image Metadata Inspector & Cleaner](https://tools.securetools.app/image/metadata/) — inspect supported metadata and save a verified cleaned copy without pixel re-encoding. +- [Image to Text OCR](https://tools.securetools.app/image/to-text/) — recognize English/Korean text locally and save editable UTF-8 text. ### Privacy -The [Privacy hub](https://tools.securetools.app/privacy/) links to the specialized Image and PDF metadata tools. It is a cross-category navigation surface, not a generic sanitizer. Scan/OCR and Media remain planned. +The [Privacy hub](https://tools.securetools.app/privacy/) links to the specialized Image and PDF metadata tools. It is a cross-category navigation surface, not a generic sanitizer. The Scan & OCR category links to the existing OCR tools; document scanning and Media tools remain planned. Detailed formats, limits, and behavior are listed in [tool status](./docs/tool-status.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/about/index.html b/about/index.html index a1d4607..47f146e 100644 --- a/about/index.html +++ b/about/index.html @@ -34,21 +34,17 @@ - + +

About

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/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/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/README.md b/docs/README.md index a7e6b91..e33a408 100644 --- a/docs/README.md +++ b/docs/README.md @@ -25,6 +25,10 @@ The root [README](../README.md) introduces Secure Tools. This directory owns det ## Release evidence +- [v2.3 release readiness](./v2.3-release-readiness.md) freezes feature scope, + inventories the integration delta and open findings, and separates candidate + artifact validation from the later [production verification gate](./v2.3-post-deploy-checklist.md). + - [v1.0.0 release QA](./release-qa.md) is a historical Sprint 11 release-candidate snapshot. Its unchecked items remain historical and are not current requirements. - [v2 promotion QA](./v2-release-qa.md) preserves the automated, manual Chrome, Orientation-regression, and promotion evidence for the v2.0.0 pre-release line. - The root [changelog](../CHANGELOG.md) records release and change history; it is not a technical specification. 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/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..aa399ae --- /dev/null +++ b/docs/v2.3-bootstrap.md @@ -0,0 +1,478 @@ +# 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 | 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 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 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 + +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 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` | 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). +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 + +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. + +### 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. + +### 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. + +### 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 + +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 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. + +| 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 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 | +| `@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 | + +### 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 + +- **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). +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, now integrated through PR #122. Issue #117 implements hosting headers +now integrated through PR #123, with production verification pending. Recommended next +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 + +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) + +The refreshed provenance branch incorporates the reviewed bootstrap policy from +PR #119 through the integration branch. The baseline audit matrix is retained; +this section supersedes its historical F-06 implementation gap. Issue #112 remains +open until live production verification is completed. + +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 generated artifact contains `dist/build-info.json`; its public path after +production promotion will be `/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/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. 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/docs/v2.3-post-deploy-checklist.md b/docs/v2.3-post-deploy-checklist.md new file mode 100644 index 0000000..96c2352 --- /dev/null +++ b/docs/v2.3-post-deploy-checklist.md @@ -0,0 +1,135 @@ +# v2.3.0 production verification — later authorization required + +No step here authorizes merging to main, deploying, tagging or publishing. +Use a clean GitHub-hosted Ubuntu runner for authoritative HTTP/browser evidence; +local AdGuard rewriting must fail closed and must not change expected headers. + +## Before authorized promotion + +1. Review/merge the release-readiness PR into `v2.3` only with explicit permission. + Confirm package/lock root version `2.3.0`, frozen feature scope, no new blockers, + and green CI/security checks at the final integration SHA. +2. Open/review the dedicated `v2.3` to `main` release PR. Require separate explicit + merge authorization; never squash/rebase the preserved sprint history. +3. Record the actual resulting **main merge commit** as `RELEASE_SHA`. Do not use + the integration head or the PR's synthetic test merge as production identity. + The current workflow automatically deploys main pushes: authorization to + merge must explicitly account for this deployment trigger. + +## Artifact and deployment identity + +4. Verify main CI and `Deploy Cloudflare bridge` checkout/build source are + `RELEASE_SHA`, version `2.3.0`, Node 24, locked dependency inputs and prepared + asset hashes/licenses. Check the CI-generated record before upload: + + ```text + schemaVersion = 1 + commit = RELEASE_SHA (40 lowercase hex characters) + version = 2.3.0 + build.source = github-actions + ``` + + The reviewed candidate archive/digest identifies its own CI build only. A + later main build has a different source SHA and must be checked again. A ZIP + digest/source record is not a signed attestation or reproducibility proof. +5. Check isolated deployment output contains `_headers`, `_redirects`, license + metadata and the full expected site; no CNAME, test/debug/config/agent files, + TS source/maps, runtime CDN or injected telemetry. Root/generic CNAME must + remain `securetools.app`; strip only the isolated Cloudflare copy. +6. Record the successful deployment run, GitHub deployment, Cloudflare deployment + ID and **new immutable URL** from that run. Confirm the expected project, + canonical custom domain and disabled Web Analytics without changing settings + as part of verification. Never reuse an old immutable URL as release evidence. + +## F-05: live HTTP policy + +7. Check canonical `https://tools.securetools.app` and the new immutable origin on + `/`, `/pdf/merge/`, `/image/to-text/`, `/pdf/to-text/`, `/build-info.json`. + Use real HTTP responses without redirects/fallback HTML. The existing clean + browser smoke calls the shared strict `assertSecurityHeaders` validator. + Require on each document/JSON response: + + - CSP default/script/style/font sources restricted to self; `img-src 'self' + blob: data:`; `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`. + + Keep the already-reviewed narrow Tesseract entry-worker header-detach exception; + do not infer that document CSP may be relaxed. PDF.js retains strict policy. + Verify canonical indexing remains allowed and pages.dev aliases retain noindex. + +## F-06 / Issue #112: live provenance equality + +8. Check out `RELEASE_SHA`, then run on the clean runner with the actual immutable + URL (substitute the recorded values, never run literal angle-bracket labels): + + ```sh + node scripts/verify-build-provenance.mjs https://tools.securetools.app "$RELEASE_SHA" + node scripts/verify-build-provenance.mjs "$IMMUTABLE_ORIGIN" "$RELEASE_SHA" + node tests/deployment-smoke.mjs "$IMMUTABLE_ORIGIN" noindex + node tests/deployment-smoke.mjs https://tools.securetools.app indexable + ``` + + Confirm HTTP 200 JSON, strict schema, version `2.3.0`, source `github-actions`: + + ```text + main/release source SHA == CI build-info commit + == immutable build-info commit + == canonical production build-info commit + ``` + + Existing bounded alias retries allow propagation; do not accept stale bytes. + Only after equality and browser checks pass is #112 eligible for closure of + its compact-provenance scope. Full manifests/attestation/reproducible builds + were not implemented and must not be claimed. + +## Production browser gate + +9. Dispatch **Production smoke** at the reviewed main workflow with inputs: + `production_origin=https://tools.securetools.app`, `immutable_origin` equal to + the recorded new URL, and `source_commit=RELEASE_SHA`. Verify checkout uses the + same SHA. Do not dispatch it during preparation. +10. Require all existing production gates: canonical/immutable assets/locales, + strict headers/provenance, English/Korean OCR, exact TXT and searchable PDF + downloads, visible content preservation, cancellation/retry/replacement, + object URL cleanup, zero external requests/analytics, console/page errors or + CSP violations. Record the successful hosted summary; failures mean NO-GO. + +## F-02 / F-04: default-branch activation + +11. Confirm `.github/dependabot.yml` is now present on default branch main, with + Actions/npm weekly entries targeting `v2.3` and reviewed commit prefixes. + Confirm recognition through **Insights → Dependency graph → Dependabot** / + update-job configuration logs showing both ecosystems, or an available API + exposing equivalent recognized jobs. A source file alone is insufficient + evidence of recognition; do not require an immediate dependency PR. + If the token/API cannot expose this, record the specific missing evidence + and request maintainer UI evidence; do not broaden credentials silently. +12. Distinguish version-update configuration from Dependabot alerts/security + updates (observed disabled before promotion). Default-branch placement does + not itself enable these separate settings; no automatic merges or silent + setting changes are approved. Record the actual state and scoped limitation. +13. Confirm **Security monitoring** runs on the actual main SHA and succeeds for + CodeQL JS/TS upload plus exact lockfile/vendor advisories. Read the resulting + default-branch analysis, not only a PR status. Keep nested/native bundle, + unpublished-project and undisclosed-advisory limitations explicit. + +## Closure and remaining manual work + +14. Update #111/#113/#116/#117/#112 only to the extent supported by collected + activation/live evidence; verify implementation issues #114/#115/#128 and + release closing links. A merged implementation is not automatic audit closure. +15. Retain #126 as v2.4 work; keep JSZip deferred. Record physical iOS Safari and + Android Chrome pickers plus VoiceOver/TalkBack header/menu/select checks as + manual follow-up without blocking solely on device access. +16. Declare production GO only after the above gates pass. Tag/release publication + requires new explicit authorization after verification. Update SECURITY.md's + latest stable row when the GitHub release is actually published; do not + advertise an unpublished candidate as supported stable. + +References: [default-branch Dependabot placement](https://docs.github.com/en/code-security/concepts/supply-chain-security/about-the-dependabot-yml-file), +[target-branch/version versus security updates](https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference), +[artifact digests](https://docs.github.com/en/actions/tutorials/store-and-share-data). diff --git a/docs/v2.3-release-pr-draft.md b/docs/v2.3-release-pr-draft.md new file mode 100644 index 0000000..1992601 --- /dev/null +++ b/docs/v2.3-release-pr-draft.md @@ -0,0 +1,60 @@ +# Prepared v2.3.0 release PR body + +PR #130 is integrated at `4c24ffbd77514cfdfd70ddcb4c560492561c29e5`. +Base `main`, head `v2.3`, title `🚀[Deploy] Release v2.3.0`. +The submitted PR records the final documentation-head SHA, latest checks and +candidate artifact; confirm no duplicate release PR before creating one. + +## Summary + +Prepare v2.3.0 security/reliability hardening and mobile UX improvements on the +existing v2.2 local-only tool baseline. No new document/media tools or dependency +upgrades are included. Image/PDF OCR and searchable PDF export already existed. + +## Security and reliability changes + +- Compact commit/version CI provenance; strict future canonical/immutable equality. +- Full-SHA Action pins and reviewed weekly maintenance configuration. +- Shared byte-zero PDF signature admission, retaining parser/resource limitations. +- SECURITY.md and private reporting route. +- Reviewed HTTP headers, preserving the existing narrow OCR worker exception. +- CodeQL JS/TS, exact lockfile/vendor/project advisories and unchanged release pins. +- Explicit dependency-maintenance decisions: keep pdf-lib/JSZip; scope v2.4 separately. +- Public artifact root allowlist, isolated CNAME removal and review artifact inspection. + +## UX changes + +Native mobile navigation disclosure, compact category scrolling, shared workspace +spacing, metadata limitations after results, corrected system-font/narrow fit, +and native select theming with mobile system pickers retained. Six locales, +keyboard, reduced motion, local-only processing and CSP remain supported. + +## Known release-time verification still required + +- Live HTTP header enforcement on canonical and new immutable deployment. +- `/build-info.json` equals the **actual main release source SHA**, version 2.3.0, + CI source marker and strict schema on both origins. +- Default-branch Dependabot configuration recognition and actual main CodeQL/ + advisory runs. Nested/native coverage remains incomplete; version-update + recognition does not silently enable separate Dependabot security settings. +- Clean hosted production smoke/browser verification; physical mobile/AT follow-up. + +## Test evidence + +Fresh merged integration passed +[full CI](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/40979245684) +and [security monitoring](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/40979245857), +including artifact inspection, real OCR/download/cancellation and all 441 +responsive cases. Before submission, refresh to the final documentation-head +CI and archive digest. Two existing High-labeled CodeQL test-helper diagnostics +are reviewed in the readiness record, remain open and are not claimed fixed. +These are pre-production results; do not reuse old production signoff. +See [readiness record](./v2.3-release-readiness.md) and +[post-deploy checklist](./v2.3-post-deploy-checklist.md). + +## Release boundary + +This PR prepares production promotion. Merge/deployment/tagging require separate +explicit authorization. Main pushes currently trigger the deployment workflow; +review that consequence before authorizing the release merge. This is not +production GO or full audit closure. diff --git a/docs/v2.3-release-readiness.md b/docs/v2.3-release-readiness.md new file mode 100644 index 0000000..c432d04 --- /dev/null +++ b/docs/v2.3-release-readiness.md @@ -0,0 +1,247 @@ +# v2.3.0 release-readiness record + +## Final integration review — 2026-10-30 + +PR #129 was merged normally into `v2.3` at +`4e6adf734876db6f77e601c25c4e13a2c59fcd7f` after clean review/check preflight. +Its expected head was `f4a549cf72b62b8c1336c735ae61afd119d926be`, one commit, +39 files, no blocking review or unresolved thread. No dependency, parser or +production changes were introduced by that UX PR. + +Main remains `4b07f2962e524f4cfa5736de35e0f31ad52aaa15` / published `v2.2.0`. +PR #130 merged normally on 2026-10-30 at +`4c24ffbd77514cfdfd70ddcb4c560492561c29e5`, preserving reviewed commits +`77a53ae63b776aedaa8816bca2d27eb54d0b2af5` and +`1154bf069d15d2a57f225bdc9dc610a7ef32757e`. No unrelated commits landed +between the October 15 review and this run. At that merge, integration is +**22 commits ahead, zero behind**, with 103 changed files, 2,953 additions and +247 deletions. The subsequent documentation-only refresh does not alter runtime +or build behavior. Final SHA/compare counts and checks are recorded in the release +PR to avoid a self-referential source SHA in this document. + +**Feature scope is frozen.** Only release blockers, regression/build/deployment +fixes, release documentation, required security hardening and production +verification support may enter. No scope exceptions are introduced here. + +## Version and concrete artifact findings + +`scripts/build-provenance.mjs` reads the canonical version from `package.json`. +Integration now reports **2.3.0** in package.json and both root lockfile version +fields, replacing the previous 0.0.0 placeholder. Dependency +entries, resolved URLs, integrity values and vendored runtime bytes remain unchanged. + +Inspection also found root-page sibling copying published `.gitignore`, AGENTS, +README/changelog/security policy, npm manifests and TypeScript build configs in +dist. The integrated fix copies public root files explicitly, enforces a strict +artifact root allowlist and an injection regression, and excludes empty scaffolding. +It retains LICENSE and generic/root +CNAME ownership; only the existing isolated Cloudflare copy strips CNAME. + +The CI review artifact runs the **actual deployment preparation recipe** without +credentials/deployment and retains the resulting site plus inspection record for +seven days. Its GitHub artifact SHA-256 is archive integrity evidence, not a +reproducible-build claim. A PR's synthetic CI merge SHA is a candidate source; +the future main merge and deployment must be verified independently. + +## Open-item inventory + +GitHub snapshot after #130 merge: no other open PRs and no new issues created +after the October 15 readiness review. Open issues below include historical +body text that predates their integrated implementation; classification uses +merged commits, current source and verification, not stale body statuses. + +| Item | Classification | Reason / exit criterion | +| --- | --- | --- | +| Canonical integration version | RESOLVED | package.json/root-lock metadata is 2.3.0 through #130 | +| Unexpected public root files | RESOLVED | Explicit build/validation fix and negative regression integrated; isolated candidate inspection passes | +| #130 hardening integration | RESOLVED | Explicitly authorized normal merge completed at the recorded integration SHA | +| #111 bootstrap/audit umbrella | RELEASE-VERIFY | Reconcile final findings with actual activation/live evidence; no blanket audit closure | +| #112 / F-06 provenance | RELEASE-VERIFY | Live main/CI/canonical/immutable SHA and version equality required | +| #113 / F-02 Action maintenance | RELEASE-VERIFY | SHA pins implemented; verify default-branch configuration recognition after promotion | +| #114 PDF admission | NOT-APPLICABLE | Required implementation integrated via #122 and regressions pass; not an outstanding blocker | +| #115 disclosure | NOT-APPLICABLE | SECURITY.md integrated via #124; private reporting verified; stable remains v2.2.0 until publication | +| #116 / F-04 monitoring | RELEASE-VERIFY | PR/integration checks exist; verify main analysis/automation; nested/native coverage remains partial | +| #117 / F-05 headers | RELEASE-VERIFY | Policy integrated via #123; live canonical/immutable responses and browser behavior required | +| #128 mobile UX | NOT-APPLICABLE | Integrated via #129 with 441-case clean CI; issue still open because closing linkage targets integration, not default main | +| #126 pdf-lib investigation | POST-RELEASE | Bounded v2.4 prototype only; no new blocker evidence identified | +| Physical iOS/Android + VoiceOver/TalkBack | POST-RELEASE | Browser matrix passes; record manual device/AT results when available | +| JSZip compatibility refresh | POST-RELEASE | DEFER decision retained; no version change or new supported input requirement | +| CodeQL alerts #1/#2 in test helpers | NOT-APPLICABLE | Reviewed existing diagnostics do not establish a production vulnerability; remain open with context below | + +No known unpatched P0/Critical/High issue requiring action was identified in the +current exact-input advisory evidence. This does not establish comprehensive +coverage or vulnerability absence. No new dependency candidate was adopted. + +F-01 and F-03 are implemented. F-02/F-04/F-05/F-06 retain their explicit limits. +Live checks are release-time gates, not reasons by themselves to block preparation. + +### Existing CodeQL diagnostics reviewed + +The actual integration analysis +[2058862880](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/40979245857) +completed with 87 rules and two results, not zero. Both alerts were created on +2026-10-15 and remain open; no dismissal or suppression was performed: + +- [Alert #1](https://github.com/SecureToolsProject/Secure_Tools/security/code-scanning/1), + High-labeled `js/incomplete-sanitization`, flags the test's regex construction + in `tests/file-input-queue-state.test.mjs`. Its inputs are the fixed repository + strings `renderQueue()`, `render()` and `renderSource()`; none contains a + backslash, and there is no user-controlled escaping boundary or runtime sink. +- [Alert #2](https://github.com/SecureToolsProject/Secure_Tools/security/code-scanning/2), + High-labeled `js/incomplete-url-substring-sanitization`, flags a **negative** + absence assertion against `local.adguard.org` in saved-artifact HTML inside + `tests/verify-hardening-network.mjs`. That assertion rejects any occurrence; + it does not authorize a hostname. The earlier resource-origin decision uses + parsed `URL.origin` exact equality. This historical diagnostic is outside the + current CI/production smoke entry points, which allow no external traffic. + +The rule labels alone do not establish an unpatched High production issue in +these contexts. Record test-helper/scanner clarity as follow-up; revisit this +assessment if the strings become externally driven or these diagnostic paths +become a release trust decision. The clean CI/security workflows remain required. + +## Toolchain and verification + +Local Node **24.16.0**, npm **11.13.0**; package engine `>=24`; CI uses Node 24. +Pinned TypeScript **7.0.2**, Playwright **1.63.0** and its packaged Chromium. +CI runner OS/browser/tool versions are recorded by the run; Ubuntu latest is a +moving image, not a pinned toolchain/reproducibility guarantee. + +Run pinned install, full tests/typecheck, security/release/Action/monitoring gates, +fresh npm/vendor/project advisories, production build/provenance/artifact/CNAME +inspection, real English/Korean/combined OCR, browser export/cancel gates and +441 responsive cases (seven sizes, seven routes, EN/KO/JA, three themes), plus +six-catalog structural/i18n and native no-JS navigation checks. + +The merged #130 source passed fresh October 30 +[full integration CI](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/40979245684) +and [CodeQL/advisories](https://github.com/SecureToolsProject/Secure_Tools/actions/runs/40979245857). +This includes strict HTTP/CSP, real OCR/native downloads/cancellation, all 441 +responsive cases, no-JS navigation, six locales and isolated artifact inspection. +Fresh lockfile/vendor/project advisory queries returned no known advisory matches +within their documented coverage. Final documentation-head CI and candidate ZIP +digest/provenance evidence are recorded in the dedicated release PR. +Local AdGuard rewrites headers/injects external scripts; +strict local failures must remain failures. Only clean hosted runs establish the +complete HTTP/CSP/browser security result; no gate is weakened. + +## Release decision and handoff + +**Pre-release state: READY_FOR_RELEASE_PR_REVIEW.** Version and artifact-root +blockers are resolved through #130, fresh integration CI/security checks pass, +and no concrete release blocker was found. The documentation-only refresh and +dedicated release PR must retain green checks at their final tested sources. + +The [prepared release PR body](./v2.3-release-pr-draft.md) and +[exact post-deploy checklist](./v2.3-post-deploy-checklist.md) are prepared. +Open the dedicated `v2.3` to `main` release PR after final checks. +Opening that PR does not authorize its merge, main's push-triggered deployment, +tagging or release publication. No production operation occurs in this pass. + +## Complete release file inventory versus main + +Paths below are repository-relative. A = added, M = modified; no removals. + +- A: .github/codeql/config.yml +- A: .github/dependabot.yml +- M: .github/workflows/ci.yml +- M: .github/workflows/deploy-cloudflare-bridge.yml +- M: .github/workflows/production-smoke.yml +- A: .github/workflows/security-monitoring.yml +- M: 404.html +- M: AGENTS.md +- M: CHANGELOG.md +- M: README.md +- A: SECURITY.md +- M: about/index.html +- A: config/cloudflare/_headers +- A: config/security/vendor-dependencies.json +- A: config/security/vendor-release-pins.json +- M: css/base.css +- M: css/categories.css +- M: css/components.css +- M: docs/README.md +- M: docs/development-workflow.md +- M: docs/production-verification.md +- A: docs/v2.3-bootstrap.md +- A: docs/v2.3-dependency-maintenance-assessment.md +- A: docs/v2.3-mobile-ux.md +- A: docs/v2.3-post-deploy-checklist.md +- A: docs/v2.3-release-pr-draft.md +- A: docs/v2.3-release-readiness.md +- M: index.html +- M: js/locales/de.js +- M: js/locales/en.js +- M: js/locales/es.js +- M: js/locales/fr.js +- M: js/locales/ja.js +- M: js/locales/ko.js +- M: js/main.js +- A: js/navigation.js +- M: package-lock.json +- M: package.json +- M: privacy/index.html +- A: scripts/build-provenance.mjs +- M: scripts/build-site.mjs +- A: scripts/check-security-advisories.mjs +- A: scripts/http-security-headers.mjs +- A: scripts/inspect-release-artifact.mjs +- A: scripts/security-inventory.mjs +- A: scripts/validate-action-pins.mjs +- M: scripts/validate-branch-policy.mjs +- M: scripts/validate-build.mjs +- A: scripts/verify-build-provenance.mjs +- A: tests/action-pins.test.mjs +- M: tests/branch-policy.test.mjs +- A: tests/browser/responsive.mjs +- A: tests/build-provenance.test.mjs +- M: tests/ci-foundation.test.mjs +- M: tests/cloudflare-bridge.test.mjs +- M: tests/deployment-smoke.mjs +- M: tests/i18n-quality.test.mjs +- M: tests/pdf-metadata.test.mjs +- M: tests/pdf-ocr-foundation.test.mjs +- A: tests/pdf-signature.test.mjs +- M: tests/pdf-to-text.test.mjs +- A: tests/production/local-smoke.mjs +- M: tests/production/smoke.mjs +- A: tests/release-artifact.test.mjs +- M: tests/release-gate.test.mjs +- M: tests/release-hardening-http.test.mjs +- M: tests/run-all.mjs +- M: tests/searchable-pdf.test.mjs +- M: tests/security-hardening.test.mjs +- A: tests/security-monitoring.test.mjs +- M: tests/serve-ocr-smoke.mjs +- M: tests/typography-i18n-layout.test.mjs +- M: tools/image/compress/index.html +- M: tools/image/converter/index.html +- M: tools/image/index.html +- M: tools/image/metadata/index.html +- M: tools/image/metadata/tool.css +- M: tools/image/resize/index.html +- M: tools/image/to-text/index.html +- M: tools/media/index.html +- M: tools/pdf/images-to-pdf/index.html +- M: tools/pdf/index.html +- M: tools/pdf/merge/app.js +- M: tools/pdf/merge/index.html +- M: tools/pdf/metadata/app.js +- M: tools/pdf/metadata/index.html +- M: tools/pdf/metadata/pdf.js +- M: tools/pdf/metadata/tool.css +- M: tools/pdf/organize/app.js +- M: tools/pdf/organize/index.html +- M: tools/pdf/organize/pdf.js +- M: tools/pdf/split/app.js +- M: tools/pdf/split/index.html +- M: tools/pdf/to-images/app.js +- M: tools/pdf/to-images/index.html +- M: tools/pdf/to-text/index.html +- M: tools/scan/index.html +- M: tools/shared/pdf-ocr.ts +- M: tools/shared/pdf-renderer.js +- M: tools/shared/pdf.d.ts +- M: tools/shared/pdf.js +- M: tools/shared/searchable-pdf.ts +- M: tools/shared/tool.css diff --git a/index.html b/index.html index 1040b0e..b5ec6da 100644 --- a/index.html +++ b/index.html @@ -34,19 +34,16 @@ -
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/package-lock.json b/package-lock.json index 81ccc27..cf7c553 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "secure-tools-web-utilities", - "version": "0.0.0", + "version": "2.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "secure-tools-web-utilities", - "version": "0.0.0", + "version": "2.3.0", "dependencies": { "@fontsource/noto-sans-kr": "5.3.0", "@pdf-lib/fontkit": "1.1.1", diff --git a/package.json b/package.json index c107991..0b01aed 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "secure-tools-web-utilities", - "version": "0.0.0", + "version": "2.3.0", "private": true, "type": "module", "scripts": { 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 @@ - + +

Privacy model

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..f0c2fca 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 }); @@ -14,7 +17,7 @@ fs.mkdirSync(output, { recursive: true }); for (const directory of ["assets", "css", "js"]) { fs.cpSync(path.join(root, directory), path.join(output, directory), { recursive: true, - filter: (source) => !/\.(?:d\.ts|ts|tsx|map)$/.test(source), + filter: (source) => path.basename(source) !== ".gitkeep" && !/\.(?:d\.ts|ts|tsx|map)$/.test(source), }); } fs.cpSync(path.join(root, "tools", "shared"), path.join(output, "shared"), { @@ -30,6 +33,9 @@ for (const { source, route } of canonicalPages) { fs.copyFileSync(path.join(root, source), destination); const sourceDirectory = path.dirname(path.join(root, source)); + // The root page has no sibling tool assets. Copy its public files explicitly + // below rather than publishing package manifests, agent policy or build config. + if (sourceDirectory === root) continue; for (const entry of fs.readdirSync(sourceDirectory, { withFileTypes: true })) { if (entry.name === "index.html" || entry.isDirectory() || /\.(?:d\.ts|ts|tsx|map)$/.test(entry.name)) continue; fs.copyFileSync(path.join(sourceDirectory, entry.name), path.join(path.dirname(destination), entry.name)); @@ -44,11 +50,13 @@ for (const module of compiledBrowserModules) { fs.copyFileSync(source, destination); } -for (const file of ["404.html", "robots.txt", "sitemap.xml"]) { +for (const file of ["404.html", "robots.txt", "sitemap.xml", "LICENSE", "CNAME"]) { fs.copyFileSync(path.join(root, file), path.join(output, file)); } 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/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/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/inspect-release-artifact.mjs b/scripts/inspect-release-artifact.mjs new file mode 100644 index 0000000..d5a26fc --- /dev/null +++ b/scripts/inspect-release-artifact.mjs @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { canonicalVersion, validateBuildProvenance } from './build-provenance.mjs'; + +// Execute the deployed packaging recipe without credentials or any deployment. +const review = path.resolve('.ts-build/release-review'); +assert.equal(path.dirname(review),path.resolve('.ts-build')); +fs.rmSync(review,{recursive:true,force:true}); fs.mkdirSync(review,{recursive:true}); +const artifact = path.join(review,'site'); +const workflow = fs.readFileSync('.github/workflows/deploy-cloudflare-bridge.yml','utf8'); +const preparation = workflow.match(/- name: Prepare isolated bridge artifact[\s\S]*?run: \|\n([\s\S]*?)\n - name:/)?.[1]; +assert.ok(preparation,'Actual isolated deployment recipe must exist'); +const shell = process.platform === 'win32' ? path.join(process.env.ProgramFiles,'Git/bin/bash.exe') : 'bash'; +const target = process.platform === 'win32' ? artifact.replaceAll('\\','/').replace(/^([A-Za-z]):\//,(_,drive)=>`/${drive.toLowerCase()}/`) : artifact; +const result = spawnSync(shell,['-e','-o','pipefail','-c',preparation.replace(/^ /gm,'')],{env:{...process.env,BRIDGE_DIRECTORY:target},stdio:'inherit'}); +assert.equal(result.status,0,'Release review must pass actual deployment packaging'); +const info = validateBuildProvenance(artifact); +assert.match(canonicalVersion,/^[1-9]\d*\.\d+\.\d+$/,'Release version must be intentional, not placeholder 0.0.0'); +assert.equal(info.version,canonicalVersion); +assert.ok(!fs.existsSync(path.join(artifact,'CNAME'))); +assert.equal(fs.readFileSync('CNAME','utf8').trim(),'securetools.app'); +assert.equal(fs.readFileSync('dist/CNAME','utf8').trim(),'securetools.app'); +const files = []; +function visit(directory) { + for (const entry of fs.readdirSync(directory,{withFileTypes:true})) { + const file = path.join(directory,entry.name); + if (entry.isDirectory()) visit(file); + else files.push(path.relative(artifact,file).replaceAll('\\','/')); + } +} +visit(artifact); files.sort(); +for (const file of files) { + assert.doesNotMatch(file,/(^|\/)(?:node_modules|tests|scripts|\.git)(\/|$)|\.(?:ts|tsx|map)$/,'No test/build/debug files'); + if (file.endsWith('.html')) { + const html = fs.readFileSync(path.join(artifact,file),'utf8'); + assert.doesNotMatch(html,/]+src=["']https?:|]+rel=["']stylesheet["'][^>]+href=["']https?:/i,'No runtime CDN'); + assert.doesNotMatch(html,/static\.cloudflareinsights\.com|\/cdn-cgi\/rum|beacon\.min\.js/i,'No telemetry injection'); + } +} +const report = {provenance:info,fileCount:files.length,files,isolatedCnameAbsent:true,headersPresent:fs.existsSync(path.join(artifact,'_headers')),note:'Review candidate only; future main/deployment SHA must be verified separately. Not an attestation or reproducible-build proof.'}; +fs.writeFileSync(path.join(review,'inspection.json'),JSON.stringify(report,null,2)+'\n'); +console.log(JSON.stringify({...report,files:undefined},null,2)); 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/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/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/scripts/validate-build.mjs b/scripts/validate-build.mjs index 5526432..f5e4d67 100644 --- a/scripts/validate-build.mjs +++ b/scripts/validate-build.mjs @@ -5,9 +5,19 @@ 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 expectedRootFiles = ["index.html", "404.html", "robots.txt", "sitemap.xml", "LICENSE", "_headers", "_redirects", "build-info.json", ...(process.argv[2] ? [] : ["CNAME"])]; +const expectedRootDirectories = new Set(["assets", "css", "js", "shared", ...canonicalPages.map(({route}) => route.split('/')[1]).filter(Boolean)]); +for (const entry of fs.readdirSync(output, { withFileTypes: true })) { + assert.ok(entry.isDirectory() ? expectedRootDirectories.has(entry.name) : expectedRootFiles.includes(entry.name), `Unexpected artifact root entry: ${entry.name}`); +} +for (const file of expectedRootFiles) assert.ok(fs.statSync(path.join(output, file)).isFile(), `Missing public root file: ${file}`); const htmlFiles = []; const outputFiles = []; @@ -23,6 +33,7 @@ function visit(directory) { } visit(output); +assert.ok(outputFiles.every(file => path.basename(file) !== ".gitkeep"), "Production output excludes repository scaffolding"); assert.equal(htmlFiles.length, canonicalPages.length, "build output canonical page count matches the route manifest"); for (const { route } of canonicalPages) { const target = route === "/" ? path.join(output, "index.html") : path.join(output, route.slice(1), "index.html"); 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/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/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/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/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/ci-foundation.test.mjs b/tests/ci-foundation.test.mjs index f4631b9..58b41c5 100644 --- a/tests/ci-foundation.test.mjs +++ b/tests/ci-foundation.test.mjs @@ -4,9 +4,9 @@ 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, /uses: actions\/checkout@v4/); -assert.match(workflow, /uses: actions\/setup-node@v4/); +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@[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/); @@ -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 344b584..e9af6b0 100644 --- a/tests/cloudflare-bridge.test.mjs +++ b/tests/cloudflare-bridge.test.mjs @@ -2,8 +2,11 @@ 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"; +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); @@ -23,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/); @@ -81,8 +85,11 @@ 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/); + 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/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/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/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 2b1ddf7..a289e20 100644 --- a/tests/production/smoke.mjs +++ b/tests/production/smoke.mjs @@ -3,11 +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`); @@ -18,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) { @@ -39,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"; @@ -48,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 = []; @@ -182,7 +197,14 @@ 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("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); @@ -211,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-artifact.test.mjs b/tests/release-artifact.test.mjs new file mode 100644 index 0000000..42f9a1b --- /dev/null +++ b/tests/release-artifact.test.mjs @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; + +// cloudflare-bridge.test has just exercised the real build and isolated packaging. +for (const file of ['AGENTS.md','package.json','package-lock.json','tsconfig.json','tsconfig.build.json','.gitignore','README.md','CHANGELOG.md','SECURITY.md']) { + assert.ok(!fs.existsSync(path.join('dist',file)), `${file} is not a public root asset`); +} +assert.equal(fs.readFileSync('dist/CNAME','utf8').trim(),'securetools.app'); +assert.ok(fs.existsSync('dist/LICENSE')); +for (const file of ['assets/icons/.gitkeep','assets/images/.gitkeep']) assert.ok(!fs.existsSync(path.join('dist',file)), 'No repository scaffolding'); +const probe = path.resolve('dist','unexpected-release-file.txt'); +assert.equal(path.dirname(probe), path.resolve('dist')); +try { + fs.writeFileSync(probe,'synthetic artifact inventory regression'); + const result = spawnSync(process.execPath,['scripts/validate-build.mjs'],{encoding:'utf8'}); + assert.notEqual(result.status,0,'Unexpected output must fail artifact validation'); + assert.match(result.stderr,/Unexpected artifact root entry/); +} finally { fs.unlinkSync(probe); } +console.log('Release artifact root allowlist rejects accidental repository/config files; license and generic CNAME preserved.'); 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/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/run-all.mjs b/tests/run-all.mjs index 9fc9196..b95802f 100644 --- a/tests/run-all.mjs +++ b/tests/run-all.mjs @@ -40,7 +40,9 @@ 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/security-monitoring.test.mjs", "tests/release-gate.test.mjs", "tests/seo-foundation.test.mjs", "tests/url-namespace.test.mjs", @@ -54,8 +56,11 @@ 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", + "tests/release-artifact.test.mjs", "tests/release-hardening-http.test.mjs", "tests/verify-browser-export-artifacts.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/tests/security-hardening.test.mjs b/tests/security-hardening.test.mjs index 07a49bf..4d39921 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, @@ -89,4 +90,40 @@ 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(); +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-")); +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/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."); 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", }); 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 @@ -
+