diff --git a/.github/workflows/portals.yml b/.github/workflows/portals.yml index c9c5863..8f70d9a 100644 --- a/.github/workflows/portals.yml +++ b/.github/workflows/portals.yml @@ -2,7 +2,7 @@ name: Public portal compatibility on: workflow_dispatch: push: - branches: [feat/paste-verification] + branches: [feat/paste-verification, feat/application-workflows] permissions: contents: read jobs: diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 3888c6d..29ececf 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -27,7 +27,10 @@ jobs: - run: npm test - run: npx playwright install chromium - run: npm run test:browser + - run: node tests/workflows.mjs + if: ${{ !cancelled() }} - run: xvfb-run --auto-servernum --server-args="-screen 0 1280x1024x24" node tests/popup.mjs + if: ${{ !cancelled() }} - run: | python3 scripts/package.py cp dist/SHA256SUMS /tmp/first-checksum @@ -41,6 +44,7 @@ jobs: path: | dist/ test-results/browser-summary.json + test-results/workflow-summary.json test-results/popup-summary.json test-results/screenshots/*.png retention-days: 14 @@ -58,4 +62,4 @@ jobs: GH_TOKEN: ${{ github.token }} run: | version="$(node -p "require('./extension/manifest.json').version")" - gh release create "v$version" "dist/draft-cairn-$version.zip" "dist/draft-cairn-store-kit-$version.zip" dist/SHA256SUMS --target "$GITHUB_SHA" --prerelease --title "Draft Cairn $version · preview" --notes-file docs/release-notes.md + gh release create "v$version" "dist/draft-cairn-$version.zip" "dist/draft-cairn-store-kit-$version.zip" dist/SHA256SUMS --target "$GITHUB_SHA" --prerelease --title "Draft Cairn $version · preview" --notes-file docs/release-notes.md diff --git a/PRIVACY.md b/PRIVACY.md index d991a8a..a482d19 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,6 +1,6 @@ # Privacy policy -Effective 23 October 2026 · Draft Cairn 0.3.0 preview +Effective 5 November 2026 · Draft Cairn 0.4.0 preview Draft Cairn keeps supported field text only on websites you explicitly enable. It also keeps complete oversized, changed or unverified paste originals temporarily, and library answers you deliberately save or import. No account is required. Nothing is sent to the developer. @@ -10,7 +10,7 @@ Recovery records contain answer text, the exact website origin (scheme, host and Raw URL paths, query strings, fragments, cookies and a general browsing-history log are not stored. Hashes are fingerprints, not guaranteed anonymization: someone who knows candidate pages or fields may guess them. Selected site origins are retained for capture and recovery. Arbitrary narrative answers can contain sensitive information even when credential fields are excluded. -Library records contain title, answer text, optional project, local identifier and save time. They have no website association. Settings include selected and blocked origins, field exclusions, retention, metadata and session-storage choices, encryption mode, and appearance (system, light or dark). The extension does not use Chrome Sync. +Library records contain title, answer text, optional project, local identifier and save time. They have no website association. Settings include selected and blocked origins, field exclusions, global/per-site retention, metadata and session-storage choices, encryption mode, and appearance (system, light or dark). The extension does not use Chrome Sync. ## Encryption choices @@ -33,7 +33,7 @@ Copy writes to the system clipboard. Other apps, clipboard managers, Windows cli ## Capture exclusions -Visible, editable standard long-answer fields and recognized top-level Quill, ProseMirror/Tiptap, CKEditor 5 and inline TinyMCE roots qualify. Rich-text snapshots contain rendered plain text, not formatting or attachments, and support copy back only. Password, payment, one-time-code, hidden, read-only and other sensitive-hint fields are filtered. Sensitive autocomplete tokens are excluded; `autocomplete="off"` is allowed. Incognito, frames, generic contenteditable and shadow-root fields are unsupported. Filters are imperfect. Use only where you have authority to retain a local copy. +Visible, editable standard long-answer fields and recognized Quill, ProseMirror/Tiptap, CKEditor 5 and inline TinyMCE roots qualify. Rich-text snapshots contain rendered plain text, not formatting or attachments, and support copy back only. Password, payment, one-time-code, hidden, read-only and other sensitive-hint fields are filtered. Sensitive autocomplete tokens are excluded; `autocomplete="off"` is allowed. Eligible fields in open shadow roots and HTTP/HTTPS frames can save. Embedded frames require both their own origin and the containing website enabled; frame/shadow recovery is copy-only. Incognito, closed shadow roots, opaque/about:blank/srcdoc frames and generic contenteditable are unsupported. Filters are imperfect. Use only where you have authority to retain a local copy. Post-paste checks inspect the plain-text clipboard payload only during a trusted paste in a qualifying field. They compare visible text after 1.5 seconds, or keep an original for manual review when comparison is interrupted or a rich selection cannot be matched. Originals are encrypted under the selected storage mode. The page can hold at most four original/observed-text reviews in memory until dismissed, reload, protection off or close; vault locking does not erase text already present on a website or these page-memory copies. Visible matches do not prove server acceptance. No background clipboard history is collected. @@ -41,7 +41,7 @@ You can block a site from the popup. A field can be excluded from the larger on- ## Retention and deletion -New installations default to one day of recovery. Existing installations retain their choice. Options are 1, 3, 7, 14 or 30 days. Separate original-paste records expire within one hour. Expired records are excluded on reads and removed on successful writes, hourly cleanup or startup while Chrome runs. Closed-browser files may retain expired bytes until cleanup succeeds. +New installations default to one day of recovery. Existing installations retain their choice. Options are 1, 3, 7, 14 or 30 days globally and per site. Organization-managed policy can restrict allowed origins and cap retention. Increasing retention does not extend earlier expiry or override storage budgets. Separate original-paste records expire within one hour. Expired records are excluded on reads and removed on successful writes, hourly cleanup or startup while Chrome runs. Closed-browser files may retain expired bytes until cleanup succeeds. Recovery is a rolling buffer: the oldest revisions can disappear earlier at the 180-record or 6 MiB total plaintext budget. Library capacity reserves space for recovery; library answers are never evicted. Evictions are shown in the UI. @@ -54,3 +54,13 @@ Individual drafts, site drafts/access, library answers or all extension data can Handled data is used only for the disclosed answer-recovery, paste-protection and answer-library features. It is not sold, used for advertising or credit decisions, or made accessible to the developer. Use follows the Chrome Web Store User Data Policy, including Limited Use requirements. Use [GitHub issues](https://github.com/librerob/draft-cairn/issues) for general questions with synthetic examples only. Never post confidential answers. For vulnerabilities use the route in [SECURITY.md](SECURITY.md). + +## Optional workflow actions (0.4.0) + +The library picker sends saved titles/projects, and the selected answer, to the isolated content script only after the user opens it on an enabled page. Its closed-shadow editor is a convenience, not a security boundary against a compromised live website or browser. Explicit insertion exposes text to that website. Existing text outside the saved selection is preserved; changed destinations cancel insertion. Visible results are checked after 1.5 seconds without verifying server receipt. + +Counter hints read short visible field-associated counters on enabled pages. They are advisory; no counter contents or usage analytics are sent to the developer. The shortcut opens the same explicit picker and does not insert automatically. + +Application snapshot export writes selected saved answers to readable local Markdown, including question labels only where page details were saved. No automatic submission receipt is collected. It is not proof that an application was sent or accepted. The exported file is outside vault protection. The local practice page stores synthetic answer text in the ordinary encrypted recovery buffer, capped at one day, without enabling any website. + +Frame capture additionally uses a hashed containing-page/frame scope. Raw containing-page paths and queries are not stored. Exact origins and per-site retention settings remain operational metadata under the automatic profile key. Organization policy is read from Chrome managed storage. It supplies restrictions only; it does not grant access, enable a server, share answers, or upload usage. diff --git a/README.md b/README.md index 6af3081..bb123a0 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![Draft Cairn — Your words. Still within reach.](docs/store/readme-header.svg) -Local answer recovery for long web applications. A free, MIT-licensed Chrome extension for grant writers, consultants, and agencies working through application portals. +Keep a local safety copy of long application answers. Recover lost writing, check answer fit, and reuse approved paragraphs. Free, MIT-licensed, and private by default. Draft Cairn keeps a local safety copy of supported answers on websites you choose. @@ -28,7 +28,7 @@ This is an early preview. Commercial demand and broad compatibility have not bee ## Install -1. Download `draft-cairn-0.3.1.zip` from [Releases](https://github.com/librerob/draft-cairn/releases), verify it against `SHA256SUMS`, and extract it. +1. Download `draft-cairn-0.4.0.zip` from [Releases](https://github.com/librerob/draft-cairn/releases), verify it against `SHA256SUMS`, and extract it. 2. Open `chrome://extensions`, enable Developer mode, choose **Load unpacked**, and select the extracted folder containing `manifest.json`. 3. Pin Draft Cairn. On an ordinary HTTP/HTTPS website, open its popup and choose **Enable for this site**. Approve Chrome's site-access request. 4. Type in a supported field and wait for **saved on this device**. Open **Recovery & library** to inspect saved text. @@ -42,10 +42,26 @@ Preparing a store listing? The release also includes a separate `draft-cairn-sto - Visible, editable standard textareas, and ordinary text inputs with a declared `maxlength` of at least 120. - Plain-text answers in targeted top-level Quill, ProseMirror/Tiptap, CKEditor 5 and inline TinyMCE roots. Rich-text recovery uses copy back; formatting and attachments are not saved. - Up to 180 recovery records in a rolling history; the oldest recovery records are removed when the count or byte budget is reached, with a visible notice. Explicit library answers are never evicted. Up to four snapshots per field. Rapid edits update the current snapshot; revisions at least 30 seconds apart can remain as earlier snapshots. -- One day of recovery by default on new installs (existing choices are preserved), configurable to 1, 3, 7, 14, or 30 days. Complete oversized pastes expire within one hour. Expiry cleanup runs hourly while Chrome is running and on reads/startup. +- One day of recovery by default on new installs (existing choices are preserved), configurable to 1, 3, 7, 14, or 30 days globally and per site. Increasing retention does not extend earlier records or defeat storage eviction. Complete oversized pastes expire within one hour. Expiry cleanup runs hourly while Chrome is running and on reads/startup. - Library answers with a title and optional project. These remain until deleted; import/export uses a [documented v1 format](docs/library-format.md). -The current source supports only the top-level page. Generic contenteditable, frames, shadow-root fields, browser-internal pages and incognito remain excluded. See the [public portal and editor sample matrix](docs/portal-matrix.md) and [precise compatibility limits](docs/compatibility.md). A public demo result does not establish compatibility with every customer portal using that technology. +Supported ordinary fields and targeted rich editors can also save in open shadow roots and authorized HTTP/HTTPS frames. Enable both the containing site and an embedded form’s exact origin. Frame and shadow-root recovery is copy-only. Closed shadow roots, opaque/about:blank/srcdoc frames, generic contenteditable, browser-internal pages and incognito remain excluded. See the [public portal and editor sample matrix](docs/portal-matrix.md) and [precise compatibility limits](docs/compatibility.md). A public demo result does not establish compatibility with every customer portal using that technology. + +![Real local save, reload and recovery exercise](docs/images/recovery-demo.gif) + +## Reuse an answer without guessing the fit + +Focus a supported field, open the on-page Draft Cairn editor and choose **Use library answer**, or press **Alt+Shift+L** (configure conflicts in `chrome://extensions/shortcuts`). Choose a saved paragraph, inspect the projected result and character/word counts, then explicitly insert it at the saved cursor. Existing text outside your selection stays. A changed destination cancels insertion; oversized HTML limits disable it. The extension checks the visible result after 1.5 seconds. Rich editors remain copy-only. + +A visible, explicitly linked `342/500 words` or `120/500 characters` counter can supply an advisory website limit. Local word counts are whitespace estimates; website rules can differ. Conflicting or unrecognized counters are ignored. These hints do not prove server acceptance or block form submission. + +## Try it and keep an application copy + +Choose **Try a sample recovery** in the toolbar popup for a local, synthetic save → reload → recover exercise using the real encrypted store. It does not grant website access. On real sites, enable protection before writing. + +In Recovery drafts, select the saved revisions you want and choose **Export selected snapshot**. The readable Markdown file contains only those revisions, with question labels when page details were saved. It is an application snapshot, **not proof of submission**. It can miss fields that were never captured or have expired; exports remain outside vault protection. + +For several portals, use **Sites & settings → Enable several exact website origins** to request their host access together. Both the parent website and the embedded form origin must be enabled for frame capture. No vendor-wide wildcard presets or untested compatibility promises are bundled. Optional [organization policies](docs/managed-policy.md) restrict allowed origins and maximum retention; they never silently grant Chrome access. ## Appearance @@ -101,6 +117,9 @@ Plain JavaScript, HTML, and CSS keep review and maintenance straightforward. The Restoration uses a hashed page path, a stable field descriptor, and the ordered form structure. Duplicate or missing identities refuse restoration. Pages with query strings or fragments support copying only. This conservatism reduces wrong-field restoration; it cannot prove that a website has kept the same meaning for an identifier. Always check restored text before submitting. +- [Ten-tester pilot kit](docs/tester-kit.md) — invitation, synthetic tasks and grant-portal worksheet. +- [Organization policy](docs/managed-policy.md) — optional origin restrictions and retention caps. +- [Edge handoff](docs/edge-handoff.md) — prepared instructions; native Edge testing and submission remain pending. - [Commercial validation](docs/commercial-validation.md) — first users, alternatives, and decision criteria. - [Costs](docs/costs.md) — current requirements, no recurring infrastructure, future cost categories. - [Store listing and submission checklist](docs/chrome-web-store.md). diff --git a/demo/frame.html b/demo/frame.html new file mode 100644 index 0000000..009ba68 --- /dev/null +++ b/demo/frame.html @@ -0,0 +1 @@ +Synthetic embedded form diff --git a/demo/workflows-fixture.js b/demo/workflows-fixture.js new file mode 100644 index 0000000..abe7671 --- /dev/null +++ b/demo/workflows-fixture.js @@ -0,0 +1,8 @@ +for(const [id,mode] of [['shadow-host','open'],['private-host','open'],['closed-host','closed']]){ + const host=document.getElementById(id),root=host.attachShadow({mode}); + const label=document.createElement('label');label.textContent='Synthetic shadow narrative'; + const area=document.createElement('textarea');area.id=id+'-answer';area.rows=5;label.append(area);root.append(label); + if(mode==='closed')globalThis.focusClosed=()=>area.focus(); +} +document.getElementById('narrative').addEventListener('input',e=>{document.getElementById('narrative-count').textContent=(e.target.value.trim().match(/\S+/g)||[]).length+'/50 words';}); +document.getElementById('synthetic-form').addEventListener('submit',e=>e.preventDefault()); diff --git a/demo/workflows.html b/demo/workflows.html new file mode 100644 index 0000000..d2b9dce --- /dev/null +++ b/demo/workflows.html @@ -0,0 +1 @@ +Synthetic workflow fixture

Synthetic application

0/50 words
diff --git a/docs/chrome-web-store.md b/docs/chrome-web-store.md index 73253bb..91b774c 100644 --- a/docs/chrome-web-store.md +++ b/docs/chrome-web-store.md @@ -1,14 +1,14 @@ # Chrome Web Store preparation -Updated 24 October 2026. The publisher reports that Draft Cairn is already live. Upload this higher-version package to the existing item; this agent has not submitted the Store update. +Updated 5 November 2026. The publisher reports that Draft Cairn is already live. Upload this higher-version package to the existing item; this agent has not submitted the Store update. ## Readiness -The **0.3.1 preparation kit contains the required image assets**, the install ZIP, listing copy, privacy policy, reviewer instructions and a public compatibility matrix. Version 0.3.1 fixes a narrow toolbar popup. It retains the post-paste visible-text checks and targeted plain-text rich-editor recovery introduced in 0.3.0. The system/light/dark Material-inspired interface, optional passphrase vault and privacy controls remain. The store icon has a 96×96 design inside its 128×128 PNG with 16px transparent margins. The promotional tile is 440×280; the four real-interface screenshots are 1280×800. Dimensions and margins are checked by `scripts/check-assets.py` against the current official image guide. +The **0.4.0 preparation kit contains the required image assets**, the install ZIP, listing copy, privacy policy, reviewer instructions and a public compatibility matrix. Version 0.4.0 adds guarded library insertion, scoped frame/open-shadow capture, advisory counter hints, per-site retention, selected Markdown snapshots and a local practice exercise. It retains the post-paste visible-text checks and targeted plain-text rich-editor recovery introduced in 0.3.0. The system/light/dark Material-inspired interface, optional passphrase vault and privacy controls remain. The store icon has a 96×96 design inside its 128×128 PNG with 16px transparent margins. The promotional tile is 440×280; the four real-interface screenshots are 1280×800. Dimensions and margins are checked by `scripts/check-assets.py` against the current official image guide. **Submission remains pending final manual checks:** load the unmodified ZIP in a fresh Chrome profile, test the real optional host-permission approval/denial/revocation, actual OS clipboard paste/copy, and an intended application portal with synthetic data. The [manual smoke-test worksheet](store/manual-smoke-test.md) gives the exact steps. Browser CI pre-grants localhost access, so it does not verify those native flows. The owner's developer account, verification, and distribution settings must also be completed in the dashboard. -Download `draft-cairn-store-kit-0.3.1.zip` from GitHub Releases and extract it. **Only upload the inner `extension/draft-cairn-0.3.1.zip` as the package.** The outer kit is a preparation folder, not an installable extension. Upload the files under `listing/` separately into their respective image/text fields. Editable brand sources stay in `docs/store/` in the source repository. +Download `draft-cairn-store-kit-0.4.0.zip` from GitHub Releases and extract it. **Only upload the inner `extension/draft-cairn-0.4.0.zip` as the package.** The outer kit is a preparation folder, not an installable extension. Upload the files under `listing/` separately into their respective image/text fields. Editable brand sources stay in `docs/store/` in the source repository. ## Draft listing @@ -33,11 +33,11 @@ Review saved revisions by site and saved time. Page titles and field details are Before a paste exceeds an HTML field's declared character limit, Draft Cairn stops the paste and opens a larger editor with the complete original and a counter. After an allowed paste it compares the visible text after 1.5 seconds. Changed or unverified pastes offer the complete original for review, with a short-lived local copy if saving succeeds. Server acceptance and later changes are not checked. It never rewrites or shortens your answer. -Keep reusable answers in a simple library with titles, projects, search, copying, and JSON export/import. Choose a light or dark theme, or let the workspace, popup and larger editor follow your system. All implemented local features are free. +Keep reusable answers in a simple library with titles, projects, search, copying, explicit insertion previews and JSON export/import. Optional linked website counters supply advisory word/character limits. Select saved revisions to export an application snapshot as readable Markdown; it is not proof of submission. Choose a light or dark theme, or let the workspace, popup and larger editor follow your system. All implemented local features are free. No account, analytics, ads, remote AI, or answer transmission. Answers stay in this browser profile. New installations default to one day of recovery (existing choices are preserved), with oldest-first eviction if the recovery budget fills; temporary original pastes last up to one hour. Library answers stay until deleted. Answer records are encrypted automatically with a key in the same profile. An optional passphrase vault protects answer contents in copied profile files and keeps saving while locked. Unlock to read; forgotten passphrases cannot be reset. Operational metadata has a separate automatic key in the profile; the vault does not hide it from a profile holder. Session-only recovery, site/field exclusions, encrypted library backups and a popup wipe are available. Sensitive text cannot always be recognized. Clipboard history and exported copies remain outside extension controls. -Protection must be enabled before a loss, and the save must complete. This preview supports standard textareas, long ordinary text inputs and targeted rich-text roots on top-level web pages. Rich-text snapshots preserve plain text and use copy back only. It excludes incognito, generic contenteditable, frames, shadow roots and sensitive-hint fields. The public sample matrix records tested configurations and access limits. Recovery cannot recover earlier unsaved text or extend a website's session. Keep a separate copy of important work. +Protection must be enabled before a loss, and the save must complete. This preview supports standard textareas, long ordinary text inputs and targeted rich-text roots in HTTP/HTTPS documents, open shadow roots and explicitly enabled frames. Rich-text snapshots preserve plain text and use copy back only. It excludes incognito, generic contenteditable, closed shadow roots, opaque frames and sensitive-hint fields. Frames need both their own origin and the containing site enabled; frame/shadow recovery is copy-only. The public sample matrix records tested configurations and access limits. Recovery cannot recover earlier unsaved text or extend a website's session. Keep a separate copy of important work. **Suggested category:** Tools (under Productivity if grouped). @@ -56,7 +56,7 @@ Protection must be enabled before a loss, and the save must complete. This previ | `scripting` | Register and inject the capture script only for granted hosts; enable it immediately in the chosen tab. | | `activeTab` | Identify the user's chosen website when opening the toolbar popup, without global browsing-history permission. | | `alarms` | Expire draft records periodically while Chrome runs. | -| Optional `http://*/*`, `https://*/*` | Allow the user to select an arbitrary application website. Only the exact chosen host pattern is requested in a user gesture. Chrome host grants cover all ports; the worker separately enforces the exact origin. No blanket host grant at installation. | +| Optional `http://*/*`, `https://*/*` | Allow the user to select an arbitrary application website. Only explicitly chosen host patterns are requested in a user gesture, individually or in a reviewed batch. Embedded forms require both parent and frame origins enabled. Chrome host grants cover all ports; the worker separately enforces the exact origin. No blanket host grant at installation. | No remotely hosted code, externally connectable API, analytics, or server communication. Explain local handling of website contents accurately in the current dashboard's data-use fields; do not conflate “not transmitted to the developer” with “no sensitive information is processed.” The privacy policy describes local text, site metadata, clipboard/export, retention, and deletion. @@ -72,7 +72,7 @@ No sale/transfer to third parties, unrelated use or credit/lending use. No remot - [ ] Review limitations and privacy policy for the exact version. Do not call the preview production-ready or universally compatible. - [ ] Register/sign in to the intended Google developer account, verify email and publisher details, enable required two-step verification, and complete any identity/trader/contact verification currently required. Owner accepts legal agreements personally. - [ ] Confirm the one-time registration fee (official source: US$5) and obtain explicit payment authorization before paying. No recurring services are required. -- [ ] Run CI and deterministic packaging. Verify `SHA256SUMS`. Upload only `draft-cairn-0.3.1.zip`, with `manifest.json` at its root. +- [ ] Run CI and deterministic packaging. Verify `SHA256SUMS`. Upload only `draft-cairn-0.4.0.zip`, with `manifest.json` at its root. - [ ] Supply the original 128×128 icon from `extension/icons/128.png`. The synthetic screenshots `docs/images/recovery.png` and `docs/images/library.png` are prepared at 1280×800. Review them against the current [image guide](https://developer.chrome.com/docs/webstore/images) before upload; they show the real extension UI with synthetic fixtures. - [ ] Review and upload the prepared 440×280 small promotional tile, `docs/store/small-promo.png`, and any desired optional assets under the current image guide. No invented customers, rankings, or paid offers are included. - [ ] Fill listing, single purpose, permission justifications, remote-code declaration, data-use/privacy fields, distribution, support/privacy URLs, and test instructions. Check consistency with `PRIVACY.md`. diff --git a/docs/commercial-validation.md b/docs/commercial-validation.md index c27077b..a1c0da6 100644 --- a/docs/commercial-validation.md +++ b/docs/commercial-validation.md @@ -17,6 +17,7 @@ Sources checked 22 October 2026. These are a feature and license review, not a p | [Typio Form Recovery Reboot](https://github.com/tsukumijima/typio-form-recovery-reboot) | Automatic form-input history and recovery, including manual selection of a target. | Its [license.txt](https://github.com/tsukumijima/typio-form-recovery-reboot/blob/master/license.txt) uses CC BY-NC-ND 4.0, which restricts commercial use and sharing adaptations. Do not describe that license as open-source software licensing or reuse its code here. | | [Form History Control II](https://github.com/stephanmahieu/formhistorycontrol-2) | General form-history viewing, management, and recovery. | [MIT](https://github.com/stephanmahieu/formhistorycontrol-2/blob/master/LICENSE). A direct open-source alternative. No source copied. | | [Form Recover](https://formrecover.com/docs/) | Documentation describes immediate across-site capture and local recovery. | No reusable source license was established in the documentation reviewed; treat it as a product reference, not a source-code dependency. Security claims were not independently audited. | +| [Typeback](https://addons.mozilla.org/en-US/firefox/addon/typeback/) | Advertises rich-editor/web-component recovery and local version history. | Firefox listing declares MIT. Complete public extension source and advertised compatibility were not independently verified; the linked GitHub repository currently contains its website/privacy files. Checked 5 November 2026. | | A local document or approved-text folder | Draft outside the portal and manually copy; often already sufficient. | Depends on the chosen editor. This is the strongest low-complexity substitute. | Draft Cairn's specific deliverable is a deliberately opt-in workflow combining conservative long-answer recovery, selection-aware declared-limit paste interception, and a project-grouped answer library. Exact-origin capture, copy-only uncertain matches, and short default retention make the tradeoff visible. Individual features have precedents; no claim to be the first, unique, safer than every competitor, or universally compatible is warranted. @@ -44,3 +45,7 @@ Treat the following as preselected decision thresholds, not achieved results: - **Stop or pause product investment:** fewer than three return after onboarding, none takes a concrete payment-related step, most are satisfied with document-first drafting, or confidentiality requirements make the approach unacceptable. Any wrong-field restore, loss caused by the extension, or unexpected sensitive capture blocks expanding deployment until investigated and fixed. The first ten testers provide directional evidence, not proof of market size or recurring revenue. + +## Pilot materials + +Use the [tester kit](tester-kit.md) for invitations, interview questions and the five-platform worksheet. Materials prepared does not mean participants recruited or demand validated. No outreach, account creation, paid plan or Store submission is performed by preparing these files. diff --git a/docs/compatibility.md b/docs/compatibility.md index b3f8ce8..c589d7f 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -2,13 +2,13 @@ Chrome 120+ · Manifest V3 · preview release -Supported: editable visible standard textareas and `input type=text` with `maxlength` at least 120, in the top-level HTTP/HTTPS page. Long ordinary inputs without a declared limit are deliberately skipped. Dynamic fields are handled through delegated trusted input and paste events. Programmatically dispatched events are ignored; sites that make changes without real input events may not save them. Unsupported editable focus shows “not protected in this field”; no focused supported field shows a neutral prompt. Standard `input` and `change` events are dispatched after an explicit restoration; framework-controlled fields may still reject or transform text. +Supported: editable visible standard textareas and `input type=text` with `maxlength` at least 120, in ordinary HTTP/HTTPS documents, including open shadow roots and explicitly authorized frames. Long ordinary inputs without a declared limit are deliberately skipped. Dynamic fields are handled through delegated trusted input and paste events. Programmatically dispatched events are ignored; sites that make changes without real input events may not save them. Unsupported editable focus shows “not protected in this field”; no focused supported field shows a neutral prompt. Standard `input` and `change` events are dispatched after an explicit restoration; framework-controlled fields may still reject or transform text. ## Targeted rich text -Plain-text capture also recognizes top-level editable DIV roots for Quill (`ql-editor`), ProseMirror/Tiptap (`ProseMirror`), CKEditor 5 (`ck-editor__editable` with textbox role), and inline TinyMCE (`mce-content-body`). These are DOM adapters, not privileged integrations with vendor APIs. They capture rendered text after trusted input, including events originating in nested paragraphs. Formatting, images, attachments and editor document models are not saved. All rich-text recovery is **copy back only**, even with page details enabled. Generic contenteditable fields are not automatically included. Consult the [public sample matrix](portal-matrix.md) for which actual configurations have been exercised; recognizing an editor's class is not proof of every version or portal integration. +Plain-text capture also recognizes editable DIV roots for Quill (`ql-editor`), ProseMirror/Tiptap (`ProseMirror`), CKEditor 5 (`ck-editor__editable` with textbox role), and inline TinyMCE (`mce-content-body`). These are DOM adapters, not privileged integrations with vendor APIs. They capture rendered text after trusted input, including events originating in nested paragraphs. Formatting, images, attachments and editor document models are not saved. All rich-text recovery is **copy back only**, even with page details enabled. Generic contenteditable fields are not automatically included. Consult the [public sample matrix](portal-matrix.md) for which actual configurations have been exercised; recognizing an editor's class is not proof of every version or portal integration. -Excluded: incognito, frames (including iframe-based TinyMCE), generic contenteditable, shadow-root fields, password/payment/OTP/hidden fields, disabled/read-only/inert fields, fields with sensitive autocomplete tokens (ordinary `off` is supported), and elements inside `data-cairn-ignore`. Rich roots containing nested inputs, autocomplete attributes or private regions are skipped. The extension UI is excluded from capture. +Excluded: incognito, closed shadow roots, opaque/about:blank/srcdoc frames, generic contenteditable, password/payment/OTP/hidden fields, disabled/read-only/inert fields, fields with sensitive autocomplete tokens (ordinary `off` is supported), and elements inside `data-cairn-ignore`. Rich roots containing nested inputs, autocomplete attributes or private regions are skipped. The extension UI is excluded from capture. ## Paste checks @@ -33,3 +33,17 @@ The 180-record/6 MiB recovery budget is rolling: oldest recovery records can be Expiry is enforced on reads and cleanup attempts while Chrome runs, not while the browser is closed. Site deletion keeps explicitly saved library answers. Clearing extension data does not erase exports, OS clipboard history, browser-profile backups, or the website's own copies. Direct restoration also requires saving page titles and field details in settings before capture. New installations leave this off and use copy-only recovery. Enabling the option does not recreate descriptors for older drafts. Vault reading/restoration requires unlocking; capture can continue while locked. + +## Embedded forms and web components (0.4.0) + +Delegated trusted events use their composed path to find eligible fields in open shadow roots, including dynamically attached components. Sensitive, hidden and private ancestors across open shadow hosts are checked. Closed roots are not pierced. Recovery from shadow roots is copy-only; dynamic component identities are not treated as safe restore targets. + +HTTP/HTTPS frames need their own exact origin enabled **and** an enabled containing top-level origin, with Chrome host grants for both. No `webNavigation`, `` installation grant, main-world code or opaque-origin fallback is added. Frame identities include a hashed containing-page scope and frame identifier to separate copies; frame recovery is copy-only. Repeated identical frames or navigation can create distinct revision groups. Reload open pages after batch enablement. An inaccessible frame never inherits authorization solely from its parent's permission. Private markers in a cross-origin parent cannot be inspected from its child; disable that frame origin if local retention is inappropriate. Same-origin hidden/private frame containers are filtered. + +## Explicit library insertion and counter hints + +The on-page editor and Alt+Shift+L shortcut offer a searchable title/project picker only after a deliberate action. Unlock the vault in the workspace first. Choosing an answer loads a preview; insertion into eligible ordinary inputs/textareas requires another click. The saved selection is replaced, leaving all other text intact. Destination value, identity, connectivity, exclusion and access are checked again. A site changing text after insertion is reported after 1.5 seconds; changes later than that and server acceptance are not checked. Rich editors offer copying only. As with the larger editor, selected library text is now in the page context; vault locking does not erase that text. + +Only short visible `N/M words` or `N/M characters` counters linked through `aria-describedby`, or explicit counter elements in a single-field container, are recognized. Ambiguous limits are ignored. Local words are whitespace-delimited estimates and characters use UTF-16 units; portal counters can use other rules. Counter hints are advisory and never inferred from arbitrary nearby prose. A submit event can display an advisory warning, but submission is never intercepted or certified. + +The practice page uses a real encrypted synthetic recovery record with a one-day cap; Delete practice drafts removes it. It does not test native host grants. Snapshot export is explicit selection of existing saved revisions, not automatic submit detection, a full form backup, or a server receipt. It does not capture unchecked controls, files or unsaved values. diff --git a/docs/edge-handoff.md b/docs/edge-handoff.md new file mode 100644 index 0000000..94f8f6b --- /dev/null +++ b/docs/edge-handoff.md @@ -0,0 +1,9 @@ +# Microsoft Edge submission handoff + +The Chromium MV3 package is prepared for an Edge pilot, not a verified Edge release. No Edge listing has been submitted. + +Before submission, load the unmodified ZIP in a fresh current Edge profile and test native host permission approval/denial/revocation, actual toolbar sizing in both themes, saving/restart/recovery, clipboard behavior, shortcut conflicts, and encrypted library backup. Chrome/Linux CI is not Edge evidence. + +Use the current extension ZIP, existing local icon/screenshots, accurate listing copy and public privacy policy. Register/open the publisher account in [Microsoft Partner Center](https://partner.microsoft.com/dashboard/microsoftedge/overview), create the Edge add-on listing, and review its current required fields. The Edge listing ID is separate from Chrome; do not promise automatic transfer of saved Chrome drafts or vault keys. Follow the [official publishing guide](https://learn.microsoft.com/en-us/microsoft-edge/extensions/publish/publish-extension). + +Publisher account verification and submission remain owner actions. The repository contains no payment integration, tracking or remote code. diff --git a/docs/images/library-dark.png b/docs/images/library-dark.png index a2a3901..fd9f6e4 100644 Binary files a/docs/images/library-dark.png and b/docs/images/library-dark.png differ diff --git a/docs/images/library.png b/docs/images/library.png index 2c7d5de..9a95a65 100644 Binary files a/docs/images/library.png and b/docs/images/library.png differ diff --git a/docs/images/recovery-dark.png b/docs/images/recovery-dark.png index 6d02758..8d0e391 100644 Binary files a/docs/images/recovery-dark.png and b/docs/images/recovery-dark.png differ diff --git a/docs/images/recovery-demo.gif b/docs/images/recovery-demo.gif new file mode 100644 index 0000000..d8901ba Binary files /dev/null and b/docs/images/recovery-demo.gif differ diff --git a/docs/images/recovery.png b/docs/images/recovery.png index c27cc6e..6418207 100644 Binary files a/docs/images/recovery.png and b/docs/images/recovery.png differ diff --git a/docs/images/workflow-library-dark.png b/docs/images/workflow-library-dark.png new file mode 100644 index 0000000..760c8e2 Binary files /dev/null and b/docs/images/workflow-library-dark.png differ diff --git a/docs/images/workflow-library.png b/docs/images/workflow-library.png new file mode 100644 index 0000000..2445e7a Binary files /dev/null and b/docs/images/workflow-library.png differ diff --git a/docs/managed-policy.md b/docs/managed-policy.md new file mode 100644 index 0000000..6cd05d3 --- /dev/null +++ b/docs/managed-policy.md @@ -0,0 +1,18 @@ +# Organization policy + +Draft Cairn 0.4.0 reads Chrome `storage.managed` using the packaged managed schema. This is an optional local restriction mechanism, not a paid team service or cloud administration product. + +```json +{ + "AllowedOrigins": ["https://your-organization.example"], + "MaxRetentionDays": 7 +} +``` + +`AllowedOrigins` is an optional list of up to 80 exact HTTP/HTTPS origins, with no paths, wildcards or login details. When absent, users can choose sites normally. An explicitly empty list denies all website capture. Both the containing page and any embedded frame origin must be allowed. Invalid entries are ignored, leaving the list restrictive. This policy does not request Chrome permissions or enable any site automatically. Existing settings for newly disallowed sites are removed during maintenance; existing saved drafts are retained until expiry or deletion. + +`MaxRetentionDays` is one of 1, 3, 7, 14 or 30. It caps new recovery records and shortens existing recovery expiry during policy-change/startup/hourly maintenance. Site/global retention controls cannot exceed it. A longer future policy does not resurrect expired records. The one-hour original-paste cap and storage eviction still apply. Explicit library answers remain until deleted; this policy is not an organization-wide data retention guarantee. + +Deploy the values through your organization's supported Chrome extension policy channel, using the actual published extension ID. Follow [Chrome's managed-storage documentation](https://developer.chrome.com/docs/extensions/reference/manifest/storage). Do not paste policy settings into a website or grant all-site host access merely to deploy these restrictions. + +Tests simulate managed values through Chrome's managed-storage reader and exercise capture/API enforcement. Native managed Chrome deployment and OS-specific registry/plist delivery remain unverified. Test with synthetic answers in a managed pilot profile before rollout. diff --git a/docs/popup-validation-0.4.0.json b/docs/popup-validation-0.4.0.json new file mode 100644 index 0000000..0e6323a --- /dev/null +++ b/docs/popup-validation-0.4.0.json @@ -0,0 +1,126 @@ +{ + "version": "0.4.0", + "browser": "151.0.7922.34", + "nativeToolbar": true, + "syntheticOnly": true, + "shortcuts": [ + { + "scale": 1, + "opened": true + }, + { + "scale": 1.25, + "opened": true + } + ], + "permissionPrompt": "not tested; loopback host pre-granted in test copy", + "results": [ + { + "scale": 1, + "theme": "light", + "enabled": false, + "width": 395, + "height": 600, + "rootWidth": 380, + "bodyWidth": 380, + "scheme": "light", + "status": "Protection is off", + "toggle": 302, + "card": 340 + }, + { + "scale": 1, + "theme": "dark", + "enabled": false, + "width": 395, + "height": 600, + "rootWidth": 380, + "bodyWidth": 380, + "scheme": "dark", + "status": "Protection is off", + "toggle": 302, + "card": 340 + }, + { + "scale": 1, + "theme": "light", + "enabled": true, + "width": 395, + "height": 600, + "rootWidth": 380, + "bodyWidth": 380, + "scheme": "light", + "status": "Protection is on", + "toggle": 302, + "card": 340 + }, + { + "scale": 1, + "theme": "dark", + "enabled": true, + "width": 395, + "height": 600, + "rootWidth": 380, + "bodyWidth": 380, + "scheme": "dark", + "status": "Protection is on", + "toggle": 302, + "card": 340 + }, + { + "scale": 1.25, + "theme": "light", + "enabled": false, + "width": 395, + "height": 600, + "rootWidth": 380, + "bodyWidth": 380, + "scheme": "light", + "status": "Protection is off", + "toggle": 302.3999938964844, + "card": 340 + }, + { + "scale": 1.25, + "theme": "dark", + "enabled": false, + "width": 395, + "height": 600, + "rootWidth": 380, + "bodyWidth": 380, + "scheme": "dark", + "status": "Protection is off", + "toggle": 302.3999938964844, + "card": 340 + }, + { + "scale": 1.25, + "theme": "light", + "enabled": true, + "width": 395, + "height": 600, + "rootWidth": 380, + "bodyWidth": 380, + "scheme": "light", + "status": "Protection is on", + "toggle": 302.3999938964844, + "card": 340 + }, + { + "scale": 1.25, + "theme": "dark", + "enabled": true, + "width": 395, + "height": 600, + "rootWidth": 380, + "bodyWidth": 380, + "scheme": "dark", + "status": "Protection is on", + "toggle": 302.3999938964844, + "card": 340 + } + ], + "testedCommit": "5048269d37b4fb237d320096c40de4653ce66beb", + "ciRun": "https://github.com/librerob/draft-cairn/actions/runs/42023649695", + "date": "2026-11-05" +} diff --git a/docs/portal-matrix.md b/docs/portal-matrix.md index f7880dd..01dcb1a 100644 --- a/docs/portal-matrix.md +++ b/docs/portal-matrix.md @@ -1,37 +1,43 @@ # Public application compatibility matrix -Tested 23 October 2026 using Chromium 151.0.7922.34 on Linux, the real installed extension and synthetic narrative text. **Three application samples passed capture, visible-paste comparison and saved-text recovery after reload.** This is sample-level evidence, not certification of an entire platform or a completed application workflow. +5 November 2026 · Draft Cairn 0.4.0 · Linux Chromium 151.0.7922.34 · synthetic narratives only. -[Recorded results](portal-results-0.3.0.json) · [Public-site run](https://github.com/librerob/draft-cairn/actions/runs/39995486919) · tested runtime commit `5d2b786caf01a024aa9e59960419982a37b9bfd3`. The harness pre-grants named test hosts in a temporary manifest; native permission prompts remain a separate manual check. A successful collection workflow does not mean every row passed. +**Three public application samples passed capture, visible-paste checks and saved-text recovery after reload.** These results apply to the exact samples/configurations below, not every tenant or a completed application workflow. -| Platform and exact sample | Typing capture | Visible paste / recovery after reload | Direct restore | Scope and limitation | -| --- | --- | --- | --- | --- | -| [Jotform grant preview](https://www.jotform.com/form-templates/preview/50246885080962/classic&nofs&disableSmartEmbed=1) | Passed, textarea `input_33` | Passed / passed | Refused after reload; copy back available | Opened the template preview as a standalone page and used Next to reach its narrative page without entering contact information. The embedded preview on the template landing page is unsupported. | -| [Greenhouse application](https://job-boards.greenhouse.io/anthropic/jobs/5065894008) | Passed, textarea `question_14439958008` | Passed / passed | Passed into the empty matched field | One public application question, tested without signing in or submitting an application. Other questions, uploads and tenant configurations were not tested. | -| [Ashby application](https://jobs.ashbyhq.com/Ashby/0f5dbf59-687b-4d88-88a7-73ee0a66b48d/application) | Passed, textarea | Passed / passed | Copy back only | Opened the Application view of this public role. The tested entry retained a query string, so conservative restoration rules disabled direct restore. | -| [SmartyGrants training round](https://training4.smartygrants.com.au/testround) | Not verified | Not verified | Not verified | Reached the public round information page; no editable narrative application field was reached without an applicant session. The closed Sneak Peek TEST round was also inspected. No account was created. | -| [Submittable sign-in](https://manager.submittable.com/signin) | Not verified | Not verified | Not verified | Redirected to sign-in. No account, application fields or authenticated workflow were tested. This row does not establish compatibility. | +[Recorded results](portal-results-0.4.0.json) · [Passing collection run](https://github.com/librerob/draft-cairn/actions/runs/42023649710) · tested runtime commit `5048269d37b4fb237d320096c40de4653ce66beb`. A collection run succeeding does not mean every row passed. Native permissions are pre-granted only in a temporary test manifest. -For each passing sample, the harness typed a unique synthetic narrative, checked its saved contents, pasted different synthetic text with a trusted keyboard shortcut, confirmed that the visible paste matched and the pasted answer was saved, reloaded the page, and verified the saved pasted answer remained available. The Greenhouse test also requested explicit restoration. It did not press Submit, create an account, upload a document, fill personal/financial information, solve a CAPTCHA or verify the server's receipt of an application. Native OS clipboard behavior, forced session expiry and full multipage workflows remain unverified. +| Exact sample | Typing / saved paste / reload recovery | Direct restore | Limit | +| --- | --- | --- | --- | +| [Jotform standalone grant preview](https://www.jotform.com/form-templates/preview/50246885080962/classic&nofs&disableSmartEmbed=1), textarea input_33 | Passed / passed / passed | Refused after reload; copy back available | Reached a narrative after Next without entering contact details. | +| [Greenhouse application](https://job-boards.greenhouse.io/anthropic/jobs/5065894008), textarea question_14439958008 | Passed / passed / passed | Passed into an empty matched field | One public question, no account or application submission. | +| [Ashby application](https://jobs.ashbyhq.com/Ashby/0f5dbf59-687b-4d88-88a7-73ee0a66b48d/application), textarea | Passed / passed / passed | Copy only | Query-based entry; no full application workflow. | +| Jotform embedded preview on its template landing page | Not verified | Copy only by design | Both origins enabled; no eligible narrative reached in the embedded check. Standalone success does not establish embedding success. | +| Cognito grant template, embedded and standalone | Not verified | Not established | No eligible narrative reached in the initial configuration. | +| Wufoo public builder | Not verified | Not established | No eligible narrative reached; a builder is not an applicant workflow. | +| [SmartyGrants training round](https://training4.smartygrants.com.au/testround) | Not verified | Not established | Reached round information, not an authorized applicant narrative. | +| [Submittable](https://manager.submittable.com/signin) | Not verified | Not established | Sign-in required. No account used. | +| Fluxx, Foundant, WizeHive / Zengine | Not verified | Not established | Authorized tenant sessions were not available or exercised. | -## Actual rich-editor demos +The passing checks use trusted typing and paste, confirm exact saved synthetic text, reload, then verify the saved pasted answer remains available. Only Greenhouse passed direct restoration in this public run. No form was submitted, no applicant account was created, and no contact/financial/client information was entered. Native OS clipboard behavior, forced remote session expiry and complete multipage workflows remain unverified. -| Official public demo | Typed plain-text capture | Whole-field paste check / saved paste after reload | Recovery | -| --- | --- | --- | --- | -| [Quill](https://quilljs.com/) | Passed | Passed / passed | Copy back only | -| [ProseMirror](https://prosemirror.net/examples/basic/) | Passed | Passed / passed | Copy back only | -| [CKEditor 5](https://ckeditor.com/ckeditor-5/demo/feature-rich/) | Passed | Passed / passed | Copy back only | -| Inline TinyMCE | DOM adapter fixture passed; vendor demo not tested | Not established on a vendor demo | Copy back only; iframe TinyMCE excluded | -| Tiptap | Shares the ProseMirror DOM adapter; no separate live Tiptap configuration tested | Not separately established | Copy back only | +## Editor and component evidence -These checks save rendered words, not formatting, images, attachments, collaboration state or the editor's internal document model. Quill and CKEditor consume native editing events differently from ordinary fields; the extension observes rendered text after trusted beforeinput editing intent and persists the checked result of trusted pastes too. Partial rich-text selections keep the clipboard original for manual comparison instead of claiming a reliable automatic match. +| Configuration | Evidence | Recovery | +| --- | --- | --- | +| [Quill official demo](https://quilljs.com/) | Typed text, trusted whole-field paste and saved text after reload passed | Plain text, copy only | +| [ProseMirror official demo](https://prosemirror.net/examples/basic/) | Same checks passed | Plain text, copy only | +| [CKEditor 5 official demo](https://ckeditor.com/ckeditor-5/demo/feature-rich/) | Same checks passed | Plain text, copy only | +| Inline TinyMCE | Synthetic DIV adapter fixture only; no actual vendor iframe configuration tested | Copy only | +| Tiptap | Shares the ProseMirror adapter; no separate live configuration tested | Copy only | +| Open shadow-root ordinary fields | Synthetic capture/private-ancestor/closed-root/forged-event tests passed | Copy only | +| Same-origin and cross-origin HTTP/HTTPS frames | Synthetic capture and origin/parent consent tests passed | Copy only | -## Additional access observations +Synthetic component tests establish the tested boundary, not a compatibility pass for an authenticated portal. Closed roots, opaque/about:blank/srcdoc frames and generic contenteditable remain unsupported. Formatting, files and editor document models are not recovered. -Cognito Forms' public grant template embeds a multipage form. Neither the landing page nor its standalone first page exposed an eligible narrative textarea during this check; later pages were not exercised. Wufoo's public builder did not expose an eligible editable narrative field in its initial state. These are **not compatibility passes**, and neither substitutes for a real applicant workflow. +## Reproduce and contribute -## Reproduce or report a different configuration +Run `npm ci --ignore-scripts`, `npx playwright install chromium`, then `node tests/portals.mjs`, or dispatch Public portal compatibility. The harness contacts named public samples only and writes compact reports and synthetic screenshots. It never signs in, submits forms or solves access challenges. Sites and editor configurations change. -Run `npm ci --ignore-scripts`, `npx playwright install chromium`, then `node tests/portals.mjs`, or dispatch the **Public portal compatibility** workflow. This opt-in test contacts only the listed public samples, uses a disposable profile and writes a compact JSON report plus synthetic screenshots to `test-results/portals/`. Sites may change, close their samples, introduce access checks or use different field configurations. The results file omits URL queries/fragments and does not contain answer text or credentials. +For real grant workflows use the [tester kit](tester-kit.md) and [native smoke-test worksheet](store/manual-smoke-test.md). Report vendor, extension/Chrome/OS versions, editor/frame type and passed/failed/unexercised steps. Never publish confidential application URLs, answers, profiles or session tokens. -Use the [native Chrome smoke-test worksheet](store/manual-smoke-test.md) with the unmodified ZIP before Web Store submission. A new report should identify the sample, date, Chrome/OS version, field type, saved-text and reload result, and any access blocker. Never attach real answers, profile data, session tokens or a live confidential application URL to a public issue. See [compatibility boundaries](compatibility.md) for timing, sensitive-field exclusions and restore requirements. +Historical results remain available in [the 0.3.0 report](portal-results-0.3.0.json). See [precise compatibility boundaries](compatibility.md). diff --git a/docs/portal-results-0.4.0.json b/docs/portal-results-0.4.0.json new file mode 100644 index 0000000..b590542 --- /dev/null +++ b/docs/portal-results-0.4.0.json @@ -0,0 +1,282 @@ +{ + "date": "2026-11-05T12:03:19.691Z", + "commit": "5048269d37b4fb237d320096c40de4653ce66beb", + "browser": "151.0.7922.34", + "syntheticOnly": true, + "submissionPerformed": false, + "permissionPrompt": "Test copy pre-grants named public hosts; native prompts are not tested.", + "results": [ + { + "name": "SmartyGrants", + "scope": "public top-level sample", + "url": "https://training4.smartygrants.com.au/testround", + "status": "not verified", + "reason": "No eligible visible narrative field reached; embedded forms, closed rounds or access gates may require a separate check.", + "surfaces": [ + { + "url": "https://training4.smartygrants.com.au/testround", + "topLevel": true, + "textareas": 0 + } + ] + }, + { + "name": "Submittable", + "scope": "public top-level sample", + "url": "https://accounts.submittable.com/u/login/identifier", + "status": "not verified", + "reason": "Sign-in required; no account was used and no application fields were tested." + }, + { + "name": "Jotform grant template", + "scope": "public top-level sample", + "url": "https://www.jotform.com/form-templates/grant-application", + "status": "not verified", + "reason": "No eligible visible narrative field reached; embedded forms, closed rounds or access gates may require a separate check.", + "surfaces": [ + { + "url": "https://www.jotform.com/form-templates/grant-application", + "topLevel": true, + "textareas": 0 + }, + { + "url": "https://www.jotform.com/form-templates/preview/50246885080962/classic&nofs&disableSmartEmbed=1", + "topLevel": false, + "textareas": 4 + }, + { + "url": "non-web frame", + "topLevel": false, + "textareas": 0 + }, + { + "url": "https://consentcdn.cookiebot.com/sdk/bc-v5.min.html", + "topLevel": false, + "textareas": 0 + } + ] + }, + { + "name": "Jotform grant template", + "scope": "embedded HTTP/HTTPS preview with both origins enabled", + "url": "https://www.jotform.com/form-templates/preview/50246885080962/classic&nofs&disableSmartEmbed=1", + "status": "not verified", + "reason": "No eligible narrative field reached in the authorized embedded preview." + }, + { + "name": "Jotform grant template", + "scope": "public preview opened as a standalone page", + "url": "https://www.jotform.com/form-templates/preview/50246885080962/classic&nofs&disableSmartEmbed=1", + "status": "capture and reload recovery passed", + "field": { + "tag": "TEXTAREA", + "id": "input_33", + "type": null + }, + "capture": true, + "copyText": true, + "directRestoreAvailable": true, + "paste": "visible match", + "pastedAnswerSaved": true, + "recoveryAfterReload": true, + "restore": "refused; copy back available" + }, + { + "name": "Cognito Forms grant template", + "scope": "public top-level sample", + "url": "https://www.cognitoforms.com/templates/grant-application-template", + "status": "not verified", + "reason": "No eligible visible narrative field reached; embedded forms, closed rounds or access gates may require a separate check.", + "surfaces": [ + { + "url": "https://www.cognitoforms.com/templates/grant-application-template", + "topLevel": true, + "textareas": 0 + }, + { + "url": "https://www.cognitoforms.com/f/B0C3a5tQlU6yutYOU9Qv-g/387", + "topLevel": false, + "textareas": 0 + } + ] + }, + { + "name": "Cognito Forms grant template", + "scope": "embedded HTTP/HTTPS preview with both origins enabled", + "url": "https://www.cognitoforms.com/f/B0C3a5tQlU6yutYOU9Qv-g/387", + "status": "not verified", + "reason": "No eligible narrative field reached in the authorized embedded preview." + }, + { + "name": "Cognito Forms grant template", + "scope": "public preview opened as a standalone page", + "url": "https://www.cognitoforms.com/f/B0C3a5tQlU6yutYOU9Qv-g/387", + "status": "not verified", + "reason": "No eligible visible narrative field reached; embedded forms, closed rounds or access gates may require a separate check.", + "surfaces": [ + { + "url": "https://www.cognitoforms.com/f/B0C3a5tQlU6yutYOU9Qv-g/387", + "topLevel": true, + "textareas": 0 + } + ] + }, + { + "name": "Wufoo builder demo", + "scope": "public top-level sample", + "url": "https://www.wufoo.com/form-builder/", + "status": "not verified", + "reason": "No eligible visible narrative field reached; embedded forms, closed rounds or access gates may require a separate check.", + "surfaces": [ + { + "url": "https://www.wufoo.com/form-builder/", + "topLevel": true, + "textareas": 5 + }, + { + "url": "non-web frame", + "topLevel": false, + "textareas": 0 + }, + { + "url": "https://www.wufoo.com/form-builder/signup/", + "topLevel": false, + "textareas": 1 + }, + { + "url": "https://www.wufoo.com/form-builder/signup/", + "topLevel": false, + "textareas": 1 + }, + { + "url": "https://www.recaptcha.net/recaptcha/enterprise/anchor", + "topLevel": false, + "textareas": 0 + }, + { + "url": "https://www.recaptcha.net/recaptcha/enterprise/anchor", + "topLevel": false, + "textareas": 0 + }, + { + "url": "non-web frame", + "topLevel": false, + "textareas": 0 + }, + { + "url": "non-web frame", + "topLevel": false, + "textareas": 0 + }, + { + "url": "non-web frame", + "topLevel": false, + "textareas": 0 + }, + { + "url": "non-web frame", + "topLevel": false, + "textareas": 0 + }, + { + "url": "non-web frame", + "topLevel": false, + "textareas": 0 + } + ] + }, + { + "name": "Greenhouse application", + "scope": "public top-level sample", + "url": "https://job-boards.greenhouse.io/anthropic/jobs/5065894008", + "status": "capture and reload recovery passed", + "field": { + "tag": "TEXTAREA", + "id": "question_14439958008", + "type": null + }, + "capture": true, + "copyText": true, + "directRestoreAvailable": true, + "paste": "visible match", + "pastedAnswerSaved": true, + "recoveryAfterReload": true, + "restore": "passed" + }, + { + "name": "Ashby application", + "scope": "public top-level sample", + "url": "https://jobs.ashbyhq.com/Ashby/0f5dbf59-687b-4d88-88a7-73ee0a66b48d/application", + "status": "capture and reload recovery passed", + "field": { + "tag": "TEXTAREA", + "id": "8656671d-078b-4c4e-9177-ead75a5c911e", + "type": null + }, + "capture": true, + "copyText": true, + "directRestoreAvailable": false, + "paste": "visible match", + "pastedAnswerSaved": true, + "recoveryAfterReload": true, + "restore": "copy back only" + }, + { + "name": "Quill official demo", + "scope": "public top-level sample", + "url": "https://quilljs.com/", + "status": "capture and reload recovery passed", + "field": { + "tag": "DIV", + "id": "", + "type": null, + "classes": "ql-editor" + }, + "capture": true, + "copyText": true, + "directRestoreAvailable": false, + "paste": "visible match", + "pastedAnswerSaved": true, + "recoveryAfterReload": true, + "restore": "copy back only" + }, + { + "name": "ProseMirror official demo", + "scope": "public top-level sample", + "url": "https://prosemirror.net/examples/basic/", + "status": "capture and reload recovery passed", + "field": { + "tag": "DIV", + "id": "", + "type": null, + "classes": "ProseMirror ProseMirror-example-setup-style" + }, + "capture": true, + "copyText": true, + "directRestoreAvailable": false, + "paste": "visible match", + "pastedAnswerSaved": true, + "recoveryAfterReload": true, + "restore": "copy back only" + }, + { + "name": "CKEditor 5 official demo", + "scope": "public top-level sample", + "url": "https://ckeditor.com/ckeditor-5/demo/feature-rich/", + "status": "capture and reload recovery passed", + "field": { + "tag": "DIV", + "id": "", + "type": null, + "classes": "ck-table-show-hidden-borders ck-blurred ck ck-content ck-editor__editable ck-rounded-corners ck-editor__editable_root ck-editor__editable_inline" + }, + "capture": true, + "copyText": true, + "directRestoreAvailable": false, + "paste": "visible match", + "pastedAnswerSaved": true, + "recoveryAfterReload": true, + "restore": "copy back only" + } + ] +} diff --git a/docs/release-notes.md b/docs/release-notes.md index 08f4f29..d4887e7 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,9 +1,9 @@ -Draft Cairn 0.3.1 — fix the narrow Chrome toolbar popup. +Draft Cairn 0.4.0 — reuse answers with a fit check and recover supported embedded fields. -The popup now declares its minimum width on the document and no longer caps its body against Chrome's initial viewport. This prevents the narrow column of wrapped text reported in the published extension. +Choose a library answer in the on-page editor or with Alt+Shift+L, inspect the projected result, then explicitly insert it into a supported ordinary field. Existing text outside your selection stays. Changed destinations cancel insertion and visible results are checked after 1.5 seconds. Rich editors remain copy-only. -The light/dark interface, paste checks, recovery, answer library and encryption behavior are unchanged. No new permissions are added. +Eligible fields can save in open shadow roots and HTTP/HTTPS frames. Both the containing site and a cross-origin frame must be enabled separately. Frame and shadow recovery is copy-only. Closed roots and opaque frames remain unsupported. -Validation includes the existing unit and Chromium regression suites plus a headed Chromium test opening the actual toolbar popup, rather than a tab with a preset viewport. See docs/validation.md for the exact results and remaining manual checks. The public portal matrix retains its dated 0.3.0 evidence; portal behavior was not changed by this layout fix. +Added advisory linked website word/character counters, per-site retention, reviewed multi-site access requests, optional organization allowlist/retention limits, selected-answer Markdown snapshots and a local save/reload/recover practice page. Snapshots do not prove submission. No telemetry, network API, mandatory host grant or new API permission is added. -Update the existing Chrome Web Store item using draft-cairn-0.3.1.zip. Its manifest version is higher than 0.3.0. Upload only the install ZIP, not the outer preparation kit. Reload a test website after the update and open the toolbar popup again. +Read docs/validation.md for exact evidence and remaining manual checks. Public applicant sessions, native host prompts, enterprise deployment and Windows/macOS daily use are not established by synthetic CI. Update the existing Store item with the install ZIP only; review the updated privacy policy and listing before submission. diff --git a/docs/store/manual-smoke-test.md b/docs/store/manual-smoke-test.md index 453b0e9..4591d9e 100644 --- a/docs/store/manual-smoke-test.md +++ b/docs/store/manual-smoke-test.md @@ -1,8 +1,8 @@ # Final Chrome smoke test -Status: **not yet performed on the unmodified 0.3.1 ZIP**. Automated Chromium tests use a test-only localhost host grant; they cannot stand in for these checks. Use only synthetic text. Stop submission if a required step fails. +Status: **not yet performed on the unmodified 0.4.0 ZIP**. Automated Chromium tests use a test-only localhost host grant; they cannot stand in for these checks. Use only synthetic text. Stop submission if a required step fails. -1. Extract `draft-cairn-0.3.1.zip` and load that extracted folder in a fresh supported Chrome profile via `chrome://extensions` → Developer mode → Load unpacked. Pin the extension. Do not change its manifest or permissions. +1. Extract `draft-cairn-0.4.0.zip` and load that extracted folder in a fresh supported Chrome profile via `chrome://extensions` → Developer mode → Load unpacked. Pin the extension. Do not change its manifest or permissions. 2. Run `node scripts/demo.mjs` from a source checkout and open `http://127.0.0.1:8765/index.html` in that Chrome profile. Before enabling protection, type a synthetic answer. Confirm no draft is captured. 3. Open the popup and choose Enable for this site. Deny Chrome's native access request. Confirm protection stays off. Repeat and approve. If Chrome closes the popup, reopen it and confirm protection has finished enabling. Type a new synthetic answer in Project summary and wait for “saved on this device”. 4. With default metadata minimization, reload and verify the answer is available to copy. For direct restoration, first enable page titles/field details in settings, create a fresh saved revision, then reload and restore it into the now-empty Project summary. Check it is exact. Put new text in the destination and confirm restoration refuses to overwrite it. @@ -19,7 +19,7 @@ Record Chrome/OS version, date, pass/fail, and any issue using synthetic descrip On an enabled eligible field, paste a harmless synthetic paragraph and wait for the visible-paste check and completed save. Reload and verify the pasted answer, rather than just an earlier typing revision, is available in recovery. A matching visible value does not prove server submission. Compare the dated [public sample matrix](../portal-matrix.md) with the actual page configuration; a landing-page iframe is not a standalone form. -On a targeted top-level rich editor, type and paste synthetic text, then verify plain-text recovery after reload. Recovery is copy back only. Check partial rich selections produce manual-review wording, excluded/read-only fields are not captured, and generic contenteditable/iframe editors say not protected. No formatting or attachment recovery is promised. +On a targeted top-level rich editor, type and paste synthetic text, then verify plain-text recovery after reload. Recovery is copy back only. Check partial rich selections produce manual-review wording, excluded/read-only fields are not captured, and generic contenteditable and unauthorized iframe editors say not protected. No formatting or attachment recovery is promised. ## Optional vault and privacy controls @@ -38,3 +38,16 @@ On a targeted top-level rich editor, type and paste synthetic text, then verify - [ ] Switch the OS/browser between light and dark while System is selected; inspect workspace, popup and on-page editor. - [ ] Choose Light/Dark explicitly, reload/restart, and verify the override survives and synchronizes across open extension pages. - [ ] Check at increased text size, a narrow viewport, reduced motion and Windows High Contrast. + +## 0.4.0 workflow checks + +- [ ] Try a sample recovery: save synthetic text, reload, recover, delete practice drafts. Check vault-locked behavior. +- [ ] Focus an ordinary field, open the on-page editor, choose Use library answer. Preview a short saved answer, insert explicitly, and verify unchanged text outside the selected range. Repeat with an oversized answer, a changed destination, a changed route and a website that clips text. Rich editors stay copy-only. +- [ ] Configure/use Alt+Shift+L in Chrome shortcuts; check conflicts and focus in an embedded field. +- [ ] Use an open shadow-root narrative field and verify capture/reload/copy recovery. Private ancestors and closed roots must not save. Direct restore remains unavailable. +- [ ] Enable a containing site and a distinct embedded HTTP/HTTPS form origin through the reviewed batch. Capture must require both; deny/revoke each grant and verify stopping. Reload after enabling. +- [ ] Verify a linked website word counter is advisory, shows the local estimate separately, and does not become a guessed limit for another field. Submission is not blocked or certified. +- [ ] Choose per-site retention and confirm shorter expiry applies. A longer period does not extend existing records; storage eviction can happen earlier. +- [ ] Select saved revisions and export a readable Markdown snapshot. Confirm only selected records and allowed labels appear, with the submission disclaimer. Protect the file separately. +- [ ] On a managed pilot profile, exercise AllowedOrigins and MaxRetentionDays with native organization policy. Simulated CI is not native policy delivery evidence. +- [ ] Run the [ten-tester pilot](../tester-kit.md) on authorized grant portals. Record access blockers and exact configurations without real answers. diff --git a/docs/store/reviewer-instructions.txt b/docs/store/reviewer-instructions.txt index cfd617d..2e2a06d 100644 --- a/docs/store/reviewer-instructions.txt +++ b/docs/store/reviewer-instructions.txt @@ -1,4 +1,4 @@ -Draft Cairn 0.3.1 preview — synthetic reviewer test instructions +Draft Cairn 0.4.0 preview — synthetic reviewer test instructions No account, payment, reviewer credentials, remote service, or client data is needed. @@ -13,7 +13,7 @@ Source and local demo: https://github.com/librerob/draft-cairn 8. Recovery uses oldest-first eviction at 180 records or the byte budget, with a visible notice; library answers are never automatically removed. 9. Sites & settings controls retention (one day by default on fresh installs; existing choices are preserved), disabling protection, deleting site data, and deleting all extension data. -Supported fields are standard top-level textareas, long ordinary text inputs, and targeted top-level Quill, ProseMirror/Tiptap, CKEditor 5 and inline TinyMCE roots. Rich-text recovery is plain text and copy back only. Password/payment/OTP/hidden and sensitive-hint fields, generic contenteditable, frames, shadow roots and incognito are excluded. See docs/portal-matrix.md for the exact tested samples. Filtering cannot identify every sensitive answer. Text that has not finished saving can be lost. Persisted records/settings use AES-256-GCM with an automatic non-extractable key in this browser profile. An optional passphrase vault is available; the default automatic mode uses a same-profile key. A compromised live browser/device can still expose answers. No analytics, external answer transmission, remotely hosted code, or paid features are present. +Supported fields are standard textareas, long ordinary text inputs, and targeted Quill, ProseMirror/Tiptap, CKEditor 5 and inline TinyMCE roots. Rich-text recovery is plain text and copy back only. Password/payment/OTP/hidden and sensitive-hint fields, generic contenteditable, closed shadow roots, opaque frames and incognito are excluded. See docs/portal-matrix.md for the exact tested samples. Filtering cannot identify every sensitive answer. Text that has not finished saving can be lost. Persisted records/settings use AES-256-GCM with an automatic non-extractable key in this browser profile. An optional passphrase vault is available; the default automatic mode uses a same-profile key. A compromised live browser/device can still expose answers. No analytics, external answer transmission, remotely hosted code, or paid features are present. 0.2 vault/privacy checks (synthetic data only): - Fresh installs use one-day recovery and omit page titles/field details. Enable page details in Sites & settings before testing direct restoration; otherwise copy-only is expected. @@ -25,3 +25,11 @@ Supported fields are standard top-level textareas, long ordinary text inputs, an Appearance: in Sites & settings choose System, Light or Dark. System follows OS/browser preference changes. Explicit choices override that preference and apply to the popup and on-page editor too. Appearance remains changeable while the vault is locked. + +0.4.0 workflow checks: +- The popup's Try a sample recovery opens a packaged local practice page; save synthetic text, reload, recover. No host access is granted by this exercise. +- In an enabled ordinary field, open the on-page editor and choose Use library answer, or use Alt+Shift+L. Choose a saved answer, inspect its fit/result, then explicitly insert. Existing text outside the saved selection stays. Changed destinations cancel. Rich editors offer copying only. +- Open shadow-root fields and authorized HTTP/HTTPS frame fields support copy-only recovery. A frame needs both its own origin and the containing page origin enabled. Closed roots and opaque/about:blank/srcdoc frames are unsupported. +- Website-associated explicit word/character counters are advisory hints; submission and server acceptance are never certified. +- Site-specific retention and reviewed multi-site grants are in Sites & settings. Optional managed policy restricts origins/maximum retention without granting Chrome access. +- Select saved revisions to export a readable Markdown application snapshot. This is not an automatic full-form capture or a submission receipt. diff --git a/docs/tester-kit.md b/docs/tester-kit.md new file mode 100644 index 0000000..74086f5 --- /dev/null +++ b/docs/tester-kit.md @@ -0,0 +1,39 @@ +# Ten-tester pilot + +Status: prepared, not recruited. No messages have been sent and no applicant accounts have been created. + +Recruit four independent grant writers, three agency staff and three consultants who currently fill long application forms. Use consented, manual outreach. Avoid asking for client documents, account access or answer contents. + +## Invitation to send yourself + +> I maintain Draft Cairn, a free browser extension that keeps local recovery copies of long application answers and helps reuse saved paragraphs. I’m looking for people who actually use grant portals to try a short synthetic recovery task, then optionally use it for two weeks where their data policy allows. Have you lost an answer recently, or do you usually draft somewhere else? I don’t need your client answers or login details. + +## First interview, before demonstrating + +1. Which actual portal and editor do you use? Give the vendor name or a public, non-confidential sample only. +2. When did you last lose work? What happened, and what did you do afterward? +3. Do you already draft in Word or another document? What still goes wrong? +4. Are local copies of these answers permitted under your organization's rules? +5. Do you reuse approved answers, and how do you check their length? + +## Synthetic supervised task + +Use the unmodified install ZIP in a fresh Chrome profile. Complete the native permission approve/deny/revoke checklist. Type only a made-up project description, wait for saved on this device, reload and recover. Repeat in a portal field the participant is authorized to use. Test an ordinary field, a rich editor and an embedded form if available. Choose a library answer, inspect its preview/fit, insert explicitly where supported, and verify retained text. Do not submit an application, bypass access controls or use real client data for the test. + +## Two-week private tally + +Record only counts and consented descriptions: protected sessions, recoveries needed/successful, missed fields, copy-only frustrations, approximate time saved and unwanted capture. Keep answers and confidential URLs out of reports. No telemetry is added to collect these automatically. + +## Grant-portal worksheet + +| Platform | Evidence needed | Current status | +| --- | --- | --- | +| Fluxx | Authorized tenant session, narrative field, frame/editor type, save/reload/copy recovery | Not verified | +| Foundant | Authorized tenant session and exact editor configuration | Not verified | +| SmartyGrants | Authorized applicant session; public training info page is insufficient | Not verified | +| Submittable | Authorized application session; sign-in is insufficient | Not verified | +| WizeHive / Zengine | Authorized tenant session and exact editor configuration | Not verified | + +Use a redacted report: extension version, OS/Chrome version, vendor name, field type, permission result, capture/paste/reload result and any blocker. Synthetic examples only. Mark each check passed/failed/not exercised; never turn a vendor-name guess into a compatibility claim. + +Continue after ten testers if at least six repeat real workflows voluntarily and at least four report measurable recovery/reuse value. Any wrong-field write, unexpected sensitive capture or extension-caused loss blocks wider rollout until investigated. Ask for a concrete, nonbinding next step if testing willingness to pay. No payments or hosted service have been enabled. diff --git a/docs/validation-results-0.4.0.json b/docs/validation-results-0.4.0.json new file mode 100644 index 0000000..58f4cba --- /dev/null +++ b/docs/validation-results-0.4.0.json @@ -0,0 +1,74 @@ +{ + "browser": "151.0.7922.34", + "automated": [ + "no capture before explicit site enable", + "forged input and paste cannot create drafts; no branded host attribute", + "typing saves through the real service worker", + "unsupported fields and generic contenteditable visibly say not protected", + "inherited autocomplete off permits ordinary narrative capture", + "reload and explicit restoration to the original empty field", + "nonempty destination is never overwritten", + "deliberate session-expiry navigation and return recovery", + "similar fields keep separate draft records", + "duplicate field identities refuse restoration", + "password, card, OTP, ignored and short inputs excluded", + "oversized selected-text paste is blocked and full original persisted", + "larger editor exposes a labelled dialog and complete original answer to accessibility APIs", + "a fitting trusted paste over a selection is allowed", + "matching post-paste value is verified without storing an extra clipboard original", + "multiline trusted paste normalizes line endings and preserves Unicode", + "delayed custom truncation preserves the complete original and exposes visible-text review", + "continued typing interrupts verification without falsely claiming text loss", + "website-cancelled paste keeps its original without altering the field", + "a disappearing destination still preserves its original using the paste-time descriptor", + "four targeted rich-text DOM adapters capture plain text, refuse direct restore and respect read-only status", + "trusted beforeinput captures a model-managed rich editor that consumes native input", + "rich whole-field paste is compared; partial rich selections preserve an original for manual review", + "rich-text private regions never create recovery records", + "query and fragment omitted, query-based pages copy only", + "hostile library content rendered as literal text", + "malformed import is atomic", + "aborted record/index transaction preserves earlier data and shows a visible warning", + "unrelated successful writes do not clear earlier failure badges", + "turning protection off and on works in an already-open page", + "expiry and individual draft deletion", + "persistent answer records encrypt text, titles and original origins", + "capture continues at 180 drafts near 6 MB with incremental encrypted writes", + "unchanged host patterns leave registered content scripts in place", + "drafts and library survive a real browser process restart", + "workspace follows live system light/dark changes", + "on-page editor follows explicit appearance changes independently of the website theme", + "explicit appearance overrides persist after reload and synchronize with the popup", + "dialogs use the dark palette; high-contrast and reduced-motion preferences remain usable", + "workspace fits a 390px viewport", + "site erasure and all-data deletion remove ciphertext and local keys", + "legacy plaintext migrates atomically while preserving existing retention and metadata choices", + "automatic AES-256 key persists as a nonextractable CryptoKey", + "ciphertext tampering fails closed without overwriting damaged data", + "worker completes a pending enable without a popup and rejects expired intent", + "fresh installations default to one-day recovery without page titles or field descriptors", + "minimal metadata captures are copy-only and omit titles and field descriptors", + "vault setup through the real UI migrates existing drafts and library answers", + "locking scrubs rendered answers and unsaved editors; incorrect passwords reveal no records", + "appearance changes remain available while the vault is locked", + "trusted typing continues to encrypt while locked and decrypts after unlocking", + "passphrase changes reject the old password and preserve saved answers", + "vault unlock survives service-worker suspension within the same browser session", + "a full browser restart locks the vault while public-key capture still works", + "session-only draft storage clears on browser exit while the encrypted library survives", + "returning to automatic encryption rekeys records and preserves password-free restart recovery", + "encrypted backup UI round-trips safely, rejects wrong passwords, and skips duplicates", + "trusted field exclusion deletes its drafts, persists across reload, warns, and can be removed", + "Never capture site blocks prevent accidental re-enabling until removed", + "failed near-capacity vault migration rolls back records, index and key atomically", + "near-capacity vault migration succeeds; locked session-only conversion evicts oldest drafts to fit memory", + "all-data deletion works without unlocking the vault", + "v0.1.2 encrypted records upgrade without data loss and legacy ciphertext/key are removed" + ], + "permissionPrompt": "not automated; temporary loopback host pre-grant; native removal simulated", + "clipboard": "browser clipboard populated by API, trusted keyboard paste; daily-use OS clipboard still manual", + "syntheticOnly": true, + "testedCommit": "5048269d37b4fb237d320096c40de4653ce66beb", + "ciRun": "https://github.com/librerob/draft-cairn/actions/runs/42023649695", + "date": "2026-11-05" +} diff --git a/docs/validation.md b/docs/validation.md index a781bb4..5840ef6 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -1,6 +1,18 @@ # Validation record -24 October 2026 · synthetic fixtures and public samples +5 November 2026 · current and historical synthetic/public evidence + +## 0.4.0 workflow and component coverage + +5 November 2026. **22 unit groups, 63 existing Chromium scenarios, 26 new workflow scenarios, eight actual toolbar-popup cases and two trusted keyboard-shortcut cases passed** on runtime commit `5048269d37b4fb237d320096c40de4653ce66beb`. [Passing run](https://github.com/librerob/draft-cairn/actions/runs/42023649695) · [existing regressions](validation-results-0.4.0.json) · [new workflows](workflow-validation-0.4.0.json) · [native popup/shortcut results](popup-validation-0.4.0.json). + +The workflow suite exercises open shadow roots, private shadow ancestors, excluded closed roots, rejection of synthetic composed input, separately scoped same-origin frames, exact-origin enforcement across ports, cross-origin frame opt-in, disabled containing pages, complete-batch permission gating, worker completion after initiating UI closure, per-site retention and shorter expiry, selection-preserving library insertion, oversized/stale/route-changed destinations, delayed clipping, rich copy-only use, linked counters and unrecognized hints, locked library access, policy denial after preview, managed origin and retention enforcement, Markdown snapshot download and encrypted practice recovery after reload. Managed values and host grants are simulated in isolated profiles; native permission dialogs and actual enterprise policy delivery remain manual. + +The headed suite opens the actual action popup without setting its viewport, checks eight theme/on-off/scale combinations, then presses Alt+Shift+L in a real focused field at 100% and 125% scale and verifies the picker opens. The default chord also has a trusted page-key fallback for Chromium environments that pass it through instead of dispatching the command. Changed or unassigned Chrome shortcuts disable that fallback. No shortcut inserts automatically. + +Public samples were rerun separately on the same runtime commit. Jotform standalone, Greenhouse and Ashby passed capture/paste/reload recovery; three official editor demos passed plain-text checks. Embedded Jotform/Cognito previews did not expose an eligible narrative in that run and remain unverified. No authenticated grant-portal workflow is established. [Current sample matrix](portal-matrix.md) · [public run](https://github.com/librerob/draft-cairn/actions/runs/42023649710). + +Static/syntax checks, 26 text contrast pairs, six control-boundary pairs, asset dimensions, unit checks and reproducible packaging passed. New workflow screenshots show the shipped light/dark interface with synthetic answers. The 20-second README GIF uses four real practice screenshots from runtime-equivalent practice UI in commit `b0ae76835de48b13f64ea31f00f94c7114ca8941`; no mock application response is shown. There is no native Windows/macOS, Edge, screen-reader, full grant-session, enterprise deployment or independent cryptographic-audit claim. The native host prompt and daily OS clipboard gates remain in the smoke-test worksheet. ## 0.3.1 native toolbar popup diff --git a/docs/workflow-validation-0.4.0.json b/docs/workflow-validation-0.4.0.json new file mode 100644 index 0000000..986395b --- /dev/null +++ b/docs/workflow-validation-0.4.0.json @@ -0,0 +1,38 @@ +{ + "version": "0.4.0", + "browser": "151.0.7922.34", + "automated": [ + "top-level capture remains available with the new frame scope", + "open shadow-root capture works and remains copy-only", + "private markers on shadow hosts and ancestors prevent capture", + "closed shadow roots remain unsupported and are not captured", + "synthetic composed input cannot create a shadow draft", + "same-origin frame recovery saves a separately scoped copy-only draft", + "Chrome host access across ports does not enable a different frame origin", + "cross-origin frame saves only after its own exact origin is enabled", + "disabling the containing site stops capture in enabled cross-origin children", + "batch enablement waits for every requested host grant before enabling any new origin", + "fully granted batch requests finish through the worker after the initiating UI can close", + "per-site retention controls new records and shortens existing expiry", + "library insertion previews and preserves existing text outside the saved selection", + "oversized library insertion is disabled and leaves the website untouched", + "stale insertion previews cannot overwrite a changed destination", + "a route change cancels an existing insertion preview", + "post-insertion verification detects delayed clipping and preserves the library original", + "rich-text library use remains copy-only", + "linked word counters are shown as website reports alongside local estimates", + "unrecognized counters produce no inferred limit", + "locked vaults do not release library titles or answers into a new picker", + "access denied after preview cancels insertion before releasing text", + "managed origin restrictions and maximum retention apply to UI actions and frame captures", + "managed maximum retention caps new captures immediately", + "selected saved revisions export as readable Markdown with an explicit submission disclaimer", + "local first-run practice saves through encryption and recovers after reload" + ], + "syntheticOnly": true, + "permissions": "temporary loopback pre-grant; native prompt remains manual", + "managed": "managed values simulated through chrome.storage.managed.get; enterprise deployment remains manual", + "testedCommit": "5048269d37b4fb237d320096c40de4653ce66beb", + "ciRun": "https://github.com/librerob/draft-cairn/actions/runs/42023649695", + "date": "2026-11-05" +} diff --git a/extension/background.js b/extension/background.js index 99a4b04..e746327 100644 --- a/extension/background.js +++ b/extension/background.js @@ -1,24 +1,28 @@ import './core.js'; import * as S from './storage.js'; -const C=globalThis.Cairn; +const C=globalThis.Cairn,W=globalThis.CairnWorkflows; +async function managed() {return W.policy(await chrome.storage.managed.get(null).catch(()=>({})));} +function policyAllows(policy,origin){return policy.allowed===null || policy.allowed.includes(origin);} let queue=Promise.resolve(),lastError=''; const ready=Promise.all([chrome.storage.local.setAccessLevel({accessLevel:'TRUSTED_CONTEXTS'}),chrome.storage.session.setAccessLevel({accessLevel:'TRUSTED_CONTEXTS'})]); function serial(fn){const next=queue.then(async()=>{await ready;return fn();});queue=next.catch(()=>{});return next;} const digest=async text=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(text))),b=>b.toString(16).padStart(2,'0')).join(''); -const trusted=sender=>sender.id===chrome.runtime.id && !sender.tab?.incognito && ['popup.html','workspace.html'].some(p=>sender.url?.split('?')[0]===chrome.runtime.getURL(p)); +const trusted=sender=>sender.id===chrome.runtime.id && !sender.tab?.incognito && ['popup.html','workspace.html','practice.html'].some(p=>sender.url?.split('?')[0]===chrome.runtime.getURL(p)); async function registerSites(state) { const current=(await chrome.scripting.getRegisteredContentScripts()).find(s=>s.id==='cairn-protection'); - const patterns=[...new Set(state.sites.map(C.hostPattern))].sort(); + const policy=await managed(); + const patterns=[...new Set(state.sites.filter(o=>policyAllows(policy,o)).map(C.hostPattern))].sort(); if(!patterns.length){if(current)await chrome.scripting.unregisterContentScripts({ids:[current.id]});return;} - if(current && JSON.stringify([...current.matches].sort())===JSON.stringify(patterns))return; - const script={id:'cairn-protection',matches:patterns,js:['core.js','content.js'],runAt:'document_start',allFrames:false,persistAcrossSessions:true}; + if(current && JSON.stringify([...current.matches].sort())===JSON.stringify(patterns) && current.allFrames===true && current.js.includes('workflows.js'))return; + const script={id:'cairn-protection',matches:patterns,js:['core.js','workflows.js','content.js'],runAt:'document_start',allFrames:true,persistAcrossSessions:true}; if(current)await chrome.scripting.updateContentScripts([script]);else await chrome.scripting.registerContentScripts([script]); } async function recheckPages() { const tabs=await chrome.tabs.query({}); - await Promise.allSettled(tabs.map(t=>chrome.tabs.sendMessage(t.id,{type:'RECHECK'},{frameId:0}))); + await Promise.allSettled(tabs.map(t=>chrome.tabs.sendMessage(t.id,{type:'RECHECK'}))); } async function enable(origin,tabId) { + if(!policyAllows(await managed(),origin))throw new Error('Site is not allowed by your organization.'); if(!(await chrome.permissions.contains({origins:[C.hostPattern(origin)]})))throw new Error('Site access was not granted.'); await S.updateIndex(state=>{ if(state.blockedSites.includes(origin))throw new Error('Site is blocked. Remove it from Never capture in settings first.'); @@ -30,8 +34,8 @@ async function enable(origin,tabId) { if(Number.isInteger(tabId)) { const tab=await chrome.tabs.get(tabId).catch(()=>null); if(tab && !tab.incognito && tab.url && C.originOf(tab.url)===origin) { - await chrome.scripting.executeScript({target:{tabId},files:['core.js','content.js']}); - await chrome.tabs.sendMessage(tabId,{type:'START'},{frameId:0}); + await chrome.scripting.executeScript({target:{tabId,allFrames:true},files:['core.js','workflows.js','content.js']}); + await chrome.tabs.sendMessage(tabId,{type:'START'}); } } } @@ -40,21 +44,29 @@ async function finishPending() { for(const [name,item] of Object.entries(pending)) { if(!name.startsWith('enable-'))continue; if(!item || Date.now()-item.created>120000 || item.created>Date.now()){await chrome.storage.session.remove(name);continue;} + if(Array.isArray(item.origins)){ + const origins=W.siteList(item.origins.join(' ')),state=await S.publicState(),policy=await managed(); + if(origins.some(o=>state.blockedSites.includes(o) || !policyAllows(policy,o))){await chrome.storage.session.remove(name);continue;} + if(await chrome.permissions.contains({origins:[...new Set(origins.map(C.hostPattern))]})){ + for(const origin of origins)await enable(origin); + await chrome.storage.session.remove(name); + } + continue; + } const origin=C.originOf(item.origin); if(await chrome.permissions.contains({origins:[C.hostPattern(origin)]})) { await enable(origin,item.tabId);await chrome.storage.session.remove(name); } } } -async function stopPages(origin) { - const tabs=await chrome.tabs.query({}); - await Promise.allSettled(tabs.filter(t=>!origin || t.url && (()=>{try{return C.originOf(t.url)===origin;}catch{return false;}})()).map(t=>chrome.tabs.sendMessage(t.id,{type:'STOP'},{frameId:0}))); -} +async function stopPages() { await recheckPages(); } async function activeOrigin(sender) { - if(!sender.tab || sender.tab.incognito || sender.frameId!==0)throw new Error('This page is not supported.'); - const origin=C.originOf(sender.url),state=await S.publicState(); + if(!sender.tab || sender.tab.incognito || !Number.isInteger(sender.frameId))throw new Error('This page is not supported.'); + const origin=C.originOf(sender.url),state=await S.publicState(),policy=await managed(); + const top=new URL(sender.frameId===0 ? sender.url : sender.tab.url); + if(!state.sites.includes(top.origin) || state.blockedSites.includes(top.origin) || !policyAllows(policy,top.origin) || !policyAllows(policy,origin) || !(await chrome.permissions.contains({origins:[C.hostPattern(top.origin)]})))throw new Error('Protection is off for the containing website.'); if(!state.sites.includes(origin) || state.blockedSites.includes(origin) || !(await chrome.permissions.contains({origins:[C.hostPattern(origin)]})))throw new Error('Protection is off for this site.'); - return {origin,state,url:new URL(sender.url)}; + return {origin,state,url:new URL(sender.url),policy,scope:sender.frameId===0 ? '' : '|frame|'+top.origin+top.pathname+'|'+sender.frameId}; } function validateField(f) { if(!f || !C.allowedField(f))throw new Error('Field is not supported.'); @@ -64,11 +76,14 @@ function validateField(f) { async function handle(m,sender) { if(!m || typeof m.type!=='string')throw new Error('Invalid request.'); if(sender.tab && !trusted(sender)) { - const {origin,state,url}=await activeOrigin(sender); - if(m.type==='HELLO')return {active:true,appearance:state.appearance,ignoredFields:state.ignoredFields.filter(f=>f.origin===origin).map(f=>f.id)}; + let context;try{context=await activeOrigin(sender);}catch(error){if(m.type==='HELLO')return {active:false};throw error;} + const {origin,state,url,policy,scope}=context; + if(m.type==='LIBRARY_LIST'){const view=await S.load();return view.library.map(({id,title,project})=>({id,title,project}));} + if(m.type==='LIBRARY_GET'){const view=await S.load(),answer=view.library.find(a=>a.id===m.id);if(!answer)throw new Error('Choose an existing library answer.');return {text:answer.text,title:answer.title};} + if(m.type==='HELLO')return {active:true,scope,shortcut:(await chrome.commands.getAll()).find(c=>c.name==='open-library')?.shortcut || '',appearance:state.appearance,ignoredFields:state.ignoredFields.filter(f=>f.origin===origin).map(f=>f.id)}; if(!['CAPTURE','IGNORE_FIELD'].includes(m.type))throw new Error('Unavailable from this page.'); const f=m.field;validateField(f); - const pageKey=await digest(origin+url.pathname),fieldKey=await digest(origin+pageKey+C.fieldIdentity(f)); + const pageKey=await digest(origin+url.pathname+scope),fieldKey=await digest(origin+pageKey+C.fieldIdentity(f)); if(m.type==='IGNORE_FIELD') { await S.updateIndex(next=>{ if(next.ignoredFields.some(f=>f.id===fieldKey))return; @@ -82,16 +97,19 @@ async function handle(m,sender) { if(typeof m.title!=='string' || m.title.length>160 || !['draft','paste'].includes(m.kind))throw new Error('Invalid draft.'); if(!Number.isInteger(m.slot) || m.slot<0 || m.slot>10000)throw new Error('Invalid field position.'); const key=await digest(origin+pageKey+C.fieldIdentity(f)+m.slot+m.kind); - return S.capture({origin,pageKey,fieldKey,key,structure:m.structure,field:f,title:m.title,kind:m.kind,text:m.text,restorable:!url.search && !url.hash && m.kind==='draft' && ['TEXTAREA','INPUT'].includes(f.tag)}); + return S.capture({origin,pageKey,fieldKey,key,structure:m.structure,field:f,title:m.title,kind:m.kind,text:m.text,restorable:sender.frameId===0 && !m.field.shadow && !url.search && !url.hash && m.kind==='draft' && ['TEXTAREA','INPUT'].includes(f.tag)},policy.maxDays); } if(!trusted(sender))throw new Error('Unavailable from this context.'); switch(m.type) { + case 'PRACTICE_SAVE':return S.capture({origin:'practice',key:'practice',fieldKey:'practice',pageKey:'practice',structure:'practice',title:'',field:{label:''},kind:'draft',text:m.text,restorable:false},1); + case 'PRACTICE_READ':{const state=await S.load(),draft=state.drafts.find(d=>d.origin==='practice');if(!draft)throw new Error('Choose Save practice answer first.');return draft.text;} + case 'PRACTICE_CLEAR':await S.updateIndex(s=>{s.drafts=s.drafts.filter(d=>d.key!=='practice');});return true; case 'THEME_GET':return {appearance:(await S.publicState()).appearance}; case 'THEME_SET': { if(!['system','light','dark'].includes(m.appearance))throw new Error('Choose system, light or dark appearance.'); await S.updateIndex(state=>{state.appearance=m.appearance;});await recheckPages();return true; } - case 'STATE':return {...await S.view(m.origin),lastError:lastError || (await chrome.storage.session.get('lastError')).lastError || ''}; + case 'STATE':return {...await S.view(m.origin),policy:await managed(),lastError:lastError || (await chrome.storage.session.get('lastError')).lastError || ''}; case 'ACK_ERROR':lastError='';await chrome.storage.session.remove('lastError');await chrome.action.setBadgeText({text:''});return true; case 'ENABLE':{const origin=C.originOf(m.origin);await enable(origin,m.tabId);await chrome.storage.session.remove(`enable-${m.tabId}`);return true;} case 'BLOCK_SITE': @@ -104,6 +122,7 @@ async function handle(m,sender) { if(m.type==='BLOCK_SITE' && !state.blockedSites.includes(origin)) { if(state.blockedSites.length>=80)throw new Error('Site block limit reached. Remove a blocked site first.');state.blockedSites.push(origin); } + if(m.erase)delete state.siteDays[origin]; if(m.erase)state.ignoredFields=state.ignoredFields.filter(f=>f.origin!==origin); }); await stopPages(origin);const state=await S.publicState();await registerSites(state); @@ -122,8 +141,16 @@ async function handle(m,sender) { C.libraryBounded(state);await S.commit(state);return true; } case 'RETENTION': { - if(![1,3,7,14,30].includes(m.days))throw new Error('Choose a supported retention period.'); - await S.updateIndex(s=>{s.days=m.days;s.drafts=s.drafts.map(d=>({...d,expires:Math.min(d.expires,d.saved+m.days*C.DAY)}));});return true; + if(!W.DAYS.includes(m.days))throw new Error('Choose a supported retention period.'); + const policy=await managed();if(m.days>policy.maxDays)throw new Error('Choose retention within your organization limit.'); + const origin=m.origin ? C.originOf(m.origin) : ''; + const before=await S.publicState(),siteDays={...before.siteDays}; + if(origin){if(!before.sites.includes(origin))throw new Error('Site must be enabled first.');siteDays[origin]=m.days;} + const limits=new Map(await Promise.all(Object.entries(siteDays).map(async([o,days])=>[await digest(o),days]))); + await S.updateIndex(s=>{ + if(origin)s.siteDays=siteDays;else s.days=m.days; + s.drafts=s.drafts.map(d=>({...d,expires:Math.min(d.expires,d.saved+Math.min(limits.get(d.site) || s.days,policy.maxDays)*C.DAY)})); + });return true; } case 'PRIVACY':await S.privacy({metadata:m.metadata,sessionOnly:m.sessionOnly});return true; case 'VAULT_ENABLE':if(m.acknowledged!==true)throw new Error('Vault setup requires acknowledging that a forgotten passphrase cannot be recovered.');await S.enableVault(m.passphrase);return true; @@ -160,9 +187,9 @@ function recordError(safe) { } async function maintenance() { return serial(async()=>{ - const state=await S.publicState(),sites=[]; - for(const origin of state.sites)if(!state.blockedSites.includes(origin) && await chrome.permissions.contains({origins:[C.hostPattern(origin)]}))sites.push(origin); - await S.updateIndex(s=>{s.sites=sites;});await registerSites(await S.publicState());await finishPending();await recheckPages(); + const state=await S.publicState(),sites=[],policy=await managed(); + for(const origin of state.sites)if(policyAllows(policy,origin) && !state.blockedSites.includes(origin) && await chrome.permissions.contains({origins:[C.hostPattern(origin)]}))sites.push(origin); + await S.updateIndex(s=>{s.sites=sites;s.drafts=s.drafts.map(d=>({...d,expires:Math.min(d.expires,d.saved+policy.maxDays*C.DAY)}));});await registerSites(await S.publicState());await finishPending();await recheckPages(); await chrome.alarms.create('retention',{periodInMinutes:60}); }).catch(()=>recordError('Could not maintain local storage. Keep a separate copy.')); } @@ -170,5 +197,12 @@ chrome.runtime.onInstalled.addListener(maintenance);chrome.runtime.onStartup.add chrome.alarms.onAlarm.addListener(a=>{if(a.name==='retention')maintenance();});chrome.permissions.onRemoved.addListener(maintenance); chrome.permissions.onAdded.addListener(()=>serial(finishPending).catch(()=>recordError('Could not finish enabling protection. Reopen the popup and try again.'))); chrome.storage.onChanged.addListener((changes,area)=>{ + if(area==='managed')maintenance(); if(area==='session' && Object.entries(changes).some(([name,change])=>name.startsWith('enable-') && change.newValue))serial(finishPending).catch(()=>recordError('Could not finish enabling protection. Reopen the popup and try again.')); }); + +chrome.commands.onCommand.addListener(async command=>{ + if(command!=='open-library')return; + const [tab]=await chrome.tabs.query({active:true,currentWindow:true}); + if(tab?.id && !tab.incognito)await chrome.tabs.sendMessage(tab.id,{type:'OPEN_LIBRARY'}).catch(()=>{}); +}); diff --git a/extension/content.js b/extension/content.js index d61eadc..89146df 100644 --- a/extension/content.js +++ b/extension/content.js @@ -1,7 +1,9 @@ (() => { if (globalThis.__draftCairn) return; globalThis.__draftCairn = true; - const C = globalThis.Cairn; + const C = globalThis.Cairn,W=globalThis.CairnWorkflows; + let frameScope='',fallbackShortcut=false; + const embedded=window!==window.top; let active = false; let activation = 0; let timer; @@ -21,37 +23,72 @@ return 'tinymce-inline'; } function fieldFrom(target) { - if(!(target instanceof Element) || target.getRootNode()!==document)return null; + if(!(target instanceof Element))return null; + const tree=target.getRootNode();if(tree!==document && (!(tree instanceof ShadowRoot) || tree.mode!=='open'))return null; if(target.matches('textarea,input'))return target; const el=target.closest('[contenteditable]'); return el && editorType(el) ? el : null; } + function parentOf(el){return el.parentElement || (el.getRootNode() instanceof ShadowRoot ? el.getRootNode().host : null);} + function across(el,selector){for(let node=el;node;node=parentOf(node))if(node.matches(selector))return node;return null;} + function activeElement(){let el=document.activeElement;while(el?.shadowRoot?.activeElement)el=el.shadowRoot.activeElement;return el;} + function eventField(e){return fieldFrom(e.composedPath()[0]);} + function shadowPath(el){ + const parts=[];let tree=el.getRootNode(); + while(tree instanceof ShadowRoot){const h=tree.host;parts.unshift(h.tagName+':'+h.id+':'+Array.from(h.parentNode?.children || []).indexOf(h));tree=h.getRootNode();} + return parts.join('/').slice(0,160); + } + function allFields(tree=document){ + const found=[]; + for(const el of tree.querySelectorAll('*')){ + if(el===host)continue; + if(el.matches('textarea,input,'+richSelector))found.push(el); + if(el.shadowRoot)found.push(...allFields(el.shadowRoot)); + } + return found; + } const textOf = el => editorType(el) ? el.innerText : el.value; async function excludedField(el) { const identity=C.fieldIdentity(describe(el)); - const pageKey=await digest(location.origin+location.pathname); + const pageKey=await digest(location.origin+location.pathname+frameScope); const id=await digest(location.origin+pageKey+identity); checkedFields.set(el,identity); if(ignoredFields.has(id)){excluded.add(el);return true;} return false; } - function configure(data){ignoredFields=new Set(data.ignoredFields || []);excluded=new WeakSet();checkedFields=new WeakMap();appearance=['light','dark'].includes(data.appearance) ? data.appearance : 'system';if(host)host.dataset.theme=appearance;} + function deactivate(){activation++;active=false;pending=null;clearTimeout(timer);clearTimeout(pasteWatch?.timer);pasteWatch=null;pasteIssues.clear();root?.replaceChildren();host?.remove();host=null;root=null;status=null;} + function configure(data){if(!data.active){deactivate();return false;}active=true;fallbackShortcut=data.shortcut==='Alt+Shift+L';frameScope=data.scope || '';ignoredFields=new Set(data.ignoredFields || []);excluded=new WeakSet();checkedFields=new WeakMap();appearance=['light','dark'].includes(data.appearance) ? data.appearance : 'system';if(host)host.dataset.theme=appearance;return true;} const shorten = s => (s || '').trim().replace(/\s+/g,' ').slice(0,200); const digest = async text => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(text))), b=>b.toString(16).padStart(2,'0')).join(''); function describe(el) { const rich=editorType(el), form=el.form || el.closest('form'); return {tag:el.tagName, type:rich || el.type || 'textarea', id:shorten(el.id), name:shorten(el.getAttribute('name')), - label:shorten(el.labels?.[0]?.textContent || el.getAttribute('aria-label') || (el.getAttribute('aria-labelledby') || '').split(/\s+/).slice(0,8).map(id=>document.getElementById(id)?.textContent || '').join(' ')), - form:shorten(form?.id || form?.getAttribute('name') || ''), + label:shorten(el.labels?.[0]?.textContent || el.getAttribute('aria-label') || (el.getAttribute('aria-labelledby') || '').split(/\s+/).slice(0,8).map(id=>el.getRootNode().getElementById(id)?.textContent || '').join(' ')), + form:shorten((form?.id || form?.getAttribute('name') || '')+(shadowPath(el) ? '|shadow|'+shadowPath(el) : '')),shadow:el.getRootNode()!==document, placeholder:shorten(el.getAttribute('placeholder') || el.getAttribute('data-placeholder')), autocomplete:shorten(el.getAttribute('autocomplete') || form?.getAttribute('autocomplete')), visible:Array.from(el.getClientRects()).some(r=>r.width>0 && r.height>0) && (el.checkVisibility ? el.checkVisibility({checkOpacity:true,checkVisibilityCSS:true}) : getComputedStyle(el).visibility !== 'hidden') && - !el.closest('[inert],[aria-hidden="true"],[hidden]'), - disabled:!!el.disabled || el.matches(':disabled') || !!el.closest('[aria-disabled="true"]'), readOnly:!!el.readOnly || !!el.closest('[aria-readonly="true"]') || !!rich && !el.isContentEditable, - private:excluded.has(el) || !!el.closest('[data-cairn-ignore]') || !!rich && !!el.querySelector('[data-cairn-ignore],input,textarea,[autocomplete]'), maxLength:rich ? -1 : el.maxLength}; + !across(el,'[inert],[aria-hidden="true"],[hidden]') && !framePrivate(), + disabled:!!el.disabled || el.matches(':disabled') || !!across(el,'[aria-disabled="true"]'), readOnly:!!el.readOnly || !!across(el,'[aria-readonly="true"]') || !!rich && !el.isContentEditable, + private:excluded.has(el) || !!across(el,'[data-cairn-ignore]') || !!rich && !!el.querySelector('[data-cairn-ignore],input,textarea,[autocomplete]'), maxLength:rich ? -1 : el.maxLength}; + } + function framePrivate(){ + try {for(let w=window;w!==w.top;w=w.parent){const frame=w.frameElement;if(frame && (across(frame,'[data-cairn-ignore],[hidden],[inert],[aria-hidden="true"]') || !frame.checkVisibility({checkVisibilityCSS:true})))return true;}} + catch { /* Cross-origin parents are authorized independently by the worker. */ } + return false; + } + function hintFor(el){ + const tree=el.getRootNode(),ids=(el.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean); + const candidates=ids.map(id=>tree.getElementById(id)); + // An adjacent counter is accepted only in a container with exactly this one field. + const parent=el.parentElement; + if(parent && parent.querySelectorAll('textarea,input,[contenteditable="true"]').length===1)candidates.push(...parent.querySelectorAll('[role="status"],output,[data-word-count],[data-character-count]')); + const hints=candidates.filter(n=>n && n!==el && n.checkVisibility({checkVisibilityCSS:true})).map(n=>W.counterHint(n.textContent)).filter(Boolean); + const unique=[...new Map(hints.map(h=>[h.limit+'|'+h.unit,h])).values()]; + return unique.length===1 ? unique[0] : null; } function fields() { - return Array.from(document.querySelectorAll('textarea,input,'+richSelector)).map(el=>({el,...describe(el)})).filter(C.allowedField); + return allFields().map(el=>({el,...describe(el)})).filter(C.allowedField); } async function signature(list) { return digest(JSON.stringify(list.map(C.fieldIdentity))); } async function message(m) { @@ -67,12 +104,12 @@ style.textContent = `:host{all:initial;color-scheme:light;--c-paper:#fff;--c-input:#f0f4f1;--c-ink:#1a211d;--c-muted:#505d55;--c-line:#748279;--c-primary:#226b4c;--c-on-primary:#fff;--c-error:#ffdad5;--c-on-error:#6e1712;--c-scrim:#101c1673;font:14px/1.6 'Segoe UI',Roboto,Arial,sans-serif;color:var(--c-ink)} :host([data-theme=dark]){color-scheme:dark;--c-paper:#1a211c;--c-input:#202923;--c-ink:#e1e9e2;--c-muted:#b2c0b5;--c-line:#85978a;--c-primary:#97d5b0;--c-on-primary:#093922;--c-error:#62302a;--c-on-error:#ffdad5;--c-scrim:#0009} @media(prefers-color-scheme:dark){:host(:not([data-theme=light]):not([data-theme=dark])){color-scheme:dark;--c-paper:#1a211c;--c-input:#202923;--c-ink:#e1e9e2;--c-muted:#b2c0b5;--c-line:#85978a;--c-primary:#97d5b0;--c-on-primary:#093922;--c-error:#62302a;--c-on-error:#ffdad5;--c-scrim:#0009}} -*{box-sizing:border-box}button,textarea{font:inherit}button{min-height:40px;padding:9px 16px;border:1px solid var(--c-line);background:var(--c-paper);color:var(--c-primary);border-radius:999px;cursor:pointer;font-size:13px;font-weight:600}button:hover{background:var(--c-input)}button:focus-visible,textarea:focus-visible{outline:3px solid var(--c-primary);outline-offset:3px}.pill{position:fixed;bottom:16px;right:16px;z-index:2147483647;background:var(--c-paper);color:var(--c-primary);border:1px solid var(--c-line);box-shadow:0 3px 16px #0002;border-radius:999px;padding:10px 16px;max-width:min(380px,90vw);text-align:left;font-size:12px;font-weight:500}.error{background:var(--c-error);color:var(--c-on-error)}dialog{color:var(--c-ink);background:var(--c-paper);border:1px solid var(--c-line);border-radius:24px;padding:24px;width:min(700px,94vw);max-height:90vh;overflow:auto;box-shadow:0 20px 70px #0004}dialog::backdrop{background:var(--c-scrim)}h2{font-size:22px;line-height:1.35;font-weight:500;margin:0 0 12px}textarea{display:block;width:100%;height:38vh;min-height:160px;resize:vertical;padding:14px;background:var(--c-input);color:var(--c-ink);border:1px solid var(--c-line);border-radius:12px;line-height:1.65}label{display:block;font-weight:600;margin-bottom:8px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:18px}.primary{background:var(--c-primary);color:var(--c-on-primary)}.primary:hover{background:var(--c-primary)}p{margin:10px 0}small{display:block;color:var(--c-muted)}@media(forced-colors:active){.pill,.primary,dialog{border:1px solid ButtonText}}`; +*{box-sizing:border-box}button,textarea,input{font:inherit}input[type=search]{display:block;width:100%;padding:12px;border-radius:12px;border:1px solid var(--c-line);background:var(--c-input);color:var(--c-ink)}section[data-library]{border-top:1px solid var(--c-line);margin-top:20px;padding-top:20px}button{min-height:40px;padding:9px 16px;border:1px solid var(--c-line);background:var(--c-paper);color:var(--c-primary);border-radius:999px;cursor:pointer;font-size:13px;font-weight:600}button:hover{background:var(--c-input)}button:disabled{opacity:.6;cursor:default}button:focus-visible,textarea:focus-visible{outline:3px solid var(--c-primary);outline-offset:3px}.pill{position:fixed;bottom:16px;right:16px;z-index:2147483647;background:var(--c-paper);color:var(--c-primary);border:1px solid var(--c-line);box-shadow:0 3px 16px #0002;border-radius:999px;padding:10px 16px;max-width:min(380px,90vw);text-align:left;font-size:12px;font-weight:500}.error{background:var(--c-error);color:var(--c-on-error)}dialog{color:var(--c-ink);background:var(--c-paper);border:1px solid var(--c-line);border-radius:24px;padding:24px;width:min(700px,94vw);max-height:90vh;overflow:auto;box-shadow:0 20px 70px #0004}dialog::backdrop{background:var(--c-scrim)}h2{font-size:22px;line-height:1.35;font-weight:500;margin:0 0 12px}textarea{display:block;width:100%;height:38vh;min-height:160px;resize:vertical;padding:14px;background:var(--c-input);color:var(--c-ink);border:1px solid var(--c-line);border-radius:12px;line-height:1.65}label{display:block;font-weight:600;margin-bottom:8px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:18px}.primary{background:var(--c-primary);color:var(--c-on-primary)}.primary:hover{background:var(--c-primary)}p{margin:10px 0}small{display:block;color:var(--c-muted)}@media(forced-colors:active){.pill,.primary,dialog{border:1px solid ButtonText}}`; root.append(style); status = document.createElement('button'); status.className = 'pill'; status.type = 'button'; status.setAttribute('aria-live','polite'); - status.title = 'Open a larger editor for the last supported field'; - status.onclick = ()=>{if(lastField?.isConnected && C.allowedField(describe(lastField))) {const issue=pasteIssues.get(lastField);editor(lastField,issue?.original ?? textOf(lastField),false,issue);}}; + status.title = 'Open the editor or choose a library answer for this field (Alt+Shift+L)'; + status.onclick = e=>{if(e.isTrusted && lastField?.isConnected && C.allowedField(describe(lastField))) {const issue=pasteIssues.get(lastField);editor(lastField,issue?.original ?? textOf(lastField),false,issue);}}; status.textContent = 'Draft Cairn · choose a supported answer field'; root.append(status); document.documentElement.append(host); @@ -83,8 +120,8 @@ async function focusedStatus() { if (!active) return; const version=++focusVersion; - const focused=document.activeElement,el=fieldFrom(focused); - if (focused===host) return; + const focused=activeElement(),el=fieldFrom(focused); + if (focused===host || embedded && !document.hasFocus()) return; if (el && C.allowedField(describe(el))) { if(ignoredFields.size) { announce('checking field…'); @@ -98,6 +135,7 @@ if(pasteWatch?.el===el){announce('checking visible paste…');return;} const saved=fieldStatus.get(el); announce(saved?.text || (editorType(el) ? 'rich text · plain-text recovery · not saved yet' : 'supported field · not saved yet'),saved?.error || false); + const hint=hintFor(el);if(hint){const report=W.fit(textOf(el),el.maxLength,hint);status.textContent+=' · '+report.message;} } else { lastField=null; const editable=focused?.matches?.('textarea,input,iframe,[contenteditable]:not([contenteditable="false"]),[role="textbox"]') || focused?.isContentEditable || focused?.shadowRoot?.activeElement; @@ -143,7 +181,8 @@ function editor(el, original, oversized, issue) { mount(); if (root.querySelector('dialog')) return; - const before = document.activeElement; + const before = activeElement(); + const destination={url:location.href,value:textOf(el),start:el.selectionStart,end:el.selectionEnd,identity:C.fieldIdentity(describe(el))}; const dialog = document.createElement('dialog'); dialog.setAttribute('aria-labelledby','cairn-heading'); const heading = document.createElement('h2'); heading.id = 'cairn-heading'; @@ -156,8 +195,7 @@ const help = document.createElement('small'); help.textContent = 'Counts use UTF-16 units, as HTML maxlength does. Custom website limits may differ. Emoji can use several units. Edits here are kept in memory until copied.'; const result = document.createElement('p'); result.setAttribute('role','status'); function count() { - const limit = el.maxLength; - counter.textContent = `${area.value.length.toLocaleString()} units · ${Array.from(area.value).length.toLocaleString()} Unicode code points${limit >= 0 ? ` · declared field limit ${limit}` : ' · no detectable limit'}`; + counter.textContent=W.fit(area.value,el.maxLength,hintFor(el)).message; } area.oninput = count; count(); const actions = document.createElement('div'); actions.className = 'actions'; @@ -170,7 +208,10 @@ try{await message({type:'IGNORE_FIELD',field:describe(el)});excluded.add(el);pasteIssues.delete(el);if(pasteWatch?.el===el){clearTimeout(pasteWatch.timer);pasteWatch=null;}if(pending?.el===el)pending=null;dialog.close();lastField=null;announce('not protected in this field · excluded in settings',true);} catch{result.textContent='Could not exclude this field. Turn protection off from the toolbar popup.';} }; - actions.append(copy,close,ignore); dialog.append(heading,note,label,area,counter,help,actions,result); + const library=document.createElement('button');library.type='button';library.textContent='Use library answer'; + library.onclick=e=>{if(e.isTrusted)openLibrary(dialog,el,destination,area,counter,result);}; + library.addEventListener('cairn-library',()=>openLibrary(dialog,el,destination,area,counter,result)); + actions.append(copy,library,close,ignore); dialog.append(heading,note,label,area,counter,help,actions,result); if(issue) { area.style.height='120px';area.style.minHeight='120px'; help.textContent='Edits here stay in memory until copied. Review the website before pasting. Formatting is not compared.'; @@ -183,6 +224,62 @@ dialog.addEventListener('close',()=>{dialog.remove();if(before?.isConnected)before.focus();}); root.append(dialog); dialog.showModal(); area.focus(); } + async function openLibrary(dialog,el,destination,area,counter,result){ + if(dialog.querySelector('[data-library]'))return; + const section=document.createElement('section');section.dataset.library=''; + const label=document.createElement('label');label.textContent='Find a library answer';label.htmlFor='cairn-library-search'; + const search=document.createElement('input');search.type='search';search.id='cairn-library-search';search.placeholder='Search titles and projects'; + const options=document.createElement('div');options.className='actions'; + const fit=document.createElement('p');fit.setAttribute('role','status'); + const insert=document.createElement('button');insert.type='button';insert.className='primary';insert.textContent='Insert at saved cursor';insert.disabled=true; + const note=document.createElement('p');note.textContent='Choose an answer to preview below. Existing text outside your selection stays. Rich editors support copying only. Inserting makes the text available to this website.'; + const preview=document.createElement('textarea');preview.readOnly=true;preview.setAttribute('aria-label','Result after insertion');preview.style.height='120px'; + const controls=dialog.querySelector('.actions'),answerLabel=dialog.querySelector('label[for="cairn-answer"]'); + dialog.querySelector('h2').textContent='Use a library answer'; + dialog.querySelector('p').textContent='Choose a saved paragraph, review its fit and result, then insert when ready.'; + dialog.querySelector('small')?.remove(); + answerLabel.textContent='Selected answer (editable copy)';area.style.height='120px';area.style.minHeight='120px';area.value='';counter.textContent=''; + for(const button of controls.querySelectorAll('button'))if(['Use library answer','Never capture this field'].includes(button.textContent))button.hidden=true; + section.append(label,search,options,answerLabel,area,counter,note,fit,preview,insert);dialog.insertBefore(section,controls);search.focus(); + let selected=false; + function update(){ + const expected=C.expectedPaste(destination.value,destination.start,destination.end,area.value); + const report=W.fit(expected ?? area.value,el.maxLength,hintFor(el)); + preview.value=expected ?? '';fit.textContent=report.message+(destination.start!==destination.end ? ' · selected website text will be replaced' : ''); + insert.disabled=!selected || report.blocked || expected===null || !!editorType(el); + } + area.addEventListener('input',update); + try{ + const items=await message({type:'LIBRARY_LIST'}); + function render(){ + options.replaceChildren(); + const matches=items.filter(a=>(a.title+' '+a.project).toLowerCase().includes(search.value.toLowerCase())); + if(!matches.length)options.textContent='No matching library answers. Save an answer in Recovery & library first.'; + for(const item of matches.slice(0,30)){ + const choice=document.createElement('button');choice.type='button';choice.textContent=item.title+(item.project ? ' · '+item.project : ''); + choice.onclick=async e=>{if(!e.isTrusted)return;try{const answer=await message({type:'LIBRARY_GET',id:item.id});if(!dialog.isConnected || !active)return;area.value=answer.text;selected=true;counter.textContent=W.fit(area.value,el.maxLength,hintFor(el)).message;update();}catch{fit.textContent='Unlock your vault in the workspace before using library answers.';}}; + options.append(choice); + } + } + search.oninput=render;render(); + }catch{fit.textContent='Unlock your vault in the workspace before using library answers.';} + insert.onclick=async e=>{ + if(!e.isTrusted || insert.disabled)return;insert.disabled=true; + try{ + if(!(await message({type:'HELLO'})).active)throw new Error(); // Recheck access immediately before releasing text. + if(await excludedField(el) || !active || !el.isConnected || !C.allowedField(describe(el)) || editorType(el) || location.href!==destination.url || C.fieldIdentity(describe(el))!==destination.identity || el.value!==destination.value)throw new Error(); + const expected=C.expectedPaste(destination.value,destination.start,destination.end,area.value); + if(expected===null || W.fit(expected,el.maxLength,hintFor(el)).blocked)throw new Error(); + const proto=el.tagName==='TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; + Object.getOwnPropertyDescriptor(proto,'value').set.call(el,expected); + el.dispatchEvent(new Event('input',{bubbles:true,composed:true}));el.dispatchEvent(new Event('change',{bubbles:true,composed:true})); + fit.textContent='Inserted · checking what the website retained…'; + await new Promise(resolve=>setTimeout(resolve,1500)); + if(!active || !el.isConnected || el.value!==expected){fit.textContent='The website changed or removed the inserted text. Your library original is unchanged. Review and copy it manually.';return;} + const saved=await enqueue(el,expected);fit.textContent='Visible insertion matches · '+(saved ? 'saved on this device' : 'not saved; keep a separate copy')+' · submission not checked'; + }catch{fit.textContent='The destination changed or protection is unavailable. Reopen the editor to choose the field again.';} + }; + } function preservePaste(watch,note,actual,comparison) { if(!active || watch.version!==activation)return; const issue={original:watch.original,note,actual:actual.slice(0,C.MAX_TEXT),comparison,saved:null}; @@ -220,7 +317,7 @@ window.addEventListener('blur',()=>setTimeout(focusedStatus,0)); document.addEventListener('input',e=>{ if (!e.isTrusted) return; - const el = fieldFrom(e.target); + const el = eventField(e); if (!active || !el || !C.allowedField(describe(el))) return; if(pasteWatch && (pasteWatch.el!==el || e.inputType!=='insertFromPaste'))finishPaste('Typing continued before the paste check finished. Compare the original manually.'); if (pending && pending.el !== el) flush(); @@ -232,7 +329,7 @@ const richEdits=new WeakMap(); document.addEventListener('beforeinput',e=>{ if(!e.isTrusted || !active || !/^(insert|delete|historyUndo|historyRedo)/.test(e.inputType))return; - const el=fieldFrom(e.target); + const el=eventField(e); if(!el || !editorType(el) || !C.allowedField(describe(el)))return; if(pasteWatch && (pasteWatch.el!==el || e.inputType!=='insertFromPaste'))finishPaste('Typing continued before the paste check finished. Compare the original manually.'); const version=activation,edit={};richEdits.set(el,edit); @@ -247,7 +344,7 @@ window.addEventListener('pagehide',()=>{finishPaste('The page closed before verification finished. Compare the original manually.');flush();}); document.addEventListener('paste',e=>{ if (!e.isTrusted) return; - const el=fieldFrom(e.target); + const el=eventField(e); if (!active || !el || !C.allowedField(describe(el)) || !e.clipboardData || !e.clipboardData.types.includes('text/plain')) return; if(ignoredFields.size && checkedFields.get(el)!==C.fieldIdentity(describe(el))){announce('paste check unavailable until field exclusion check finishes',true);return;} const text=e.clipboardData.getData('text/plain'); @@ -266,23 +363,43 @@ const watch={el,original:text,expected,version:activation,snapshot:snapshot(el,text,'paste').catch(()=>null)};pasteWatch=watch; watch.timer=setTimeout(()=>finishPaste(),1500);focusedStatus(); },true); + document.addEventListener('submit',e=>{ + if(!e.isTrusted || !active)return; + const over=fields().filter(f=>f.el.form===e.target).filter(f=>{const h=hintFor(f.el);return h && (h.unit==='words' ? W.countWords(textOf(f.el)) : textOf(f.el).length)>h.limit;}); + if(over.length)announce('website counter limit may be exceeded · submission was not blocked',true); + },true); + function openFocusedLibrary(){ + const el=fieldFrom(activeElement()); + if(!active || !document.hasFocus() || !el?.isConnected || !C.allowedField(describe(el)) || root?.querySelector('dialog'))return; + lastField=el;editor(el,textOf(el),false); + const button=Array.from(root.querySelectorAll('button')).find(b=>b.textContent==='Use library answer');button?.dispatchEvent(new Event('cairn-library')); + } + // Some Chromium environments pass the chord to the page instead of the command + // service. Both entry points open the same picker; neither inserts automatically. + document.addEventListener('keydown',e=>{ + if(e.isTrusted && e.altKey && e.shiftKey && !e.ctrlKey && !e.metaKey && e.code==='KeyL' && fallbackShortcut && active && fieldFrom(activeElement())){e.preventDefault();openFocusedLibrary();} + },true); chrome.runtime.onMessage.addListener((m,sender,respond)=>{ + if(sender.id===chrome.runtime.id && m.type==='OPEN_LIBRARY'){ + openFocusedLibrary(); + respond({ok:true});return; + } if (sender.id === chrome.runtime.id && m.type === 'RECHECK') { respond({ok:true}); const version=activation; - message({type:'HELLO'}).then(data=>{if(version===activation){configure(data);active=true;focusedStatus();}}).catch(()=>{if(version===activation){active=false;pending=null;clearTimeout(timer);clearTimeout(pasteWatch?.timer);pasteWatch=null;pasteIssues.clear();host?.remove();}});return; + message({type:'HELLO'}).then(data=>{if(version===activation){if(!configure(data))return;focusedStatus();}}).catch(()=>{if(version===activation){deactivate();}});return; } if (sender.id === chrome.runtime.id && m.type === 'START') { const version=++activation;respond({ok:true}); - message({type:'HELLO'}).then(data=>{if(version===activation){configure(data);active=true;focusedStatus();}}).catch(()=>{});return; + message({type:'HELLO'}).then(data=>{if(version===activation){if(!configure(data))return;focusedStatus();}}).catch(()=>{});return; } - if (sender.id === chrome.runtime.id && m.type === 'STOP') {activation++;active=false;pending=null;clearTimeout(timer);clearTimeout(pasteWatch?.timer);pasteWatch=null;pasteIssues.clear();host?.remove();respond({ok:true});return;} + if (sender.id === chrome.runtime.id && m.type === 'STOP') {deactivate();respond({ok:true});return;} if (sender.id !== chrome.runtime.id || m.type !== 'RESTORE') return; (async()=>{ - if (!active) return {ok:false,error:'Protection is off. Copy the answer instead.'}; - const list=fields(), structure=await signature(list), pageKey=await digest(location.origin+location.pathname); + if (!active || embedded) return {ok:false,error:'Protection is off. Copy the answer instead.'}; + const list=fields(), structure=await signature(list), pageKey=await digest(location.origin+location.pathname+frameScope); const found=C.matchField(m.draft,list,pageKey,structure,!location.search && !location.hash); - if (!found || !found.el.isConnected || !C.allowedField(describe(found.el)) || await excludedField(found.el) || found.el.value !== '') + if (!found || !found.el.isConnected || !C.allowedField(describe(found.el)) || found.el.getRootNode()!==document || await excludedField(found.el) || found.el.value !== '') return {ok:false,error:'The page or field changed, the match is uncertain, or the field already has text. Copy the answer instead.'}; if (found.el.maxLength >= 0 && m.draft.text.length > found.el.maxLength) return {ok:false,error:'The page limit changed. Copy the answer instead.'}; @@ -296,5 +413,5 @@ return true; }); const initialVersion=activation; - message({type:'HELLO'}).then(data=>{if(initialVersion!==activation)return;configure(data);active=true;if(document.documentElement)focusedStatus();else document.addEventListener('DOMContentLoaded',()=>{if(active)focusedStatus();},{once:true});}).catch(()=>{}); + message({type:'HELLO'}).then(data=>{if(initialVersion!==activation)return;if(!configure(data))return;if(document.documentElement)focusedStatus();else document.addEventListener('DOMContentLoaded',()=>{if(active)focusedStatus();},{once:true});}).catch(()=>{}); })(); diff --git a/extension/core.js b/extension/core.js index 57e9400..c9bd7f0 100644 --- a/extension/core.js +++ b/extension/core.js @@ -59,11 +59,11 @@ state.drafts = state.drafts.filter(d => d.expires > now); return state; } - function fresh() { return {version:1,days:1,metadata:false,sessionOnly:false,appearance:'system',sites:[],blockedSites:[],ignoredFields:[],drafts:[],library:[]}; } + function fresh() { return {version:1,days:1,metadata:false,sessionOnly:false,appearance:'system',siteDays:{},sites:[],blockedSites:[],ignoredFields:[],drafts:[],library:[]}; } function privacyDefaults(state) { return {...state,metadata:state.metadata ?? true,sessionOnly:state.sessionOnly ?? false, appearance:['system','light','dark'].includes(state.appearance) ? state.appearance : 'system', - blockedSites:state.blockedSites || [],ignoredFields:state.ignoredFields || []}; + siteDays:state.siteDays || {},blockedSites:state.blockedSites || [],ignoredFields:state.ignoredFields || []}; } function minimalDraft(draft) { return {...draft,title:'',field:{label:''},restorable:false}; diff --git a/extension/managed-schema.json b/extension/managed-schema.json new file mode 100644 index 0000000..8cef788 --- /dev/null +++ b/extension/managed-schema.json @@ -0,0 +1,24 @@ +{ + "type": "object", + "properties": { + "AllowedOrigins": { + "title": "Allowed website origins", + "description": "Restrict enabled sites to exact origins. Does not grant Chrome permissions.", + "type": "array", + "items": { + "type": "string" + } + }, + "MaxRetentionDays": { + "title": "Maximum recovery retention", + "type": "integer", + "enum": [ + 1, + 3, + 7, + 14, + 30 + ] + } + } +} diff --git a/extension/manifest.json b/extension/manifest.json index 2f4b843..b658aa6 100644 --- a/extension/manifest.json +++ b/extension/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 3, "name": "Draft Cairn", - "version": "0.3.1", + "version": "0.4.0", "description": "Local answer recovery, paste-limit warnings, and a reusable answer library for sites you choose.", "minimum_chrome_version": "120", "incognito": "not_allowed", @@ -32,5 +32,16 @@ }, "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'none'; connect-src 'none'; base-uri 'none'" + }, + "commands": { + "open-library": { + "suggested_key": { + "default": "Alt+Shift+L" + }, + "description": "Preview a library answer in the focused supported field" + } + }, + "storage": { + "managed_schema": "managed-schema.json" } } diff --git a/extension/popup.html b/extension/popup.html index 13727c3..a5f1dce 100644 --- a/extension/popup.html +++ b/extension/popup.html @@ -2,4 +2,4 @@
Draft Cairn
On this device

