@witbitz/sdk 4.6.0 → 4.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sdkCloudDevice.js CHANGED
@@ -2,7 +2,7 @@ import { sealDoc } from './accountSeal.js'
2
2
  import { disconnectKeptSpace, keptAgentSpaceIds } from './sdkKeptAgent.js'
3
3
 
4
4
  const fail = (code, text, status) => Object.assign(new Error('witbitz: ' + text), { code, ...(status ? { status } : {}) })
5
- const current = (wb, session, state) => { if (wb._session !== session || wb.backup._s !== state) throw fail('account_changed', 'the account changed during the cloud-device operation') }
5
+ const current = (wb, session, state) => { if (wb._session !== session || wb.backup?._s !== state) throw fail('account_changed', 'the account changed during the cloud-device operation') }
6
6
 
7
7
  /** A kept Space remains solo and has no private lane of its own, on every SDK/vault device. */
8
8
  export async function assertNotKept(space) {
@@ -45,14 +45,23 @@ export async function disconnectRoomLanes(w, room) {
45
45
  current(w, session, state)
46
46
  if (!result?.ok) throw fail('index_unavailable', 'the disconnected lanes could not be synced')
47
47
  }
48
- if (w.account?.enabled) await sync()
49
- const held = w._heldLaneRooms?.(room) || []
50
- const children = new Set([...held, ...(w.backup?.rooms || []).filter(r => r.kind === 'lane' && r.shared === room).map(r => r.room)])
51
- const links = (w.account?.links || []).filter(l => l.a === room || l.b === room)
52
- for (const link of links) w.account._dropLink(link.a, link.b)
53
- for (const child of children) w.backup?._detachLane(child, room)
54
- if (held.length) { await w._detachHeldLanes(room); current(w, session, state) }
55
- if (w.account?.enabled && (links.length || children.size)) await sync()
48
+ // Persist the links and children already known on this device before asking the index for remote ones.
49
+ // If the network is down, the next sync still has the local removal to send.
50
+ const detachKnown = async () => {
51
+ const held = w._heldLaneRooms?.(room) || []
52
+ const children = new Set([...held, ...(w.backup?.rooms || []).filter(r => r.kind === 'lane' && r.shared === room).map(r => r.room)])
53
+ const links = (w.account?.links || []).filter(l => l.a === room || l.b === room)
54
+ for (const link of links) w.account._dropLink(link.a, link.b)
55
+ for (const child of children) w.backup?._detachLane(child, room)
56
+ if (held.length) { await w._detachHeldLanes(room); current(w, session, state) }
57
+ return !!(links.length || children.size)
58
+ }
59
+ await detachKnown()
60
+ current(w, session, state)
61
+ if (w.account?.enabled) {
62
+ await sync()
63
+ if (await detachKnown()) await sync()
64
+ }
56
65
  }
57
66
 
58
67
  /** Requests use the attested, encrypted cloud-device channel. */
package/sdkComputers.js CHANGED
@@ -200,6 +200,7 @@ export class Computers {
200
200
  }
