Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkgs/bedside-and-away/design/identity-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ The `*` policy is the store read gate. A deny there denies the entire view; use

`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.

## Invitation lifecycle (BA-W01 L3)

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.

## 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.
Expand Down
13 changes: 13 additions & 0 deletions pkgs/bedside-and-away/tests/backend.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ await call('stores/'+sid+'/settings',{data:{type:'shared'}});
[code,r]=await call('stores/'+sid+'/invites',{data:{email:'bob@example.com',role:'reader'}});assert.equal(code,201);const iid=r.invitation.id;
assert.equal((await call('invites/'+iid+'/respond',{user:'mallory',data:{action:'accept'}}))[0],404);
assert.equal((await call('invites/'+iid+'/respond',{user:'bob',data:{action:'accept'}}))[0],200);
for(const action of ['accept','decline']){const [replayCode,replay]=await call('invites/'+iid+'/respond',{user:'bob',data:{action}});assert.equal(replayCode,409);assert.equal(replay.status,'accepted')}
assert.equal((await call('stores/'+sid,{user:'bob'}))[0],200);
assert.equal((await call('stores/'+sid+'/events',{user:'bob',data:{expectedVersion:1,event:{...event,id:'ev_3'}}}))[0],403);
assert.equal((await call('stores/'+sid+'/access',{user:'bob'}))[0],403);
Expand Down Expand Up @@ -156,3 +157,15 @@ console.log('PASS: scoped variant commands fail closed for administrators as wel
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.');
{const xid=(await call('stores',{data:{name:'Expiry',type:'shared',initialState:state}}))[1].store.id;
const made=(await call('stores/'+xid+'/invites',{data:{email:'erin@example.com',role:'reader'}}))[1].invitation;
assert.equal(Date.parse(made.expiresAt)-Date.now()>13*86400000,true);
assert.equal((await call('bootstrap',{user:'erin'}))[1].invitations.length,1);
sql.prepare('UPDATE invitations SET created_at=? WHERE id=?').run(new Date(Date.now()-15*86400000).toISOString(),made.id);
assert.equal((await call('bootstrap',{user:'erin'}))[1].invitations.length,0);
const [expiredCode,expired]=await call('invites/'+made.id+'/respond',{user:'erin',data:{action:'accept'}});
assert.equal(expiredCode,409);assert.equal(expired.status,'expired');assert.equal((await call('stores/'+xid,{user:'erin'}))[0],404);
assert.equal((await call('stores/'+xid+'/access'))[1].invitations.find(x=>x.id===made.id).status,'expired');
const again=(await call('stores/'+xid+'/invites',{data:{email:'erin@example.com',role:'reader'}}))[1].invitation;assert.notEqual(again.id,made.id);
assert.equal((await call('invites/'+again.id+'/respond',{user:'erin',data:{action:'accept'}}))[0],200);assert.equal((await call('stores/'+xid,{user:'erin'}))[0],200);}
console.log('PASS: invitations expire, replays of accepted or expired invitations fail closed, and a fresh invitation replaces an expired one.');
27 changes: 17 additions & 10 deletions pkgs/bedside-and-away/worker/api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ async function body(req){
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}}
// 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;
const inviteCutoff=(at=Date.now())=>new Date(at-INVITE_TTL_MS).toISOString();
const inviteStatus=row=>row.status==='pending'&&!(row.created_at>inviteCutoff())?'expired':row.status;
const inviteExpiresAt=row=>new Date(Date.parse(row.created_at)+INVITE_TTL_MS).toISOString();
const settingsDefault={nickname:'',showHidden:false,showArchived:false,showHiddenStores:false,stores:{}};
async function getSettings(db,user){const r=await db.prepare('SELECT settings_json FROM user_settings WHERE user_id=?').bind(user.id).first();return {...settingsDefault,...(r?parse(r.settings_json):{})}}
async function access(db,id,user,level='reader',allowArchived=true){
Expand Down Expand Up @@ -86,7 +92,7 @@ async function accessible(db,user){
}
async function bootstrap(db,user){
const stores=(await accessible(db,user)).map(storeData);
const invitations=user.email?(await db.prepare("SELECT i.id,i.store_id AS storeId,i.role,i.status,i.created_at AS createdAt,s.name AS storeName FROM invitations i JOIN stores s ON s.id=i.store_id WHERE i.email=? AND i.status='pending' AND s.type='shared' AND s.archived=0 ORDER BY i.created_at").bind(user.email).all()).results:[];
const invitations=user.email?(await db.prepare("SELECT i.id,i.store_id AS storeId,i.role,i.status,i.created_at AS createdAt,s.name AS storeName FROM invitations i JOIN stores s ON s.id=i.store_id WHERE i.email=? AND i.status='pending' AND i.created_at>? AND s.type='shared' AND s.archived=0 ORDER BY i.created_at").bind(user.email,inviteCutoff()).all()).results.map(x=>({...x,expiresAt:new Date(Date.parse(x.createdAt)+INVITE_TTL_MS).toISOString()})):[];
const refs=(await db.prepare("SELECT key,store_id FROM default_stores WHERE key IN (?, 'shared')").bind('personal:'+user.id).all()).results;
const ref=k=>{const found=refs.find(r=>r.key===k)?.store_id;return stores.some(s=>s.id===found)?found:null};
return {user,settings:await getSettings(db,user),stores,invitations,personalStoreId:ref('personal:'+user.id),defaultSharedStoreId:ref('shared')};
Expand Down Expand Up @@ -164,15 +170,16 @@ export async function api(request,env){
const b=await body(request),iid=path[2];if(!ident(iid)||!['accept','decline'].includes(b.action))fail(400,'Invalid invitation response');
const i=await db.prepare('SELECT i.*,s.type,s.archived FROM invitations i JOIN stores s ON s.id=i.store_id WHERE i.id=? AND i.email=?').bind(iid,email).first();
if(!email||!i)fail(404,'Invitation not found for this signed-in account');
if(i.status!=='pending')return json({status:i.status});
// Replays of an accepted, declined, revoked or expired invitation fail closed.
const current=inviteStatus(i);if(current!=='pending')return json({error:'This invitation is '+current,status:current,storeId:i.store_id},409);
if(b.action==='accept'&&(i.type!=='shared'||i.archived))fail(409,'This store is not currently accepting members');
const at=now(),status=b.action==='accept'?'accepted':'declined';
const at=now(),status=b.action==='accept'?'accepted':'declined',cutoff=inviteCutoff(Date.parse(at));
const receipt=crypto.randomUUID();
const stmts=[db.prepare("INSERT INTO access_events(id,store_id,actor_id,at,action,details_json) SELECT ?,i.store_id,?,?,?,? FROM invitations i JOIN stores s ON s.id=i.store_id WHERE i.id=? AND i.email=? AND i.status='pending' AND (?='decline' OR (s.type='shared' AND s.archived=0))").bind(receipt,id,at,'invite.'+status,JSON.stringify({inviteId:iid,email}),iid,email,b.action)];
const stmts=[db.prepare("INSERT INTO access_events(id,store_id,actor_id,at,action,details_json) SELECT ?,i.store_id,?,?,?,? FROM invitations i JOIN stores s ON s.id=i.store_id WHERE i.id=? AND i.email=? AND i.status='pending' AND i.created_at>? AND (?='decline' OR (s.type='shared' AND s.archived=0))").bind(receipt,id,at,'invite.'+status,JSON.stringify({inviteId:iid,email}),iid,email,cutoff,b.action)];
if(b.action==='accept')stmts.push(db.prepare("INSERT INTO memberships(store_id,user_id,email,role,created_at) SELECT store_id,?,?,role,? FROM invitations WHERE id=? AND status='pending' AND EXISTS(SELECT 1 FROM access_events WHERE id=?) ON CONFLICT(store_id,user_id) DO NOTHING").bind(id,email,at,iid,receipt));
stmts.push(db.prepare("UPDATE invitations SET status=?,responded_at=? WHERE id=? AND status='pending' AND EXISTS(SELECT 1 FROM access_events WHERE id=?)").bind(status,at,iid,receipt));
const results=await db.batch(stmts);
if(!results[0]?.meta?.changes){const actual=await db.prepare('SELECT status FROM invitations WHERE id=? AND email=?').bind(iid,email).first();if(actual&&actual.status!=='pending')return json({status:actual.status,storeId:i.store_id});fail(409,'Invitation or store changed; reload before responding');}
if(!results[0]?.meta?.changes){const actual=await db.prepare('SELECT status,created_at FROM invitations WHERE id=? AND email=?').bind(iid,email).first(),now_=actual&&inviteStatus(actual);if(now_&&now_!=='pending')return json({error:'This invitation is '+now_,status:now_,storeId:i.store_id},409);fail(409,'Invitation or store changed; reload before responding');}
return json({status,storeId:i.store_id});
}
if(path[1]!=='stores'||!path[2])fail(404,'Route not found');
Expand Down Expand Up @@ -264,10 +271,10 @@ export async function api(request,env){
await access(db,sid,user,'admin');
const [members,invites,history]=await Promise.all([
db.prepare('SELECT user_id AS userId,email,role,created_at AS createdAt FROM memberships WHERE store_id=?').bind(sid).all(),
db.prepare('SELECT id,email,role,status,created_at AS createdAt,responded_at AS respondedAt FROM invitations WHERE store_id=? ORDER BY created_at').bind(sid).all(),
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,history:history.results.map(x=>({...x,details:parse(x.details)}))});
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)}))});
}
if(sub==='members'&&path[4]&&method==='POST'){
const s=await access(db,sid,user,'admin'),b=await body(request),uid=path[4];
Expand All @@ -286,11 +293,11 @@ export async function api(request,env){
if(s.type!=='shared')fail(409,'Change store type to shared before inviting');
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 FROM invitations WHERE store_id=? AND email=? AND status='pending'").bind(sid,email).first();
if(existing)return json({invitation:{id:existing.id,email,role:existing.role,status:'pending'},sent:false,note:'Invitation already pending. No email was sent.'});
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.'});
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'},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,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)}
Expand Down