From 28c3eadc42fc2a454169d28b4a625743656c15d2 Mon Sep 17 00:00:00 2001 From: maruson08 Date: Tue, 17 Nov 2026 22:13:00 +0900 Subject: [PATCH 1/4] =?UTF-8?q?=F0=9F=94=A7[Config]=20Establish=20v2.4=20i?= =?UTF-8?q?ntegration=20workflow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/dependabot.yml | 4 ++-- .github/workflows/ci.yml | 2 +- .github/workflows/security-monitoring.yml | 4 ++-- AGENTS.md | 12 ++++++------ docs/development-workflow.md | 20 ++++++++++--------- scripts/validate-branch-policy.mjs | 2 +- tests/action-pins.test.mjs | 4 ++-- tests/branch-policy.test.mjs | 24 +++++++++++------------ tests/ci-foundation.test.mjs | 2 +- tests/security-monitoring.test.mjs | 4 ++-- 10 files changed, 40 insertions(+), 38 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7c60bf9..986b65e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -2,7 +2,7 @@ version: 2 updates: - package-ecosystem: "github-actions" directory: "/" - target-branch: "v2.3" + target-branch: "v2.4" schedule: interval: "weekly" pull-request-branch-name: @@ -12,7 +12,7 @@ updates: prefix: "🔧[Config] " - package-ecosystem: "npm" directory: "/" - target-branch: "v2.3" + target-branch: "v2.4" schedule: interval: "weekly" open-pull-requests-limit: 5 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8aeab54..a00db96 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,7 @@ on: branches: - main - v2 - - v2.3 + - v2.4 permissions: contents: read diff --git a/.github/workflows/security-monitoring.yml b/.github/workflows/security-monitoring.yml index 5850615..9c8c232 100644 --- a/.github/workflows/security-monitoring.yml +++ b/.github/workflows/security-monitoring.yml @@ -2,9 +2,9 @@ name: Security monitoring on: pull_request: - branches: [v2.3, main] + branches: [v2.4, main] push: - branches: [v2.3, main] + branches: [v2.4, main] schedule: - cron: '29 3 * * 3' workflow_dispatch: diff --git a/AGENTS.md b/AGENTS.md index af82669..dba696e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,13 +2,13 @@ ## Protected branches -- `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`. +- `main` is production-only. `v2.4` is the active integration branch for the v2.4.0 development cycle, bootstrapped from production `main` after v2.3.0. +- Never commit feature, fix, test, or chore work directly to `main` or `v2.4`. ## Development work -- Create short-lived `feat/*`, `fix/*`, `test/*`, or `chore/*` branches from `v2.3`. -- Sprint and routine development pull requests target `v2.3`, not `main`. +- Create short-lived `feat/*`, `fix/*`, `test/*`, or `chore/*` branches from `v2.4`. +- Sprint and routine development pull requests target `v2.4`, 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.3`. -- Creating the v2.3.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.4`. +- Creating the v2.4.0 tag or release requires separate explicit authorization after final verification. ## Hotfixes diff --git a/docs/development-workflow.md b/docs/development-workflow.md index f93a1f0..3d6ae8a 100644 --- a/docs/development-workflow.md +++ b/docs/development-workflow.md @@ -5,28 +5,30 @@ 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.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. +- `v2.4` is the active integration branch for the v2.4.0 cycle. +- Short-lived `feat/*`, `fix/*`, `test/*`, and `chore/*` branches start from `v2.4` and return through pull requests into `v2.4`. +- Direct feature or fix commits to `main` or `v2.4` are prohibited. ```text main (production) ↑ -release PR after v2.3 hardening +release PR after v2.4 hardening ↑ -v2.3 (active integration) +v2.4 (active integration) ↑ Sprint PRs ↑ feat/* fix/* test/* chore/* ``` +The v2.4 branch starts at production main commit `2eb8e865e32558bfd031cd65c85d5d0fea64f5c7`. The policy migration is reviewed as a separate prerequisite commit in the first v2.4 PR; no integration or production merge is implied. Existing v2.3 dependency proposals remain unmerged and require separate review. + ## Sprint delivery -1. Update local `v2.3` from `origin/v2.3`. +1. Update local `v2.4` from `origin/v2.4`. 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.3` and wait for required CI. +4. Open a pull request into `v2.4` 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 +42,7 @@ CI validates non-merge commits introduced by the pull request’s actual base-to ## Production 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. +The v2.3.0 cycle is released. The v2.4.0 cycle is active development. After the v2.4.0 scope is integrated, complete release hardening and final verification on `v2.4`. Promote it through a dedicated `v2.4` → `main` pull request. Only after that pull request is explicitly reviewed and merged may a separately authorized task create the v2.4.0 tag and release. ## Hotfixes @@ -48,4 +50,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.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. +CI permits routine `feat/*`, `fix/*`, `test/*`, and `chore/*` pull requests into `v2.4`. Pull requests into `main` pass the branch-policy gate only when the head is exactly `v2.4` 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/scripts/validate-branch-policy.mjs b/scripts/validate-branch-policy.mjs index e3ff75f..385e4e5 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.3"; +export const ACTIVE_INTEGRATION_BRANCH = "v2.4"; const routineBranch = /^(?:feat|fix|test|chore)\/.+$/; const hotfixBranch = /^hotfix\/.+$/; diff --git a/tests/action-pins.test.mjs b/tests/action-pins.test.mjs index 1f073bd..53881c0 100644 --- a/tests/action-pins.test.mjs +++ b/tests/action-pins.test.mjs @@ -22,10 +22,10 @@ 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, /target-branch: "v2\.4"/); 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.equal(validateBranchPolicy("v2.4", "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 e355573..8b3ea16 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.3"); +assert.equal(ACTIVE_INTEGRATION_BRANCH, "v2.4"); for (const [headRef, baseRef] of [ - ["feat/example", "v2.3"], - ["fix/example", "v2.3"], - ["test/example", "v2.3"], - ["chore/example", "v2.3"], - ["v2.3", "main"], + ["feat/example", "v2.4"], + ["fix/example", "v2.4"], + ["test/example", "v2.4"], + ["chore/example", "v2.4"], + ["v2.4", "main"], ["hotfix/example", "main"], ]) { assert.deepEqual(validateBranchPolicy(baseRef, headRef), { valid: true, reason: null }, `${headRef} → ${baseRef}`); @@ -33,14 +33,14 @@ for (const [headRef, baseRef] of [ ]) { const result = validateBranchPolicy(baseRef, headRef); assert.equal(result.valid, false, `${headRef} → ${baseRef}`); - 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/); + assert.match(result.reason, /Only v2\.4 release promotion or an explicit hotfix/); + assert.throws(() => run([baseRef, headRef]), /Only v2\.4 release promotion or an explicit hotfix/); } for (const headRef of ["v2.1", "main", "hotfix/example", "feature/example"]) { - 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\/\*/); + const result = validateBranchPolicy("v2.4", headRef); + assert.equal(result.valid, false, `${headRef} → v2.4`); + assert.match(result.reason, /Pull requests into v2\.4 must come from feat\/\*, fix\/\*, test\/\*, or chore\/\*/); } for (const base of ["v2.2", "v2.1", "unknown"]) { @@ -83,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.3 integration, production promotion, hotfix, and rejection branch-policy checks passed."); +console.log("v2.4 integration, production promotion, hotfix, and rejection branch-policy checks passed."); diff --git a/tests/ci-foundation.test.mjs b/tests/ci-foundation.test.mjs index 58b41c5..54fb1ff 100644 --- a/tests/ci-foundation.test.mjs +++ b/tests/ci-foundation.test.mjs @@ -4,7 +4,7 @@ import fs from "node:fs"; const workflow = fs.readFileSync(".github/workflows/ci.yml", "utf8"); assert.match(workflow, /^name: CI$/m); assert.match(workflow, /^\s{2}pull_request:$/m); -assert.match(workflow, /^\s{2}push:\s*$[\s\S]*?^\s{6}- main$[\s\S]*?^\s{6}- v2$[\s\S]*?^\s{6}- v2\.3$/m); +assert.match(workflow, /^\s{2}push:\s*$[\s\S]*?^\s{6}- main$[\s\S]*?^\s{6}- v2$[\s\S]*?^\s{6}- v2\.4$/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/); diff --git a/tests/security-monitoring.test.mjs b/tests/security-monitoring.test.mjs index 9d0a0ab..e5f1312 100644 --- a/tests/security-monitoring.test.mjs +++ b/tests/security-monitoring.test.mjs @@ -87,7 +87,7 @@ await assert.rejects(scanGithubVendor(github, projectRequest({ advisories: {} }) 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, /branches: \[v2\.4, 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/); @@ -96,7 +96,7 @@ 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: "npm"[\s\S]*?target-branch: "v2\.4"/); assert.match(dependabot, /package-ecosystem: "github-actions"/); assert.doesNotMatch(dependabot, /auto-merge/); auditActionPins(); From 89f048a635bce559ab5fb156c5675c7d3a3b41ec Mon Sep 17 00:00:00 2001 From: maruson08 Date: Tue, 17 Nov 2026 22:24:36 +0900 Subject: [PATCH 2/4] =?UTF-8?q?=E2=9C=A8[Feat]=20Add=20document=20scanner?= =?UTF-8?q?=20core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 4 + CHANGELOG.md | 6 + README.md | 4 + docs/architecture.md | 6 + docs/sprint-24a-scanner-core.md | 71 +++++++ docs/tool-status.md | 7 +- js/i18n.js | 4 +- js/locales/document-scanner.js | 254 ++++++++++++++++++++++++++ scripts/site-routes.mjs | 1 + scripts/typescript-modules.mjs | 2 + sitemap.xml | 1 + tests/browser/scanner.mjs | 134 ++++++++++++++ tests/category-availability.test.mjs | 4 +- tests/i18n-quality.test.mjs | 4 +- tests/pdf-to-text.test.mjs | 2 +- tests/release-hardening-http.test.mjs | 4 +- tests/run-all.mjs | 1 + tests/scanner.test.mjs | 86 +++++++++ tests/seo-foundation.test.mjs | 2 +- tests/typescript-foundation.test.mjs | 2 +- tests/url-namespace.test.mjs | 2 +- tools/scan/document/app.js | 107 +++++++++++ tools/scan/document/index.html | 19 ++ tools/scan/document/state.ts | 97 ++++++++++ tools/scan/document/tool.css | 12 ++ tools/scan/index.html | 2 +- tools/shared/image.d.ts | 12 ++ tools/shared/scan.ts | 63 +++++++ tsconfig.build.json | 4 +- tsconfig.json | 10 +- 30 files changed, 909 insertions(+), 18 deletions(-) create mode 100644 docs/sprint-24a-scanner-core.md create mode 100644 js/locales/document-scanner.js create mode 100644 tests/browser/scanner.mjs create mode 100644 tests/scanner.test.mjs create mode 100644 tools/scan/document/app.js create mode 100644 tools/scan/document/index.html create mode 100644 tools/scan/document/state.ts create mode 100644 tools/scan/document/tool.css create mode 100644 tools/shared/image.d.ts create mode 100644 tools/shared/scan.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a00db96..ecb0360 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -88,6 +88,9 @@ jobs: - name: Verify responsive navigation, metadata layouts and accessibility run: node tests/browser/responsive.mjs + - name: Verify scanner inputs, orientation, lifecycle and privacy + run: node tests/browser/scanner.mjs + - name: Inspect isolated release review artifact run: node scripts/inspect-release-artifact.mjs @@ -107,4 +110,5 @@ jobs: path: | .ts-build/production-smoke .ts-build/responsive + .ts-build/scanner-qa retention-days: 7 diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e54d3a..41ec2db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 2.4.0 — Unreleased + +- Add Document Scanner Core with local JPEG/PNG/WebP input, page ordering, removal, clear, EXIF-aware bounded previews, and Original/Grayscale/Document modes. +- Bound the scanner queue to 20 pages and 200 MiB, release temporary resources, and invalidate cancelled or replaced preview work. +- Establish v2.4 integration policy and scanner regression/browser coverage. PDF export and scanner OCR are reserved for later sprints. + ## 2.3.0 — Release candidate, unpublished ### Security and reliability diff --git a/README.md b/README.md index 685215a..85076f5 100644 --- a/README.md +++ b/README.md @@ -86,3 +86,7 @@ Release history is recorded in the [changelog](./CHANGELOG.md). The current v2.0 Source: [SecureToolsProject/Secure_Tools](https://github.com/SecureToolsProject/Secure_Tools) See [LICENSE](./LICENSE). Vendored third-party code retains its own license beside each dependency. + +## v2.4 development + +Document Scanner Core is available in the development build at `/scan/document/`: local multi-image input, accessible ordering, orientation-aware previews, and Original/Grayscale/Document appearance. PDF export and scanner OCR remain planned. See [Sprint 24A implementation and QA](docs/sprint-24a-scanner-core.md). diff --git a/docs/architecture.md b/docs/architecture.md index 7ec1dd6..42b84fe 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,3 +74,9 @@ Secure Tools may evolve as both: - a discovery hub for separately deployed companion applications that need different runtime or resource models. This is a direction, not a current integration contract. There is no companion registry, external-application schema, plugin framework, service discovery mechanism, or v3 navigation implementation in the present architecture. + +## Document Scanner Core (v2.4 / 24A) + +`tools/shared/scan.ts` decodes through the existing signature-validated, EXIF-aware image helper, bounds previews to 1,000 pixels on the longest edge, composites transparency over white, and provides deterministic pixel preprocessing. `tools/scan/document/state.ts` holds ordered source Files and preview URLs, with 20-page/200-MiB aggregate limits, per-operation cancellation and stale-result guards. It releases replaced/removed/cleared URLs and decoded/canvas resources. Only one current queue operation may publish results. The UI is a static ES module with native picker, drop/paste inputs and keyboard ordering. + +Appearance is recorded per page; cancelling a batch retains completed previews. Apply to all pages retries the selected mode. Originals remain immutable and are retained as File references for future full-resolution export. 24B must decode originals again and must not compose a PDF from bounded thumbnails. Shared OCR/PDF services remain unchanged. No new external service, persistence, runtime dependency or CSP relaxation is introduced. diff --git a/docs/sprint-24a-scanner-core.md b/docs/sprint-24a-scanner-core.md new file mode 100644 index 0000000..ff49a3d --- /dev/null +++ b/docs/sprint-24a-scanner-core.md @@ -0,0 +1,71 @@ +# Sprint 24A — Document Scanner Core + +## Implementation + +The v2.4 development scanner is `/scan/document/`. It accepts signature-validated JPEG, PNG and WebP from the native multi-file picker, drop and paste. Pages can be moved with semantic keyboard-accessible buttons, removed, or cleared. All six existing locales are supported. Original, Grayscale and Document modes operate locally; Document uses a deterministic threshold of 160, with no corner detection or perspective correction. + +Previews retain aspect ratio and EXIF normalization through `decodeImage`. Each preview is at most 1,000 pixels on its longest edge. Source File references remain unchanged; decoded bitmaps and canvas backing stores are released after processing. Preview URLs are revoked on replacement, removal, clear and page exit. The queue admits at most 20 pages / 200 MiB total, plus existing 50-MiB-file / 50-megapixel / 16,384-pixel decoder limits. Oversized or broken inputs produce recoverable messages, while valid files in the batch remain available. + +Adding another batch cancels publication from the previous batch. Clear and cancellation invalidate in-flight results. Cancelling appearance changes retains completed pages with their actual mode labels; Apply to all pages is the retry mechanism. Native decoding/encoding cannot be interrupted mid-call, but resources are released and stale results cannot enter the queue. + +## Branch policy + +Production `main` and tag v2.3.0 were inspected at `2eb8e865e32558bfd031cd65c85d5d0fea64f5c7`; no v2.4 branch existed. v2.4 was bootstrapped from that production commit. The prerequisite policy migration is an independent Config commit in the scanner feature branch, covering AGENTS, workflow documentation, CI/security triggers, Dependabot targets and policy tests. It remains reviewable in the v2.4 PR; neither integration nor production was merged. Existing v2.3 maintenance PRs were not changed. + +## Verification + +- `npm run typecheck`: passed. +- `npm run compile:ts`: passed. +- `node tests/scanner.test.mjs`: passed (state/order, all modes, invalid inputs, limits, stale completion, orientation contract, resource cleanup). +- `npm run build`: passed; 20 canonical pages, 17 existing redirects, pinned OCR/font asset checks unchanged. +- `npm test`: local functional/regression tests passed through release artifact checks; the HTTP hardening gate failed because host AdGuard rewrites CSP. The strict expected policy was preserved. Clean hosted CI is required for the full result. +- `node tests/browser/scanner.mjs`: completed 30 viewport/locale functional cases (320×568, 390×844, 844×390, 768×1024, 1280×900; en/ko/ja/es/de/fr), actual JPEG/PNG/WebP inputs, EXIF orientation=6 JPEG, grayscale pixels, Document mode, keyboard ordering/focus, removal/clear, drop/paste, two 12-megapixel photos, stale clear, URL cleanup. The local privacy gate failed on injected `local.adguard.org` traffic/CSP mutations; it was not waived. The same strict test is included in hosted CI. +- Browser screenshots were visually inspected at Korean 320px and English desktop widths. Physical mobile, Firefox and Edge were not exercised locally. + +No upload, telemetry, document persistence, new dependency or global CSP change was added. Host-injected traffic is recorded separately from app behavior; a clean privacy pass must come from hosted CI. Local diagnostic output and screenshots are in ignored `.ts-build/scanner-qa/`; the hosted failure artifact retains the same directory. + +## Follow-ups + +24B: compose the ordered original source images with shared PDF tooling, applying the chosen per-page appearance at export resolution; add output preview/download, export budgets, cancellation and cleanup. Do not export thumbnail pixels. 24C: adapt the existing shared OCR worker service. 24D: adapt existing OCR geometry/searchable-PDF capabilities. No PDF export, OCR controls, searchable-PDF rewrite, library replacement, production deployment, release tag or merge is included here. + +## Changed files + +- `.github/dependabot.yml` +- `.github/workflows/ci.yml` +- `.github/workflows/security-monitoring.yml` +- `AGENTS.md` +- `CHANGELOG.md` +- `README.md` +- `docs/architecture.md` +- `docs/development-workflow.md` +- `docs/sprint-24a-scanner-core.md` +- `docs/tool-status.md` +- `js/i18n.js` +- `js/locales/document-scanner.js` +- `scripts/site-routes.mjs` +- `scripts/typescript-modules.mjs` +- `scripts/validate-branch-policy.mjs` +- `sitemap.xml` +- `tests/action-pins.test.mjs` +- `tests/branch-policy.test.mjs` +- `tests/browser/scanner.mjs` +- `tests/category-availability.test.mjs` +- `tests/ci-foundation.test.mjs` +- `tests/i18n-quality.test.mjs` +- `tests/pdf-to-text.test.mjs` +- `tests/release-hardening-http.test.mjs` +- `tests/run-all.mjs` +- `tests/scanner.test.mjs` +- `tests/security-monitoring.test.mjs` +- `tests/seo-foundation.test.mjs` +- `tests/typescript-foundation.test.mjs` +- `tests/url-namespace.test.mjs` +- `tools/scan/document/app.js` +- `tools/scan/document/index.html` +- `tools/scan/document/state.ts` +- `tools/scan/document/tool.css` +- `tools/scan/index.html` +- `tools/shared/image.d.ts` +- `tools/shared/scan.ts` +- `tsconfig.build.json` +- `tsconfig.json` diff --git a/docs/tool-status.md b/docs/tool-status.md index f92f717..ff5c027 100644 --- a/docs/tool-status.md +++ b/docs/tool-status.md @@ -16,12 +16,13 @@ | Image | [Image Metadata Inspector & Cleaner](https://tools.securetools.app/image/metadata/) | Production | Supported JPEG, PNG, WebP metadata | | Image | [Image → Text OCR](https://tools.securetools.app/image/to-text/) | Production | One PNG, JPEG, or WebP → editable English/Korean text | | Privacy | [Privacy hub](https://tools.securetools.app/privacy/) | Production hub | Navigation to Image and PDF metadata tools | -| Scan/OCR | Category surface | Planned | No production processing tool | +| Scan/OCR | Category surface | Available | Image/PDF OCR links; Document Scanner Core in v2.4 development | +| Scan/OCR | Document Scanner | Development (24A) | JPEG/PNG/WebP; arrange pages; local appearance previews; no PDF/OCR export yet | | Media | Category surface | Planned | No production processing tool | “Production” means linked and covered by the current repository validation. “Planned” cards are non-interactive. Secure Tools may later link separately deployed companion applications, but no Companion status or integration exists on the live site today. -The Image category exposes the tested OCR runtime through a single-image Image → Text workflow with English, Korean, and combined recognition. The broader Scan/OCR category remains planned; PDF OCR and searchable PDF output are deferred. +The Image category exposes the tested OCR runtime through a single-image Image → Text workflow with English, Korean, and combined recognition. PDF OCR and searchable PDF output already exist in PDF to Text. Scanner Core is available in v2.4 development; scanner PDF export and optional OCR are deferred to 24B/24C. ## Shared Image boundaries @@ -79,7 +80,7 @@ Inspects Title, Author, Subject, Keywords, Creator, Producer, Creation Date, and ## Deferred directions -Broader PDF modification, compression, encryption, XMP/structural sanitization, PDF OCR, searchable PDF output, broader Scan/OCR workflows, Media, and offline/PWA work remain deferred. Separately deployed companion applications are an architectural possibility, not a current product status or integration. +Broader PDF modification, compression, encryption, XMP/structural sanitization, scanner PDF export/OCR integration, broader Scan/OCR workflows, Media, and offline/PWA work remain deferred. Separately deployed companion applications are an architectural possibility, not a current product status or integration. ## Related guarantees diff --git a/js/i18n.js b/js/i18n.js index 9542849..a772eb8 100644 --- a/js/i18n.js +++ b/js/i18n.js @@ -1,3 +1,4 @@ +import { documentScannerLocales } from "./locales/document-scanner.js"; import { en } from "./locales/en.js"; import { ko } from "./locales/ko.js"; import { ja } from "./locales/ja.js"; @@ -16,9 +17,10 @@ const STORAGE_KEY = "secure-tools-language"; const baseTranslations = { en, ko, ja, es, de, fr }; export const translations = Object.fromEntries(Object.entries(baseTranslations).map(([language, catalog]) => [language, { ...catalog, - metadata: { ...catalog.metadata, imageResize: imageResizeLocales[language].metadata, imageCompressor: imageCompressorLocales[language].metadata, imageMetadata: imageMetadataLocales[language].metadata, imageToText: imageToTextLocales[language].metadata, pdfToText: pdfToTextLocales[language].metadata, privacyCategory: privacyHubLocales[language].metadata }, + metadata: { ...catalog.metadata, documentScanner: documentScannerLocales[language].metadata, imageResize: imageResizeLocales[language].metadata, imageCompressor: imageCompressorLocales[language].metadata, imageMetadata: imageMetadataLocales[language].metadata, imageToText: imageToTextLocales[language].metadata, pdfToText: pdfToTextLocales[language].metadata, privacyCategory: privacyHubLocales[language].metadata }, tools: { ...catalog.tools, imageMetadata: imageMetadataLocales[language].toolName, imageToText: imageToTextLocales[language].toolName, pdfToText: pdfToTextLocales[language].toolName, categoryDescriptions: { ...catalog.tools.categoryDescriptions, privacy: privacyHubLocales[language].categoryDescription } }, categories: { ...catalog.categories, pdf: { ...catalog.categories.pdf, toText: pdfToTextLocales[language].categoryDescription }, image: { ...catalog.categories.image, metadata: imageMetadataLocales[language].categoryDescription, toText: imageToTextLocales[language].categoryDescription }, scan: { ...catalog.categories.scan, pdfToText: pdfToTextLocales[language].categoryDescription } }, + documentScanner: documentScannerLocales[language].copy, imageResize: imageResizeLocales[language].copy, imageCompressor: imageCompressorLocales[language].copy, imageMetadata: { ...imageMetadataLocales[language].copy, source: { ...imageMetadataLocales[language].copy.source, ...metadataUxLocales[language].image.source }, inspector: { ...imageMetadataLocales[language].copy.inspector, ...metadataUxLocales[language].image.inspector }, clean: { ...imageMetadataLocales[language].copy.clean, ...metadataUxLocales[language].image.clean }, policy: metadataUxLocales[language].image.policy }, diff --git a/js/locales/document-scanner.js b/js/locales/document-scanner.js new file mode 100644 index 0000000..033c3f4 --- /dev/null +++ b/js/locales/document-scanner.js @@ -0,0 +1,254 @@ +export const documentScannerLocales = { + "en": { + "metadata": { + "title": "Document Scanner — Secure Tools", + "description": "Arrange and clean document images on this device." + }, + "copy": { + "title": "Document Scanner", + "eyebrow": "Local scan tool", + "description": "Arrange and clean document images on this device.", + "add": "Add images", + "inputHelp": "Choose, drop or paste JPEG, PNG or WebP images. Up to 20 pages and 200 MiB total; 50 MiB per image.", + "appearance": "Scan appearance", + "mode": "Appearance for new pages", + "original": "Original", + "grayscale": "Grayscale", + "document": "Document", + "modeHelp": "Document mode uses a fixed black-and-white threshold. No automatic cropping or corner detection.", + "apply": "Apply to all pages", + "cancel": "Cancel processing", + "clear": "Clear all", + "scope": "Scanner preview only. PDF export and optional OCR are coming later.", + "pages": "Document pages", + "empty": "No pages added yet.", + "count": "{count} pages", + "preview": "Page {page} preview", + "up": "Move up", + "down": "Move down", + "remove": "Remove", + "processing": "Processing locally… {count} pages ready.", + "cancelled": "Processing cancelled. Completed previews remain available.", + "added": "Added {count} pages.", + "rejected": "Added {added} pages. Could not add: {names}", + "limit": "Image or queue limit exceeded. Try fewer or smaller images.", + "unsupported": "Unsupported or invalid image. Use JPEG, PNG or WebP.", + "decode": "Could not decode this image. Try another file.", + "failure": "Could not process previews. Try again or use smaller images.", + "cleared": "All pages cleared.", + "applied": "Appearance applied to all pages.", + "removed": "Page removed.", + "reordered": "Page order updated." + } + }, + "ko": { + "metadata": { + "title": "문서 스캐너 — Secure Tools", + "description": "이 기기에서 문서 이미지를 정렬하고 보정합니다." + }, + "copy": { + "title": "문서 스캐너", + "eyebrow": "로컬 스캔 도구", + "description": "이 기기에서 문서 이미지를 정렬하고 보정합니다.", + "add": "이미지 추가", + "inputHelp": "JPEG, PNG, WebP 이미지를 선택하거나 끌어 놓거나 붙여넣으세요. 최대 20장, 합계 200MiB, 이미지당 50MiB입니다.", + "appearance": "스캔 모양", + "mode": "새 페이지의 모양", + "original": "원본", + "grayscale": "회색조", + "document": "문서", + "modeHelp": "문서 모드는 고정 임계값으로 흑백 처리합니다. 자동 자르기나 모서리 감지는 지원하지 않습니다.", + "apply": "모든 페이지에 적용", + "cancel": "처리 취소", + "clear": "모두 지우기", + "scope": "스캔 미리보기만 지원합니다. PDF 내보내기와 선택적 OCR은 추후 제공할 예정입니다.", + "pages": "문서 페이지", + "empty": "아직 추가된 페이지가 없습니다.", + "count": "{count}페이지", + "preview": "{page}페이지 미리보기", + "up": "위로 이동", + "down": "아래로 이동", + "remove": "제거", + "processing": "기기에서 처리 중… {count}페이지 준비됨.", + "cancelled": "처리를 취소했습니다. 완료된 미리보기는 유지됩니다.", + "added": "{count}페이지를 추가했습니다.", + "rejected": "{added}페이지 추가됨. 추가 실패: {names}", + "limit": "이미지 또는 대기열 제한을 초과했습니다. 이미지 수나 크기를 줄여 주세요.", + "unsupported": "지원하지 않거나 잘못된 이미지입니다. JPEG, PNG, WebP를 사용하세요.", + "decode": "이미지를 읽을 수 없습니다. 다른 파일을 사용해 주세요.", + "failure": "미리보기를 처리하지 못했습니다. 다시 시도하거나 작은 이미지를 사용해 주세요.", + "cleared": "모든 페이지를 지웠습니다.", + "applied": "모든 페이지에 모양을 적용했습니다.", + "removed": "페이지를 제거했습니다.", + "reordered": "페이지 순서를 변경했습니다." + } + }, + "ja": { + "metadata": { + "title": "ドキュメントスキャナー — Secure Tools", + "description": "このデバイスで文書画像を並べ替えて補正します。" + }, + "copy": { + "title": "ドキュメントスキャナー", + "eyebrow": "ローカルスキャンツール", + "description": "このデバイスで文書画像を並べ替えて補正します。", + "add": "画像を追加", + "inputHelp": "JPEG、PNG、WebPを選択、ドロップ、貼り付けできます。最大20ページ、合計200 MiB、1画像50 MiB。", + "appearance": "スキャンの表示", + "mode": "新しいページの表示", + "original": "オリジナル", + "grayscale": "グレースケール", + "document": "文書", + "modeHelp": "固定しきい値で白黒に変換します。自動切り抜きや角の検出は行いません。", + "apply": "全ページに適用", + "cancel": "処理をキャンセル", + "clear": "すべてクリア", + "scope": "スキャンのプレビューのみ。PDF出力と任意のOCRは今後対応予定です。", + "pages": "文書のページ", + "empty": "ページはまだありません。", + "count": "{count}ページ", + "preview": "{page}ページのプレビュー", + "up": "上へ", + "down": "下へ", + "remove": "削除", + "processing": "ローカルで処理中… {count}ページ準備完了。", + "cancelled": "処理をキャンセルしました。完了したプレビューは保持されます。", + "added": "{count}ページを追加しました。", + "rejected": "{added}ページ追加。追加できませんでした: {names}", + "limit": "画像またはキューの上限を超えました。画像の数やサイズを減らしてください。", + "unsupported": "非対応または無効な画像です。JPEG、PNG、WebPをご使用ください。", + "decode": "画像を読み込めません。他のファイルをお試しください。", + "failure": "プレビューを処理できません。再試行するか小さい画像をお試しください。", + "cleared": "全ページをクリアしました。", + "applied": "全ページに表示を適用しました。", + "removed": "ページを削除しました。", + "reordered": "ページ順を更新しました。" + } + }, + "es": { + "metadata": { + "title": "Escáner de documentos — Secure Tools", + "description": "Ordena y mejora imágenes de documentos en este dispositivo." + }, + "copy": { + "title": "Escáner de documentos", + "eyebrow": "Herramienta de escaneo local", + "description": "Ordena y mejora imágenes de documentos en este dispositivo.", + "add": "Añadir imágenes", + "inputHelp": "Selecciona, arrastra o pega JPEG, PNG o WebP. Hasta 20 páginas y 200 MiB en total; 50 MiB por imagen.", + "appearance": "Aspecto del escaneo", + "mode": "Aspecto de páginas nuevas", + "original": "Original", + "grayscale": "Escala de grises", + "document": "Documento", + "modeHelp": "El modo Documento usa un umbral fijo de blanco y negro. Sin recorte automático ni detección de esquinas.", + "apply": "Aplicar a todas las páginas", + "cancel": "Cancelar procesamiento", + "clear": "Borrar todo", + "scope": "Solo vista previa. La exportación PDF y el OCR opcional están previstos más adelante.", + "pages": "Páginas del documento", + "empty": "Aún no hay páginas.", + "count": "{count} páginas", + "preview": "Vista previa de la página {page}", + "up": "Subir", + "down": "Bajar", + "remove": "Eliminar", + "processing": "Procesando localmente… {count} páginas listas.", + "cancelled": "Procesamiento cancelado. Se conservan las vistas previas terminadas.", + "added": "Se añadieron {count} páginas.", + "rejected": "Se añadieron {added} páginas. No se pudieron añadir: {names}", + "limit": "Se superó el límite de imagen o cola. Usa menos imágenes o imágenes más pequeñas.", + "unsupported": "Imagen no compatible o inválida. Usa JPEG, PNG o WebP.", + "decode": "No se pudo leer la imagen. Prueba otro archivo.", + "failure": "No se pudieron procesar las vistas previas. Reintenta o usa imágenes más pequeñas.", + "cleared": "Se borraron todas las páginas.", + "applied": "Aspecto aplicado a todas las páginas.", + "removed": "Página eliminada.", + "reordered": "Orden de páginas actualizado." + } + }, + "de": { + "metadata": { + "title": "Dokumentenscanner — Secure Tools", + "description": "Dokumentbilder auf diesem Gerät ordnen und verbessern." + }, + "copy": { + "title": "Dokumentenscanner", + "eyebrow": "Lokales Scanwerkzeug", + "description": "Dokumentbilder auf diesem Gerät ordnen und verbessern.", + "add": "Bilder hinzufügen", + "inputHelp": "JPEG, PNG oder WebP auswählen, ablegen oder einfügen. Bis zu 20 Seiten und insgesamt 200 MiB; 50 MiB pro Bild.", + "appearance": "Scanansicht", + "mode": "Ansicht für neue Seiten", + "original": "Original", + "grayscale": "Graustufen", + "document": "Dokument", + "modeHelp": "Der Dokumentmodus nutzt einen festen Schwarzweiß-Schwellenwert. Kein automatischer Zuschnitt oder Eckenerkennung.", + "apply": "Auf alle Seiten anwenden", + "cancel": "Verarbeitung abbrechen", + "clear": "Alles löschen", + "scope": "Nur Scanvorschau. PDF-Export und optionales OCR sind für später geplant.", + "pages": "Dokumentseiten", + "empty": "Noch keine Seiten hinzugefügt.", + "count": "{count} Seiten", + "preview": "Vorschau von Seite {page}", + "up": "Nach oben", + "down": "Nach unten", + "remove": "Entfernen", + "processing": "Lokale Verarbeitung… {count} Seiten bereit.", + "cancelled": "Verarbeitung abgebrochen. Fertige Vorschauen bleiben erhalten.", + "added": "{count} Seiten hinzugefügt.", + "rejected": "{added} Seiten hinzugefügt. Nicht hinzugefügt: {names}", + "limit": "Bild- oder Warteschlangenlimit überschritten. Weniger oder kleinere Bilder verwenden.", + "unsupported": "Nicht unterstütztes oder ungültiges Bild. JPEG, PNG oder WebP verwenden.", + "decode": "Bild konnte nicht gelesen werden. Andere Datei versuchen.", + "failure": "Vorschauen konnten nicht verarbeitet werden. Erneut versuchen oder kleinere Bilder verwenden.", + "cleared": "Alle Seiten gelöscht.", + "applied": "Ansicht auf alle Seiten angewendet.", + "removed": "Seite entfernt.", + "reordered": "Seitenreihenfolge aktualisiert." + } + }, + "fr": { + "metadata": { + "title": "Scanner de documents — Secure Tools", + "description": "Classez et améliorez vos images de documents sur cet appareil." + }, + "copy": { + "title": "Scanner de documents", + "eyebrow": "Outil de numérisation local", + "description": "Classez et améliorez vos images de documents sur cet appareil.", + "add": "Ajouter des images", + "inputHelp": "Sélectionnez, déposez ou collez des JPEG, PNG ou WebP. Jusqu’à 20 pages et 200 Mio au total ; 50 Mio par image.", + "appearance": "Aspect du scan", + "mode": "Aspect des nouvelles pages", + "original": "Original", + "grayscale": "Niveaux de gris", + "document": "Document", + "modeHelp": "Le mode Document utilise un seuil noir et blanc fixe. Sans recadrage automatique ni détection des coins.", + "apply": "Appliquer à toutes les pages", + "cancel": "Annuler le traitement", + "clear": "Tout effacer", + "scope": "Aperçu uniquement. L’export PDF et l’OCR facultatif sont prévus ultérieurement.", + "pages": "Pages du document", + "empty": "Aucune page ajoutée.", + "count": "{count} pages", + "preview": "Aperçu de la page {page}", + "up": "Monter", + "down": "Descendre", + "remove": "Supprimer", + "processing": "Traitement local… {count} pages prêtes.", + "cancelled": "Traitement annulé. Les aperçus terminés sont conservés.", + "added": "{count} pages ajoutées.", + "rejected": "{added} pages ajoutées. Échec de l’ajout : {names}", + "limit": "Limite d’image ou de file dépassée. Utilisez moins d’images ou des images plus petites.", + "unsupported": "Image non prise en charge ou invalide. Utilisez JPEG, PNG ou WebP.", + "decode": "Impossible de lire cette image. Essayez un autre fichier.", + "failure": "Impossible de traiter les aperçus. Réessayez ou utilisez des images plus petites.", + "cleared": "Toutes les pages ont été effacées.", + "applied": "Aspect appliqué à toutes les pages.", + "removed": "Page supprimée.", + "reordered": "Ordre des pages mis à jour." + } + } +}; diff --git a/scripts/site-routes.mjs b/scripts/site-routes.mjs index 025ffe9..8b70542 100644 --- a/scripts/site-routes.mjs +++ b/scripts/site-routes.mjs @@ -19,6 +19,7 @@ export const canonicalPages = [ { source: "tools/image/metadata/index.html", route: "/image/metadata/" }, { source: "tools/image/to-text/index.html", route: "/image/to-text/" }, { source: "tools/scan/index.html", route: "/scan/" }, + { source: "tools/scan/document/index.html", route: "/scan/document/", legacy: false }, { source: "tools/media/index.html", route: "/media/" }, ]; diff --git a/scripts/typescript-modules.mjs b/scripts/typescript-modules.mjs index 035249c..73edeb7 100644 --- a/scripts/typescript-modules.mjs +++ b/scripts/typescript-modules.mjs @@ -1,4 +1,6 @@ export const compiledBrowserModules = Object.freeze([ + Object.freeze({ source: "tools/shared/scan.ts", compiled: "tools/shared/scan.js", public: "shared/scan.js" }), + Object.freeze({ source: "tools/scan/document/state.ts", compiled: "tools/scan/document/state.js", public: "scan/document/state.js" }), Object.freeze({ source: "tools/pdf/to-text/app.ts", compiled: "tools/pdf/to-text/app.js", diff --git a/sitemap.xml b/sitemap.xml index e0fc784..0d97915 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -18,5 +18,6 @@ https://tools.securetools.app/image/metadata/ https://tools.securetools.app/image/to-text/ https://tools.securetools.app/scan/ + https://tools.securetools.app/scan/document/ https://tools.securetools.app/media/ diff --git a/tests/browser/scanner.mjs b/tests/browser/scanner.mjs new file mode 100644 index 0000000..b01304e --- /dev/null +++ b/tests/browser/scanner.mjs @@ -0,0 +1,134 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import { spawn } from "node:child_process"; +import { chromium } from "playwright"; +import { assertSecurityHeaders } from "../../scripts/http-security-headers.mjs"; +import { translations } from "../../js/i18n.js"; + +const directory = ".ts-build/scanner-qa"; +await fs.mkdir(directory, { recursive: true }); +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"] }); +const report = { cases: [], external: [], errors: [], headerErrors: [], status: "FAIL" }; +let browser; +try { + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("Server timed out")), 10000); + server.stdout.once("data", () => { clearTimeout(timer); resolve(); }); + server.once("error", reject); + }); + browser = await chromium.launch(); + const maker = await browser.newPage(); + const images = await maker.evaluate(async () => { + async function make(width, height, type) { + const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; + const c = canvas.getContext("2d"); c.fillStyle = "white"; c.fillRect(0,0,width,height); + c.fillStyle = "#e08050"; c.fillRect(0,0,width/2,height/2); + c.fillStyle = "black"; c.font = "20px sans-serif"; c.fillText("Document 문서", 4, height - 10); + const blob = await new Promise(resolve => canvas.toBlob(resolve, type)); + const data = [...new Uint8Array(await blob.arrayBuffer())]; canvas.width = canvas.height = 1; return data; + } + return { png: await make(180, 300, "image/png"), jpeg: await make(60, 30, "image/jpeg"), webp: await make(300, 180, "image/webp"), large: await make(4000,3000,"image/jpeg") }; + }); + await maker.close(); + // EXIF APP1/TIFF orientation=6: a real JPEG that browsers must rotate 90°. + const exif = Buffer.from([0xff,0xe1,0,34,69,120,105,102,0,0,73,73,42,0,8,0,0,0,1,0,18,1,3,0,1,0,0,0,6,0,0,0,0,0,0,0]); + const jpeg = Buffer.from(images.jpeg); + const rotated = Buffer.concat([jpeg.subarray(0,2), exif, jpeg.subarray(2)]); + const fixtures = [ + { name: "문서-portrait.png", mimeType: "image/png", buffer: Buffer.from(images.png) }, + { name: "landscape.webp", mimeType: "image/webp", buffer: Buffer.from(images.webp) }, + { name: "rotated-exif.jpg", mimeType: "image/jpeg", buffer: rotated }, + ]; + for (const language of ["en", "ko", "ja", "es", "de", "fr"]) { + const context = await browser.newContext({ locale: language }); + await context.addInitScript(language => { + localStorage.setItem("secure-tools-language", language); + window.scanUrls = { created: [], revoked: [] }; + const create = URL.createObjectURL.bind(URL); const revoke = URL.revokeObjectURL.bind(URL); + URL.createObjectURL = blob => { const url = create(blob); window.scanUrls.created.push(url); return url; }; + URL.revokeObjectURL = url => { window.scanUrls.revoked.push(url); revoke(url); }; + document.addEventListener("securitypolicyviolation", event => console.error(`CSP: ${event.effectiveDirective}`)); + }, language); + 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()); }); + const response = await page.goto(`${origin}/scan/document/`); + assert.equal(response.status(), 200); + // Check raw server headers; desktop browser middleware may append a second + // Permissions-Policy value, exposed by Playwright with embedded newlines. + try { assertSecurityHeaders((await fetch(`${origin}/scan/document/`)).headers); } + catch (error) { report.headerErrors.push(error.message); } + await page.setInputFiles("#file-input", fixtures); + await page.waitForFunction(() => document.querySelectorAll(".scan-page").length === 3 && document.querySelector("#cancel-scan").hidden); + assert.equal(await page.locator("#cancel-scan").isVisible(), false); + assert.equal(await page.locator(".scan-page").nth(2).locator("p").innerText(), `30 × 60 · ${translations[language].documentScanner.original}`); + // Deterministic preprocessing is applied to real encoded thumbnails. + await page.selectOption("#scan-mode", "grayscale"); await page.click("#apply-mode"); + await page.waitForFunction(() => document.querySelector("#cancel-scan").hidden); + const grayscale = await page.locator(".scan-page img").first().evaluate(async image => { + await image.decode(); const c = document.createElement("canvas"); c.width = image.naturalWidth; c.height = image.naturalHeight; + const ctx = c.getContext("2d"); ctx.drawImage(image,0,0); const data = ctx.getImageData(0,0,c.width,c.height).data; + return Array.from({length:data.length/4}, (_,i) => data[i*4] === data[i*4+1] && data[i*4] === data[i*4+2]).every(Boolean); + }); + assert.equal(grayscale, true); + await page.selectOption("#scan-mode", "document"); await page.click("#apply-mode"); + await page.waitForFunction(() => document.querySelector("#cancel-scan").hidden); + assert.ok((await page.locator(".scan-page p").allTextContents()).every(text => text.endsWith(translations[language].documentScanner.document))); + const firstId = await page.locator(".scan-page").first().getAttribute("data-id"); + await page.locator(".scan-page").first().locator('[data-action="down"]').focus(); await page.keyboard.press("Enter"); + assert.equal(await page.locator(".scan-page").nth(1).getAttribute("data-id"), firstId); + assert.ok(await page.locator(".scan-page").nth(1).evaluate(card => card.contains(document.activeElement))); + for (const [width,height] of [[320,568],[390,844],[844,390],[768,1024],[1280,900]]) { + await page.setViewportSize({width,height}); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), `${language} ${width}: no horizontal overflow`); + for (const button of await page.locator(".scan-page-actions button").all()) assert.ok((await button.boundingBox()).height >= 44); + if (language === "ko" && width === 320) await page.screenshot({ path: `${directory}/mobile-ko.png`, fullPage: true }); + if (language === "en" && width === 1280) await page.screenshot({ path: `${directory}/desktop-en.png`, fullPage: true }); + report.cases.push({ language, width, height, pages: 3 }); + } + await page.locator(".scan-page").first().locator('[data-action="remove"]').click(); + assert.equal(await page.locator(".scan-page").count(), 2); + await page.click("#clear-images"); assert.equal(await page.locator(".scan-page").count(), 0); + assert.ok(await page.locator("#add-images").evaluate(el => el === document.activeElement)); + const urls = await page.evaluate(() => window.scanUrls); + assert.deepEqual([...urls.created].sort(), [...urls.revoked].sort(), "All successful previews are released after clear"); + if (language === "en") { + await page.setInputFiles("#file-input", [{ name:"broken.png", mimeType:"image/png", buffer:Buffer.from([137,80,78,71,13,10,26,10,0,0,0,0]) }, {name:"bad.gif",mimeType:"image/gif",buffer:Buffer.from("gif")}]); + await page.waitForFunction(() => document.querySelector("#cancel-scan").hidden && document.querySelector("#tool-status").textContent.includes("Could not add")); + assert.equal(await page.locator(".scan-page").count(), 0); + // Actual drag/drop and paste events exercise the UI's file paths. + for (const type of ["drop", "paste"]) { + await page.evaluate(({type, bytes}) => { + const transfer = new DataTransfer(); transfer.items.add(new File([new Uint8Array(bytes)], `${type}.png`, {type:"image/png"})); + if (type === "drop") document.querySelector("#drop-zone").dispatchEvent(new DragEvent("drop", {bubbles:true,cancelable:true,dataTransfer:transfer})); + else document.dispatchEvent(new ClipboardEvent("paste", {bubbles:true,cancelable:true,clipboardData:transfer})); + }, {type, bytes:images.png}); + await page.waitForFunction(count => document.querySelectorAll(".scan-page").length === count && document.querySelector("#cancel-scan").hidden, type === "drop" ? 1 : 2); + } + await page.setInputFiles("#file-input", [1,2].map(index => ({name:`large-${index}.jpg`,mimeType:"image/jpeg",buffer:Buffer.from(images.large)}))); + await page.waitForFunction(() => document.querySelectorAll(".scan-page").length === 4 && document.querySelector("#cancel-scan").hidden); + assert.ok(await page.locator(".scan-page img").evaluateAll(async images => { await Promise.all(images.map(image => image.decode())); return images.every(image => Math.max(image.naturalWidth,image.naturalHeight) <= 1000); })); + // Trigger large input and clear synchronously before decode may finish. + await page.evaluate(bytes => { + const transfer = new DataTransfer(); for(let i=0;i<5;i++) transfer.items.add(new File([new Uint8Array(bytes)], `stale-${i}.jpg`, {type:"image/jpeg"})); + document.querySelector("#drop-zone").dispatchEvent(new DragEvent("drop", {bubbles:true,cancelable:true,dataTransfer:transfer})); + document.querySelector("#clear-images").click(); + }, images.large); + await page.waitForTimeout(300); + assert.equal(await page.locator(".scan-page").count(), 0); + const finalUrls = await page.evaluate(() => window.scanUrls); + assert.deepEqual([...finalUrls.created].sort(), [...finalUrls.revoked].sort()); + } + await context.close(); + } + assert.deepEqual(report.headerErrors, []); + assert.deepEqual(report.external, []); assert.deepEqual(report.errors, []); + report.status = "PASS"; + console.log("Scanner browser smoke passed: 30 viewport/locale cases; JPEG/PNG/WebP; EXIF; modes; keyboard order; input/drop/paste; large images; cleanup; CSP/network."); +} finally { + await fs.writeFile(`${directory}/report.json`, JSON.stringify(report,null,2)); + await browser?.close(); server.kill(); +} diff --git a/tests/category-availability.test.mjs b/tests/category-availability.test.mjs index 141281f..ccdbe38 100644 --- a/tests/category-availability.test.mjs +++ b/tests/category-availability.test.mjs @@ -68,8 +68,8 @@ assert.equal( "Image and Scan/OCR entries must resolve to the same route", ); assertRoutesExist("tools/scan/index.html", [scanOcrCard[1]]); -assert.equal((scanList.match(/
/g) || []).length, 1); -assert.equal((scanList.match(/tools\.comingSoon/g) || []).length, 1); +assert.equal((scanList.match(/
/g) || []).length, 0); +assert.equal((scanList.match(/tools\.comingSoon/g) || []).length, 0); assert.match(scanList, /data-i18n="categories\.scan\.documentTitle"/); const privacyHtml = read("privacy/index.html"); diff --git a/tests/i18n-quality.test.mjs b/tests/i18n-quality.test.mjs index 36e5e46..df425d3 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, 897); + assert.equal(english.size, 933); for (const [language, catalog] of Object.entries(translations)) { const flattened = flatten(catalog); @@ -78,7 +78,7 @@ function testResolutionDetectionAndPersistence() { function testSelectorsAndDocumentTranslation() { const pages = canonicalPages.map(({ source }) => path.join(root, source)); - assert.equal(pages.length, 19, "Every canonical page comes from the route manifest"); + assert.equal(pages.length, 20, "Every canonical page comes from the route manifest"); for (const file of pages) { const html = fs.readFileSync(file, "utf8"); const select = html.match(/]*data-language-select[^>]*>([\s\S]*?)<\/select>/)?.[1]; diff --git a/tests/pdf-to-text.test.mjs b/tests/pdf-to-text.test.mjs index b15cfc7..d594ebc 100644 --- a/tests/pdf-to-text.test.mjs +++ b/tests/pdf-to-text.test.mjs @@ -11,7 +11,7 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const read = (file) => fs.readFileSync(path.join(root, file), "utf8"); const html = read("tools/pdf/to-text/index.html"); -assert.equal(canonicalPages.length, 19); +assert.equal(canonicalPages.length, 20); assert.equal(legacyRedirects.length, 17); assert.ok(canonicalPages.some(({ route }) => route === "/pdf/to-text/")); assert.ok(!legacyRedirects.some(({ from }) => from === "/tools/pdf/to-text/")); diff --git a/tests/release-hardening-http.test.mjs b/tests/release-hardening-http.test.mjs index 628e6ba..bd364c0 100644 --- a/tests/release-hardening-http.test.mjs +++ b/tests/release-hardening-http.test.mjs @@ -69,6 +69,6 @@ try { assert.doesNotMatch(file, /(?:\.d)?\.ts$|\.map$|[\\/]\.ts-build[\\/]|[\\/]tests[\\/]/); if (/\.(?:js|mjs|html|css|json)$/.test(file)) assert.doesNotMatch(fs.readFileSync(file, "utf8"), /C:\\Users\\|C:\/Users\//); } - assert.equal(canonicalPages.length, 19); assert.equal(legacyRedirects.length, 17); - console.log(`Release hardening HTTP: all 19 routes, ${checkedAssets.size} linked static assets, 17 single-hop/query-preserving redirects, SEO/sitemap/robots, and production artifact hygiene passed.`); + assert.equal(canonicalPages.length, 20); assert.equal(legacyRedirects.length, 17); + console.log(`Release hardening HTTP: all 20 routes, ${checkedAssets.size} linked static assets, 17 single-hop/query-preserving redirects, SEO/sitemap/robots, and production artifact hygiene passed.`); } finally { server.kill(); } diff --git a/tests/run-all.mjs b/tests/run-all.mjs index b95802f..c2087de 100644 --- a/tests/run-all.mjs +++ b/tests/run-all.mjs @@ -25,6 +25,7 @@ const sourceFiles = sourceDirectories for (const file of sourceFiles) runNode(["--check", file], `Syntax check for ${path.relative(root, file)}`); for (const test of [ + "tests/scanner.test.mjs", "tests/image-to-pdf.test.mjs", "tests/image-converter.test.mjs", "tests/image-resize.test.mjs", diff --git a/tests/scanner.test.mjs b/tests/scanner.test.mjs new file mode 100644 index 0000000..37434d5 --- /dev/null +++ b/tests/scanner.test.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { File } from "node:buffer"; +import { createScanQueue, MAX_SCAN_PAGES } from "../.ts-build/tools/scan/document/state.js"; +import { createScanPreview, preprocessScanPixels } from "../.ts-build/tools/shared/scan.js"; +import { decodeImage } from "../tools/shared/image.js"; + +const pixels = new Uint8ClampedArray([240, 200, 180, 255, 20, 50, 80, 255]); +const original = pixels.slice(); +assert.deepEqual(preprocessScanPixels(pixels, "original"), original); +assert.deepEqual(preprocessScanPixels(pixels, "grayscale"), new Uint8ClampedArray([210,210,210,255,44,44,44,255])); +assert.deepEqual(preprocessScanPixels(pixels, "document"), new Uint8ClampedArray([255,255,255,255,0,0,0,255])); +assert.deepEqual(pixels, original, "Preprocessing never mutates source pixels"); +assert.throws(() => preprocessScanPixels(pixels, "invalid"), /SCAN_MODE_INVALID/); + +const file = name => new File([Uint8Array.of(137,80,78,71,13,10,26,10,0,0,0,0)], name, { type: "image/png" }); +const preview = async () => ({ blob: new Blob(["preview"]), width: 200, height: 400 }); +const revoked = []; const created = []; const modes = []; +const config = { + preview: async (file, mode) => { modes.push(mode); return preview(); }, + createUrl: () => { const url = `blob:test-${created.length}`; created.push(url); return url; }, + revokeUrl: url => revoked.push(url), +}; +const queue = createScanQueue(config); +assert.equal((await queue.add([file("one.png"), file("two.png"), file("three.png")], "original")).added, 3); +const ids = queue.pages.map(page => page.id); +queue.move(ids[2], -1); +assert.deepEqual(queue.pages.map(page => page.file.name), ["one.png", "three.png", "two.png"]); +assert.equal(queue.move(ids[0], -1), false); +queue.remove(ids[2]); +assert.deepEqual(queue.pages.map(page => page.file.name), ["one.png", "two.png"]); +await queue.setMode("document"); +assert.ok(queue.pages.every(page => page.mode === "document")); +assert.deepEqual(modes, ["original", "original", "original", "document", "document"]); +queue.clear(); assert.equal(queue.pages.length, 0); +assert.deepEqual([...revoked].sort(), [...created].sort(), "Every replaced/removed/cleared URL is revoked once"); +const bad = await queue.add([new File(["text"], "bad.gif", { type: "image/gif" }), new File(["broken"], "broken.png", { type: "image/png" })], "original"); +assert.equal(bad.added, 0); assert.equal(bad.rejected.length, 2); +assert.equal((await queue.add(Array.from({length: MAX_SCAN_PAGES + 1}, (_, i) => file(`${i}.png`)), "original")).rejected[0].code, "SCAN_QUEUE_LIMIT"); +queue.clear(); +const broken = createScanQueue({ ...config, preview: async () => { throw new Error("IMAGE_DECODE_FAILED"); } }); +assert.equal((await broken.add([file("broken.png")], "original")).rejected[0].code, "IMAGE_DECODE_FAILED"); +assert.equal(broken.busy, false); + +// Delayed work cannot resurrect pages after clear/cancel/disposal or replacement. +for (const action of ["clear", "cancel", "dispose", "replace"]) { + let release; let calls = 0; + const delayed = createScanQueue({ ...config, preview: async () => ++calls === 1 ? new Promise(resolve => { release = resolve; }) : preview() }); + const pending = delayed.add([file("old.png")], "original"); + while (!release) await new Promise(resolve => setTimeout(resolve, 0)); + if (action === "replace") await delayed.add([file("new.png")], "grayscale"); else delayed[action](); + release(await preview()); + assert.equal((await pending).cancelled, true); + assert.deepEqual(delayed.pages.map(page => page.file.name), action === "replace" ? ["new.png"] : []); + delayed.dispose(); +} + +// Disposal of a page during a mode update cannot create a leaked preview URL. +let releaseMode; +const modeQueue = createScanQueue({ ...config, preview: async (file, mode) => mode === "original" ? preview() : new Promise(resolve => { releaseMode = resolve; }) }); +await modeQueue.add([file("mode.png")], "original"); +const change = modeQueue.setMode("grayscale"); +modeQueue.remove(modeQueue.pages[0].id); +const before = created.length; releaseMode(await preview()); await change; +assert.equal(created.length, before); + +// Canvas and decoded bitmap cleanup on success, failure and mid-decode abort. +for (const outcome of ["success", "encoder", "canvas", "abort"]) { + let closed = 0; const abort = new AbortController(); + const canvas = { width: 0, height: 0, getContext: () => outcome === "canvas" ? null : ({ fillRect() {}, drawImage() {} }), toBlob(callback) { callback(outcome === "encoder" ? null : new Blob(["png"])); } }; + const options = { signal: abort.signal, canvasFactory: () => canvas, decode: async () => { if (outcome === "abort") abort.abort(); return { width: 4000, height: 6000, source: {}, close() { closed++; } }; } }; + if (outcome === "success") { const result = await createScanPreview(file("x.png"), "original", options); assert.equal(result.width, 667); assert.equal(result.height, 1000); } + else await assert.rejects(createScanPreview(file("x.png"), "original", options)); + assert.equal(closed, 1); + if (outcome !== "abort") assert.equal(canvas.width, 1); +} + +// Shared decoder must explicitly request EXIF normalization and close bitmaps. +let bitmapOptions; let closed = false; +globalThis.window = { createImageBitmap: true }; +globalThis.createImageBitmap = async (source, options) => { bitmapOptions = options; return { width: 30, height: 60, close() { closed = true; } }; }; +const decoded = await decodeImage(file("oriented.png")); +assert.deepEqual(bitmapOptions, { imageOrientation: "from-image" }); +decoded.close(); assert.equal(closed, true); +delete globalThis.window; delete globalThis.createImageBitmap; +queue.dispose(); modeQueue.dispose(); broken.dispose(); +console.log("Scanner state, ordering, limits, pixels, invalid input, stale work, orientation contract and cleanup passed."); diff --git a/tests/seo-foundation.test.mjs b/tests/seo-foundation.test.mjs index beb4c61..3970885 100644 --- a/tests/seo-foundation.test.mjs +++ b/tests/seo-foundation.test.mjs @@ -15,7 +15,7 @@ const indexableRoutes = new Map(canonicalPages.map(({ source, route }) => [sourc const excludedRoutes = ["404.html", "tools/image-to-pdf/index.html"]; const allHtmlRoutes = [...indexableRoutes.keys(), ...excludedRoutes]; -assert.equal(indexableRoutes.size, 19, "all canonical pages come from the route manifest"); +assert.equal(indexableRoutes.size, 20, "all canonical pages come from the route manifest"); const shareImagePath = "assets/images/og-image.png"; const shareImageUrl = `${origin}/${shareImagePath}`; const iconLinks = new Map([ diff --git a/tests/typescript-foundation.test.mjs b/tests/typescript-foundation.test.mjs index 7ea1ba3..5fd7add 100644 --- a/tests/typescript-foundation.test.mjs +++ b/tests/typescript-foundation.test.mjs @@ -21,7 +21,7 @@ assert.equal(typeConfig.compilerOptions.noEmit, true); assert.equal(typeConfig.compilerOptions.sourceMap, false); assert.equal(buildConfig.compilerOptions.outDir, ".ts-build"); -assert.equal(compiledBrowserModules.length, 8, "the compiled TypeScript boundary remains intentionally bounded"); +assert.equal(compiledBrowserModules.length, 10, "the compiled TypeScript boundary remains intentionally bounded"); assert.ok(compiledBrowserModules.some((module) => module.source === "tools/shared/searchable-pdf.ts")); assert.equal(new Set(compiledBrowserModules.map((module) => module.public)).size, compiledBrowserModules.length); for (const module of compiledBrowserModules) { diff --git a/tests/url-namespace.test.mjs b/tests/url-namespace.test.mjs index 47cc2c9..a3dec92 100644 --- a/tests/url-namespace.test.mjs +++ b/tests/url-namespace.test.mjs @@ -8,7 +8,7 @@ import { canonicalPages, legacyRedirects, productionOrigin, redirectStatus } fro const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const routes = new Set(canonicalPages.map(({ route }) => route)); -assert.equal(canonicalPages.length, 19); +assert.equal(canonicalPages.length, 20); assert.equal(legacyRedirects.length, 17); assert.equal(redirectStatus, 308); assert.ok(routes.has("/image/to-text/")); diff --git a/tools/scan/document/app.js b/tools/scan/document/app.js new file mode 100644 index 0000000..94a362c --- /dev/null +++ b/tools/scan/document/app.js @@ -0,0 +1,107 @@ +import { t } from "../../../js/i18n.js"; +import { createScanQueue } from "./state.js"; + +const input = document.querySelector("#file-input"); +const list = document.querySelector("#page-list"); +const mode = document.querySelector("#scan-mode"); +const status = document.querySelector("#tool-status"); +const add = document.querySelector("#add-images"); +const clear = document.querySelector("#clear-images"); +const apply = document.querySelector("#apply-mode"); +const cancel = document.querySelector("#cancel-scan"); +let notice = null; +let noticeValues = {}; +let actionVersion = 0; +const message = (key, values = {}) => Object.entries(values).reduce((text, [name, value]) => text.replaceAll(`{${name}}`, String(value)), t(`documentScanner.${key}`)); +const queue = createScanQueue({ changed: render }); + +function announce(key, values = {}) { notice = key; noticeValues = values; render(); } +function render() { + // Keep existing DOM nodes so progress and reorder do not steal keyboard focus. + const focused = document.activeElement; + for (const child of [...list.children]) if (!queue.pages.some(page => String(page.id) === child.dataset.id)) child.remove(); + queue.pages.forEach((page, index) => { + let card = list.querySelector(`[data-id="${page.id}"]`); + if (!card) { + card = document.createElement("li"); card.className = "scan-page"; card.dataset.id = String(page.id); + const image = document.createElement("img"); image.decoding = "async"; + const name = document.createElement("strong"); const details = document.createElement("p"); + const actions = document.createElement("div"); actions.className = "scan-page-actions"; + for (const action of ["up", "down", "remove"]) { + const button = document.createElement("button"); button.type = "button"; button.className = "button button--secondary"; button.dataset.action = action; actions.append(button); + } + card.append(image, name, details, actions); + } + const image = card.querySelector("img"); if (image.getAttribute("src") !== page.url) image.src = page.url; + image.alt = message("preview", { page: index + 1 }); + card.querySelector("strong").textContent = `${index + 1}. ${page.file.name}`; + card.querySelector("p").textContent = `${page.width} × ${page.height} · ${message(page.mode)}`; + for (const button of card.querySelectorAll("button")) { + const action = button.dataset.action; + button.textContent = message(action); button.setAttribute("aria-label", `${message(action)}: ${page.file.name}`); + button.disabled = (action === "up" && index === 0) || (action === "down" && index === queue.pages.length - 1); + } + // insertBefore avoids detaching nodes already in their correct position. + if (list.children[index] !== card) list.insertBefore(card, list.children[index] || null); + }); + if (focused?.isConnected && document.activeElement !== focused) focused.focus(); + document.querySelector("#queue-empty").hidden = queue.pages.length > 0; + document.querySelector("#page-count").textContent = message("count", { count: queue.pages.length }); + clear.disabled = !queue.pages.length && !queue.busy; + apply.disabled = !queue.pages.length || queue.busy; + mode.disabled = queue.busy; + cancel.hidden = !queue.busy; + list.setAttribute("aria-busy", String(queue.busy)); + status.textContent = queue.busy ? message("processing", { count: queue.pages.length }) : notice ? message(notice, noticeValues) : ""; +} + +async function addFiles(files) { + if (!files.length) return; + const version = ++actionVersion; + try { + const result = await queue.add(files, mode.value); + if (version !== actionVersion) return; + if (result.cancelled) announce("cancelled"); + else if (result.rejected.length) announce("rejected", { added: result.added, names: result.rejected.map(item => `${item.name}: ${message(errorKey(item.code))}`).join("; ") }); + else announce("added", { count: result.added }); + } catch { if (version === actionVersion) announce("failure"); } +} +function errorKey(code) { + if (["SCAN_QUEUE_LIMIT", "IMAGE_FILE_TOO_LARGE", "IMAGE_DIMENSION_EXCEEDED", "IMAGE_PIXELS_EXCEEDED"].includes(code)) return "limit"; + if (["UNSUPPORTED_IMAGE", "IMAGE_SIGNATURE_INVALID"].includes(code)) return "unsupported"; + return "decode"; +} +add.addEventListener("click", () => input.click()); +input.addEventListener("change", () => { void addFiles([...input.files]); input.value = ""; }); +const zone = document.querySelector("#drop-zone"); +for (const event of ["dragover", "drop"]) zone.addEventListener(event, e => e.preventDefault()); +zone.addEventListener("drop", event => { void addFiles([...event.dataTransfer.files]); }); +document.addEventListener("paste", event => { + if (event.target.closest?.("input, textarea, [contenteditable]")) return; + const files = [...(event.clipboardData?.files || [])]; + if (files.length) { event.preventDefault(); void addFiles(files); } +}); +clear.addEventListener("click", () => { ++actionVersion; queue.clear(); announce("cleared"); add.focus(); }); +cancel.addEventListener("click", () => { ++actionVersion; queue.cancel(); announce("cancelled"); add.focus(); }); +apply.addEventListener("click", async () => { + const version = ++actionVersion; + try { const complete = await queue.setMode(mode.value); if (version === actionVersion) announce(complete ? "applied" : "cancelled"); } + catch { if (version === actionVersion) announce("failure"); } + finally { if (version === actionVersion && !queue.busy) apply.focus(); } +}); +list.addEventListener("click", event => { + const button = event.target.closest("button[data-action]"); if (!button) return; + const card = button.closest("[data-id]"); const id = Number(card.dataset.id); + if (button.dataset.action === "remove") { + const index = queue.pages.findIndex(page => page.id === id); queue.remove(id); + const next = queue.pages[Math.min(index, queue.pages.length - 1)]; + (next ? list.querySelector(`[data-id="${next.id}"] [data-action="remove"]`) : add)?.focus(); + announce("removed"); + } else { + queue.move(id, button.dataset.action === "up" ? -1 : 1); announce("reordered"); + const target = list.querySelector(`[data-id="${id}"] button:not(:disabled)`); target?.focus(); + } +}); +document.addEventListener("securetools:languagechange", render); +window.addEventListener("pagehide", event => { ++actionVersion; if (event.persisted) queue.clear(); else queue.dispose(); }); +render(); diff --git a/tools/scan/document/index.html b/tools/scan/document/index.html new file mode 100644 index 0000000..3a8c8be --- /dev/null +++ b/tools/scan/document/index.html @@ -0,0 +1,19 @@ + + + + +Document Scanner — Secure Tools + + + + +
+

Local scan tool

Document Scanner

Arrange and clean document images on this device.

+

Add images

Choose, drop or paste JPEG, PNG or WebP images. Up to 20 pages and 200 MiB total; 50 MiB per image.

Your files stay on your device.

+

Scan appearance

Document mode uses a fixed black-and-white threshold. No automatic cropping or corner detection.

Scanner preview only. PDF export and optional OCR are coming later.

+

Document pages

No pages added yet.

    +
    + + diff --git a/tools/scan/document/state.ts b/tools/scan/document/state.ts new file mode 100644 index 0000000..c8c22a0 --- /dev/null +++ b/tools/scan/document/state.ts @@ -0,0 +1,97 @@ +import { isSupportedImage, MAX_FILE_SIZE, validateImageSignature } from "../../shared/image.js"; +import { createScanPreview } from "../../shared/scan.js"; +import type { ScanMode, ScanPreview, ScanPreviewOptions } from "../../shared/scan.js"; + +export const MAX_SCAN_PAGES = 20; +export const MAX_SCAN_BYTES = 200 * 1024 * 1024; +export interface ScanPage { id: number; file: File; url: string; width: number; height: number; mode: ScanMode } +interface QueueOptions { + preview?: (file: Blob, mode: ScanMode, options: ScanPreviewOptions) => Promise; + createUrl?: (blob: Blob) => string; + revokeUrl?: (url: string) => void; + changed?: () => void; +} + +export function createScanQueue(options: QueueOptions = {}) { + const pages: ScanPage[] = []; + const preview = options.preview || createScanPreview; + const createUrl = options.createUrl || (blob => URL.createObjectURL(blob)); + const revokeUrl = options.revokeUrl || (url => URL.revokeObjectURL(url)); + let controller: AbortController | null = null; + let sequence = 0; + let disposed = false; + const changed = () => options.changed?.(); + + function cancel() { controller?.abort(); controller = null; changed(); } + function start() { + if (disposed) throw new Error("SCAN_DISPOSED"); + cancel(); + const job = new AbortController(); + controller = job; + changed(); + return job; + } + function current(job: AbortController) { return !disposed && controller === job && !job.signal.aborted; } + function finish(job: AbortController) { if (controller === job) { controller = null; changed(); } } + function remove(id: number) { + const index = pages.findIndex(page => page.id === id); + if (index < 0) return; + revokeUrl(pages[index].url); pages.splice(index, 1); changed(); + } + function clear() { cancel(); pages.forEach(page => revokeUrl(page.url)); pages.length = 0; changed(); } + + async function add(files: readonly File[], mode: ScanMode) { + const job = start(); + const rejected: { name: string; code: string }[] = []; + let added = 0; + try { + for (const file of files) { + if (!current(job)) break; + try { + if (!isSupportedImage(file)) throw new Error("UNSUPPORTED_IMAGE"); + if (file.size > MAX_FILE_SIZE) throw new Error("IMAGE_FILE_TOO_LARGE"); + if (pages.length >= MAX_SCAN_PAGES || pages.reduce((total, page) => total + page.file.size, 0) + file.size > MAX_SCAN_BYTES) throw new Error("SCAN_QUEUE_LIMIT"); + await validateImageSignature(file); + if (!current(job)) break; + const result = await preview(file, mode, { signal: job.signal }); + if (!current(job)) break; + pages.push({ id: ++sequence, file, url: createUrl(result.blob), width: result.width, height: result.height, mode }); + added++; changed(); + } catch (error) { + if (!current(job)) break; + rejected.push({ name: file.name, code: error instanceof Error ? error.message : "IMAGE_DECODE_FAILED" }); + } + } + return { added, rejected, cancelled: !current(job) }; + } finally { finish(job); } + } + + async function setMode(mode: ScanMode) { + const job = start(); + try { + for (const page of [...pages]) { + if (!current(job)) return false; + if (page.mode === mode) continue; + const result = await preview(page.file, mode, { signal: job.signal }); + if (!current(job)) return false; + if (!pages.includes(page)) continue; + const url = createUrl(result.blob); + revokeUrl(page.url); page.url = url; page.mode = mode; changed(); + } + return current(job); + } finally { finish(job); } + } + + return { + get pages(): readonly ScanPage[] { return pages; }, + get busy() { return controller !== null; }, + add, setMode, cancel, clear, remove, + move(id: number, offset: number) { + const index = pages.findIndex(page => page.id === id); + const next = index + offset; + if (index < 0 || next < 0 || next >= pages.length) return false; + [pages[index], pages[next]] = [pages[next], pages[index]]; changed(); return true; + }, + dispose() { disposed = true; clear(); }, + }; +} diff --git a/tools/scan/document/tool.css b/tools/scan/document/tool.css new file mode 100644 index 0000000..a1f241d --- /dev/null +++ b/tools/scan/document/tool.css @@ -0,0 +1,12 @@ +.scanner-layout { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); gap: 1.25rem; margin-block: 1.5rem; } +.tool-main [hidden] { display: none !important; } +.scanner-controls, .scanner-pages { padding: clamp(1rem, 3vw, 1.5rem); min-width: 0; } +.scanner-controls select { display: block; width: 100%; margin-block: .5rem; } +.scan-page-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); gap: 1rem; padding: 0; list-style: none; } +.scan-page { min-width: 0; border: 1px solid var(--border); border-radius: .75rem; padding: 1rem; } +.scan-page img { display: block; width: 100%; height: 280px; object-fit: contain; background: #fff; } +.scan-page strong, .scan-page p { display: block; overflow-wrap: anywhere; margin-block: .75rem; } +.scan-page-actions { display: flex; flex-wrap: wrap; gap: .5rem; } +.scan-page-actions button { min-height: 44px; min-width: 44px; white-space: normal; overflow-wrap: anywhere; } +#tool-status { overflow-wrap: anywhere; } +@media (max-width: 700px) { .scanner-layout { grid-template-columns: minmax(0, 1fr); } } diff --git a/tools/scan/index.html b/tools/scan/index.html index d5c6b22..91378b0 100644 --- a/tools/scan/index.html +++ b/tools/scan/index.html @@ -23,4 +23,4 @@
    Menu
    -

    Tool category

    Scan & OCR tools

    Turn scans into useful documents while keeping source material on your device.

    Available tools process file contents locally in browser memory.

    +
    diff --git a/tools/shared/image.d.ts b/tools/shared/image.d.ts new file mode 100644 index 0000000..026cc97 --- /dev/null +++ b/tools/shared/image.d.ts @@ -0,0 +1,12 @@ +export interface DecodedImage { + source: CanvasImageSource; + width: number; + height: number; + close(): void; +} +export const ACCEPTED_IMAGE_TYPES: string; +export const MAX_FILE_SIZE: number; +export function decodeImage(file: Blob): Promise; +export function isSupportedImage(file: Blob): boolean; +export function validateImageSignature(file: Blob): Promise; +export function validateImageDimensions(width: number, height: number): boolean; diff --git a/tools/shared/scan.ts b/tools/shared/scan.ts new file mode 100644 index 0000000..b5aceef --- /dev/null +++ b/tools/shared/scan.ts @@ -0,0 +1,63 @@ +import { decodeImage } from "./image.js"; +import type { DecodedImage } from "./image.js"; + +export const SCAN_MODES = ["original", "grayscale", "document"] as const; +export type ScanMode = typeof SCAN_MODES[number]; +export const SCAN_PREVIEW_EDGE = 1000; + +// Return a copy: callers may safely reuse the original pixels for other modes. +export function preprocessScanPixels(source: Uint8ClampedArray, mode: ScanMode): Uint8ClampedArray { + if (!SCAN_MODES.includes(mode)) throw new Error("SCAN_MODE_INVALID"); + const output = new Uint8ClampedArray(source); + if (mode === "original") return output; + for (let i = 0; i < output.length; i += 4) { + const gray = Math.round(source[i] * 0.299 + source[i + 1] * 0.587 + source[i + 2] * 0.114); + const value = mode === "document" ? (gray >= 160 ? 255 : 0) : gray; + output[i] = output[i + 1] = output[i + 2] = value; + } + return output; +} + +function checkCancellation(signal?: AbortSignal): void { + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); +} + +export interface ScanPreview { blob: Blob; width: number; height: number } +export interface ScanPreviewOptions { + signal?: AbortSignal; + decode?: (file: Blob) => Promise; + canvasFactory?: () => HTMLCanvasElement; +} + +// Only the source File and a bounded preview are retained by the page queue. +// Future exports can decode the source again without exporting thumbnail pixels. +export async function createScanPreview(file: Blob, mode: ScanMode, options: ScanPreviewOptions = {}): Promise { + checkCancellation(options.signal); + const image = await (options.decode || decodeImage)(file); + let canvas: HTMLCanvasElement | undefined; + try { + checkCancellation(options.signal); + canvas = (options.canvasFactory || (() => document.createElement("canvas")))(); + const ratio = Math.min(1, SCAN_PREVIEW_EDGE / Math.max(image.width, image.height)); + const width = canvas.width = Math.max(1, Math.round(image.width * ratio)); + const height = canvas.height = Math.max(1, Math.round(image.height * ratio)); + const context = canvas.getContext("2d", { alpha: false }); + if (!context) throw new Error("CANVAS_UNAVAILABLE"); + context.fillStyle = "#ffffff"; + context.fillRect(0, 0, width, height); + context.drawImage(image.source, 0, 0, width, height); + if (mode !== "original") { + const pixels = context.getImageData(0, 0, width, height); + pixels.data.set(preprocessScanPixels(pixels.data, mode)); + context.putImageData(pixels, 0, 0); + } + const blob = await new Promise((resolve, reject) => canvas!.toBlob( + result => result ? resolve(result) : reject(new Error("IMAGE_EXPORT_FAILED")), "image/png", + )); + checkCancellation(options.signal); + return { blob, width, height }; + } finally { + image.close(); + if (canvas) canvas.width = canvas.height = 1; + } +} diff --git a/tsconfig.build.json b/tsconfig.build.json index 73e475a..a0e481d 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -14,6 +14,8 @@ "tools/pdf/to-text/output.ts", "tools/shared/pdf-ocr.ts", "tools/shared/searchable-pdf.ts", - "tools/shared/*.d.ts" + "tools/shared/*.d.ts", + "tools/shared/scan.ts", + "tools/scan/document/*.ts" ] } diff --git a/tsconfig.json b/tsconfig.json index fd68b31..052d259 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,7 +4,11 @@ "declaration": false, "forceConsistentCasingInFileNames": true, "isolatedModules": true, - "lib": ["ES2022", "DOM", "DOM.Iterable"], + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], "module": "ESNext", "moduleResolution": "Bundler", "noEmit": true, @@ -21,6 +25,8 @@ "tools/shared/searchable-pdf.ts", "tools/shared/*.d.ts", "tools/pdf/split/*.d.ts", - "js/*.d.ts" + "js/*.d.ts", + "tools/shared/scan.ts", + "tools/scan/document/*.ts" ] } From f346ff6c4144ba50c798ad4cf9bd0c79d53ae0cd Mon Sep 17 00:00:00 2001 From: maruson08 Date: Tue, 17 Nov 2026 22:27:32 +0900 Subject: [PATCH 3/4] =?UTF-8?q?=F0=9F=90=9B[Fix]=20Serialize=20scanner=20p?= =?UTF-8?q?review=20decoding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/sprint-24a-scanner-core.md | 2 +- tests/browser/scanner.mjs | 8 ++++++-- tests/scanner.test.mjs | 6 +++++- tools/scan/document/state.ts | 16 ++++++++++++++-- 4 files changed, 26 insertions(+), 6 deletions(-) diff --git a/docs/sprint-24a-scanner-core.md b/docs/sprint-24a-scanner-core.md index ff49a3d..8fcd38b 100644 --- a/docs/sprint-24a-scanner-core.md +++ b/docs/sprint-24a-scanner-core.md @@ -6,7 +6,7 @@ The v2.4 development scanner is `/scan/document/`. It accepts signature-validate Previews retain aspect ratio and EXIF normalization through `decodeImage`. Each preview is at most 1,000 pixels on its longest edge. Source File references remain unchanged; decoded bitmaps and canvas backing stores are released after processing. Preview URLs are revoked on replacement, removal, clear and page exit. The queue admits at most 20 pages / 200 MiB total, plus existing 50-MiB-file / 50-megapixel / 16,384-pixel decoder limits. Oversized or broken inputs produce recoverable messages, while valid files in the batch remain available. -Adding another batch cancels publication from the previous batch. Clear and cancellation invalidate in-flight results. Cancelling appearance changes retains completed pages with their actual mode labels; Apply to all pages is the retry mechanism. Native decoding/encoding cannot be interrupted mid-call, but resources are released and stale results cannot enter the queue. +Adding another batch cancels publication from the previous batch. Clear and cancellation invalidate in-flight results. Cancelling appearance changes retains completed pages with their actual mode labels; Apply to all pages is the retry mechanism. Native decoding/encoding cannot be interrupted mid-call, but resources are released and stale results cannot enter the queue. Replacement previews wait for existing native work to finish, preventing overlapping full-resolution decodes under rapid input changes. ## Branch policy diff --git a/tests/browser/scanner.mjs b/tests/browser/scanner.mjs index b01304e..13f3495 100644 --- a/tests/browser/scanner.mjs +++ b/tests/browser/scanner.mjs @@ -10,7 +10,7 @@ await fs.mkdir(directory, { recursive: true }); 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"] }); -const report = { cases: [], external: [], errors: [], headerErrors: [], status: "FAIL" }; +const report = { cases: [], external: [], mutating: [], errors: [], headerErrors: [], status: "FAIL" }; let browser; try { await new Promise((resolve, reject) => { @@ -51,7 +51,10 @@ try { URL.revokeObjectURL = url => { window.scanUrls.revoked.push(url); revoke(url); }; document.addEventListener("securitypolicyviolation", event => console.error(`CSP: ${event.effectiveDirective}`)); }, language); - context.on("request", request => { if (!request.url().startsWith(`${origin}/`) && !/^(blob:|data:|about:)/.test(request.url())) report.external.push(request.url()); }); + context.on("request", request => { + if (!request.url().startsWith(`${origin}/`) && !/^(blob:|data:|about:)/.test(request.url())) report.external.push(request.url()); + if (!["GET", "HEAD"].includes(request.method())) report.mutating.push({ url: request.url(), method: request.method() }); + }); 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()); }); @@ -125,6 +128,7 @@ try { await context.close(); } assert.deepEqual(report.headerErrors, []); + assert.deepEqual(report.mutating, [], "No document data is posted even to the same origin"); assert.deepEqual(report.external, []); assert.deepEqual(report.errors, []); report.status = "PASS"; console.log("Scanner browser smoke passed: 30 viewport/locale cases; JPEG/PNG/WebP; EXIF; modes; keyboard order; input/drop/paste; large images; cleanup; CSP/network."); diff --git a/tests/scanner.test.mjs b/tests/scanner.test.mjs index 37434d5..5aa8340 100644 --- a/tests/scanner.test.mjs +++ b/tests/scanner.test.mjs @@ -47,9 +47,12 @@ for (const action of ["clear", "cancel", "dispose", "replace"]) { const delayed = createScanQueue({ ...config, preview: async () => ++calls === 1 ? new Promise(resolve => { release = resolve; }) : preview() }); const pending = delayed.add([file("old.png")], "original"); while (!release) await new Promise(resolve => setTimeout(resolve, 0)); - if (action === "replace") await delayed.add([file("new.png")], "grayscale"); else delayed[action](); + let replacement; + if (action === "replace") replacement = delayed.add([file("new.png")], "grayscale"); else delayed[action](); + assert.equal(calls, 1, "Replacement decode waits for native work already in flight"); release(await preview()); assert.equal((await pending).cancelled, true); + await replacement; assert.deepEqual(delayed.pages.map(page => page.file.name), action === "replace" ? ["new.png"] : []); delayed.dispose(); } @@ -59,6 +62,7 @@ let releaseMode; const modeQueue = createScanQueue({ ...config, preview: async (file, mode) => mode === "original" ? preview() : new Promise(resolve => { releaseMode = resolve; }) }); await modeQueue.add([file("mode.png")], "original"); const change = modeQueue.setMode("grayscale"); +while (!releaseMode) await new Promise(resolve => setTimeout(resolve, 0)); modeQueue.remove(modeQueue.pages[0].id); const before = created.length; releaseMode(await preview()); await change; assert.equal(created.length, before); diff --git a/tools/scan/document/state.ts b/tools/scan/document/state.ts index c8c22a0..e64d411 100644 --- a/tools/scan/document/state.ts +++ b/tools/scan/document/state.ts @@ -20,8 +20,20 @@ export function createScanQueue(options: QueueOptions = {}) { let controller: AbortController | null = null; let sequence = 0; let disposed = false; + let previewWork: Promise = Promise.resolve(); const changed = () => options.changed?.(); + // Native decode cannot be interrupted. Serialize replacements behind it so + // rapid input changes cannot accumulate concurrent full-resolution bitmaps. + function renderPreview(file: File, mode: ScanMode, signal: AbortSignal) { + const result = previewWork.then(() => { + if (signal.aborted) throw new DOMException("Cancelled", "AbortError"); + return preview(file, mode, { signal }); + }); + previewWork = result.then(() => {}, () => {}); + return result; + } + function cancel() { controller?.abort(); controller = null; changed(); } function start() { if (disposed) throw new Error("SCAN_DISPOSED"); @@ -53,7 +65,7 @@ export function createScanQueue(options: QueueOptions = {}) { if (pages.length >= MAX_SCAN_PAGES || pages.reduce((total, page) => total + page.file.size, 0) + file.size > MAX_SCAN_BYTES) throw new Error("SCAN_QUEUE_LIMIT"); await validateImageSignature(file); if (!current(job)) break; - const result = await preview(file, mode, { signal: job.signal }); + const result = await renderPreview(file, mode, job.signal); if (!current(job)) break; pages.push({ id: ++sequence, file, url: createUrl(result.blob), width: result.width, height: result.height, mode }); added++; changed(); @@ -72,7 +84,7 @@ export function createScanQueue(options: QueueOptions = {}) { for (const page of [...pages]) { if (!current(job)) return false; if (page.mode === mode) continue; - const result = await preview(page.file, mode, { signal: job.signal }); + const result = await renderPreview(page.file, mode, job.signal); if (!current(job)) return false; if (!pages.includes(page)) continue; const url = createUrl(result.blob); From f33acada5e0406fdb3d20a9e938ce62556c6acec Mon Sep 17 00:00:00 2001 From: maruson08 Date: Tue, 17 Nov 2026 22:28:58 +0900 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=93=84[Docs]=20Clarify=20integration?= =?UTF-8?q?=20protection=20follow-ups?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/development-workflow.md | 2 +- docs/sprint-24a-scanner-core.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/development-workflow.md b/docs/development-workflow.md index 3d6ae8a..e0050a8 100644 --- a/docs/development-workflow.md +++ b/docs/development-workflow.md @@ -50,4 +50,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.4`. Pull requests into `main` pass the branch-policy gate only when the head is exactly `v2.4` 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.4`. Pull requests into `main` pass the branch-policy gate only when the head is exactly `v2.4` or a dedicated `hotfix/*` branch. Existing main/v2.3 branch protections are unchanged. The new v2.4 branch does not inherit remote branch protections automatically; equivalent required-PR/check, resolved-conversation, force-push and deletion protections remain an administrator follow-up. This PR enforces the branch policy in CI but does not claim to configure remote protection settings. Because the repository currently has one maintainer, an approving-review count is not required; explicit merge authorization remains mandatory. diff --git a/docs/sprint-24a-scanner-core.md b/docs/sprint-24a-scanner-core.md index 8fcd38b..8618a24 100644 --- a/docs/sprint-24a-scanner-core.md +++ b/docs/sprint-24a-scanner-core.md @@ -10,7 +10,7 @@ Adding another batch cancels publication from the previous batch. Clear and canc ## Branch policy -Production `main` and tag v2.3.0 were inspected at `2eb8e865e32558bfd031cd65c85d5d0fea64f5c7`; no v2.4 branch existed. v2.4 was bootstrapped from that production commit. The prerequisite policy migration is an independent Config commit in the scanner feature branch, covering AGENTS, workflow documentation, CI/security triggers, Dependabot targets and policy tests. It remains reviewable in the v2.4 PR; neither integration nor production was merged. Existing v2.3 maintenance PRs were not changed. +Production `main` and tag v2.3.0 were inspected at `2eb8e865e32558bfd031cd65c85d5d0fea64f5c7`; no v2.4 branch existed. v2.4 was bootstrapped from that production commit. The prerequisite policy migration is an independent Config commit in the scanner feature branch, covering AGENTS, workflow documentation, CI/security triggers, Dependabot targets and policy tests. It remains reviewable in the v2.4 PR; neither integration nor production was merged. Existing v2.3 maintenance PRs were not changed. Remote protections do not inherit automatically onto a newly created branch; equivalent v2.4 protection settings remain an administrator follow-up. Dependabot’s new target configuration takes effect when present on the repository default branch; this task does not promote development changes into main. ## Verification