From 46e77705e5855c96db26ec370335d9ab6605f74c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:38:10 +0000 Subject: [PATCH] feat(bedside): structural Unicode text classes and golden corpus (BA-W01 L6) worker/text.mjs defines identifier, name and comment classes. Names keep emoji sequences (ZWJ families, tag flags) and a ZWNJ between letters while dropping other invisible characters; comments refuse only unpaired surrogates and control characters other than tab and line breaks; identifiers refuse every control and format character and unpaired surrogates. The API cleans names with it, refuses malformed new or edited comments, and steering text keeps emoji. The browser's blanket ZWJ removal is gone. tests/unicode-corpus.json is the golden corpus. Co-Authored-By: Claude Opus 5.5 --- .../design/identity-access.md | 4 + pkgs/bedside-and-away/public/app.js | 4 +- pkgs/bedside-and-away/scripts/check.mjs | 1 + .../tests/unicode-corpus.json | 173 ++++++++++++++++++ pkgs/bedside-and-away/tests/unicode.mjs | 30 +++ pkgs/bedside-and-away/worker/api.mjs | 4 +- pkgs/bedside-and-away/worker/steering.mjs | 3 +- pkgs/bedside-and-away/worker/text.mjs | 17 ++ .../bedside-and-away/worker/variant-graph.mjs | 3 +- 9 files changed, 235 insertions(+), 4 deletions(-) create mode 100644 pkgs/bedside-and-away/tests/unicode-corpus.json create mode 100644 pkgs/bedside-and-away/tests/unicode.mjs create mode 100644 pkgs/bedside-and-away/worker/text.mjs diff --git a/pkgs/bedside-and-away/design/identity-access.md b/pkgs/bedside-and-away/design/identity-access.md index b50e039396..7c7b7f48cb 100644 --- a/pkgs/bedside-and-away/design/identity-access.md +++ b/pkgs/bedside-and-away/design/identity-access.md @@ -26,6 +26,10 @@ The `*` policy is the store read gate. A deny there denies the entire view; use `principalFromGateway` in `identity.mjs` is the one place a request's principal comes from: the account headers the Worker rebuilds after verifying the gateway signature (`external/worker.mjs`), as `{kind:'account',id,email}`. A request with none is refused. No body field (`actor`, `actorId`, `principal`, `author`) names a principal: events take `actorId` from it, new notes and inventory rows are stamped with it, and an existing row keeps the `actorId`, `author`, `recordedAt` and `device` it was first stamped with whatever a later snapshot says. The browser's installation ID is continuity metadata only: `continuityId` keeps it when it is a UUID and drops anything else, and nothing reads it for a decision. +## Text classes (BA-046, BA-W01 L6) + +`worker/text.mjs` defines three structural classes, checked on the server; `tests/unicode-corpus.json` is the golden corpus. An identifier is well-formed with no control or format character, so zero-width and bidirectional override characters are refused there. A name (store name, label, nickname) is cleaned: control and format characters and unpaired surrogates are dropped, except inside an emoji sequence (ZWJ families, tag flags) and a zero-width non-joiner between letters. A comment is refused only for an unpaired surrogate or a control character other than tab, line feed and carriage return. The browser's blanket zero-width-joiner removal is gone; its clean-up now keeps emoji sequences too, and is a convenience, never the check. + ## Guest/account proof design `identity.mjs` supplies random UUID installation IDs and 256-bit guest-claim token primitives. Only the SHA-256 hash is persisted; token is returned once. Claims bind guest ID and store ID, expire in at most ten minutes, and reject consumed records, changed stores, invalid tokens and absent authenticated accounts. These primitives do not create sessions or authenticate accounts. diff --git a/pkgs/bedside-and-away/public/app.js b/pkgs/bedside-and-away/public/app.js index 62e9f6ff30..b92ce24add 100644 --- a/pkgs/bedside-and-away/public/app.js +++ b/pkgs/bedside-and-away/public/app.js @@ -1,7 +1,9 @@ 'use strict'; const $=(s)=>document.querySelector(s), app=$('#app'), modal=$('#modal'), form=$('#dialogform'); const seed=window.SEED, uid=()=>crypto.randomUUID(), copy=x=>JSON.parse(JSON.stringify(x)); -const tidy=s=>String(s??'').replace(/[\p{Cc}\p{Cf}]/gu,'').normalize('NFC').trim(); +// Emoji sequences keep their joiners and a ZWNJ between letters stays (BA-046); the server's text classes are the check. +const invisible=(()=>{try{return new RegExp('(\\p{RGI_Emoji})|((?<=[\\p{L}\\p{M}])\\u200C(?=[\\p{L}\\p{M}]))|[\\p{Cc}\\p{Cf}]','gv')}catch{return /()()[\p{Cc}\p{Cf}]/gu}})(); +const tidy=s=>String(s??'').replace(invisible,(m,a,b)=>a||b?m:'').normalize('NFC').trim(); const prose=s=>String(s??'').replace(/[^\S\n\t ]/g,' ').replace(/[\u0000-\u0008\u000B-\u001F\u007F]/g,'').normalize('NFC').trim(); const e=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const norm=s=>tidy(s).toLocaleLowerCase(); diff --git a/pkgs/bedside-and-away/scripts/check.mjs b/pkgs/bedside-and-away/scripts/check.mjs index ad24fdadea..5ae0586964 100644 --- a/pkgs/bedside-and-away/scripts/check.mjs +++ b/pkgs/bedside-and-away/scripts/check.mjs @@ -17,6 +17,7 @@ assert.match(els['#storebar'].innerHTML,/New store/); const evalJSON=s=>JSON.parse(vm.runInContext('JSON.stringify('+s+')',context)); assert.equal(evalJSON("key('https://www.amazon.com/gp/product/b01ckmp24e/ref=test?tag=foo')"),'asin:B01CKMP24E'); assert.equal(evalJSON("tidy('日本語\u200d\u0001 Привет')"),'日本語 Привет'); +assert.equal(evalJSON("tidy(' Kids \u{1F468}\u200d\u{1F469}\u200d\u{1F467}\u200b ')"),'Kids \u{1F468}\u200d\u{1F469}\u200d\u{1F467}'); assert.deepEqual(evalJSON("attr('{\"Ports\":3,\"Fast\":true}')"),[['Ports',3],['Fast',true]]); assert.deepEqual(evalJSON("patch(['new'],['old'],['old','historic'],true,'tags')"),['new','old','historic']); assert.equal(evalJSON("analyze('a | https://www.amazon.com/dp/B01CKMP24E\\nb | https://www.amazon.com/gp/product/B01CKMP24E')[1].kind"),'duplicate'); diff --git a/pkgs/bedside-and-away/tests/unicode-corpus.json b/pkgs/bedside-and-away/tests/unicode-corpus.json new file mode 100644 index 0000000000..6dfcdc458f --- /dev/null +++ b/pkgs/bedside-and-away/tests/unicode-corpus.json @@ -0,0 +1,173 @@ +{ + "_note": "Golden corpus for the BA-046 text classes (worker/text.mjs). Each comment and identifier entry is [text, accepted]; each name entry is [input, cleaned]. Lone surrogates are written as JSON escapes.", + "comment": [ + [ + "Plain text", + true + ], + [ + "\u65e5\u672c\u8a9e\u3068\u041f\u0440\u0438\u0432\u0435\u0442 and \u0627\u0644\u0639\u0631\u0628\u064a\u0629", + true + ], + [ + "Family \ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67", + true + ], + [ + "Flag \ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f", + true + ], + [ + "Skin tone \ud83d\udc4d\ud83c\udffd", + true + ], + [ + "Heart on fire \u2764\ufe0f\u200d\ud83d\udd25", + true + ], + [ + "Keycap 1\ufe0f\u20e3", + true + ], + [ + "Two lines\nand a\ttab\r\n", + true + ], + [ + "Persian \u0645\u06cc\u200c\u062e\u0648\u0627\u0647\u0645", + true + ], + [ + "Bidi override \u202e is free text in a comment", + true + ], + [ + "", + true + ], + [ + "Bell \u0007", + false + ], + [ + "Escape \u001b[31m", + false + ], + [ + "NUL \u0000", + false + ], + [ + "DEL \u007f", + false + ], + [ + "C1 \u0085", + false + ], + [ + "Lone high \ud800", + false + ], + [ + "Lone low \udc00 first", + false + ] + ], + "identifier": [ + [ + "item_1", + true + ], + [ + "asin:B01CKMP24E", + true + ], + [ + "\u65e5\u672c\u8a9e", + true + ], + [ + "receipt:2026-01", + true + ], + [ + "", + false + ], + [ + "a\u200db", + false + ], + [ + "a\u202eb", + false + ], + [ + "a\u2066b", + false + ], + [ + "tab\there", + false + ], + [ + "zero\u200bwidth", + false + ], + [ + "\ud800", + false + ], + [ + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + false + ] + ], + "name": [ + [ + "Kids \ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67", + "Kids \ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67" + ], + [ + "\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f trip", + "\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f trip" + ], + [ + " Spaced ", + "Spaced" + ], + [ + "\u65e5\u672c\u8a9e\u200d\u0001 \u041f\u0440\u0438\u0432\u0435\u0442", + "\u65e5\u672c\u8a9e \u041f\u0440\u0438\u0432\u0435\u0442" + ], + [ + "a\u202eb", + "ab" + ], + [ + "Zero\u200bwidth", + "Zerowidth" + ], + [ + "\u0645\u06cc\u200c\u062e\u0648\u0627\u0647\u0645", + "\u0645\u06cc\u200c\u062e\u0648\u0627\u0647\u0645" + ], + [ + "\u200c leading", + "leading" + ], + [ + "Lone \ud800 surrogate", + "Lone surrogate" + ], + [ + "Dangling\u200d", + "Dangling" + ], + [ + "Thumbs \ud83d\udc4d\ud83c\udffd", + "Thumbs \ud83d\udc4d\ud83c\udffd" + ] + ] +} diff --git a/pkgs/bedside-and-away/tests/unicode.mjs b/pkgs/bedside-and-away/tests/unicode.mjs new file mode 100644 index 0000000000..bd21037a1a --- /dev/null +++ b/pkgs/bedside-and-away/tests/unicode.mjs @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {DatabaseSync} from 'node:sqlite'; +import {name,isComment,isIdentifier,visible} from '../worker/text.mjs'; +import {api} from '../worker/api.mjs'; +const corpus=JSON.parse(readFileSync(new URL('./unicode-corpus.json',import.meta.url),'utf8')); +for(const [text,ok] of corpus.comment)assert.equal(isComment(text),ok,'comment '+JSON.stringify(text)); +for(const [text,ok] of corpus.identifier)assert.equal(isIdentifier(text),ok,'identifier '+JSON.stringify(text)); +for(const [input,cleaned] of corpus.name)assert.equal(name(input),cleaned,'name '+JSON.stringify(input)); +// The same emoji is a valid comment and refused as an identifier: the classes differ by structure, not by blocklist. +const family=corpus.name[0][1].slice(5); +assert.ok(isComment(family));assert.ok(!isIdentifier(family));assert.equal(visible('a\u0001'+family+'​b',' '),'a '+family+' b'); +console.log('PASS unicode corpus: comment, identifier and name classes ('+(corpus.comment.length+corpus.identifier.length+corpus.name.length)+' cases)'); + +// Server: a comment keeps its emoji, a malformed comment is refused, a store name keeps its emoji. +const sql=new DatabaseSync(':memory:'); +for(const f of ['0000_tracker.sql','0001_store_defaults.sql'])sql.exec(readFileSync(new URL('../drizzle/'+f,import.meta.url),'utf8')); +const db={prepare(q){let b=[];return {bind(...v){b=v;return this},async first(){return sql.prepare(q).get(...b)||null},async all(){return {results:sql.prepare(q).all(...b)}},async run(){return {meta:{changes:Number(sql.prepare(q).run(...b).changes)}}}}},async batch(s){sql.exec('BEGIN');try{const out=[];for(const x of s)out.push(await x.run());sql.exec('COMMIT');return out}catch(e){sql.exec('ROLLBACK');throw e}}}; +async function call(path,data){const r=await api(new Request('https://app.test/api/'+path,{method:data?'POST':'GET',headers:{'oai-authenticated-user-id':'alice','oai-authenticated-user-email':'alice@example.com',...(data?{origin:'https://app.test','content-type':'application/json'}:{})},body:data?JSON.stringify(data):undefined}),{DB:db});return [r.status,await r.json()]} +const state={items:[],tags:[],people:['Shared'],notes:[],inventory:[],prefs:{},rules:{},recs:{},overrides:{}}; +const [code,created]=await call('stores',{name:'Trip '+family,type:'private',initialState:state}); +assert.equal(code,201);assert.equal(created.store.name,'Trip '+family); +const sid=created.store.id,note=text=>({id:crypto.randomUUID(),targets:[],text,part:'General',pref:'',at:'2026-01-01T00:00:00Z'}); +let [c,r]=await call('stores/'+sid+'/events',{expectedVersion:0,event:{id:'u1',label:'Comment',after:{...state,notes:[note('Love it '+family)]}}}); +assert.equal(c,200);assert.equal((await call('stores/'+sid))[1].state.notes[0].text,'Love it '+family); +[c,r]=await call('stores/'+sid+'/events',{expectedVersion:1,event:{id:'u2',label:'Comment',after:{...state,notes:[...(await call('stores/'+sid))[1].state.notes,note('Lone \ud800')]}}}); +assert.equal(c,400);assert.match(r.error,/unpaired surrogate/); +[c,r]=await call('stores/'+sid+'/events',{expectedVersion:1,event:{id:'u3',label:'Comment',after:{...state,notes:[...(await call('stores/'+sid))[1].state.notes,note('Bell \u0007')]}}}); +assert.equal(c,400); +console.log('PASS unicode server: emoji ZWJ comments and store names kept, malformed comments refused'); diff --git a/pkgs/bedside-and-away/worker/api.mjs b/pkgs/bedside-and-away/worker/api.mjs index 3c1d2fb4e2..9fb06f6fe0 100644 --- a/pkgs/bedside-and-away/worker/api.mjs +++ b/pkgs/bedside-and-away/worker/api.mjs @@ -4,11 +4,12 @@ import {transitionSteering,assertSteeringUnchanged} from './steering.mjs'; import {validateVariantGraph,assertVariantMetadataUnchanged} from './variant-graph.mjs'; import {variantPlan} from './variant-plan.mjs'; import {principalFromGateway,continuityId} from './identity.mjs'; +import {name,isComment} from './text.mjs'; const roles = ['reader','editor','admin']; const headers = {'content-type':'application/json; charset=utf-8','cache-control':'no-store','x-content-type-options':'nosniff'}; const json = (body,status=200)=>new Response(JSON.stringify(body),{status,headers}); const fail = (status,message)=>{throw Object.assign(new Error(message),{status})}; -const clean = (x,max=200)=>String(x??'').normalize('NFC').replace(/[\p{Cc}\p{Cf}]/gu,'').trim().slice(0,max); +const clean = (x,max=200)=>name(x,max); const ident = x=>typeof x==='string'&&/^[A-Za-z0-9_-]{1,100}$/.test(x); const parse = x=>JSON.parse(x); const now = ()=>new Date().toISOString(); @@ -39,6 +40,7 @@ function validateNewRecords(before,after,user,name){ for(const field of ['notes','inventory']){ const previous=new Map(before[field].filter(x=>x?.id!=null).map(x=>[x.id,x])); for(const row of after[field]){const prior=previous.get(row?.id);if(prior)for(const f of provenance){if(Object.hasOwn(prior,f))row[f]=prior[f];else delete row[f]}} + if(field==='notes')for(const row of after[field])if(typeof row?.text==='string'&&row.text!==previous.get(row.id)?.text&&!isComment(row.text,100000))fail(400,'Comment holds an unpaired surrogate or a control character'); for(const row of after[field])if(!previous.has(row.id)){ if(!ident(row.id)&&!(typeof row.id==='string'&&/^receipt:[A-Za-z0-9_:-]{1,190}$/.test(row.id)))fail(400,'Record ID required'); row.actorId=user.id;row.author=name;row.recordedAt=now();if('device' in row)row.device=continuityId(row.device); diff --git a/pkgs/bedside-and-away/worker/steering.mjs b/pkgs/bedside-and-away/worker/steering.mjs index 17a3855d88..fd020c4cd6 100644 --- a/pkgs/bedside-and-away/worker/steering.mjs +++ b/pkgs/bedside-and-away/worker/steering.mjs @@ -1,9 +1,10 @@ +import {visible} from './text.mjs'; // Pure, server-owned state machine. Persist returned state and audit atomically using store CAS. const clone=x=>structuredClone(x); const stable=x=>JSON.stringify(x,(k,v)=>v&&typeof v==='object'&&!Array.isArray(v)?Object.fromEntries(Object.entries(v).sort(([a],[b])=>a.localeCompare(b))):v); const error=(status,message)=>{throw Object.assign(new Error(message),{status})}; const id=x=>typeof x==='string'&&/^[A-Za-z0-9_-]{1,100}$/.test(x); -const prose=(s,max=12000)=>typeof s==='string'?s.normalize('NFC').replace(/[\p{Cc}\p{Cf}]/gu,' ').trim().slice(0,max):''; +const prose=(s,max=12000)=>typeof s==='string'?visible(s.normalize('NFC'),' ').trim().slice(0,max):''; const collection=(s,kind)=>kind==='item'?s.items:kind==='category'?s.tags:null; const key=t=>t.kind+':'+t.id; export const STEERING_REPORTS=Object.freeze({spend:'Spending',inventory:'Inventory',activity:'Activity',defaults:'Defaults', 'buying-guide':'Buying guide'}); diff --git a/pkgs/bedside-and-away/worker/text.mjs b/pkgs/bedside-and-away/worker/text.mjs new file mode 100644 index 0000000000..0d310972a3 --- /dev/null +++ b/pkgs/bedside-and-away/worker/text.mjs @@ -0,0 +1,17 @@ +/** Structural text classes (BA-046, BA-W01 L6). Server-side: the browser's own clean-up is a convenience, never the check. + * + * - identifier: an opaque ID. Well-formed, 1 to 200 code units, no control or format character (so no + * zero-width or bidirectional override character). + * - name: a label shown to people (store name, nickname, item name). Cleaned rather than refused: control and + * format characters and unpaired surrogates are dropped, except inside an emoji sequence (a ZWJ family, a flag + * tag sequence) and a zero-width non-joiner between letters, which some scripts need. + * - comment: free text a person wrote. Refused only when it holds an unpaired surrogate or a control character + * other than tab, line feed and carriage return; emoji and every script are accepted as written. + */ +const keep=/(\p{RGI_Emoji})|((?<=[\p{L}\p{M}])‌(?=[\p{L}\p{M}]))|[\p{Cc}\p{Cf}\p{Cs}]/gv; +const wellFormed=s=>!/\p{Cs}/u.test(s); +/** `s` with every invisible character dropped (or replaced) except the joiners that belong to the text. */ +export const visible=(s,replacement='')=>s.replace(keep,(m,emoji,zwnj)=>emoji||zwnj?m:replacement); +export const name=(x,max=200)=>visible(String(x??'').normalize('NFC')).trim().slice(0,max).replace(/\p{Cs}$/u,''); +export const isIdentifier=x=>typeof x==='string'&&x.length>0&&x.length<=200&&wellFormed(x)&&!/[\p{Cc}\p{Cf}]/u.test(x); +export const isComment=(x,max=12000)=>typeof x==='string'&&x.length<=max&&wellFormed(x)&&!/[^\P{Cc}\t\n\r]/u.test(x); diff --git a/pkgs/bedside-and-away/worker/variant-graph.mjs b/pkgs/bedside-and-away/worker/variant-graph.mjs index 2b94291daa..61c852cb22 100644 --- a/pkgs/bedside-and-away/worker/variant-graph.mjs +++ b/pkgs/bedside-and-away/worker/variant-graph.mjs @@ -1,4 +1,5 @@ -const idOK = x => typeof x === 'string' && x.length > 0 && x.length <= 200 && !/[\p{Cc}\p{Cf}]/u.test(x); +import {isIdentifier} from './text.mjs'; +const idOK = isIdentifier; const familyIds = x => [...new Set([...(x.variantFamilyIds || []), x.variantFamilyId].filter(Boolean))]; export function validateVariantGraph(items) { if (!Array.isArray(items)) throw Error('Items must be an array');