diff --git a/pkgs/bedside-and-away/design/identity-access.md b/pkgs/bedside-and-away/design/identity-access.md index acb421d3ac..b50e039396 100644 --- a/pkgs/bedside-and-away/design/identity-access.md +++ b/pkgs/bedside-and-away/design/identity-access.md @@ -22,6 +22,10 @@ The `*` policy is the store read gate. A deny there denies the entire view; use - `assertSnapshotMutation` rejects any policy/group change by a nonadmin, and rejects whole-snapshot writes by scope-limited editors. Admin writes cannot alter denied records. This is an honest read-only limitation, not a finished per-entity editing solution. Admin policy recovery requires a dedicated endpoint that never overwrites unseen data. - Apply the projection before search, summaries, exports, research context, and any callback response. API authorization must use stored state, not the client projection. Reject malformed policy before mutation persistence. Existing authenticated role and optimistic-version transaction checks remain mandatory. +## Principal and installation (BA-W01 L1) + +`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. + ## 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/scripts/test.mjs b/pkgs/bedside-and-away/scripts/test.mjs new file mode 100644 index 0000000000..46174ffca5 --- /dev/null +++ b/pkgs/bedside-and-away/scripts/test.mjs @@ -0,0 +1,8 @@ +// `npm test`: the unit check, then every test file in its own process. +// tests/local-server.mjs is a manual dev server, not a test. +import {spawnSync} from 'node:child_process'; +import {readdirSync} from 'node:fs'; +const files=['scripts/check.mjs',...readdirSync('tests').filter(f=>f.endsWith('.mjs')&&f!=='local-server.mjs').sort().map(f=>'tests/'+f)]; +const failed=files.filter(f=>spawnSync(process.execPath,[f],{stdio:'inherit'}).status!==0); +if(failed.length){console.error('FAILED: '+failed.join(', '));process.exit(1)} +console.log('All '+files.length+' test files passed.'); diff --git a/pkgs/bedside-and-away/tests/backend.mjs b/pkgs/bedside-and-away/tests/backend.mjs index c835a97533..56a03a0f6f 100644 --- a/pkgs/bedside-and-away/tests/backend.mjs +++ b/pkgs/bedside-and-away/tests/backend.mjs @@ -147,3 +147,12 @@ console.log('PASS: nullable allocation collection accepted; malformed elements r const restricted=(await call('stores/'+sid))[1]; assert.equal((await call('stores/'+sid+'/variants',{data:{expectedVersion:restricted.version,commandId:'acl_variant',ids:['one'],options:{action:'group',name:'Unsafe family'}}}))[0],403); console.log('PASS: scoped variant commands fail closed for administrators as well as editors.'); +{const lid=(await call('stores',{data:{name:'L1',type:'private',initialState:state}}))[1].store.id,base=(await call('stores/'+lid))[1],note={id:'note_l1',targets:[],text:'hi',part:'General',pref:'',at:'2026-01-01T00:00:00Z',author:'Mallory',actorId:'mallory',device:'mallory'}; + [code,r]=await call('stores/'+lid+'/events',{data:{expectedVersion:base.version,event:{id:'ev_l1',label:'Note',device:'mallory',actorId:'mallory',principal:{id:'mallory'},after:{...base.state,notes:[note]}}}}); + assert.equal(code,200);assert.equal(r.event.actorId,'alice');assert.equal(r.event.device,''); + const stored=(await call('stores/'+lid))[1].state.notes.find(x=>x.id==='note_l1');assert.equal(stored.actorId,'alice');assert.equal(stored.device,'');assert.notEqual(stored.author,'Mallory'); + const uuid=crypto.randomUUID();[code,r]=await call('stores/'+lid+'/events',{data:{expectedVersion:base.version+1,event:{id:'ev_l1b',label:'Note',device:uuid,after:{...base.state,notes:[note,{...note,id:'note_l1b',device:uuid}]}}}}); + assert.equal(code,200);assert.equal(r.event.device,uuid);assert.equal((await call('stores/'+lid))[1].state.notes.find(x=>x.id==='note_l1b').device,uuid); + const kept=(await call('stores/'+lid))[1].state.notes.find(x=>x.id==='note_l1');assert.equal(kept.actorId,'alice');assert.equal(kept.author,stored.author);assert.equal(kept.device,''); + assert.equal((await call('stores/'+lid,{user:'bob',headers:{'x-bedaway-actor':'alice'}}))[0],404);} +console.log('PASS: principal is the gateway account; body actor fields and non-UUID installation IDs are dropped.'); diff --git a/pkgs/bedside-and-away/tests/identity.mjs b/pkgs/bedside-and-away/tests/identity.mjs index 41ec87fe65..82e66bd65d 100644 --- a/pkgs/bedside-and-away/tests/identity.mjs +++ b/pkgs/bedside-and-away/tests/identity.mjs @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import {newGuestClaim,verifyGuestClaim,installationId} from '../worker/identity.mjs'; +import {newGuestClaim,verifyGuestClaim,installationId,continuityId,principalFromGateway} from '../worker/identity.mjs'; assert.match(installationId(),/^[a-f\d-]{36}$/); const c=await newGuestClaim({guestId:'g1',storeId:'s1',at:1000,ttlMs:60000}); assert.equal(c.record.token,undefined);assert.equal(c.record.tokenHash.length,64); @@ -7,4 +7,13 @@ const args={record:c.record,token:c.token,guestId:'g1',storeId:'s1',accountId:'t assert.deepEqual(await verifyGuestClaim(args),{guestId:'g1',storeId:'s1',accountId:'trusted-account',claimId:c.record.id}); for(const change of [{token:'bad'},{guestId:'g2'},{storeId:'s2'},{accountId:''},{at:61000},{record:{...c.record,consumedAt:2000}}])await assert.rejects(()=>verifyGuestClaim({...args,...change})); assert.notEqual((await newGuestClaim({guestId:'g1',storeId:'s1'})).token,c.token); +const uuid=installationId(); +assert.equal(continuityId(uuid),uuid);assert.equal(continuityId(uuid.toUpperCase()),uuid); +for(const x of ['alice','trusted-account','',null,undefined,42,{id:uuid},uuid+'x',' '+uuid])assert.equal(continuityId(x),''); +const h=o=>({get:k=>o[k]??null}); +assert.deepEqual({...principalFromGateway(h({'oai-authenticated-user-id':'acct_1','oai-authenticated-user-email':' Kay@Example.TEST\u200b'}))},{kind:'account',id:'acct_1',email:'kay@example.test'}); +assert.ok(Object.isFrozen(principalFromGateway(h({'oai-authenticated-user-id':'acct_1'})))); +for(const id of ['','a b','a\u200bb','x'.repeat(101)])assert.equal(principalFromGateway(h(id?{'oai-authenticated-user-id':id}:{})),null); +assert.equal(principalFromGateway(h({'x-bedaway-actor':'acct_1','actor':'acct_1'})),null); +console.log('PASS principal from gateway headers only, installation ID as UUID continuity only'); console.log('PASS guest proof token hashing, expiry, binding, consumed claims and account presence'); diff --git a/pkgs/bedside-and-away/worker/api.mjs b/pkgs/bedside-and-away/worker/api.mjs index bd6335c601..3c1d2fb4e2 100644 --- a/pkgs/bedside-and-away/worker/api.mjs +++ b/pkgs/bedside-and-away/worker/api.mjs @@ -3,6 +3,7 @@ import {evaluateAccess,projectSnapshot,projectEvents,assertSnapshotMutation,vali 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'; 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}); @@ -32,12 +33,15 @@ function validateState(s) { try{validateVariantGraph(s.items)}catch(e){fail(400,e.message)} return s; } +// Who recorded a row is the server's word, fixed when the row is first written (BA-W01 L1). +const provenance=['actorId','author','recordedAt','device']; function validateNewRecords(before,after,user,name){ for(const field of ['notes','inventory']){ - const previous=new Set(before[field].map(x=>x.id)); + 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]}} 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(); + row.actorId=user.id;row.author=name;row.recordedAt=now();if('device' in row)row.device=continuityId(row.device); if(field==='inventory'){ if(!['Bought','Consumed','Stock adjustment','Expense'].includes(row.mode)||!Number.isFinite(row.qty)||(row.mode!=='Stock adjustment'&&row.qty<0))fail(400,'Invalid inventory quantity or mode'); if(row.totalMinor!==undefined&&row.totalMinor!==null&&(!Number.isSafeInteger(row.totalMinor)||row.totalMinor<0))fail(400,'Invalid integer minor-unit total'); @@ -89,9 +93,9 @@ export async function api(request,env){ try{ const url=new URL(request.url),path=url.pathname.split('/').filter(Boolean),method=request.method; if(path[0]!=='api')return json({error:'Not found'},404); - const id=request.headers.get('oai-authenticated-user-id'),email=clean(request.headers.get('oai-authenticated-user-email'),320).toLowerCase(); - if(!id)return json({error:'Sign in with ChatGPT to use your private database',signIn:'/signin-with-chatgpt?returnTo=/'},401); - const user={id,email}; + const user=principalFromGateway(request.headers); + if(!user)return json({error:'Sign in with ChatGPT to use your private database',signIn:'/signin-with-chatgpt?returnTo=/'},401); + const {id,email}=user; if(!env.DB)fail(503,'Dedicated database binding is not available'); const db=env.DB; if(!['GET','POST'].includes(method))fail(405,'Method not allowed'); @@ -230,7 +234,7 @@ export async function api(request,env){ if(!dedicated){if(source.access&&!hasScopedAccess(source)&&!Object.hasOwn(event.after??{},'access'))event.after={...event.after,access:source.access};if(event.operation&&event.operation!=='change')fail(400,'Use the dedicated command endpoint');if(canonical(source.access??null)!==canonical(event.after?.access??null))fail(403,'Use the administrator policy endpoint');if(hasScopedAccess(source))fail(403,'Scoped stores require per-entity commands; snapshot editing is read-only');assertSnapshotMutation(source,event.after,context);assertSteeringUnchanged(source,event.after);try{assertVariantMetadataUnchanged(source.items,event.after.items)}catch(e){fail(400,e.message)}} const after=validateState(structuredClone(event.after)),settings=await getSettings(db,user),version=s.version+1; if(sub!=='history')validateNewRecords(source,after,user,settings.nickname||email||'Signed-in user'); - const accepted={intent,...(requestResult?{requestResult}:{}),id:event.id,at:now(),actor:settings.nickname||email||'Signed-in user',actorId:id,device:clean(event.device,100),label:clean(event.label,300)||'Edited tracker',operation:clean(event.operation,32)||'change',target:clean(event.target,100),before:parse(s.state_json),after,version}; + const accepted={intent,...(requestResult?{requestResult}:{}),id:event.id,at:now(),actor:settings.nickname||email||'Signed-in user',actorId:id,device:continuityId(event.device),label:clean(event.label,300)||'Edited tracker',operation:clean(event.operation,32)||'change',target:clean(event.target,100),before:parse(s.state_json),after,version}; const encoded=JSON.stringify(accepted); const results=await db.batch([ db.prepare("INSERT OR IGNORE INTO events(id,store_id,version,actor_id,actor_email,actor_name,at,payload_json) SELECT ?,id,?,?,?,?,?,? FROM stores WHERE id=? AND version=? AND archived=0 AND (type='shared' OR owner_id=?) AND EXISTS(SELECT 1 FROM memberships WHERE store_id=stores.id AND user_id=? AND (role='admin' OR (?!='policy' AND role='editor')))").bind(event.id,version,id,email,accepted.actor,accepted.at,encoded,sid,s.version,id,id,sub), diff --git a/pkgs/bedside-and-away/worker/identity.mjs b/pkgs/bedside-and-away/worker/identity.mjs index 87a418e11b..b661ee86d6 100644 --- a/pkgs/bedside-and-away/worker/identity.mjs +++ b/pkgs/bedside-and-away/worker/identity.mjs @@ -3,6 +3,15 @@ const failure=()=>Object.assign(new Error('Guest claim is invalid or expired'),{ const text=x=>typeof x==='string'&&x.length>0&&x.length<=200; const digest=async token=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(token)))).map(b=>b.toString(16).padStart(2,'0')).join(''); export const installationId=()=>crypto.randomUUID(); +/** The browser's installation ID, kept only as continuity metadata: a UUID or nothing. It never authenticates, authorizes or names a principal. */ +export const continuityId=x=>typeof x==='string'&&/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i.test(x)?x.toLowerCase():''; +/** The principal on a request, from the headers the verified gateway rebuilt (external/worker.mjs), never from a browser-supplied field. Null when there is none. */ +export function principalFromGateway(headers){ + const id=headers.get('oai-authenticated-user-id')||''; + if(!id||id.length>100||/[\p{Cc}\p{Cf}\s]/u.test(id))return null; + const email=(headers.get('oai-authenticated-user-email')||'').normalize('NFC').replace(/[\p{Cc}\p{Cf}]/gu,'').trim().slice(0,320).toLowerCase(); + return Object.freeze({kind:'account',id,email}); +} export async function newGuestClaim({guestId,storeId,at=Date.now(),ttlMs=600000}){ if(!text(guestId)||!text(storeId)||!Number.isSafeInteger(at)||!Number.isSafeInteger(ttlMs)||ttlMs<1000||ttlMs>600000)throw failure(); const token=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(b=>b.toString(16).padStart(2,'0')).join('');