diff --git a/pkgs/bedside-and-away/design/identity-access.md b/pkgs/bedside-and-away/design/identity-access.md index cdd5072905..1e1db68a42 100644 --- a/pkgs/bedside-and-away/design/identity-access.md +++ b/pkgs/bedside-and-away/design/identity-access.md @@ -34,6 +34,10 @@ The `*` policy is the store read gate. A deny there denies the entire view; use An invitation is `pending` until it is accepted, declined or revoked, and expires 14 days after it was made (`INVITE_TTL_MS` in `worker/api.mjs`). Expiry is derived from `created_at` rather than stored, because the `invitations.status` CHECK predates `expired`; the API reports `expired` and each invitation's `expiresAt`, and an expired invitation leaves the invitee's list. The invitation ID is its single-use token: only the signed-in account whose email it names can respond, every transition is a compare-and-set on `status='pending'` and an unexpired `created_at`, and a response to an invitation that is no longer pending (a replay, or one that expired) fails closed with 409 and its status. A new invitation to the same email replaces an expired one. +## Stores, roles and provisioning (BA-W01 L2) + +Roles are `viewer`, `editor` and `administrator` (`worker/roles.mjs`). The database and earlier API store them as `reader`, `editor` and `admin`; requests take either name, and responses keep the stored `role` and add the contract `roleName`. Ownership is separate from roles. Provisioning gives each account one personal private store, whose ID derives from the account ID, and seeds the Site default shared store only for the account `DEFAULT_SHARED_OWNER` names (`none` for no account; unset keeps the first-creator rule for existing deployments). No account joins the shared store by provisioning; membership comes only from an invitation. The display name is a label: changing it renames the personal store while that store still has its automatic name, keeps a name the owner chose, and never changes an identifier. + ## 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. @@ -49,7 +53,7 @@ The future linking route must obtain guest proof through a secure HttpOnly/SameS ## Acceptance and remaining scope -Implemented pure logic: BA-088/089 evaluation and projection foundation, role negative tests for BA-078, proof-token foundation for BA-083/084. Integration is not established merely by these tests. BA-043 browser persistence/reset UI remains partial; BA-044 fingerprinting deliberately absent pending explicit transparent consent and minimization design; BA-045 display-name changes remain existing prototype behavior; BA-079 invitation expiry and complete lifecycle integration remain follow-up; BA-080 anonymous store provision absent; BA-081 second-person ingress not granted; BA-082 Google/password login absent; BA-083/084 full guest/account linking not implemented; BA-085 open-store gateway audience remains existing approved scope; BA-086 filtered API integration required; BA-087 Atlas explicitly deferred. Scoped editor commands, granular history projections, policy administration UI, typed note-target adapters and ACL-safe derived reports are not claimed complete. +Implemented pure logic: BA-088/089 evaluation and projection foundation, role negative tests for BA-078, proof-token foundation for BA-083/084. Integration is not established merely by these tests. BA-043 browser persistence/reset UI remains partial; BA-044 fingerprinting deliberately absent pending explicit transparent consent and minimization design; BA-045 display name is separate from identifiers (L2 above); BA-079 invitation expiry and complete lifecycle integration remain follow-up; BA-080 anonymous store provision absent; BA-081 second-person ingress not granted; BA-082 Google/password login absent; BA-083/084 full guest/account linking not implemented; BA-085 open-store gateway audience remains existing approved scope; BA-086 filtered API integration required; BA-087 Atlas explicitly deferred. Scoped editor commands, granular history projections, policy administration UI, typed note-target adapters and ACL-safe derived reports are not claimed complete. ## Rollback and migration diff --git a/pkgs/bedside-and-away/tests/stores.mjs b/pkgs/bedside-and-away/tests/stores.mjs new file mode 100644 index 0000000000..ecaf022f3d --- /dev/null +++ b/pkgs/bedside-and-away/tests/stores.mjs @@ -0,0 +1,93 @@ +// BA-W01 L2: store roles by their contract names, default store provisioning and the display name. +import {DatabaseSync} from 'node:sqlite'; +import {readFileSync} from 'node:fs'; +import assert from 'node:assert/strict'; +import {api} from '../worker/api.mjs'; +import {storedRole,roleName,roleAtLeast,personalStoreName,maySeedDefaultShared,STORED_ROLES} from '../worker/roles.mjs'; + +for(const [asked,stored] of [['viewer','reader'],['reader','reader'],['editor','editor'],['administrator','admin'],['admin','admin']])assert.equal(storedRole(asked),stored); +for(const x of ['owner','Viewer','remove','','toString','__proto__',null,undefined,1])assert.equal(storedRole(x),null); +assert.deepEqual(STORED_ROLES.map(roleName),['viewer','editor','administrator']); +assert.equal(roleName('owner'),null);assert.equal(roleName('constructor'),null); +assert.ok(roleAtLeast('admin','editor')&&roleAtLeast('editor','editor')&&!roleAtLeast('reader','editor')&&!roleAtLeast('owner','reader')); +assert.equal(personalStoreName(''),'Personal');assert.equal(personalStoreName('Kay'),'Kay personal store'); +assert.ok(maySeedDefaultShared({},'a')&&maySeedDefaultShared({DEFAULT_SHARED_OWNER:' '},'a')&&maySeedDefaultShared({DEFAULT_SHARED_OWNER:'a'},'a')); +assert.ok(!maySeedDefaultShared({DEFAULT_SHARED_OWNER:'a'},'b')&&!maySeedDefaultShared({DEFAULT_SHARED_OWNER:'none'},'a')); +console.log('PASS role names, personal store naming and default shared seeding rule'); + +function harness(env={}){ + 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 binds=[];return {bind(...v){binds=v;return this},async first(){return sql.prepare(q).get(...binds)||null},async all(){return {results:sql.prepare(q).all(...binds)}},async run(){const r=sql.prepare(q).run(...binds);return {meta:{changes:Number(r.changes)}}}}},async batch(statements){sql.exec('BEGIN');try{const results=[];for(const s of statements)results.push(await s.run());sql.exec('COMMIT');return results}catch(e){sql.exec('ROLLBACK');throw e}}}; + return async(path,{user='alice',data}={})=>{const r=await api(new Request('https://app.test/api/'+path,{method:data?'POST':'GET',headers:{'oai-authenticated-user-id':user,'oai-authenticated-user-email':user+'@example.com',...(data?{origin:'https://app.test','content-type':'application/json'}:{})},...(data?{body:JSON.stringify(data)}:{})}),{...env,DB:db});return [r.status,await r.json()]}; +} +const state={items:[],tags:[],people:['Shared'],notes:[],inventory:[],prefs:{},rules:{},recs:{},overrides:{}}; + +// Configured owner: only that account seeds the default shared store, whoever provisions first. +{ + const call=harness({DEFAULT_SHARED_OWNER:'carol'}); + let [code,r]=await call('provision',{user:'bob',data:{initialState:state}}); + assert.equal(code,200);assert.ok(r.personalStoreId);assert.equal(r.defaultSharedStoreId,null); + assert.deepEqual(r.stores.map(s=>s.id),[r.personalStoreId]); + [code,r]=await call('provision',{user:'carol',data:{initialState:state}}); + assert.equal(code,200);assert.ok(r.defaultSharedStoreId); + const shared=r.defaultSharedStoreId; + assert.equal(r.stores.find(s=>s.id===shared).roleName,'administrator'); + [code,r]=await call('provision',{user:'bob',data:{initialState:state}}); + assert.equal(r.defaultSharedStoreId,null,'provisioning never joins another account to the shared store'); + assert.equal((await call('stores/'+shared,{user:'bob'}))[0],404); + // Contract role names are accepted on invitations and role changes; the stored names are kept. + [code,r]=await call('stores/'+shared+'/invites',{user:'carol',data:{email:'bob@example.com',role:'viewer'}}); + assert.equal(code,201);assert.equal(r.invitation.role,'reader');assert.equal(r.invitation.roleName,'viewer'); + assert.equal((await call('invites/'+r.invitation.id+'/respond',{user:'bob',data:{action:'accept'}}))[0],200); + [code,r]=await call('stores/'+shared,{user:'bob'});assert.equal(code,200);assert.equal(r.store.role,'reader');assert.equal(r.store.roleName,'viewer'); + assert.equal((await call('stores/'+shared+'/members/bob',{user:'carol',data:{role:'administrator'}}))[0],200); + [code,r]=await call('stores/'+shared+'/access',{user:'bob'});assert.equal(code,200); + assert.deepEqual(r.members.map(m=>[m.userId,m.role,m.roleName]).sort(),[['bob','admin','administrator'],['carol','admin','administrator']]); + assert.equal(r.invitations[0].roleName,'viewer'); + for(const role of ['owner','Viewer','',null])assert.equal((await call('stores/'+shared+'/members/bob',{user:'carol',data:{role}}))[0],400); + assert.equal((await call('stores/'+shared+'/invites',{user:'carol',data:{email:'dan@example.com',role:'owner'}}))[0],400); + assert.equal((await call('stores/'+shared+'/members/bob',{user:'carol',data:{role:'remove'}}))[0],200); + assert.equal((await call('stores/'+shared,{user:'bob'}))[0],404); +} +// `none`: no account seeds a shared store; each still gets one personal store. +{ + const call=harness({DEFAULT_SHARED_OWNER:'none'}); + const [code,r]=await call('provision',{data:{initialState:state}}); + assert.equal(code,200);assert.equal(r.defaultSharedStoreId,null);assert.equal(r.stores.length,1);assert.equal(r.stores[0].type,'private'); +} +// Unset keeps the prototype rule: the first account seeds it, later accounts do not join. +{ + const call=harness(); + const first=(await call('provision',{data:{initialState:state}}))[1]; + assert.ok(first.defaultSharedStoreId); + assert.equal((await call('provision',{user:'bob',data:{initialState:state}}))[1].defaultSharedStoreId,null); +} +console.log('PASS default shared store seeded only by its configured owner, never joined by provisioning; contract role names at the API'); + +// The personal store's automatic name follows the display name; a chosen name stays; the ID never changes. +{ + const call=harness(); + let r=(await call('provision',{data:{initialState:state}}))[1]; + const personal=r.personalStoreId,named=()=>call('bootstrap').then(([,b])=>b.stores.find(s=>s.id===personal)); + assert.equal((await named()).name,'Personal'); + await call('settings',{data:{nickname:'Kay'}}); + assert.equal((await named()).name,'Kay personal store'); + await call('settings',{data:{nickname:'Kay R'}}); + assert.equal((await named()).name,'Kay R personal store'); + await call('settings',{data:{nickname:''}}); + assert.equal((await named()).name,'Personal'); + assert.equal((await call('stores/'+personal+'/settings',{data:{name:'My notes'}}))[0],200); + await call('settings',{data:{nickname:'Lee'}}); + const kept=await named();assert.equal(kept.name,'My notes');assert.equal(kept.id,personal); + assert.equal((await call('bootstrap'))[1].personalStoreId,personal); + // Another account's nickname never renames this store. + await call('provision',{user:'bob',data:{initialState:state}}); + await call('settings',{user:'bob',data:{nickname:'Personal'}}); + assert.equal((await named()).name,'My notes'); + // Settings without a nickname change leave the name alone. + await call('stores/'+personal+'/settings',{data:{name:'Lee personal store'}}); + await call('settings',{data:{showHidden:true}}); + assert.equal((await named()).name,'Lee personal store'); +} +console.log('PASS display name renames the personal store label only, never its identifier, and never a chosen name'); diff --git a/pkgs/bedside-and-away/worker/BACKEND.md b/pkgs/bedside-and-away/worker/BACKEND.md index 80de5a0ddb..f808c44882 100644 --- a/pkgs/bedside-and-away/worker/BACKEND.md +++ b/pkgs/bedside-and-away/worker/BACKEND.md @@ -20,7 +20,7 @@ Local checks: ## V2 contract and limits -POST /api/provision {initialState} creates an empty personal store per authenticated account and one Site default shared store seeded by its first creator, idempotently. The display name is a nickname or Personal; identity is server-derived, never a browser UUID. Subsequent callers do not join the default shared store. Bootstrap includes personalStoreId and defaultSharedStoreId only if accessible. Default audience types are locked; names remain editable. +POST /api/provision {initialState} creates an empty personal store per authenticated account and, idempotently, one Site default shared store. `DEFAULT_SHARED_OWNER` sets who seeds the shared store: unset keeps the prototype rule (the first account to provision), `none` seeds none, any other value is the one account ID that may. The personal store is named from the display name (nickname, or Personal) and follows it while it keeps that automatic name; identity is server-derived, never a browser UUID. Provisioning never joins an account to the default shared store. Bootstrap includes personalStoreId and defaultSharedStoreId only if accessible. Default audience types are locked; names remain editable. Open is an application audience, not public site access. Open stores start empty with their own categories. Signed-in Site visitors can read current visible items/tags, but unjoined readers get no notes, inventory, research, policy state or history. Only members with editor/admin may write. Conversion into/out of open is blocked to avoid exposing historical data. Archived open stores are inaccessible to nonmembers. diff --git a/pkgs/bedside-and-away/worker/api.mjs b/pkgs/bedside-and-away/worker/api.mjs index 19679ad5b7..31318e215d 100644 --- a/pkgs/bedside-and-away/worker/api.mjs +++ b/pkgs/bedside-and-away/worker/api.mjs @@ -5,7 +5,7 @@ import {validateVariantGraph,assertVariantMetadataUnchanged} from './variant-gra import {variantPlan} from './variant-plan.mjs'; import {principalFromGateway,continuityId} from './identity.mjs'; import {name,isComment} from './text.mjs'; -const roles = ['reader','editor','admin']; +import {storedRole,roleName,roleAtLeast,personalStoreName,maySeedDefaultShared} from './roles.mjs'; 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})}; @@ -13,7 +13,7 @@ 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(); -const roleValue = x=>{if(!roles.includes(x))fail(400,'Invalid role');return x}; +const roleValue = x=>storedRole(x)??fail(400,'Invalid role'); const canonical = value=>JSON.stringify(value,(_,v)=>v&&typeof v==='object'&&!Array.isArray(v)?Object.fromEntries(Object.keys(v).sort().map(k=>[k,v[k]])):v); const publicEvent = e=>{const {intent,requestResult,...visible}=e;return visible}; const eventIntent = (event,expectedVersion)=>({expectedVersion,after:event.after,label:clean(event.label,300)||'Edited tracker',operation:clean(event.operation,32)||'change',target:clean(event.target,100)}); @@ -57,7 +57,7 @@ async function body(req){ const raw=await req.text();if(raw.length>1700000)fail(413,'Request too large'); try{return JSON.parse(raw)}catch{fail(400,'Invalid JSON')} } -function storeData(row){return {id:row.id,name:row.name,type:row.is_open?'open':row.type,ownerId:row.owner_id,archived:!!row.archived,version:row.version,role:row.role,createdAt:row.created_at,updatedAt:row.updated_at}} +function storeData(row){return {id:row.id,name:row.name,type:row.is_open?'open':row.type,ownerId:row.owner_id,archived:!!row.archived,version:row.version,role:row.role,roleName:roleName(row.role),createdAt:row.created_at,updatedAt:row.updated_at}} // An invitation expires this long after it was made (BA-W01 L3). Expiry is derived from created_at, // so 'expired' is reported, never stored: the status column keeps 'pending' (its CHECK predates it). export const INVITE_TTL_MS=14*24*60*60*1000; @@ -70,7 +70,7 @@ async function access(db,id,user,level='reader',allowArchived=true){ if(!ident(id))fail(404,'Store not found'); const s=await db.prepare("SELECT s.*,m.role AS member_role,COALESCE(m.role,CASE WHEN s.is_open=1 THEN 'reader' END) AS role FROM stores s LEFT JOIN memberships m ON m.store_id=s.id AND m.user_id=? WHERE s.id=? AND (s.is_open=1 OR m.user_id IS NOT NULL)").bind(user.id,id).first(); if(!s||(s.is_open&&s.archived&&!s.member_role)||(!s.is_open&&s.type==='private'&&s.owner_id!==user.id))fail(404,'Store not found'); - if(roles.indexOf(s.role)x.toString(16).padStart(2,'0')).join(''); - const settings=await getSettings(db,user),name=(settings.nickname?settings.nickname+' personal store':'Personal'); - const shared='site_default_shared'; + const settings=await getSettings(db,user),name=personalStoreName(settings.nickname); + const shared='site_default_shared',seedShared=maySeedDefaultShared(env,id); const encoded=JSON.stringify(state); const personalState=JSON.stringify({...state,items:[],notes:[],inventory:[],research:[],rules:{},overrides:{},recs:{}}); await db.batch([ db.prepare("INSERT OR IGNORE INTO stores(id,name,type,owner_id,state_json,created_at,updated_at) VALUES(?,?,'private',?,?,?,?)").bind(personal,name,id,personalState,at,at), db.prepare("INSERT OR IGNORE INTO memberships(store_id,user_id,email,role,created_at) SELECT id,?,?,'admin',? FROM stores WHERE id=? AND owner_id=?").bind(id,email,at,personal,id), db.prepare("INSERT OR IGNORE INTO default_stores(key,store_id) VALUES(?,?)").bind('personal:'+id,personal), - db.prepare("INSERT OR IGNORE INTO stores(id,name,type,owner_id,state_json,created_at,updated_at) VALUES(?,'Shared household','shared',?,?,?,?)").bind(shared,id,encoded,at,at), - db.prepare("INSERT OR IGNORE INTO memberships(store_id,user_id,email,role,created_at) SELECT id,?,?,'admin',? FROM stores WHERE id=? AND owner_id=?").bind(id,email,at,shared,id), - db.prepare("INSERT OR IGNORE INTO default_stores(key,store_id) VALUES('shared',?)").bind(shared) + ...(seedShared?[ + db.prepare("INSERT OR IGNORE INTO stores(id,name,type,owner_id,state_json,created_at,updated_at) VALUES(?,'Shared household','shared',?,?,?,?)").bind(shared,id,encoded,at,at), + db.prepare("INSERT OR IGNORE INTO memberships(store_id,user_id,email,role,created_at) SELECT id,?,?,'admin',? FROM stores WHERE id=? AND owner_id=?").bind(id,email,at,shared,id), + db.prepare("INSERT OR IGNORE INTO default_stores(key,store_id) VALUES('shared',?)").bind(shared) + ]:[]) ]); return json(await bootstrap(db,user)); } @@ -151,7 +153,10 @@ export async function api(request,env){ for(const k of ['showHidden','showArchived','showHiddenStores'])if(k in b)s[k]=!!b[k]; if(b.stores&&typeof b.stores==='object'&&!Array.isArray(b.stores))s.stores=JSON.parse(JSON.stringify(b.stores)); if(JSON.stringify(s).length>50000)fail(413,'Settings too large'); - await db.prepare('INSERT INTO user_settings(user_id,settings_json,updated_at) VALUES(?,?,?) ON CONFLICT(user_id) DO UPDATE SET settings_json=excluded.settings_json,updated_at=excluded.updated_at').bind(id,JSON.stringify(s),now()).run(); + const at=now(),save=db.prepare('INSERT INTO user_settings(user_id,settings_json,updated_at) VALUES(?,?,?) ON CONFLICT(user_id) DO UPDATE SET settings_json=excluded.settings_json,updated_at=excluded.updated_at').bind(id,JSON.stringify(s),at); + // The personal store's automatic name follows the display name; a name the owner chose stays (BA-045). + const follow=personalStoreName(old.nickname)!==personalStoreName(s.nickname)?[db.prepare("UPDATE stores SET name=?,updated_at=? WHERE id=(SELECT store_id FROM default_stores WHERE key=?) AND owner_id=? AND type='private' AND name=?").bind(personalStoreName(s.nickname),at,'personal:'+id,id,personalStoreName(old.nickname))]:[]; + await db.batch([save,...follow]); return json({settings:s}); } if(path[1]==='stores'&&path.length===2&&method==='POST'){ @@ -193,7 +198,7 @@ export async function api(request,env){ if(sub==='policy'&&method==='GET'){ const s=await access(db,sid,user,'admin'); const members=await db.prepare('SELECT user_id AS userId,email,role FROM memberships WHERE store_id=?').bind(sid).all(); - return json({access:parse(s.state_json).access??{schemaVersion:1,groups:{},policies:{}},version:s.version,members:members.results}); + return json({access:parse(s.state_json).access??{schemaVersion:1,groups:{},policies:{}},version:s.version,members:members.results.map(m=>({...m,roleName:roleName(m.role)}))}); } if(['events','steering','variants','policy','history'].includes(sub)&&method==='POST'){ const s=await access(db,sid,user,'editor',false),b=await body(request),source=parse(s.state_json),context={principal:user,role:s.role}; @@ -274,13 +279,14 @@ export async function api(request,env){ db.prepare('SELECT id,email,role,status,created_at,responded_at AS respondedAt FROM invitations WHERE store_id=? ORDER BY created_at').bind(sid).all(), db.prepare('SELECT id,actor_id AS actorId,at,action,details_json AS details FROM access_events WHERE store_id=? ORDER BY at').bind(sid).all() ]); - return json({members:members.results,invitations:invites.results.map(({created_at,...x})=>({...x,status:inviteStatus({...x,created_at}),createdAt:created_at,expiresAt:inviteExpiresAt({created_at})})),history:history.results.map(x=>({...x,details:parse(x.details)}))}); + return json({members:members.results.map(m=>({...m,roleName:roleName(m.role)})),invitations:invites.results.map(({created_at,...x})=>({...x,roleName:roleName(x.role),status:inviteStatus({...x,created_at}),createdAt:created_at,expiresAt:inviteExpiresAt({created_at})})),history:history.results.map(x=>({...x,details:parse(x.details)}))}); } if(sub==='members'&&path[4]&&method==='POST'){ const s=await access(db,sid,user,'admin'),b=await body(request),uid=path[4]; if(uid===s.owner_id)fail(403,'The store owner always retains admin access'); - if(!['reader','editor','admin','remove'].includes(b.role))fail(400,'Invalid role'); - await adminMutation(db,sid,user,'member.role',{userId:uid,role:b.role},receipt=>[b.role==='remove'?db.prepare('DELETE FROM memberships WHERE store_id=? AND user_id=? AND EXISTS(SELECT 1 FROM access_events WHERE id=?)').bind(sid,uid,receipt):db.prepare('UPDATE memberships SET role=? WHERE store_id=? AND user_id=? AND EXISTS(SELECT 1 FROM access_events WHERE id=?)').bind(b.role,sid,uid,receipt)]); + const role=b.role==='remove'?'remove':storedRole(b.role); + if(!role)fail(400,'Invalid role'); + await adminMutation(db,sid,user,'member.role',{userId:uid,role},receipt=>[role==='remove'?db.prepare('DELETE FROM memberships WHERE store_id=? AND user_id=? AND EXISTS(SELECT 1 FROM access_events WHERE id=?)').bind(sid,uid,receipt):db.prepare('UPDATE memberships SET role=? WHERE store_id=? AND user_id=? AND EXISTS(SELECT 1 FROM access_events WHERE id=?)').bind(role,sid,uid,receipt)]); return json({ok:true}); } if(sub==='invites'&&method==='POST'){ @@ -294,10 +300,10 @@ export async function api(request,env){ const b=await body(request),email=clean(b.email,320).toLowerCase(),role=roleValue(b.role||'reader'); if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))fail(400,'Valid email required'); const existing=await db.prepare("SELECT id,role,created_at FROM invitations WHERE store_id=? AND email=? AND status='pending' AND created_at>?").bind(sid,email,inviteCutoff()).first(); - if(existing)return json({invitation:{id:existing.id,email,role:existing.role,status:'pending',expiresAt:inviteExpiresAt(existing)},sent:false,note:'Invitation already pending. No email was sent.'}); + if(existing)return json({invitation:{id:existing.id,email,role:existing.role,roleName:roleName(existing.role),status:'pending',expiresAt:inviteExpiresAt(existing)},sent:false,note:'Invitation already pending. No email was sent.'}); const iid=crypto.randomUUID(),at=now(); await adminMutation(db,sid,user,'invite.created',{inviteId:iid,email,role},receipt=>[db.prepare('INSERT INTO invitations(id,store_id,email,role,created_by,created_at) SELECT ?,?,?,?,?,? WHERE EXISTS(SELECT 1 FROM access_events WHERE id=?)').bind(iid,sid,email,role,id,at,receipt)],{activeShared:true}); - return json({invitation:{id:iid,email,role,status:'pending',expiresAt:inviteExpiresAt({created_at:at})},sent:false,note:'Invitation saved, not emailed. Invitees must be allowed through the Site sharing policy before accepting.'},201); + return json({invitation:{id:iid,email,role,roleName:roleName(role),status:'pending',expiresAt:inviteExpiresAt({created_at:at})},sent:false,note:'Invitation saved, not emailed. Invitees must be allowed through the Site sharing policy before accepting.'},201); } fail(404,'Route not found'); }catch(e){return json({error:e.status?e.message:'Database request failed. Your previous saved version remains available.'},e.status||500)} diff --git a/pkgs/bedside-and-away/worker/roles.mjs b/pkgs/bedside-and-away/worker/roles.mjs new file mode 100644 index 0000000000..e7d355c7b5 --- /dev/null +++ b/pkgs/bedside-and-away/worker/roles.mjs @@ -0,0 +1,26 @@ +/** Store roles (BA-W01 L2). The contract names them viewer, editor and administrator; the database + * and the existing API store reader, editor and admin. Requests may use either name; responses keep + * the stored name in `role` and add the contract name as `roleName`. Ownership is not a role. */ +export const STORED_ROLES=Object.freeze(['reader','editor','admin']); +const contract=Object.freeze({reader:'viewer',editor:'editor',admin:'administrator'}); +const stored=Object.freeze({viewer:'reader',reader:'reader',editor:'editor',administrator:'admin',admin:'admin'}); +/** The stored role for a requested role name, or null for anything else. */ +export const storedRole=x=>typeof x==='string'&&Object.hasOwn(stored,x)?stored[x]:null; +/** The contract name for a stored role, or null. */ +export const roleName=x=>typeof x==='string'&&Object.hasOwn(contract,x)?contract[x]:null; +/** Whether a stored role reaches at least the stored role `level`. */ +export const roleAtLeast=(role,level)=>STORED_ROLES.indexOf(role)>=0&&STORED_ROLES.indexOf(role)>=STORED_ROLES.indexOf(level); + +/** The automatic name of an account's personal store, from its editable display name (BA-045, BA-080). + * The name is only a label: the store ID is derived from the account ID and never changes. */ +export const personalStoreName=nickname=>nickname?nickname+' personal store':'Personal'; + +/** Who may seed the Site's default shared store on provisioning (BA-081). `DEFAULT_SHARED_OWNER` unset + * keeps the prototype rule (the first account to provision seeds it); `none` seeds no shared store; + * any other value is the one account ID allowed to seed it. Other accounts never join it by provisioning. */ +export function maySeedDefaultShared(env,accountId){ + const configured=typeof env?.DEFAULT_SHARED_OWNER==='string'?env.DEFAULT_SHARED_OWNER.trim():''; + if(!configured)return true; + if(configured==='none')return false; + return configured===accountId; +}