201
201
  const store = {
202
202
  get: async key => { const blob = await idb.get(key); return blob ? open(key, blob) : null },
203
+ getStrict: async key => { const blob = await idb.getStrict(key); return blob ? open(key, blob) : null }, // a failed read throws (codeCache removeCachedSession)
203
204
  set: async (key, value) => { const box = await sealDoc(loc.key, { key, value }); check(); return idb.set(key, { accountBox: box }) },
204
205
  entries: async prefix => Promise.all((await idb.entries(prefix)).map(async ([k, v]) => [k, await open(k, v)])),
205
206
  del: key => idb.del(key),
package/sdkExports.js CHANGED
@@ -1,4 +1,6 @@
1
- import { exportSpace, recreateSpace, missingAttachments, messageCount } from './spaceExport.js'
1
+ import { exportSpace, recreateSpace, missingAttachments, messageCount, inlineEarlier } from './spaceExport.js'
2
+ import { earlierForExport } from './earlierHistory.js'
3
+ import { readEpochChain } from './spaceFork.js'
2
4
  import { makeBundle, sealSpaceMeta, keysFileText, OFFLINE_ATTACHMENTS_MAX_BYTES, addAttachmentStats } from './offlineBundle.js'
3
5
 
4
6
  // Downloads stay in the document doing the export. A vault never returns the
@@ -17,20 +19,26 @@ export async function saveOfflineReader() {
17
19
  saveExport('witbitz-offline-decryptor.html', await response.text(), 'text/html;charset=utf-8')
18
20
  }
19
21
 
20
- export async function saveRoomExport(sp, tier, current = () => true, title = sp.title) {
22
+ // `earlierKeys` ({ room: key } — the account's rooms this client can open): a LINKED CONTINUATION's earlier versions ride along, read
23
+ // as the Spaces app reads them (offlineExport.js, earlierHistory.js); when they cannot be, the result says so (`historyIncomplete`)
24
+ export async function saveRoomExport(sp, tier, current = () => true, title = sp.title, earlierKeys = null) {
21
25
  const reader = Object.fromEntries(['poll', 'getConfig', 'blob', 'state'].map((op) => [
22
26
  op, (room, ...args) => sp._client[op](room, sp._mk, ...args),
23
27
  ]))
24
28
  const bundle = await exportSpace(sp.room, reader, { title })
25
29
  if (!current()) throw new Error('account_changed')
26
30
  bundle.tier = tier
31
+ const keys = earlierKeys && typeof earlierKeys === 'object' ? earlierKeys : {}
32
+ const { earlier, note } = await earlierForExport({ parent: bundle.config?.parent?.room, epochKeys: keys, configRead: !!bundle.config, readChain: (p, mk, ek) => readEpochChain(sp._client, p, mk, ek, 0, { whole: true }) })
33
+ if (earlier) { earlier.entries = await inlineEarlier(earlier.entries, (room, ref) => (room && keys[room] ? sp._client.blob(room, keys[room], ref) : null)); bundle.earlier = earlier }
34
+ if (!current()) throw new Error('account_changed')
27
35
  // A readable file carries no credential (a connection's callKey, the room's earlier keys): exportSpace leaves them out for
28
36
  // every caller — spaceExport.js portableConfig (side sweep: portable-export-includes-room-credentials).
29
37
  saveExport('witbitz-space-' + sp.room + '.json', JSON.stringify(bundle), 'application/json')
30
38
  // the attachments the file still carries only as a pointer to this room (their read failed): said, as the app says it — a
31
39
  // recreated room cannot open them (side sweep: portable-export-silent-attachment-read-failure)
32
40
  const missing = missingAttachments(bundle)
33
- return { count: messageCount(bundle.entries), ...(missing ? { attachmentsMissing: missing } : {}) } // the MESSAGE count: a photo's Safe media copy is not one (side sweep: room-export-counts-hidden-records-as-messages)
41
+ return { count: messageCount(bundle.entries), ...(missing ? { attachmentsMissing: missing } : {}), ...(earlier ? { earlierCount: messageCount(earlier.entries) } : note ? { historyIncomplete: note.trim() } : {}) } // the MESSAGE count: a photo's Safe media copy is not one (side sweep: room-export-counts-hidden-records-as-messages)
34
42
  }
35
43
 
36
44
  export async function recreateExport(wb, bundle, { tier = bundle?.tier || (bundle?.device?.confidential === false ? 'standard' : 'enclave') } = {}) {
package/sdkInvitations.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { sendInvite } from './inviteSend.js'
2
- import { inviteScope } from './sdkRekey.js'
2
+ import { inviteScope, sessionRole } from './sdkRekey.js'
3
3
  import { validUsername } from './address.js'
4
4
  import { EMAIL } from './memberChange.js'
5
5
  import { boxApp } from './attestedBox.js'
@@ -17,7 +17,7 @@ export async function resendInvitation(sp, { email, username } = {}) {
17
17
  try { attested = await client.attestedRoom(sp.room, sp._mk) } catch { throw fail('policy_unreadable', 'the device policy could not be read') }
18
18
  const cfg = await sp._gateConfig({ fresh: true, plainMark: true }) // the CURRENT roles: isAdmin / isOwner below read this copy (side sweep 2026-11-28: a cached one kept a demoted admin, refused a promoted one)
19
19
  if (cfg.admission === 'email') {
20
- if (!(await sp.isAdmin(wb._session.email)) && !(await sp.isOwner(wb._session.email))) throw fail('not_admin', 'only an owner or admin may resend an invitation')
20
+ if (!await sessionRole(sp, cfg, wb._session.email)) throw fail('not_admin', 'only an owner or admin may resend an invitation')
21
21
  }
22
22
  if (attested) {
23
23
  if ((sp._client && sp._client.keyless) || typeof client.verifyGovernance !== 'function') throw fail('attested', 'resend this invitation from the attested app that holds its key')
package/sdkPlan.js CHANGED
@@ -9,6 +9,7 @@
9
9
  // · CREATE-TIME — the tier, a split key, the tools the assistant may use and which run without approval: a new room
10
10
  // (`wb.createSpace`), and the SDK carries no history into it.
11
11
  // planChange() applies exactly those rules (the same functions configure() and fork() call) and changes nothing.
12
+ import { hasRoles, roleFor, rolesOf } from './roomRoles.js'
12
13
  import { planGovernance, normAdmission, forkConfig, checkAdminCollections } from './emailFork.js'
13
14
 
14
15
  const IN_PLACE_AGENT = ['name', 'instructions', 'model']
@@ -21,7 +22,7 @@ const RANK = { none: 0, in_place: 1, fork: 2, new_room: 3 }
21
22
  * @param room { cfg (the room's sealed config, or null), me (the signed-in email, or ''), lane (bool), checkData?(data) }
22
23
  * → { how: 'none'|'in_place'|'new_room'|'refused', history: 'kept'|'not_carried'|null, call, steps, reason? }
23
24
  */
24
- export function planChange (change = {}, { cfg = null, me = '', lane = false, activeLane = lane, checkData = null, gatedUnread = false, signIn = 'wb.signIn' } = {}) { // signIn: the call that signs in here ('wb.vault.signIn' in a vault) // gatedUnread: a gated room answered only its stub (not signed in)
25
+ export function planChange (change = {}, { cfg = null, me = '', role = roleFor(cfg, { email: me }), lane = false, activeLane = lane, checkData = null, gatedUnread = false, signIn = 'wb.signIn' } = {}) { // signIn: the call that signs in here ('wb.vault.signIn' in a vault) // gatedUnread: a gated room answered only its stub (not signed in)
25
26
  const steps = []
26
27
  let members = false // the change includes a member list (in place: space.changeMembers)
27
28
  let how = 'none', refusal = null
@@ -52,8 +53,8 @@ export function planChange (change = {}, { cfg = null, me = '', lane = false, ac
52
53
  if (gatedUnread && !cfg) refuse('sign_in_required', 'an email-gated room takes a change only from a signed-in member (' + signIn + ')')
53
54
  else if (cfg && cfg.ownerPolicy && !(cfg.ownerPolicy.policy && cfg.ownerPolicy.policy.app === 'chat.witbitz')) refuse('governed_room', 'an owner-governed room changes by fork-and-replay') // the sealed field is ownerPolicy (it read cfg.policy, which no config carries — sync sweep 2026-11-09); a room under Witbitz's own rule changes in place, as the server allows (spaceService op config)
54
55
  else if (cfg) {
55
- const gov = [...lower(cfg.admins), ...lower(cfg.owners)], email = String(me || '').toLowerCase()
56
- if (gov.length && !gov.includes(email)) refuse(email ? 'not_admin' : 'sign_in_required', email ? "only this room's admins can change the assistant" : 'a room with admins takes a change only from a signed-in admin (' + signIn + ')')
56
+ const email = String(me || '').toLowerCase()
57
+ if (hasRoles(cfg) && !role) refuse(email ? 'not_admin' : 'sign_in_required', email ? "only this room's admins can change the assistant" : 'a room with admins takes a change only from a signed-in admin (' + signIn + ')')
57
58
  else if (change.data !== undefined) { try { checkAdminCollections(change.data, cfg) } catch (e) { refuse(e.code || 'admins_required', String(e.message || e).replace(/^witbitz: /, '')) } }
58
59
  }
59
60
  }
@@ -74,14 +75,27 @@ export function planChange (change = {}, { cfg = null, me = '', lane = false, ac
74
75
  // the list (sdkRekey.js, sdk-people.md#members). A Space no longer moves, so a change that names a `history` is refused by name.
75
76
  if (change.history !== undefined) refuse('use_change_members', 'a Space no longer moves to a new room — its members change in place, history and all (space.changeMembers)')
76
77
  need('in_place'); members = true; steps.push('admission: changed in place — the same room and history, a new key that only the members on the list receive (space.changeMembers)')
77
- const admins = lower(cfg.admins), owners = lower(cfg.owners), email = String(me || '').toLowerCase()
78
+ const email = String(me || '').toLowerCase()
78
79
  if (!email) refuse('sign_in_required', 'a member change needs a signed-in member (' + signIn + ')')
79
- else if (!admins.length && !owners.length) refuse('not_admin', 'this Space has no owners or admins — only the Spaces app can change it (its creator)')
80
- else if ((admins.length || owners.length) && !admins.includes(email) && !owners.includes(email)) refuse('not_admin', "only this room's owners and admins change its members")
80
+ else if (!hasRoles(cfg)) refuse('not_admin', 'this Space has no owners or admins — only the Spaces app can change it (its creator)')
81
+ else if (!role) refuse('not_admin', "only this room's owners and admins change its members")
81
82
  else {
82
83
  // the same two checks space.fork() makes, in its order: governance, then an admins-only collection the
83
84
  // new room would keep with no admin or owner (emailFork.checkAdminCollections; sync sweep, 2026-10-10)
84
- try { planGovernance(cfg, gate, email, change.admission.admins !== undefined); const next = forkConfig(cfg, gate, ''); checkAdminCollections(next.dataSchema, next) } catch (e) { refuse(e.code || 'refused', String(e.message || e).replace(/^witbitz: /, '')) } }
85
+ try {
86
+ const old = rolesOf(cfg)
87
+ const ownerTags = change.admission.ownerTags ?? old.ownerTags, adminTags = change.admission.adminTags ?? old.adminTags
88
+ if (![ownerTags, adminTags].every(tags => Array.isArray(tags) && tags.every(t => typeof t === 'string' && t))) throw Object.assign(new Error('Role tags must be lists of room tags'), { code: 'invalid_argument' })
89
+ if (role !== 'owner' && (old.owners.length || old.ownerTags.length) &&
90
+ (ownerTags.length !== old.ownerTags.length || old.ownerTags.some(t => !ownerTags.includes(t)) || old.adminTags.some(t => !adminTags.includes(t) && !ownerTags.includes(t)))) {
91
+ throw Object.assign(new Error('Only an owner can change the owners or lower an admin'), { code: 'not_owner' })
92
+ }
93
+ planGovernance(cfg, gate, email, change.admission.admins !== undefined, role === 'owner')
94
+ const next = forkConfig(cfg, gate, '')
95
+ if (ownerTags.length) next.owners = { ...next.owners, tags: ownerTags }
96
+ if (adminTags.length) next.admins = { ...next.admins, tags: adminTags }
97
+ checkAdminCollections(next.dataSchema, next)
98
+ } catch (e) { refuse(e.code || 'refused', String(e.message || e).replace(/^witbitz: /, '')) } }
85
99
  }
86
100
  }
87
101
  }
@@ -92,5 +106,3 @@ export function planChange (change = {}, { cfg = null, me = '', lane = false, ac
92
106
  const call = how === 'in_place' ? (members ? (configures ? 'space.configure(…) and space.changeMembers(admission)' : 'space.changeMembers(admission)') : 'space.configure(…)') : how === 'new_room' ? 'wb.createSpace(…)' : null
93
107
  return { how, history, call, steps }
94
108
  }
95
-
96
- const lower = (g) => (g && Array.isArray(g.emails) ? g.emails.map((x) => String(x).toLowerCase()) : [])
package/sdkRekey.js CHANGED
@@ -14,13 +14,14 @@ import { checkInbox } from './inviteReceive.js' // collect(): the same reading o
14
14
  import { genRecipientKey, openBox, commit, combineShares } from './e2ee.js'
15
15
  import { tokenApp, tokenClaims } from './accountScope.js'
16
16
  import { GATE_DOMAIN } from './emailFork.js'
17
- import { EMAIL, normalizeDomains, lc, recipientsFor, membersAfter, unseenHidden, stillOnList, dropsForUsers } from './memberChange.js'
17
+ import { EMAIL, normalizeDomains, lc, hasOwnGrant, recipientsFor, membersAfter, unseenHidden, stillOnList, dropsForUsers } from './memberChange.js'
18
18
  import { ROSTER_DOC } from './roomRoster.js'
19
19
  import { hide } from './sdkRedact.js'
20
20
  import { assertNotKept } from './sdkCloudDevice.js'
21
21
  import { memberHash } from './rosterHash.js'
22
22
  import { preferredAddresses } from './addPreferred.js' // "Add me to Spaces as @username" (docs/spaces-usernames.md § 13)
23
23
  import { findInvitee } from './inviteSend.js'
24
+ import { rolesOf, roleFor, hasRoles, roleTagFor, roleTagHolders } from './roomRoles.js' // owners and admins by @username tag (docs/spaces-usernames.md § 13.1)
24
25
 
25
26
  const sdkError = (message, code) => Object.assign(new Error(message), { code })
26
27
 
@@ -119,6 +120,9 @@ export class InviteAccount {
119
120
  const client = wb && wb._client
120
121
  if (!client || typeof client.inboxFetch !== 'function') throw sdkError('witbitz: this client cannot read an invite inbox', 'unsupported')
121
122
  const out = []
123
+ // THE ACCOUNT THAT ASKED (sync sweep 11-29 #2): a sign-out or switch during the read must not hand the previous account's links on
124
+ const whoNow = () => { const s = wb._session; return s && s.email ? lc(s.email) + '|' + inviteScope(s.idToken) : '' }
125
+ const asked = whoNow()
122
126
  // a fetch that rejects before any answer is `unreachable` too, as the types say (side sweep: sdk-invite-collection-network-error)
123
127
  const n = await checkInbox({ client, inviteKey: k, onInvite: (inv) => {
124
128
  if (inv.kind || !inv.room) return false // an attested room's: its native app takes it
@@ -129,6 +133,7 @@ export class InviteAccount {
129
133
  out.push({ room: String(inv.room), link, title: typeof inv.title === 'string' ? inv.title.slice(0, 200) : '', from: typeof inv.from === 'string' ? inv.from.slice(0, 320) : '', at: Math.min(Number(inv.at) || 0, Date.now()) })
130
134
  return true
131
135
  } }).catch(() => -1)
136
+ if (whoNow() !== asked || this._key() !== k) throw sdkError('witbitz: the account changed while collecting invitations', 'account_changed')
132
137
  if (n < 0) throw sdkError('witbitz: the invite inbox could not be read', 'unreachable')
133
138
  const seen = new Set()
134
139
  return out.sort((a, b) => b.at - a.at).filter((x) => !seen.has(x.room) && seen.add(x.room)) // the newest invitation per room
@@ -239,7 +244,18 @@ async function currentMembers (space, cfg) {
239
244
  const onList = await stillOnList(cfg, space.room, Object.values(book.seen || {}).filter((x) => x && x.email && !x.left)).catch(() => null) // the records: a person in by @username is on by the entry they came in by (sync sweep 11-23 #2)
240
245
  const seen = onList ? seen0.filter((e) => onList(e, '')) : seen0
241
246
  const emails = [...new Set([...(Array.isArray(al.emails) ? al.emails : []), ...seen].map(lc))]
242
- return { book, emails, owners: ((cfg.owners && cfg.owners.emails) || []).map(lc), admins: ((cfg.admins && cfg.admins.emails) || []).map(lc) }
247
+ const rt = rolesOf(cfg) // ownerTags/adminTags: the roles held by @username tag (§ 13.1) — a change that does not touch them carries them
248
+ return { book, emails, owners: ((cfg.owners && cfg.owners.emails) || []).map(lc), admins: ((cfg.admins && cfg.admins.emails) || []).map(lc), ownerTags: rt.ownerTags, adminTags: rt.adminTags }
249
+ }
250
+
251
+ /** This session's tag for the Space (its @username's, op user mode tag) — a role it holds by its tag (§ 13.1). → [tag] | [] */
252
+ async function ownTags (space) {
253
+ const wb = space._wb
254
+ const w = wb && wb.usernames ? await wb.usernames.mine().catch(() => null) : null
255
+ if (!w || !w.username) return []
256
+ const c = (wb && wb._client) || space._client
257
+ const t = typeof c.userTag === 'function' ? await c.userTag(w.username, space.room).catch(() => null) : null
258
+ return t && t.status === 200 && typeof t.tag === 'string' && t.tag ? [t.tag] : []
243
259
  }
244
260
 
245
261
  const epochOf = (cfg) => (Array.isArray(cfg && cfg.keyChain) ? cfg.keyChain.length : 0) // the epoch a config was read at (= the app's rekeyToWant)
@@ -255,7 +271,7 @@ async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null,
255
271
  (domains.has(lc(p.email).split('@')[1]) || p.entries?.some(e => typeof e === 'string' && e.startsWith('u:')))).map(p => lc(p.email))
256
272
  const found = await recipientsFor(space.room, [...stay, ...joined], wb._client || space._client, { scope, allow: allowAfter, people }) // include observed retained legacy handles, never arbitrary roster emails
257
273
  const recipients = [...found.recipients, ...extra.filter((x) => !found.recipients.some((r) => r.mh === x.mh))], { unreachable, pending } = found
258
- if (!recipients.some((x) => x.email === me)) throw sdkError('witbitz: this account has no invite key for this app yet (wb.invite.status: ' + wb.invite.status + ') — restore wb.invite.state from the device that has it', 'no_invite_key')
274
+ if (!await hasOwnGrant(recipients, space.room, me, () => ownTags(space))) throw sdkError('witbitz: this account has no invite key for this app yet (wb.invite.status: ' + wb.invite.status + ') — restore wb.invite.state from the device that has it', 'no_invite_key')
259
275
  const split = space._split ? { userShare: fragParam(space.shareLink, 'us') } : null
260
276
  if (space._split && !split.userShare) throw sdkError('witbitz: this split Space was not opened from its link — its user half is unknown here', 'invalid_argument')
261
277
  const r = await space._client.rekey(space.room, space._mk, { ...(members ? { members } : {}), recipients: recipients.map(({ mh, boxPub }) => ({ mh, boxPub })), pending: [...pending, ...unseenHidden(allowAfter, recipients, pending)], by: me, ...(split ? { split } : {}), ...(Number.isInteger(expectEpoch) ? { expectEpoch } : {}) }).catch(() => null) // ONE SNAPSHOT (docs/state-machines.md V#5, the SDK's twin K#1): the change was planned at this epoch — a key adopted on the way (the healing client's retry) must not apply it to another
@@ -268,6 +284,15 @@ async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null,
268
284
  return { epoch: r.epoch, unreachable: unreachable.filter((e) => e !== me) }
269
285
  }
270
286
 
287
+ export async function sessionRole(space, cfg, email = space._wb?._session?.email) {
288
+ if (!email) return ''
289
+ const direct = roleFor(cfg, { email })
290
+ if (direct === 'owner') return direct
291
+ const roles = rolesOf(cfg)
292
+ if (!roles.ownerTags.length && !roles.adminTags.length) return direct
293
+ return roleFor(cfg, { email, tags: await ownTags(space) })
294
+ }
295
+
271
296
  /** May this session change this Space (`what`: 'changeMembers' | 'rotateKey')? Throws the refusal; → { cfg, me }. Exported so a
272
297
  * vault checks BEFORE it asks the person (sweep 10-23 #21). */
273
298
  export async function changeable (space, what) {
@@ -284,9 +309,9 @@ export async function changeable (space, what) {
284
309
  if (!cfg) throw sdkError(`witbitz: couldn’t read this Space’s members — try ${what} again shortly`, 'config_unavailable')
285
310
  if (cfg.admission !== 'email') throw sdkError(`witbitz: only an email-gated Space changes ${what === 'rotateKey' ? 'its key' : 'its members'}`, 'invalid_argument')
286
311
  const me = lc(wb._session.email)
287
- const owners = ((cfg.owners && cfg.owners.emails) || []).map(lc), admins = ((cfg.admins && cfg.admins.emails) || []).map(lc)
288
- if (!owners.length && !admins.length) throw sdkError('witbitz: this Space has no owners or admins — only the Spaces app can change it (its creator)', 'not_admin')
289
- if (!owners.includes(me) && !admins.includes(me)) throw sdkError('witbitz: only an owner or an admin changes this Space', 'not_admin')
312
+ if (!hasRoles(cfg)) throw sdkError('witbitz: this Space has no owners or admins — only the Spaces app can change it (its creator)', 'not_admin')
313
+ // a role held by this account's @username tag (§ 13.1) counts as one held by its email
314
+ if (!await sessionRole(space, cfg, me)) throw sdkError('witbitz: only an owner or an admin changes this Space', 'not_admin')
290
315
  return { cfg, me }
291
316
  }
292
317
 
@@ -356,6 +381,36 @@ export async function planMembers (space, admission = {}, cfg = null) {
356
381
  want[role] = retained
357
382
  }
358
383
  }
384
+ // ROLES BY @USERNAME TAG (docs/spaces-usernames.md § 13.1; the owner, 2026-11-29). `admission.ownerTags` / `adminTags` (members()'s) state
385
+ // them in full; unstated, the room's are kept — but where `owners` / `admins` are stated, a tag whose holder the guest book names by an
386
+ // email left out of that list is dropped (lowered), and an email stated for someone who holds the role by tag stays their tag.
387
+ const roleTags = [...cur.ownerTags, ...cur.adminTags, ...(Array.isArray(admission.ownerTags) ? admission.ownerTags : []), ...(Array.isArray(admission.adminTags) ? admission.adminTags : [])]
388
+ const held = roleTags.length ? await roleTagHolders(Object.values((cur.book && cur.book.seen) || {}), roleTags, { room: space.room, userTag: typeof c.userTag === 'function' ? (n, r) => c.userTag(n, r) : null }) : new Map()
389
+ const holderEmail = (t) => (held.get(t) && held.get(t).email) || ''
390
+ const roleUsers = Object.fromEntries([...held].filter(([, h]) => h.user).map(([t, h]) => [t, h.user]))
391
+ const tagWant = {}
392
+ for (const [role, key] of [['owners', 'ownerTags'], ['admins', 'adminTags']]) {
393
+ if (admission[key] !== undefined) {
394
+ if (!Array.isArray(admission[key]) || admission[key].some((t) => typeof t !== 'string' || !t)) throw sdkError(`witbitz: admission.${key} is a list of the tags members() reports`, 'invalid_argument')
395
+ tagWant[key] = [...new Set(admission[key])]
396
+ } else if (Array.isArray(admission[role])) { const stated = new Set(want[role]); tagWant[key] = cur[key].filter((t) => { const e = holderEmail(t); return !e || stated.has(e) }) } else tagWant[key] = [...cur[key]]
397
+ const byTag = new Set(tagWant[key].map(holderEmail).filter(Boolean))
398
+ want[role] = want[role].filter((e) => !byTag.has(e))
399
+ }
400
+ // SOMEONE MADE AN OWNER OR ADMIN NOW, as they prefer: by the room's tag for their @username (the email door names it, only where "find
401
+ // me by email" is on), once the server takes tag roles (roleTagFor: `roles: true`); otherwise by the email, as before.
402
+ {
403
+ const granted = [...want.owners.filter((e) => !cur.owners.includes(e)).map((e) => ['owners', e]), ...want.admins.filter((e) => !cur.admins.includes(e) && !cur.owners.includes(e) && !want.owners.includes(e)).map((e) => ['admins', e])]
404
+ const pref = granted.length ? await preferredAddresses([...new Set(granted.map(([, e]) => e))], { client: c }).catch(() => null) : null
405
+ for (const { email, username } of (pref && pref.learned) || []) {
406
+ const t = await roleTagFor(c, username, space.room)
407
+ if (!t) continue
408
+ roleUsers[t] = username
409
+ for (const [role, e] of granted) if (e === email) { want[role] = want[role].filter((x) => x !== email); tagWant[role === 'owners' ? 'ownerTags' : 'adminTags'].push(t) }
410
+ }
411
+ }
412
+ want.ownerTags = [...new Set(tagWant.ownerTags)]
413
+ want.adminTags = [...new Set(tagWant.adminTags)].filter((t) => !want.ownerTags.includes(t))
359
414
  // HOW A NEW MEMBER IS ADDED IS THEIR PREFERENCE (docs/spaces-usernames.md § 13; owner, 2026-11-29): an address NEW to the list
360
415
  // (not shown, not a manager, not yours) whose person prefers their @username — the email door names it, only where "find me by
361
416
  // email" is on — goes on the list as the room's TAG for that name: the other members never get the email. Its grant is sealed at
@@ -380,6 +435,8 @@ export async function planMembers (space, admission = {}, cfg = null) {
380
435
  }
381
436
  const m0 = await listAfter(cfg, space.room, { ...want, known: cur.emails }, { book: () => cur.book, tagOf })
382
437
  const m = asUsers.length ? { ...m0, allow: { ...m0.allow, mh: [...new Set([...(Array.isArray(m0.allow.mh) ? m0.allow.mh : []), ...asUsers.map((x) => x.tag)])] } } : m0
438
+ // a STATED role tag is one admission() reported (a role held now) or a tag on the new list — anything else names nobody, refused, never written
439
+ { const known = new Set([...(Array.isArray(m.allow.mh) ? m.allow.mh : []), ...cur.ownerTags, ...cur.adminTags]); const stray = [...(Array.isArray(admission.ownerTags) ? admission.ownerTags : []), ...(Array.isArray(admission.adminTags) ? admission.adminTags : [])].find((t) => !known.has(t)); if (stray) throw sdkError('witbitz: a role tag must be one admission() reports, or name someone on the list (' + String(stray).slice(0, 8) + '…)', 'invalid_argument') }
383
440
  // ⛔ NOT YOURSELF, SILENTLY (second review, 2026-11-27): a manager the new list does not admit is dropped (545f3a97f, so a role cannot
384
441
  // admit anyone) — a manager who leaves THEIR OWN address off the whole list would lose the Space with no word. Refused by name
385
442
  // instead: they add it, or leave the Space. Asked of the change itself (`m.removed`), so a manager who stays by a domain, a
@@ -388,7 +445,7 @@ export async function planMembers (space, admission = {}, cfg = null) {
388
445
  if (actor && (cur.owners.includes(actor) || cur.admins.includes(actor)) && (m.removed || []).map(lc).includes(actor)) {
389
446
  throw sdkError('witbitz: your own address is not on the new list — add it, or leave the Space instead', 'invalid_argument')
390
447
  }
391
- return { emails, cur, want, m, asUsers, epoch: epochOf(cfg), actor: lc(space._wb?._session?.email), roles: !asUsers.length && !m.removed.length && sameList(cfg.allow, m.allow) }
448
+ return { emails, cur, want, m, asUsers, roleUsers, epoch: epochOf(cfg), actor: lc(space._wb?._session?.email), roles: !asUsers.length && !m.removed.length && sameList(cfg.allow, m.allow) }
392
449
  }
393
450
 
394
451
  /** space.changeMembers(admission) — `admission`: { emails, domains?, admins?, owners?, advertise? }, the list stated in FULL,
package/sdkVault.js CHANGED
@@ -152,7 +152,7 @@ function openTransport(win, origin, helloMs) {
152
152
  signOut: () => call('signOut'),
153
153
  userToken: (t) => call('userToken', t), // per-user billing: the page's current token, handed over before an op that can spend
154
154
  enclaveAvailable: () => call('enclaveAvailable'),
155
- whoami: () => call('whoami'),
155
+ whoami: (...args) => call('whoami', ...args),
156
156
  lockSettings: () => call('lockSettings'), // the vault's lock sheet (a vault started with `lock: true`): the person decides there; the page learns { available, on, protect }
157
157
  notifications: () => call('notifications'), // the vault's notifications card (`push: true`): the person decides; the page learns { available, on }
158
158
  forget: (room) => call('forget', room),
package/spaceClient.js CHANGED
@@ -31,6 +31,7 @@ import { verifyRoomGovernance } from './ownerPolicy.js'
31
31
  import { staysDirect } from './roomName.js' // a direct chat that gains a third member is a group (rekey)
32
32
  import { stageMirrorAttachments } from './mirrorBatch.js'
33
33
  import { memberHash } from './rosterHash.js' // hash the email allow-list (room-bound) before sealing → co-members can't read addresses
34
+ import { roleOf } from './roomRoles.js' // owners and admins by email or @username tag (docs/spaces-usernames.md § 13.1)
34
35
 
35
36
  async function directRoster(allow, room) {
36
37
  if (!Array.isArray(allow?.emails) || !Array.isArray(allow?.mh) || !allow.mh.length) return allow
@@ -106,8 +107,8 @@ const sealConfig = async (config, mk) =>
106
107
  // (spaceService hasAdmins/isRoomAdmin/cardNeedsAdmin) — and were MISSING from this list, so an SDK room declared them
107
108
  // and sealed without them: no admins, approvals by any member (a builder measured it on production). `forkedFrom` is
108
109
  // where a fork came from; `connections` are the grants a fork carries. Undefined ⇒ dropped ⇒ sealed exactly as before.
109
- admins: config.admins && Array.isArray(config.admins.emails) ? { emails: config.admins.emails.map((x) => String(x).toLowerCase()) } : undefined,
110
- owners: config.owners && Array.isArray(config.owners.emails) ? { emails: config.owners.emails.map((x) => String(x).toLowerCase()) } : undefined, // OWNERS (2026-10-03): above admins, enforced by the room
110
+ admins: config.admins && Array.isArray(config.admins.emails) ? roleOf(config.admins.emails, config.admins.tags) : undefined, // tags: an admin by @username tag (docs/spaces-usernames.md § 13.1)
111
+ owners: config.owners && Array.isArray(config.owners.emails) ? roleOf(config.owners.emails, config.owners.tags) : undefined, // OWNERS (2026-10-03): above admins, enforced by the room
111
112
  forkedFrom: typeof config.forkedFrom === 'string' && config.forkedFrom ? config.forkedFrom.slice(0, 120) : undefined,
112
113
  connections: Array.isArray(config.connections) && config.connections.length ? config.connections : undefined,
113
114
  direct: config.direct === true ? true : undefined, // a DIRECT chat (directChat.js): the server refuses its rename, the other side files it by this
@@ -1448,7 +1449,9 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1448
1449
  if ('platformTools' in p) next.platformTools = p.platformTools === false || Array.isArray(p.platformTools) ? p.platformTools : undefined // which platform tools the assistant gets; null/true = all again
1449
1450
  if ('framing' in p) next.framing = p.framing === 'builder' ? 'builder' : undefined // builder mode: the app's prompt only; null = the Spaces framing again
1450
1451
  // WHO RUNS IT (a role change in place — no new key; the server checks who may: agent/roomRekey.mayChangeRoles)
1451
- for (const k of ['admins', 'owners']) if (k in p) next[k] = { emails: [...new Set(((p[k] && p[k].emails) || []).map((e) => String(e).trim().toLowerCase()).filter(Boolean))] }
1452
+ // a role names emails and @username tags (docs/spaces-usernames.md § 13.1): `tags` stated → those; unstated → the room's kept (a caller
1453
+ // that knows only emails never drops a role held by a tag)
1454
+ for (const k of ['admins', 'owners']) if (k in p) { const tags = p[k] && Array.isArray(p[k].tags) ? p[k].tags : (cur[k] && Array.isArray(cur[k].tags) ? cur[k].tags : []); next[k] = roleOf((p[k] && p[k].emails) || [], tags) }
1452
1455
  if ('lanes' in p) next.lanes = p.lanes === true // "Private assistants" off (or on) in place (docs/always-on-agent-plan.md Phase 0b)
1453
1456
  if ('dataWrites' in p) next.dataWrites = p.dataWrites === false ? false : undefined // false = data_query only; null/true = writes offered again
1454
1457
  if ('safeMedia' in p) next.safeMedia = p.safeMedia === true ? true : undefined // SAFE MEDIA on/off (docs/safe-media.md): the admins', any member's where there are none
@@ -1473,7 +1476,8 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1473
1476
  // builder's half and its seal stay as they are. The grants carry userShare' (never mk'); the answer carries newShare.
1474
1477
  rekey: async (room, mk, { members = null, recipients = [], pending = [], by = '', split = null, creatorPriv = null, link = null, expectEpoch: wantEpoch = null } = {}) => { // link: { roster, gk } — a LINK Space (linkMembers.js): its roster and new invite key; recipients then carry `id` (keyGrantId) and `extra` (their fresh gk grant)
1475
1478
  const r = await policyPost(room, mk)
1476
- if (!r || r.status !== 200 || !r.configSealed) return { status: (r && r.status) || 502, error: (r && r.error) || 'policy_unavailable' }
1479
+ if (!r || r.status !== 200) return { status: (r && r.status) || 502, error: (r && r.error) || 'policy_unavailable' }
1480
+ if (!r.configSealed) return { status: 502, error: 'policy_unavailable' }
1477
1481
  let cur = null
1478
1482
  try { cur = JSON.parse((await open(JSON.parse(r.configSealed), { mk })) || 'null') } catch { cur = null }
1479
1483
  if (!cur || typeof cur !== 'object') return { status: 409, error: 'config_unreadable' }
package/util.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // util.js — pure, dep-free leaf helpers (Verified-Client Phase 1). The DOM lookup ($) and formatters,
2
2
  // imported by space.js and (going forward) every extracted TCB module, so they need no rewiring.
3
3
 
4
- import { env } from './env.js' // leaf: is this frame the vault's (saveTextFile)
4
+ import { env, isIOS, nativePlatform } from './env.js' // leaf: is this frame the vault's (saveTextFile)
5
5
  import { attachSheetChrome, BACK_SVG, X_SVG } from './sheetChrome.js' // the one chrome every sheet gets: handle, ✕, pull-down, scrim tap, Escape
6
6
 
7
7
  export const $ = (id) => document.getElementById(id)
@@ -178,4 +178,14 @@ export const entryKey = entryKeyOf // ledgerView.js — the SDK keys reactions a
178
178
  // focus"). iOS ignores a focus that runs outside the tap (a timer, after a load); Android raises the keyboard for it. A
179
179
  // focus made INSIDE a tap (Reply, Rename, the search icon) is the person asking to type and stays as it is.
180
180
  export const hasMouse = () => { try { return matchMedia('(hover:hover) and (pointer:fine)').matches } catch { return false } }
181
+ // Cards follow the desktop shell even when its window is snapped or its only input is touch.
182
+ // In a browser, a mouse gets the desktop layout. Other devices retain each sheet's responsive CSS.
183
+ export function configureDesktopDialogs () {
184
+ const platform = nativePlatform()
185
+ const desktop = platform ? ['windows', 'macos', 'linux'].includes(platform) : hasMouse() && !isIOS() && !/Android/.test(navigator.userAgent)
186
+ if (!desktop) return
187
+ document.documentElement.classList.add('desktop-dialogs')
188
+ for (const style of document.querySelectorAll('style[data-desktop-dialogs]')) style.media = 'all'
189
+ for (const style of document.querySelectorAll('style[data-phone-dialogs]')) style.media = 'not all'
190
+ }
181
191
  export function focusIfMouse(el) { if (el && hasMouse()) { try { el.focus() } catch { /* a nicety */ } } }