From 568e1ff6c795b8046b995955fc231a4cb2d6dff1 Mon Sep 17 00:00:00 2001
From: librerob <260221049+librerob@users.noreply.github.com>
Date: Thu, 5 Nov 2026 11:40:48 +0000
Subject: [PATCH 1/8] Add guarded answer insertion, scoped embedded recovery
and application workflows
---
.github/workflows/portals.yml | 2 +-
.github/workflows/validate.yml | 4 +-
demo/frame.html | 1 +
demo/workflows-fixture.js | 8 ++
demo/workflows.html | 1 +
extension/background.js | 74 +++++++++-----
extension/content.js | 181 +++++++++++++++++++++++++--------
extension/core.js | 4 +-
extension/managed-schema.json | 24 +++++
extension/manifest.json | 13 ++-
extension/popup.html | 2 +-
extension/popup.js | 2 +
extension/practice.html | 1 +
extension/practice.js | 5 +
extension/storage.js | 9 +-
extension/workflows.js | 46 +++++++++
extension/workspace.html | 6 +-
extension/workspace.js | 42 +++++++-
package-lock.json | 4 +-
package.json | 4 +-
scripts/package.py | 2 +-
tests/workflows.mjs | 75 ++++++++++++++
tests/workflows.test.js | 30 ++++++
23 files changed, 452 insertions(+), 88 deletions(-)
create mode 100644 demo/frame.html
create mode 100644 demo/workflows-fixture.js
create mode 100644 demo/workflows.html
create mode 100644 extension/managed-schema.json
create mode 100644 extension/practice.html
create mode 100644 extension/practice.js
create mode 100644 extension/workflows.js
create mode 100644 tests/workflows.mjs
create mode 100644 tests/workflows.test.js
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..a9bcb8a 100644
--- a/.github/workflows/validate.yml
+++ b/.github/workflows/validate.yml
@@ -27,6 +27,7 @@ jobs:
- run: npm test
- run: npx playwright install chromium
- run: npm run test:browser
+ - run: node tests/workflows.mjs
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x1024x24" node tests/popup.mjs
- run: |
python3 scripts/package.py
@@ -41,6 +42,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 +60,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/demo/frame.html b/demo/frame.html
new file mode 100644
index 0000000..009ba68
--- /dev/null
+++ b/demo/frame.html
@@ -0,0 +1 @@
+
Synthetic embedded form
diff --git a/demo/workflows-fixture.js b/demo/workflows-fixture.js
new file mode 100644
index 0000000..abe7671
--- /dev/null
+++ b/demo/workflows-fixture.js
@@ -0,0 +1,8 @@
+for(const [id,mode] of [['shadow-host','open'],['private-host','open'],['closed-host','closed']]){
+ const host=document.getElementById(id),root=host.attachShadow({mode});
+ const label=document.createElement('label');label.textContent='Synthetic shadow narrative';
+ const area=document.createElement('textarea');area.id=id+'-answer';area.rows=5;label.append(area);root.append(label);
+ if(mode==='closed')globalThis.focusClosed=()=>area.focus();
+}
+document.getElementById('narrative').addEventListener('input',e=>{document.getElementById('narrative-count').textContent=(e.target.value.trim().match(/\S+/g)||[]).length+'/50 words';});
+document.getElementById('synthetic-form').addEventListener('submit',e=>e.preventDefault());
diff --git a/demo/workflows.html b/demo/workflows.html
new file mode 100644
index 0000000..d2b9dce
--- /dev/null
+++ b/demo/workflows.html
@@ -0,0 +1 @@
+Synthetic workflow fixtureSynthetic application
diff --git a/extension/background.js b/extension/background.js
index 99a4b04..ac07e0f 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'});
}
}
}
@@ -46,15 +50,14 @@ async function finishPending() {
}
}
}
-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.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 +67,13 @@ 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)};
+ const {origin,state,url,policy,scope}=await activeOrigin(sender);
+ 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,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 +87,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 +112,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 +131,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 +177,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 +187,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..9199dbe 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='';
+ const embedded=window!==window.top;
let active = false;
let activation = 0;
let timer;
@@ -21,37 +23,71 @@
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 configure(data){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;}
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,37 +103,38 @@
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: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.textContent = 'Draft Cairn · choose a supported answer field';
+ 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);
}
function announce(text, error = false) {
- mount(); status.textContent = `Draft Cairn · ${text}`; status.classList.toggle('error',error);
+ mount(); status.textContent = `Draft Cairn · ${text}`; status.classList.toggle('error',error);
}
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…');
+ announce('checking field…');
const blocked=await excludedField(el);
if(version!==focusVersion || !active)return;
- if(blocked){lastField=null;announce('not protected in this field · excluded in settings',true);return;}
+ if(blocked){lastField=null;announce('not protected in this field · excluded in settings',true);return;}
}
lastField=el;
const issue=pasteIssues.get(el);
- if(issue){announce(issue.saved===false ? 'paste needs review · original not saved · click to copy' : issue.saved ? 'paste needs review · original saved · click to review' : 'paste needs review · saving original…',true);return;}
- if(pasteWatch?.el===el){announce('checking visible paste…');return;}
+ if(issue){announce(issue.saved===false ? 'paste needs review · original not saved · click to copy' : issue.saved ? 'paste needs review · original saved · click to review' : 'paste needs review · saving original…',true);return;}
+ 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);
+ 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;
@@ -111,11 +148,11 @@
const result=await message(snapshot);
if (!active || version!==activation) return;
// A completed earlier write must not label a newer, unsaved edit as saved.
- if (snapshot.kind==='paste' || textOf(el)===snapshot.text) fieldStatus.set(el,{text:result.evicted ? 'saved · oldest recovery revisions removed' : 'saved on this device'+(editorType(el) ? ' · plain text · copy back' : '')});
+ if (snapshot.kind==='paste' || textOf(el)===snapshot.text) fieldStatus.set(el,{text:result.evicted ? 'saved · oldest recovery revisions removed' : 'saved on this device'+(editorType(el) ? ' · plain text · copy back' : '')});
return true;
} catch {
if (!active || version!==activation) return;
- fieldStatus.set(el,{text:'not saved — open recovery or keep a separate copy',error:true});
+ fieldStatus.set(el,{text:'not saved — open recovery or keep a separate copy',error:true});
return false;
} finally {
focusedStatus();
@@ -133,7 +170,7 @@
captures = captures.then(async()=>{
if (!el.isConnected || !C.allowedField(describe(el))) return;
return capture(await snapshot(el,text,kind),el);
- }).catch(()=>{if(active)announce('not saved — keep a separate copy',true);return false;});
+ }).catch(()=>{if(active)announce('not saved — keep a separate copy',true);return false;});
return captures;
}
function flush() {
@@ -143,7 +180,8 @@
function editor(el, original, oversized, issue) {
mount();
if (root.querySelector('dialog')) return;
- const before = document.activeElement;
+ const before = activeElement();
+ const destination={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 +194,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';
@@ -167,10 +204,13 @@
const ignore=document.createElement('button');ignore.type='button';ignore.textContent='Never capture this field';
ignore.onclick=async e=>{
if(!e.isTrusted || !confirm('Stop capturing this field and delete its recovery revisions? Fields with the same identity on this page are excluded too. Library answers remain.'))return;
- 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);}
+ 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 +223,56 @@
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';
+ section.append(label,search,options,note,fit,preview,insert);dialog.append(section);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{
+ await message({type:'HELLO'}); // Recheck permission/policy immediately before releasing text.
+ if(await excludedField(el) || !active || !el.isConnected || !C.allowedField(describe(el)) || editorType(el) || 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};
@@ -206,11 +296,11 @@
// A trusted paste can be entirely model-managed, with no native input event.
// Save the checked visible result too; an earlier typing save is not evidence
// that this paste has reached storage.
- fieldStatus.set(watch.el,{text:'visible paste matches · saving…'});focusedStatus();
+ fieldStatus.set(watch.el,{text:'visible paste matches · saving…'});focusedStatus();
enqueue(watch.el,actual).then(saved=>{
if(!active || watch.version!==activation || !watch.el.isConnected || textOf(watch.el)!==actual || pasteWatch || pasteIssues.has(watch.el))return;
const previous=fieldStatus.get(watch.el);
- fieldStatus.set(watch.el,{text:'visible paste matches · '+(saved ? 'saved on this device' : 'not saved · keep a separate copy')+(previous?.text?.includes('oldest recovery') ? ' · oldest recovery revisions removed' : '')+' · submission not checked',error:!saved});focusedStatus();
+ fieldStatus.set(watch.el,{text:'visible paste matches · '+(saved ? 'saved on this device' : 'not saved · keep a separate copy')+(previous?.text?.includes('oldest recovery') ? ' · oldest recovery revisions removed' : '')+' · submission not checked',error:!saved});focusedStatus();
});
}
}
@@ -220,26 +310,26 @@
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();
lastField=el; pending={el,text:textOf(el)};
- fieldStatus.set(el,{text:'saving…'});focusedStatus(); clearTimeout(timer); timer=setTimeout(flush,250);
+ fieldStatus.set(el,{text:'saving…'});focusedStatus(); clearTimeout(timer); timer=setTimeout(flush,250);
},true);
// Some model-based editors consume native beforeinput and do not emit a native
// input event. Observe the rendered plain text after that trusted editing intent.
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);
setTimeout(()=>{
if(!active || activation!==version || richEdits.get(el)!==edit || !el.isConnected || !C.allowedField(describe(el)))return;
if(pending && pending.el!==el)flush();
- lastField=el;pending={el,text:textOf(el)};fieldStatus.set(el,{text:'saving…'});focusedStatus();clearTimeout(timer);timer=setTimeout(flush,250);
+ lastField=el;pending={el,text:textOf(el)};fieldStatus.set(el,{text:'saving…'});focusedStatus();clearTimeout(timer);timer=setTimeout(flush,250);
},0);
},true);
document.addEventListener('focusout',()=>flush(),true);
@@ -247,11 +337,11 @@
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');
- if(!text || text.length>C.MAX_TEXT){announce('paste too large to preserve · keep a separate copy',true);return;}
+ if(!text || text.length>C.MAX_TEXT){announce('paste too large to preserve · keep a separate copy',true);return;}
finishPaste('Another paste started before verification finished. Compare the earlier original manually.');
flush();lastField=el;pasteIssues.delete(el);
if (!editorType(el) && el.maxLength>=0 && C.pasteCapacity(el.value,el.selectionStart || 0,el.selectionEnd || 0,text,el.maxLength).oversized) {
@@ -266,7 +356,16 @@
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);
chrome.runtime.onMessage.addListener((m,sender,respond)=>{
+ if(sender.id===chrome.runtime.id && m.type==='OPEN_LIBRARY'){
+ if(active && document.hasFocus() && lastField?.isConnected && C.allowedField(describe(lastField))){editor(lastField,textOf(lastField),false);root.querySelector('dialog button')?.focus();const button=Array.from(root.querySelectorAll('button')).find(b=>b.textContent==='Use library answer');button?.dispatchEvent(new Event('cairn-library'));}
+ respond({ok:true});return;
+ }
if (sender.id === chrome.runtime.id && m.type === 'RECHECK') {
respond({ok:true});
const version=activation;
@@ -279,10 +378,10 @@
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 !== '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.'};
diff --git a/extension/core.js b/extension/core.js
index 57e9400..c9bd7f0 100644
--- a/extension/core.js
+++ b/extension/core.js
@@ -59,11 +59,11 @@
state.drafts = state.drafts.filter(d => d.expires > now);
return state;
}
- function fresh() { return {version:1,days:1,metadata:false,sessionOnly:false,appearance:'system',sites:[],blockedSites:[],ignoredFields:[],drafts:[],library:[]}; }
+ function fresh() { return {version:1,days:1,metadata:false,sessionOnly:false,appearance:'system',siteDays:{},sites:[],blockedSites:[],ignoredFields:[],drafts:[],library:[]}; }
function privacyDefaults(state) {
return {...state,metadata:state.metadata ?? true,sessionOnly:state.sessionOnly ?? false,
appearance:['system','light','dark'].includes(state.appearance) ? state.appearance : 'system',
- blockedSites:state.blockedSites || [],ignoredFields:state.ignoredFields || []};
+ siteDays:state.siteDays || {},blockedSites:state.blockedSites || [],ignoredFields:state.ignoredFields || []};
}
function minimalDraft(draft) {
return {...draft,title:'',field:{label:''},restorable:false};
diff --git a/extension/managed-schema.json b/extension/managed-schema.json
new file mode 100644
index 0000000..8cef788
--- /dev/null
+++ b/extension/managed-schema.json
@@ -0,0 +1,24 @@
+{
+ "type": "object",
+ "properties": {
+ "AllowedOrigins": {
+ "title": "Allowed website origins",
+ "description": "Restrict enabled sites to exact origins. Does not grant Chrome permissions.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "MaxRetentionDays": {
+ "title": "Maximum recovery retention",
+ "type": "integer",
+ "enum": [
+ 1,
+ 3,
+ 7,
+ 14,
+ 30
+ ]
+ }
+ }
+}
diff --git a/extension/manifest.json b/extension/manifest.json
index 2f4b843..b658aa6 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Draft Cairn",
- "version": "0.3.1",
+ "version": "0.4.0",
"description": "Local answer recovery, paste-limit warnings, and a reusable answer library for sites you choose.",
"minimum_chrome_version": "120",
"incognito": "not_allowed",
@@ -32,5 +32,16 @@
},
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'none'; connect-src 'none'; base-uri 'none'"
+ },
+ "commands": {
+ "open-library": {
+ "suggested_key": {
+ "default": "Alt+Shift+L"
+ },
+ "description": "Preview a library answer in the focused supported field"
+ }
+ },
+ "storage": {
+ "managed_schema": "managed-schema.json"
}
}
diff --git a/extension/popup.html b/extension/popup.html
index 13727c3..a5f1dce 100644
--- a/extension/popup.html
+++ b/extension/popup.html
@@ -2,4 +2,4 @@

Draft Cairn
On this device
Draft protection
Current website
Checking protection…
Answers stay in this browser profile.
Recent drafts
-