Draft protection

Current website

Checking protection…

Answers stay in this browser profile.

Recent drafts

-

Enable before writing. Sensitive text can be saved. Encryption and privacy settings are in the workspace.

+ diff --git a/extension/popup.js b/extension/popup.js index 7fb665b..05863c5 100644 --- a/extension/popup.js +++ b/extension/popup.js @@ -51,3 +51,5 @@ $('wipe').onclick=async()=>{ if(!confirm('Permanently delete ALL extension drafts, library answers, vault keys, settings and site access? Exported files and clipboard history remain.'))return; try{await api('CLEAR');await render();notice('All extension data and site access deleted.');}catch(e){notice(e.message,true);} }; + +$('practice').onclick=()=>chrome.tabs.create({url:chrome.runtime.getURL('practice.html')}); diff --git a/extension/practice.html b/extension/practice.html new file mode 100644 index 0000000..aac1938 --- /dev/null +++ b/extension/practice.html @@ -0,0 +1 @@ +Try a recovery · Draft Cairn
Draft Cairn

See your words come back

This local practice page uses the real encrypted recovery store. It does not enable any website. Use sample text only.

  1. Write a few sentences below.
  2. Choose Save practice answer and wait for confirmation.
  3. Reload this page. The box will be empty.
  4. Choose Recover practice answer.

