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 @@

-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.
+
+
+
+## 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 @@
+
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 @@