Open recovery & library

On real websites, first enable the site from the toolbar popup and wait for saved on this device. Only supported fields save. This practice does not test a website’s own autosave or session timeout.

diff --git a/extension/practice.js b/extension/practice.js new file mode 100644 index 0000000..396bd43 --- /dev/null +++ b/extension/practice.js @@ -0,0 +1,5 @@ +import './theme.js'; +import {$,api,notice} from './ui.js'; +$('practice-save').onclick=async()=>{try{await api('PRACTICE_SAVE',{text:$('practice-answer').value});notice('Saved on this device. Reload the page, then recover your sample.');}catch(e){notice(e.message,true);}}; +$('practice-recover').onclick=async()=>{try{const answer=await api('PRACTICE_READ');if($('practice-answer').value)throw new Error('The box already has text. Keep or clear it yourself before recovery.');$('practice-answer').value=answer;notice('Recovered. On websites you can copy back or explicitly restore when the match is safe.');}catch(e){notice(e.message,true);}}; +$('practice-clear').onclick=async()=>{try{await api('PRACTICE_CLEAR');notice('Practice recovery drafts deleted.');}catch(e){notice(e.message,true);}}; diff --git a/extension/storage.js b/extension/storage.js index 1c6c5e6..6953d9a 100644 --- a/extension/storage.js +++ b/extension/storage.js @@ -1,3 +1,4 @@ +import './workflows.js'; import * as D from './record-store.js'; import * as V from './crypto.js'; import * as legacy from './legacy-storage.js'; @@ -10,7 +11,7 @@ const size=value=>encoder.encode(JSON.stringify(value)).length; const hash=async value=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',encoder.encode(value))),b=>b.toString(16).padStart(2,'0')).join(''); function config(state) { const s=C.privacyDefaults(state); - return {version:1,days:s.days,metadata:s.metadata,sessionOnly:s.sessionOnly,appearance:s.appearance,sites:[...s.sites], + return {version:1,days:s.days,metadata:s.metadata,sessionOnly:s.sessionOnly,appearance:s.appearance,siteDays:{...s.siteDays},sites:[...s.sites], blockedSites:[...s.blockedSites],ignoredFields:[...s.ignoredFields],evicted:s.evicted || 0}; } function blank(state=C.fresh()) {return {...config(state),v:3,generation:crypto.randomUUID(),mode:'automatic',drafts:[],library:[],sessionRef:null};} @@ -174,14 +175,14 @@ export async function commit(state) { if(before.mode==='vault' && !await privateKey(before))throw new Error('Vault is locked. Unlock it before changing saved answers.'); await replaceState(state,{...before},before); } -export async function capture(incoming) { +export async function capture(incoming,maximumDays=30) { if(typeof incoming.text!=='string' || incoming.text.length>C.MAX_TEXT) throw new Error('Invalid draft: answers over 100,000 UTF-16 units cannot be saved. Keep a separate copy.'); if(!incoming.text)return {saved:true,evicted:0}; await ensure();const before=await effective(), now=Date.now(), id=crypto.randomUUID(); let record={...incoming,id};if(!before.metadata)record=C.minimalDraft(record); const provisional=await entryFor({...record,saved:now},'drafts',before); - const drafts=C.planDraft(before.drafts,provisional,before.days,now); + const drafts=C.planDraft(before.drafts,provisional,Math.min(CairnWorkflows.retention(before,incoming.origin),maximumDays),now); record={...record,saved:drafts[0].saved,started:drafts[0].started,expires:drafts[0].expires}; drafts[0].bytes=size(record); const next={...before,drafts}, libraryBytes=next.library.reduce((n,e)=>n+e.bytes,0), overhead=size(config(next)); @@ -200,7 +201,7 @@ export async function capture(incoming) { return {saved:true,evicted}; } export async function updateIndex(change) { - await ensure();const before=await effective(), next={...before,sites:[...before.sites],blockedSites:[...before.blockedSites],ignoredFields:[...before.ignoredFields],drafts:[...before.drafts],library:[...before.library]}; + await ensure();const before=await effective(), next={...before,siteDays:{...before.siteDays},sites:[...before.sites],blockedSites:[...before.blockedSites],ignoredFields:[...before.ignoredFields],drafts:[...before.drafts],library:[...before.library]}; await change(next); next.drafts=next.drafts.filter(d=>d.expires>Date.now()); if(next.sessionOnly) { diff --git a/extension/ui.css b/extension/ui.css index 768f7ef..365fd64 100644 --- a/extension/ui.css +++ b/extension/ui.css @@ -155,3 +155,5 @@ html.popup-document{width:380px;min-width:380px} .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} .card>.row+p{margin-top:14px}.draft .actions+p{margin-top:12px;margin-bottom:0} + +#site-origins{min-height:96px;height:108px;max-width:680px;margin:12px 0} diff --git a/extension/workflows.js b/extension/workflows.js new file mode 100644 index 0000000..ac28a04 --- /dev/null +++ b/extension/workflows.js @@ -0,0 +1,46 @@ +/* Local workflow rules shared by the page and workspace. */ +(() => { + const DAYS=[1,3,7,14,30]; + function countWords(text) { return (text.trim().match(/\S+/gu) || []).length; } + function counterHint(text) { + if(typeof text!=='string' || text.length>200)return null; + const match=text.trim().match(/^(\d[\d,]*)\s*(?:\/|of)\s*(\d[\d,]*)\s*(words?|characters?)\s*(?:used)?[.!]?$/i); + if(!match)return null; + const used=Number(match[1].replaceAll(',','')),limit=Number(match[2].replaceAll(',','')); + if(!Number.isSafeInteger(used) || !Number.isSafeInteger(limit) || limit<1 || limit>1000000 || used>1000000)return null; + return {used,limit,unit:match[3].toLowerCase().startsWith('word') ? 'words' : 'characters'}; + } + function fit(text,maxLength,hint) { + const words=countWords(text),units=text.length,parts=[`${units.toLocaleString()} UTF-16 units`,`${words.toLocaleString()} estimated words`]; + let blocked=false; + if(Number.isInteger(maxLength) && maxLength>=0) { + const over=units-maxLength;blocked=over>0; + parts.push(over>0 ? `over declared character limit by ${over}` : `fits declared character limit (${maxLength-units} remaining)`); + } else parts.push('no declared HTML character limit'); + if(hint) { + const estimate=hint.unit==='words' ? words : units,over=estimate-hint.limit; + parts.push(`website reports ${hint.used}/${hint.limit} ${hint.unit}; our estimate ${estimate}${over>0 ? `, over by ${over}` : ', within that limit'}`); + } + return {blocked,words,units,message:parts.join(' · ')}; + } + function retention(state,origin) { return state.siteDays?.[origin] || state.days; } + function policy(raw={}) { + const allowed=Array.isArray(raw.AllowedOrigins) ? raw.AllowedOrigins.filter(o=>{try{return new URL(o).origin===o && /^https?:/.test(o);}catch{return false;}}).slice(0,80) : null; + return {allowed,maxDays:DAYS.includes(raw.MaxRetentionDays) ? raw.MaxRetentionDays : 30}; + } + function siteList(raw) { + const values=raw.split(/[\s,]+/).filter(Boolean); + if(!values.length || values.length>20)throw new Error('Choose between 1 and 20 exact website origins.'); + return [...new Set(values.map(value=>{ + const url=new URL(value); + if(!['http:','https:'].includes(url.protocol) || url.username || url.password || url.pathname!=='/' || url.search || url.hash)throw new Error('Choose exact HTTP or HTTPS origins without a path, query or login details.'); + return url.origin; + }))]; + } + function markdown(drafts,metadata) { + const clean=s=>String(s || '').replace(/[\r\n]+/g,' ').replace(/[\\`*_{}\[\]<>#+.!|]/g,'\\$&'); + const sections=drafts.map((d,i)=>`## ${metadata && d.field?.label ? clean(d.field.label) : `Answer ${i+1}`}\n\nSaved: ${new Date(d.saved).toISOString()}\n\n${d.text.split('\n').map(line=>'> '+line).join('\n')}`); + return `# Application snapshot\n\nExported: ${new Date().toISOString()}\n\nA local copy of selected saved answers. This is not proof of submission or server acceptance. Missing or expired fields are not included.\n\n${sections.join('\n\n')}\n`; + } + globalThis.CairnWorkflows=Object.freeze({DAYS,countWords,counterHint,fit,retention,policy,siteList,markdown}); +})(); diff --git a/extension/workspace.html b/extension/workspace.html index fdd5564..1224275 100644 --- a/extension/workspace.html +++ b/extension/workspace.html @@ -2,9 +2,9 @@
Your workspaceLocal workspace

Checking encryption…

-

01 / Recovery

Recovery drafts

Review a saved answer, then copy it or restore it to an empty, confidently matched field. Nothing is restored automatically.

Protection must have been enabled before the loss. Only successful saves can be recovered. Query-based pages and uncertain field matches support copying only.

- - +

01 / Recovery

Recovery drafts

Review a saved answer, then copy it or restore it to an empty, confidently matched field. Nothing is restored automatically.

Protection must have been enabled before the loss. Only successful saves can be recovered. Query-based pages and uncertain field matches support copying only.

+ +

Save an answer

Passphrase

diff --git a/extension/workspace.js b/extension/workspace.js index 0acfe43..ca65442 100644 --- a/extension/workspace.js +++ b/extension/workspace.js @@ -1,5 +1,8 @@ import './theme.js'; import './core.js'; +import './workflows.js'; +const W=globalThis.CairnWorkflows; +const selectedDrafts=new Set(); import {encryptExport,decryptExport} from './crypto.js'; import {$,node,api,notice,action,copy,time} from './ui.js'; let state, tabs=[], pane='recovery', refreshVersion=0, securityGeneration=0, securityMode='', pendingImport=''; @@ -19,6 +22,7 @@ function renderDrafts() { if(!list.length)$('drafts').append(empty('No recovery drafts yet.',q ? 'No drafts match your search.' : 'Enable protection from the extension popup before you write. Supported answers will appear here after saving.')); for(const d of list.sort((a,b)=>b.saved-a.saved)) { const card=node('article',undefined,'card draft'); + const selection=node('label'),check=node('input');check.type='checkbox';check.checked=selectedDrafts.has(d.id);check.onchange=()=>{if(check.checked)selectedDrafts.add(d.id);else selectedDrafts.delete(d.id);};selection.append(check,document.createTextNode(' Include in application snapshot'));card.append(selection); card.append(node('span',d.kind === 'paste' ? 'Original paste · up to 1 hour' : 'Recovery revision','badge'),node('h3',d.field.label || 'Untitled field'),node('div',d.title,'meta'),node('div',`${d.origin} · ${time(d.saved)}`,'meta'),node('pre',d.text)); const controls=node('div',undefined,'row actions'); controls.append(action('Copy',()=>copy(d.text),'primary'),action('Open editor',()=>openEditor(d.text,d.field.label || 'Recovered answer')),action('Delete',async()=>{if(confirm('Delete this revision?')){await api('DELETE_DRAFT',{id:d.id});await refresh();}},'quiet danger')); @@ -50,6 +54,8 @@ function renderLibrary() { } } function renderSettings() { + $('policy-status').textContent=state.policy?.allowed!==null || state.policy?.maxDays<30 ? `Organization policy applies: maximum ${state.policy.maxDays} days; ${state.policy.allowed===null ? 'no site restriction' : 'only listed origins allowed'}. Chrome site permission is still required.` : 'No organization restrictions configured.'; + for(const option of $('retention').options)option.disabled=Number(option.value)>state.policy.maxDays; $('retention').value=state.days;$('sites').replaceChildren(); $('metadata').checked=state.metadata;$('session-only').checked=state.sessionOnly; $('metadata').disabled=state.locked && state.metadata; @@ -58,7 +64,7 @@ function renderSettings() { $('lock-vault').hidden=!vault || state.locked;$('unlock-vault').hidden=!state.locked; $('vault-status').textContent=vault ? (state.locked ? 'Passphrase vault · locked' : 'Passphrase vault · unlocked for this session') : 'Automatic encryption · no password needed'; $('vault-help').textContent=state.locked ? 'New drafts can still save. Unlock to read, search, restore or change library answers.' : vault ? 'Lock when you finish. Your clipboard, exported files and text on websites remain outside the vault.' : 'The automatic key is stored in this profile. Enable a passphrase vault in Sites & settings for protection of answer contents in a copied profile.'; - for(const id of ['new-answer','export','export-encrypted','import','draft-search','library-search'])$(id).disabled=state.locked; + for(const id of ['snapshot','new-answer','export','export-encrypted','import','draft-search','library-search'])$(id).disabled=state.locked; $('blocked-sites').replaceChildren(node('h3','Blocked websites')); if(!state.blockedSites.length)$('blocked-sites').append(node('p','No blocked websites.','meta')); for(const origin of state.blockedSites){const row=node('div',undefined,'site');row.append(node('strong',origin),action('Remove block',async()=>{await api('UNBLOCK_SITE',{origin});await refresh();notice('Block removed. Enable protection from the site popup when ready.');}));$('blocked-sites').append(row);} @@ -72,11 +78,17 @@ function renderSettings() { const controls=node('div',undefined,'row'); if(state.sites.includes(origin))controls.append(action('Turn off',async()=>{await api('DISABLE',{origin});await refresh();notice('Protection is off. Existing drafts are kept.');})); controls.append(action('Delete site data',async()=>{if(confirm('Delete all drafts and protection settings for this site? Manually saved library answers remain.')){await api('DISABLE',{origin,erase:true});await refresh();notice('Site drafts and protection settings deleted.');}},'danger')); + if(state.sites.includes(origin)){ + const label=node('label','Recovery retention for this site'),select=node('select');select.setAttribute('aria-label',`Retention for ${origin}`); + for(const days of W.DAYS){const option=node('option',`${days} ${days===1?'day':'days'}`);option.value=days;option.disabled=days>state.policy.maxDays;select.append(option);} + select.value=state.siteDays[origin] || state.days;select.onchange=async()=>{try{await api('RETENTION',{origin,days:Number(select.value)});await refresh();notice('Site retention updated. Existing expiry is only shortened, never extended.');}catch(e){notice(e.message,true);}}; + row.append(label,select); + } row.append(controls);$('sites').append(row); } } function scrub() { - refreshVersion++;securityGeneration++;state=undefined; + refreshVersion++;securityGeneration++;state=undefined;selectedDrafts.clear(); $('drafts').replaceChildren();$('answers').replaceChildren(); $('draft-search').value='';$('library-search').value=''; if($('answer-dialog').open)$('answer-dialog').close();$('answer-form').reset(); @@ -113,8 +125,8 @@ $('answer-form').onsubmit=async e=>{ }; $('retention').onchange=async()=>{try{await api('RETENTION',{days:Number($('retention').value)});await refresh();notice('Retention updated. Shorter expiry applies to existing drafts too.');}catch(e){notice(e.message,true);}}; function libraryJSON(){return JSON.stringify({format:'draft-cairn-library',version:1,answers:state.library.map(({title,text,project})=>({title,text,project}))});} -function download(raw,name){ - const url=URL.createObjectURL(new Blob([raw],{type:'application/json'})); +function download(raw,name,type='application/json'){ + const url=URL.createObjectURL(new Blob([raw],{type})); const link=node('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); } $('export').onclick=()=>{ @@ -199,3 +211,25 @@ chrome.storage.onChanged.addListener((changes,area)=>{ if(area==='local' && changes['cairn-change'] || area==='session' && changes['cairn-vault-session'])refresh().catch(()=>notice('Could not refresh local data.',true)); }); refresh().catch(e=>notice(e.message,true)); + +$('snapshot').onclick=async()=>{ + try{ + const current=await api('STATE');if(current.locked)throw new Error('Vault is locked. Unlock it before exporting.'); + const drafts=current.drafts.filter(d=>selectedDrafts.has(d.id)); + if(!drafts.length)throw new Error('Choose saved revisions using Include in application snapshot first.'); + if(!confirm(`Export ${drafts.length} selected answers as readable Markdown? This file is outside vault protection and is not a submission receipt.`))return; + download(W.markdown(drafts,current.metadata),'draft-cairn-application-snapshot.md','text/markdown');notice('Selected saved answers exported. This does not prove submission.'); + }catch(e){notice(e.message,true);} +}; +$('enable-sites').onclick=async()=>{ + const button=$('enable-sites');button.disabled=true; + try{ + const origins=W.siteList($('site-origins').value); + if(origins.some(o=>state.blockedSites.includes(o) || state.policy.allowed!==null && !state.policy.allowed.includes(o)))throw new Error('Site is blocked or not allowed by your organization.'); + const pending=chrome.storage.session.set({'enable-batch':{origins,created:Date.now()}}); + const permission=chrome.permissions.request({origins:[...new Set(origins.map(Cairn.hostPattern))]}); + await pending;const granted=await permission; + if(!granted){await chrome.storage.session.remove('enable-batch');throw new Error('Site access was not granted. Protection remains off.');} + await api('FINISH_ENABLE');await refresh();notice('Sites enabled. Reload their open pages before writing.'); + }catch(e){notice(e.message,true);}finally{button.disabled=false;} +}; diff --git a/package-lock.json b/package-lock.json index 1adade8..2515188 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "draft-cairn", - "version": "0.3.1", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "draft-cairn", - "version": "0.3.1", + "version": "0.4.0", "devDependencies": { "playwright": "1.62.1" } diff --git a/package.json b/package.json index 1d48232..703c30a 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,10 @@ { "name": "draft-cairn", - "version": "0.3.1", + "version": "0.4.0", "private": true, "type": "module", "scripts": { - "test": "node --test tests/core.test.js tests/crypto.test.js", + "test": "node --test tests/core.test.js tests/crypto.test.js tests/workflows.test.js", "test:browser": "node tests/browser.mjs", "demo": "node scripts/demo.mjs", "check": "node scripts/check.mjs" diff --git a/scripts/check.mjs b/scripts/check.mjs index 5f7a007..8ab3d5b 100644 --- a/scripts/check.mjs +++ b/scripts/check.mjs @@ -11,6 +11,7 @@ for(const file of await readdir(root)) { if(!file.endsWith('.js'))continue; const url=new URL(file,root);execFileSync(process.execPath,['--check',fileURLToPath(url)]); const source=await readFile(url,'utf8'); + assert(!/\u00c2\u00b7|\u00e2\u20ac/.test(source),`Encoding corruption in ${file}`); assert(!/innerHTML|outerHTML|insertAdjacentHTML|\beval\(|console\.|\bfetch\(|XMLHttpRequest/.test(source),`Unsafe sink or outbound API in ${file}`); } for(const p of Object.values(manifest.icons))await readFile(new URL(p,root)); diff --git a/scripts/package.py b/scripts/package.py index 56c45e1..d8efc50 100644 --- a/scripts/package.py +++ b/scripts/package.py @@ -4,7 +4,7 @@ root=Path(__file__).resolve().parents[1] extension=root/'extension' version=json.loads((extension/'manifest.json').read_text())['version'] -files=['manifest.json','core.js','storage.js','legacy-storage.js','record-store.js','crypto.js','background.js','content.js','ui.js','theme.js','ui.css','popup.html','popup.js','workspace.html','workspace.js']+[f'icons/{n}.png' for n in [16,32,48,128]] +files=['manifest.json','practice.html','practice.js','managed-schema.json','workflows.js','core.js','storage.js','legacy-storage.js','record-store.js','crypto.js','background.js','content.js','ui.js','theme.js','ui.css','popup.html','popup.js','workspace.html','workspace.js']+[f'icons/{n}.png' for n in [16,32,48,128]] actual=sorted(p.relative_to(extension).as_posix() for p in extension.rglob('*') if p.is_file()) assert actual==sorted(files), 'Unexpected extension file. Review the release allowlist.' out=root/'dist' @@ -30,8 +30,15 @@ def deterministic_zip(destination, entries): 'listing/screenshot-library-dark-1280x800.png':(root/'docs/images/library-dark.png').read_bytes(), 'listing/reviewer-instructions.txt':(root/'docs/store/reviewer-instructions.txt').read_bytes(), 'listing/privacy-policy.md':(root/'PRIVACY.md').read_bytes(), + 'tester-kit.md':(root/'docs/tester-kit.md').read_bytes(), + 'managed-policy.md':(root/'docs/managed-policy.md').read_bytes(), + 'EDGE-HANDOFF.md':(root/'docs/edge-handoff.md').read_bytes(), 'SUBMISSION.md':(root/'docs/chrome-web-store.md').read_bytes(), - 'FINAL-MANUAL-CHECKS.md':(root/'docs/store/manual-smoke-test.md').read_text(encoding='utf-8').replace('(../portal-matrix.md)','(PUBLIC-SAMPLE-MATRIX.md)').encode('utf-8'), + 'FINAL-MANUAL-CHECKS.md':(root/'docs/store/manual-smoke-test.md').read_text(encoding='utf-8').replace('(../portal-matrix.md)','(PUBLIC-SAMPLE-MATRIX.md)').replace('(../tester-kit.md)','(tester-kit.md)').encode('utf-8'), + 'VALIDATION.md':(root/'docs/validation.md').read_text(encoding='utf-8').split('## 0.3.1 native toolbar popup',1)[0].replace('(portal-matrix.md)','(PUBLIC-SAMPLE-MATRIX.md)').encode('utf-8'), + 'workflow-validation-0.4.0.json':(root/'docs/workflow-validation-0.4.0.json').read_bytes(), + 'popup-validation-0.4.0.json':(root/'docs/popup-validation-0.4.0.json').read_bytes(), + 'validation-results-0.4.0.json':(root/'docs/validation-results-0.4.0.json').read_bytes(), 'COMPATIBILITY.md':(root/'docs/compatibility.md').read_text(encoding='utf-8').replace('(portal-matrix.md)','(PUBLIC-SAMPLE-MATRIX.md)').encode('utf-8'), 'PUBLIC-SAMPLE-MATRIX.md':(root/'docs/portal-matrix.md').read_text(encoding='utf-8').replace('(store/manual-smoke-test.md)','(FINAL-MANUAL-CHECKS.md)').replace('(compatibility.md)','(COMPATIBILITY.md)').encode('utf-8'), 'START-HERE.txt':( diff --git a/tests/popup.mjs b/tests/popup.mjs index 56995bb..349cf7b 100644 --- a/tests/popup.mjs +++ b/tests/popup.mjs @@ -19,7 +19,7 @@ await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); const origin='http://127.0.0.1:'+server.address().port; const out=path.join(root,'test-results');await mkdir(path.join(out,'screenshots'),{recursive:true}); const sleep=ms=>new Promise(r=>setTimeout(r,ms)); -const results=[];let browserVersion; +const results=[],shortcuts=[];let browserVersion; async function protocol(browser,targetId) { const pending=new Map();let sequence=0; browser.on('Target.receivedMessageFromTarget',e=>{ @@ -92,10 +92,18 @@ try { await browser.send('Target.closeTarget',{targetId:target.targetId}); console.log('PASS '+label); } + await api('SAVE_ANSWER',{answer:{title:'Synthetic shortcut answer',text:'Synthetic shortcut text',project:''}}); + await page.bringToFront();await page.locator('#narrative').focus();await page.keyboard.press('Alt+Shift+L'); + const session=await context.newCDPSession(page);let opened=false; + for(let n=0;n<60;n++){ + const names=(await session.send('Accessibility.getFullAXTree')).nodes.map(n=>n.name?.value || ''); + if(names.includes('Use a library answer') && names.includes('Synthetic shortcut answer')){opened=true;break;}await sleep(100); + } + assert(opened,'The native keyboard command must open the focused field library picker');shortcuts.push({scale,opened});console.log('PASS native-library-shortcut-'+scale); await context.close();context=null; } } finally { - await writeFile(path.join(out,'popup-summary.json'),JSON.stringify({version:manifest.version,browser:browserVersion,nativeToolbar:true,syntheticOnly:true,permissionPrompt:'not tested; loopback host pre-granted in test copy',results},null,2)+'\n'); + await writeFile(path.join(out,'popup-summary.json'),JSON.stringify({version:manifest.version,browser:browserVersion,nativeToolbar:true,syntheticOnly:true,shortcuts,permissionPrompt:'not tested; loopback host pre-granted in test copy',results},null,2)+'\n'); await context?.close();await new Promise(resolve=>server.close(resolve)); assert.equal(path.dirname(path.resolve(temp)),path.resolve(tmpdir())); await rm(temp,{recursive:true,force:true}); diff --git a/tests/portals.mjs b/tests/portals.mjs index 08e74d0..2e3cf5c 100644 --- a/tests/portals.mjs +++ b/tests/portals.mjs @@ -65,21 +65,8 @@ async function inspect(page,target,scope) { for(const frame of page.frames()) { const surface={url:publicUrl(frame.url()),topLevel:frame===page.mainFrame(),textareas:await frame.locator('textarea').count().catch(()=>0)}; result.surfaces.push(surface); - if(frame===page.mainFrame())continue; - for(const candidate of await frame.locator('textarea').all()) { - if(!(await candidate.isVisible().catch(()=>false)) || !(await candidate.isEnabled().catch(()=>false)))continue; - const hint=await candidate.evaluate(el=>[el.id,el.name,el.getAttribute('aria-label'),el.labels?.[0]?.textContent].filter(Boolean).join(' ')); - if(/password|email|phone|address|payment|bank|account|card|contact/i.test(hint))continue; - const text='Draft Cairn synthetic embedded-form exclusion check '+crypto.randomUUID(); - await candidate.fill(text,{timeout:6000});await sleep(600); - const captured=(await api('STATE')).drafts.some(d=>d.text.includes(text)); - result.status=captured ? 'unexpected frame capture' : 'embedded field exclusion confirmed'; - result.reason='Trusted typing in this embedded narrative field is not captured. Open a standalone form when available; iframe recovery is unsupported.'; - result.embeddedCapture=captured;return result; - } } - result.pageTitle=await page.title(); - result.publicNotice=await page.locator('body').innerText().then(text=>text.slice(0,700)).catch(()=>'');return result; + return result; } result.field=await field.evaluate(el=>({tag:el.tagName,id:el.id,type:el.getAttribute('type'),classes:el.matches('[contenteditable]') ? el.className : undefined})); const marker='Draft Cairn synthetic compatibility check '+crypto.randomUUID()+'. This is test text, not an application. 😀'; @@ -109,6 +96,37 @@ async function inspect(page,target,scope) { } else result.restore='copy back only'; return result; } +async function inspectEmbedded(page,target,frame){ + const result={name:target.name,scope:'embedded HTTP/HTTPS preview with both origins enabled',url:publicUrl(frame.url()),status:'not verified'}; + const origin=new URL(frame.url()).origin; + // The temporary manifest grants only the named public sample hosts, never arbitrary third-party frames. + if(!(await ui.evaluate(async origin=>chrome.permissions.contains({origins:[origin+'/*']}),origin))){result.reason='Frame host was not in the named test grants.';return result;} + await api('ENABLE',{origin}); + await frame.goto(frame.url(),{waitUntil:'domcontentloaded',timeout:30000});await sleep(1500); + if(target.name==='Jotform grant template'){ + const next=frame.getByRole('button',{name:'Next',exact:true});if(await next.count()===1 && await next.isVisible())await next.click(); + } + let field; + for(const candidate of await frame.locator('textarea').all()){ + if(!await candidate.isVisible().catch(()=>false) || !await candidate.isEnabled().catch(()=>false) || await candidate.getAttribute('readonly')!==null)continue; + const hint=await candidate.evaluate(el=>[el.id,el.name,el.getAttribute('aria-label'),el.labels?.[0]?.textContent].filter(Boolean).join(' ')); + if(!/password|email|phone|address|payment|bank|account|card|social.security|contact/i.test(hint)){field=candidate;break;} + } + if(!field){result.reason='No eligible narrative field reached in the authorized embedded preview.';return result;} + const marker='Draft Cairn synthetic embedded narrative '+crypto.randomUUID();await field.fill(marker,{timeout:10000}); + let draft;for(let n=0;n<50;n++){draft=(await api('STATE')).drafts.find(d=>d.origin===origin && d.text===marker);if(draft)break;await sleep(100);} + result.capture=!!draft;result.field=await field.evaluate(el=>({tag:el.tagName,id:el.id})); + if(!draft){result.reason='Trusted embedded typing was not observed in recovery.';return result;} + await context.grantPermissions(['clipboard-read','clipboard-write'],{origin:new URL(page.url()).origin}); + const pasted='Draft Cairn synthetic embedded paste. Complete ending.'; + await page.evaluate(text=>navigator.clipboard.writeText(text),pasted);await field.focus();await field.press('Control+A');await field.press('Control+V');await sleep(2000); + const paste=(await api('STATE')).drafts.find(d=>d.origin===origin && d.text===pasted); + result.pastedAnswerSaved=!!paste;result.visiblePaste=await field.inputValue()===pasted;result.restore='copy back only'; + if(draft.restorable || paste?.restorable)throw new Error('Embedded draft must not allow direct restore'); + await frame.goto(frame.url(),{waitUntil:'domcontentloaded',timeout:30000}); + result.recoveryAfterReload=(await api('STATE')).drafts.some(d=>d.id===(paste || draft).id); + result.status=result.recoveryAfterReload && result.pastedAnswerSaved ? 'capture and reload recovery passed' : 'partial result; not a compatibility pass';return result; +} try { for(const target of targets) { const page=await context.newPage(); @@ -121,9 +139,13 @@ try { } } const entry=await inspect(page,target,'public top-level sample');results.push(entry); + if(target.standalone && !entry.capture){ + const embedded=page.frames().find(f=>f!==page.mainFrame() && target.standalone.test(f.url())); + if(embedded)results.push(await inspectEmbedded(page,target,embedded)); + } if(target.standalone && !entry.capture) { const linked=page.frames().map(f=>f.url()).find(url=>target.standalone.test(url)); - if(linked){await page.goto(linked,{waitUntil:'domcontentloaded',timeout:30000});await sleep(1500);results.push(await inspect(page,target,'embedded preview opened as a standalone page; embedding remains unsupported'));} + if(linked){await page.goto(linked,{waitUntil:'domcontentloaded',timeout:30000});await sleep(1500);results.push(await inspect(page,target,'public preview opened as a standalone page'));} } } catch(error){results.push({name:target.name,url:target.url,status:'not verified',reason:error.name==='TimeoutError' ? 'Navigation or field interaction timed out.' : 'Sample could not be exercised in this run.'});} finally{await page.close();} diff --git a/tests/workflows.mjs b/tests/workflows.mjs new file mode 100644 index 0000000..416116b --- /dev/null +++ b/tests/workflows.mjs @@ -0,0 +1,86 @@ +// Synthetic workflow and authorization regression. No applicant sessions or submissions. +import {mkdtemp,cp,readFile,writeFile,rm,mkdir} from 'node:fs/promises'; +import {tmpdir} from 'node:os'; +import {fileURLToPath} from 'node:url'; +import {spawn} from 'node:child_process'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import {chromium} from 'playwright'; +const root=fileURLToPath(new URL('../',import.meta.url)),base='http://127.0.0.1:8765',child='http://127.0.0.1:8766'; +const temp=await mkdtemp(path.join(tmpdir(),'draft-cairn-workflows-')),extension=path.join(temp,'extension'); +await cp(path.join(root,'extension'),extension,{recursive:true}); +const manifest=JSON.parse(await readFile(path.join(extension,'manifest.json'),'utf8'));assert(!manifest.host_permissions);manifest.host_permissions=['http://127.0.0.1/*']; +await writeFile(path.join(extension,'manifest.json'),JSON.stringify(manifest)); +await writeFile(path.join(extension,'background.js'),(await readFile(path.join(extension,'background.js'),'utf8'))+'\nimport * as testStore from "./storage.js";globalThis.testStore=testStore;\n'); +const servers=[8765,8766].map(port=>spawn(process.execPath,['scripts/demo.mjs'],{cwd:root,env:{...process.env,PORT:String(port)},stdio:'ignore'})); +const wait=ms=>new Promise(r=>setTimeout(r,ms)); +for(const origin of [base,child])for(let n=0;n<60;n++){try{if((await fetch(origin+'/workflows.html')).ok)break;}catch{}await wait(100);} +let context;const report=[],check=name=>{report.push(name);console.log('PASS '+name);}; +async function poll(fn,predicate,timeout=10000){const end=Date.now()+timeout;while(Date.now()chrome.runtime.sendMessage(m),{type,...data});if(!r?.ok)throw new Error(r?.error || 'No worker response');return r.data;} +const sessions=new WeakMap(); +async function session(page){if(!sessions.has(page))sessions.set(page,await context.newCDPSession(page));return sessions.get(page);} +async function ax(page){return (await (await session(page)).send('Accessibility.getFullAXTree')).nodes;} +async function names(page){return (await ax(page)).map(n=>n.name?.value || '');} +async function button(page,name){return (await ax(page)).find(n=>n.role?.value==='button' && (typeof name==='string' ? n.name?.value===name : name(n.name?.value || '')));} +async function click(page,name){const n=await button(page,name);assert(n?.backendDOMNodeId,'Expected workflow button');const s=await session(page);await s.send('DOM.scrollIntoViewIfNeeded',{backendNodeId:n.backendDOMNodeId});const {model}=await s.send('DOM.getBoxModel',{backendNodeId:n.backendDOMNodeId});const q=model.content;await page.mouse.click((q[0]+q[2]+q[4]+q[6])/4,(q[1]+q[3]+q[5]+q[7])/4);} +async function close(page){await click(page,'Close editor');await wait(100);} +async function picker(page,selector){await page.locator(selector).focus();await click(page,n=>n.startsWith('Draft Cairn ·'));await click(page,'Use library answer');await poll(()=>names(page),n=>n.includes('Garden summary · Synthetic'));} +async function choose(page,name,text){await click(page,name);await poll(()=>ax(page),nodes=>nodes.some(n=>n.role?.value==='textbox' && n.name?.value==='Selected answer (editable copy)' && n.value?.value===text));} +async function disabled(page,name){const n=await button(page,name);assert(n);return n.properties.some(p=>p.name==='disabled' && p.value.value);} +try{ + const options={headless:true,channel:'chromium',viewport:{width:1280,height:900},args:[`--disable-extensions-except=${extension}`,`--load-extension=${extension}`]};if(process.env.CHROMIUM_PATH)options.executablePath=process.env.CHROMIUM_PATH; + context=await chromium.launchPersistentContext(path.join(temp,'profile'),options); + const worker=context.serviceWorkers()[0] || await context.waitForEvent('serviceworker'),id=new URL(worker.url()).host; + await worker.evaluate(()=>{chrome.permissions.remove=async()=>false;}); + const ui=await context.newPage();await ui.goto(`chrome-extension://${id}/workspace.html`);await ui.waitForFunction(()=>document.getElementById('summary').textContent.includes('revisions')); + await api(ui,'PRIVACY',{metadata:true});await api(ui,'ENABLE',{origin:base}); + const page=await context.newPage();await page.goto(base+'/workflows.html');await poll(()=>names(page),n=>n.some(s=>s.startsWith('Draft Cairn ·'))); + const tabId=await ui.evaluate(async url=>(await chrome.tabs.query({})).find(t=>t.url===url).id,base+'/workflows.html'); + await page.locator('#narrative').fill('Synthetic ordinary narrative');await poll(()=>api(ui,'STATE'),s=>s.drafts.some(d=>d.text==='Synthetic ordinary narrative'));check('top-level capture remains available with the new frame scope'); + await page.locator('#shadow-host textarea').fill('Synthetic open shadow answer');let state=await poll(()=>api(ui,'STATE'),s=>s.drafts.some(d=>d.text==='Synthetic open shadow answer')); + const shadow=state.drafts.find(d=>d.text==='Synthetic open shadow answer');assert(!shadow.restorable);await assert.rejects(api(ui,'RESTORE',{id:shadow.id,tabId}));check('open shadow-root capture works and remains copy-only'); + await page.locator('#private-host textarea').fill('Synthetic private shadow answer');await wait(600);assert(!(await api(ui,'STATE')).drafts.some(d=>d.text==='Synthetic private shadow answer'));check('private markers on shadow hosts and ancestors prevent capture'); + await page.evaluate(()=>globalThis.focusClosed());await page.keyboard.type('Synthetic closed shadow answer');await wait(600);assert(!(await api(ui,'STATE')).drafts.some(d=>d.text==='Synthetic closed shadow answer'));check('closed shadow roots remain unsupported and are not captured'); + await page.locator('#shadow-host textarea').evaluate(el=>{el.value='Synthetic forged shadow';el.dispatchEvent(new Event('input',{bubbles:true,composed:true}));});await wait(600);assert(!(await api(ui,'STATE')).drafts.some(d=>d.text==='Synthetic forged shadow'));check('synthetic composed input cannot create a shadow draft'); + const same=page.frame({url:base+'/frame.html'}),cross=page.frame({url:child+'/frame.html'});assert(same&&cross); + await same.locator('#frame-answer').fill('Synthetic same-origin frame');await poll(()=>api(ui,'STATE'),s=>s.drafts.some(d=>d.text==='Synthetic same-origin frame' && !d.restorable));check('same-origin frame recovery saves a separately scoped copy-only draft'); + await cross.locator('#frame-answer').fill('Synthetic disabled cross frame');await wait(600);assert(!(await api(ui,'STATE')).drafts.some(d=>d.text==='Synthetic disabled cross frame'));check('Chrome host access across ports does not enable a different frame origin'); + await api(ui,'ENABLE',{origin:child});await page.reload();await wait(500); + await page.frame({url:child+'/frame.html'}).locator('#frame-answer').fill('Synthetic enabled cross frame');await poll(()=>api(ui,'STATE'),s=>s.drafts.some(d=>d.text==='Synthetic enabled cross frame' && !d.restorable));check('cross-origin frame saves only after its own exact origin is enabled'); + await api(ui,'DISABLE',{origin:base});await page.frame({url:child+'/frame.html'}).locator('#frame-answer').fill('Synthetic disabled containing page');await wait(600);assert(!(await api(ui,'STATE')).drafts.some(d=>d.text==='Synthetic disabled containing page'));check('disabling the containing site stops capture in enabled cross-origin children'); + await api(ui,'ENABLE',{origin:base,tabId});await wait(250); + const extra='http://127.0.0.1:8767'; + await worker.evaluate(async extra=>chrome.storage.session.set({'enable-batch':{origins:[extra,'https://ungranted.example'],created:Date.now()}}),extra); + await api(ui,'FINISH_ENABLE');assert(!(await api(ui,'STATE')).sites.includes(extra));await worker.evaluate(()=>chrome.storage.session.remove('enable-batch'));check('batch enablement waits for every requested host grant before enabling any new origin'); + await worker.evaluate(async extra=>chrome.storage.session.set({'enable-batch':{origins:[extra,'http://127.0.0.1:8768'],created:Date.now()}}),extra); + await api(ui,'FINISH_ENABLE');assert((await api(ui,'STATE')).sites.includes(extra));await api(ui,'DISABLE',{origin:extra});await api(ui,'DISABLE',{origin:'http://127.0.0.1:8768'});check('fully granted batch requests finish through the worker after the initiating UI can close'); + await api(ui,'RETENTION',{origin:base,days:14});await page.locator('#other').fill('Synthetic fourteen-day answer');state=await poll(()=>api(ui,'STATE'),s=>s.drafts.some(d=>d.text==='Synthetic fourteen-day answer'));const retained=state.drafts.find(d=>d.text==='Synthetic fourteen-day answer');assert.equal(retained.expires-retained.saved,14*86400000); + await api(ui,'RETENTION',{origin:base,days:3});state=await api(ui,'STATE');assert.equal(state.drafts.find(d=>d.id===retained.id).expires,retained.saved+3*86400000);check('per-site retention controls new records and shortens existing expiry'); + await api(ui,'SAVE_ANSWER',{answer:{title:'Garden summary',project:'Synthetic',text:'A garden for everyone.'}}); + await api(ui,'SAVE_ANSWER',{answer:{title:'Oversized answer',text:'x'.repeat(600),project:'Synthetic'}}); + await page.locator('#narrative').fill('Prefix suffix');await page.locator('#narrative').evaluate(el=>el.setSelectionRange(7,7));await picker(page,'#narrative');await choose(page,'Garden summary · Synthetic','A garden for everyone.');await poll(()=>disabled(page,'Insert at saved cursor'),d=>!d);await click(page,'Insert at saved cursor');await poll(()=>names(page),n=>n.some(s=>s.includes('Visible insertion matches')));assert.equal(await page.locator('#narrative').inputValue(),'Prefix A garden for everyone.suffix');check('library insertion previews and preserves existing text outside the saved selection'); + await mkdir(path.join(root,'test-results/screenshots'),{recursive:true});const dialog=(await ax(page)).find(n=>n.role?.value==='dialog');const resolved=await (await session(page)).send('DOM.resolveNode',{backendNodeId:dialog.backendDOMNodeId});await (await session(page)).send('Runtime.callFunctionOn',{objectId:resolved.object.objectId,functionDeclaration:'function(){this.scrollTop=0;}'}); + await page.screenshot({path:path.join(root,'test-results/screenshots/workflow-library.png')});await api(ui,'THEME_SET',{appearance:'dark'});await wait(200);await page.screenshot({path:path.join(root,'test-results/screenshots/workflow-library-dark.png')});await api(ui,'THEME_SET',{appearance:'light'});await close(page); + await picker(page,'#narrative');await choose(page,'Oversized answer · Synthetic','x'.repeat(600));assert(await disabled(page,'Insert at saved cursor'));assert.equal(await page.locator('#narrative').inputValue(),'Prefix A garden for everyone.suffix');check('oversized library insertion is disabled and leaves the website untouched');await close(page); + await picker(page,'#narrative');await choose(page,'Garden summary · Synthetic','A garden for everyone.');await page.locator('#narrative').evaluate(el=>{el.value='Changed behind the preview';});await click(page,'Insert at saved cursor');await poll(()=>names(page),n=>n.some(s=>s.includes('destination changed')));assert.equal(await page.locator('#narrative').inputValue(),'Changed behind the preview');check('stale insertion previews cannot overwrite a changed destination');await close(page); + await picker(page,'#narrative');await choose(page,'Garden summary \u00b7 Synthetic','A garden for everyone.');await page.evaluate(()=>history.replaceState(null,'','?record=changed'));await click(page,'Insert at saved cursor');await poll(()=>names(page),n=>n.some(s=>s.includes('destination changed')));assert.equal(await page.locator('#narrative').inputValue(),'Changed behind the preview');check('a route change cancels an existing insertion preview');await close(page);await page.evaluate(()=>history.replaceState(null,'','/workflows.html')); + await page.locator('#narrative').fill('');await page.locator('#narrative').evaluate(el=>el.addEventListener('input',()=>setTimeout(()=>{el.value=el.value.slice(0,5);},100),{once:true}));await picker(page,'#narrative');await choose(page,'Garden summary · Synthetic','A garden for everyone.');await click(page,'Insert at saved cursor');await poll(()=>names(page),n=>n.some(s=>s.includes('website changed or removed')));assert((await api(ui,'STATE')).library.some(a=>a.text==='A garden for everyone.'));check('post-insertion verification detects delayed clipping and preserves the library original');await close(page); + await picker(page,'#rich');await choose(page,'Garden summary · Synthetic','A garden for everyone.');assert(await disabled(page,'Insert at saved cursor'));check('rich-text library use remains copy-only');await close(page); + await page.locator('#narrative').fill(Array(51).fill('word').join(' '));await poll(()=>names(page),n=>n.some(s=>s.includes('website reports 51/50 words') && s.includes('over by 1')));check('linked word counters are shown as website reports alongside local estimates'); + await page.locator('#narrative-count').evaluate(el=>{el.textContent='Section 1/2';});await page.locator('#other').focus();await page.locator('#narrative').focus();assert(!(await names(page)).some(s=>s.includes('website reports')));check('unrecognized counters produce no inferred limit'); + const password='Synthetic workflow vault passphrase';await api(ui,'VAULT_ENABLE',{passphrase:password,acknowledged:true});await api(ui,'VAULT_LOCK');await page.locator('#narrative').fill('');await page.locator('#narrative').focus();await click(page,n=>n.startsWith('Draft Cairn ·'));await click(page,'Use library answer');await poll(()=>names(page),n=>n.some(s=>s.includes('Unlock your vault in the workspace')));assert(!(await names(page)).includes('Garden summary · Synthetic'));check('locked vaults do not release library titles or answers into a new picker');await close(page); + await api(ui,'VAULT_UNLOCK',{passphrase:password}); + await picker(page,'#narrative');await choose(page,'Garden summary \u00b7 Synthetic','A garden for everyone.'); + await worker.evaluate(()=>{chrome.storage.managed.get=async()=>({AllowedOrigins:[]});});await click(page,'Insert at saved cursor');await poll(()=>names(page),n=>n.some(s=>s.includes('destination changed')));assert.equal(await page.locator('#narrative').inputValue(),'');check('access denied after preview cancels insertion before releasing text');await close(page); + // Simulated managed storage input: tests apply policy through the shipping reader, not a second implementation. + await worker.evaluate(()=>{chrome.storage.managed.get=async()=>({AllowedOrigins:['http://127.0.0.1:8765'],MaxRetentionDays:3});}); + await assert.rejects(api(ui,'ENABLE',{origin:child}));await assert.rejects(api(ui,'RETENTION',{origin:base,days:14}));await page.frame({url:child+'/frame.html'}).locator('#frame-answer').fill('Synthetic policy denied frame');await wait(600);assert(!(await api(ui,'STATE')).drafts.some(d=>d.text==='Synthetic policy denied frame'));check('managed origin restrictions and maximum retention apply to UI actions and frame captures'); + await page.locator('#other').fill('Synthetic policy-capped answer');state=await poll(()=>api(ui,'STATE'),s=>s.drafts.some(d=>d.text==='Synthetic policy-capped answer'));const capped=state.drafts.find(d=>d.text==='Synthetic policy-capped answer');assert(capped.expires-capped.saved<=3*86400000);check('managed maximum retention caps new captures immediately'); + await ui.getByRole('button',{name:'Recovery drafts',exact:true}).click();await ui.locator('#refresh').click();await ui.getByLabel('Include in application snapshot').first().check();ui.once('dialog',d=>d.accept());const downloadPromise=ui.waitForEvent('download');await ui.locator('#snapshot').click();const download=await downloadPromise;const raw=await readFile(await download.path(),'utf8');assert.match(raw,/not proof of submission/);assert.match(raw,/## /);check('selected saved revisions export as readable Markdown with an explicit submission disclaimer'); + const practice=await context.newPage();await practice.goto(`chrome-extension://${id}/practice.html`);await practice.screenshot({path:path.join(root,'test-results/screenshots/practice-1.png')});await practice.locator('#practice-answer').fill('Synthetic practice recovery');await practice.locator('#practice-save').click();await practice.getByRole('status').filter({hasText:'Saved on this device'}).waitFor();await practice.screenshot({path:path.join(root,'test-results/screenshots/practice-2.png')});await practice.reload();await practice.screenshot({path:path.join(root,'test-results/screenshots/practice-3.png')});assert.equal(await practice.locator('#practice-answer').inputValue(),'');await practice.locator('#practice-recover').click();await poll(()=>practice.locator('#practice-answer').inputValue(),v=>v==='Synthetic practice recovery');await practice.screenshot({path:path.join(root,'test-results/screenshots/practice-4.png')});await practice.locator('#practice-clear').click();check('local first-run practice saves through encryption and recovers after reload'); + await writeFile(path.join(root,'test-results/workflow-summary.json'),JSON.stringify({version:manifest.version,browser:context.browser().version(),automated:report,syntheticOnly:true,permissions:'temporary loopback pre-grant; native prompt remains manual',managed:'managed values simulated through chrome.storage.managed.get; enterprise deployment remains manual'},null,2)); +}finally{ + await context?.close();for(const server of servers)server.kill(); + assert.equal(path.dirname(path.resolve(temp)),path.resolve(tmpdir()));assert(path.basename(temp).startsWith('draft-cairn-workflows-'));await rm(temp,{recursive:true,force:true}); +} diff --git a/tests/workflows.test.js b/tests/workflows.test.js new file mode 100644 index 0000000..dad747d --- /dev/null +++ b/tests/workflows.test.js @@ -0,0 +1,30 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import '../extension/workflows.js'; +const W=globalThis.CairnWorkflows; +test('counter hints accept explicit bounded counters and reject unrelated or ambiguous prose',()=>{ + assert.deepEqual(W.counterHint('342/500 words'),{used:342,limit:500,unit:'words'}); + assert.deepEqual(W.counterHint('1,200 of 2,000 characters used'),{used:1200,limit:2000,unit:'characters'}); + for(const text of ['500 words remaining','Section 2/3','The deadline is 3/5 words','9/0 words','9999999999/10 words','20/50 bytes'])assert.equal(W.counterHint(text),null); +}); +test('fit checks preserve UTF-16 limits and distinguish word estimates from website reports',()=>{ + assert(W.fit('😀',1,null).blocked);assert(!W.fit('😀',2,null).blocked); + const fit=W.fit('one two three',-1,{used:1,limit:2,unit:'words'}); + assert.equal(fit.words,3);assert(!fit.blocked);assert.match(fit.message,/website reports 1\/2 words/);assert.match(fit.message,/over by 1/); + assert.equal(W.countWords(' one\ntwo\tthree '),3); +}); +test('site batches require exact origins, reject credentials and paths, and stay bounded',()=>{ + assert.deepEqual(W.siteList('https://one.example\nhttps://two.example:444 https://one.example'),['https://one.example','https://two.example:444']); + for(const raw of ['', 'https://one.example/form','https://u:p@one.example','https://one.example/?secret=x','file:///tmp/x',Array(21).fill('https://one.example').join('\n')])assert.throws(()=>W.siteList(raw)); +}); +test('retention overrides and managed policies are explicit and fail closed for an empty allowlist',()=>{ + assert.equal(W.retention({days:1,siteDays:{'https://one.example':14}},'https://one.example'),14); + assert.equal(W.retention({days:1},'https://two.example'),1); + assert.deepEqual(W.policy({AllowedOrigins:[],MaxRetentionDays:7}),{allowed:[],maxDays:7}); + assert.deepEqual(W.policy({AllowedOrigins:['https://one.example/path','https://one.example','file:///x']}),{allowed:['https://one.example'],maxDays:30}); +}); +test('snapshot exports label selected saved answers without implying successful submission',()=>{ + const draft={field:{label:'\nquestion'},saved:1000,text:'line one\n# answer heading\n\nline two'}; + const plain=W.markdown([draft],false);assert.match(plain,/## Answer 1/);assert(!plain.includes('Private'));assert.match(plain,/> # answer heading/);assert.match(plain,/not proof of submission/); + const labelled=W.markdown([draft],true);assert.match(labelled,/\\/);assert(!labelled.includes('## ')); +});