@witbitz/sdk 4.7.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/sdkRekey.js CHANGED
@@ -14,7 +14,7 @@ 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'
@@ -271,7 +271,7 @@ async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null,
271
271
  (domains.has(lc(p.email).split('@')[1]) || p.entries?.some(e => typeof e === 'string' && e.startsWith('u:')))).map(p => lc(p.email))
272
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
273
273
  const recipients = [...found.recipients, ...extra.filter((x) => !found.recipients.some((r) => r.mh === x.mh))], { unreachable, pending } = found
274
- 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')
275
275
  const split = space._split ? { userShare: fragParam(space.shareLink, 'us') } : null
276
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')
277
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
@@ -284,6 +284,15 @@ async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null,
284
284
  return { epoch: r.epoch, unreachable: unreachable.filter((e) => e !== me) }
285
285
  }
286
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
+
287
296
  /** May this session change this Space (`what`: 'changeMembers' | 'rotateKey')? Throws the refusal; → { cfg, me }. Exported so a
288
297
  * vault checks BEFORE it asks the person (sweep 10-23 #21). */
289
298
  export async function changeable (space, what) {
@@ -302,9 +311,7 @@ export async function changeable (space, what) {
302
311
  const me = lc(wb._session.email)
303
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')
304
313
  // a role held by this account's @username tag (§ 13.1) counts as one held by its email
305
- const rt = rolesOf(cfg)
306
- const tags = !roleFor(cfg, { email: me }) && (rt.ownerTags.length || rt.adminTags.length) ? await ownTags(space) : []
307
- if (!roleFor(cfg, { email: me, tags })) throw sdkError('witbitz: only an owner or an admin changes this Space', 'not_admin')
314
+ if (!await sessionRole(space, cfg, me)) throw sdkError('witbitz: only an owner or an admin changes this Space', 'not_admin')
308
315
  return { cfg, me }
309
316
  }
310
317
 
@@ -377,8 +384,10 @@ export async function planMembers (space, admission = {}, cfg = null) {
377
384
  // ROLES BY @USERNAME TAG (docs/spaces-usernames.md § 13.1; the owner, 2026-11-29). `admission.ownerTags` / `adminTags` (members()'s) state
378
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
379
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.
380
- const held = (cur.ownerTags.length || cur.adminTags.length) ? await roleTagHolders(Object.values((cur.book && cur.book.seen) || {}), [...cur.ownerTags, ...cur.adminTags], { room: space.room, userTag: typeof c.userTag === 'function' ? (n, r) => c.userTag(n, r) : null }) : new Map()
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()
381
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]))
382
391
  const tagWant = {}
383
392
  for (const [role, key] of [['owners', 'ownerTags'], ['admins', 'adminTags']]) {
384
393
  if (admission[key] !== undefined) {
@@ -396,6 +405,7 @@ export async function planMembers (space, admission = {}, cfg = null) {
396
405
  for (const { email, username } of (pref && pref.learned) || []) {
397
406
  const t = await roleTagFor(c, username, space.room)
398
407
  if (!t) continue
408
+ roleUsers[t] = username
399
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) }
400
410
  }
401
411
  }
@@ -435,7 +445,7 @@ export async function planMembers (space, admission = {}, cfg = null) {
435
445
  if (actor && (cur.owners.includes(actor) || cur.admins.includes(actor)) && (m.removed || []).map(lc).includes(actor)) {
436
446
  throw sdkError('witbitz: your own address is not on the new list — add it, or leave the Space instead', 'invalid_argument')
437
447
  }
438
- 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) }
439
449
  }
440
450
 
441
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
@@ -1476,7 +1476,8 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1476
1476
  // builder's half and its seal stay as they are. The grants carry userShare' (never mk'); the answer carries newShare.
1477
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)
1478
1478
  const r = await policyPost(room, mk)
1479
- 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' }
1480
1481
  let cur = null
1481
1482
  try { cur = JSON.parse((await open(JSON.parse(r.configSealed), { mk })) || 'null') } catch { cur = null }
1482
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 */ } } }
package/vault-core.js CHANGED
@@ -22,7 +22,7 @@ import { routingIndex } from './opRouting.js'
22
22
  import { memberHash } from './rosterHash.js'
23
23
  import { Witbitz, Space, Lane } from './witbitz-sdk.js'
24
24
  import { LaneA2A, assertAgentTarget } from './sdkA2A.js'
25
- import { openGrant, relink, changeMembers, rotateKey, changeable, planMembers } from './sdkRekey.js' // a Space's members changed in place (https://witbitz.chat/docs/sdk-people.md#members)
25
+ import { openGrant, relink, changeMembers, rotateKey, changeable, planMembers, sessionRole } from './sdkRekey.js' // a Space's members changed in place (https://witbitz.chat/docs/sdk-people.md#members)
26
26
  import { setPendingKeyStore } from './connections.js' // the SDK's pending-key store (N#7): this vault's
27
27
  import { adoptPendingKeys } from './connPending.js'
28
28
  import { idb } from './idb.js'
@@ -34,6 +34,7 @@ import { liveLocks } from './chatLock.js'
34
34
  import { openItem, cardUrlOf, mcpUrlOf } from './a2aCore.js'
35
35
  import { judgeMove, checkNewRoomGov } from './emailFork.js'
36
36
  import { ROSTER_DOC, selfRow, ensureSelf, unseenIn, entriesMissing, announcedIn } from './roomRoster.js'
37
+ import { signedInRoomTags } from './roomRoles.js'
37
38
  import { findEmptySpaces, removeEmptySpaces, ownAdmissionEntries } from './emptySpaces.js'
38
39
  import { readAllPages } from './ledgerView.js'
39
40
  import { commit as keyCommit } from './e2ee.js'
@@ -57,6 +58,17 @@ export const VAULT_PROTOCOL = 1
57
58
  // cross-room), subscribe/unsubscribe (push belongs to the vault), and the intake ops (the account's). Sealed exports and supported chat imports are allowed.
58
59
  // (no 'safeCopy': a safe copy is made only where the sign-in and the key are — space.safeMedia.make is refused in a vault, and
59
60
  // nothing in vault mode posts one; sync sweep backlog P7)
61
+ export function roleSummary(emails, tags, roleUsers) {
62
+ const labels = [...emails]
63
+ let unknown = 0
64
+ for (const tag of tags || []) {
65
+ if (Object.hasOwn(roleUsers, tag)) labels.push('@' + roleUsers[tag])
66
+ else unknown++
67
+ }
68
+ if (unknown) labels.push(unknown + (unknown === 1 ? ' unidentified member' : ' unidentified members'))
69
+ return labels.join(', ') || 'none'
70
+ }
71
+
60
72
  export const PAGE_OPS = new Set(['poll', 'pollSealed', 'turn', 'state', 'data', 'title', 'decide', 'pending', 'mirror', 'toolResult', 'getConfig', 'setConfig', 'blob', 'react', 'mark', 'sealed', 'exportSealed', 'stop', 'toolRules', 'importChat', 'importWhatsApp'])
61
73
  const KEYS = { rooms: 'wbvault:rooms', session: 'wbvault:session', siri: 'wbvault:siri', a2a: 'wbvault:a2a', invite: 'wbvault:invite', connections: 'wbvault:connections', backup: 'wbvault:backup', keep: 'wbvault:keep', connPending: 'wbvault:connPending', connGone: 'wbvault:connGone', pendingForget: 'wbvault:pendingForget', pendingGrants: 'wbvault:pendingGrants' }
62
74
  // THE ACCOUNT, through the vault's session (docs/sdk-vault-mode.md § The account). The page asks; the vault runs it on its
@@ -82,7 +94,7 @@ export const ACCOUNT_CALLS = {
82
94
  /** The backup calls that need an account on the Witbitz account service (sync sweep 11-16 #15). */
83
95
  const SERVICE_CALLS = new Set(['manageSecurityKeys', 'signOutOthers', 'newRecoveryCode', 'emailMove', 'requestMoveTime', 'cancelEmailMove'])
84
96
  export const ROOM_ACCOUNT_CALLS = {
85
- roster: { list: {}, admission: {} },
97
+ roster: { list: {}, admission: {}, isOwner: {}, isAdmin: {}, sessionRole: {} },
86
98
  portable: { export: { confirm: true } },
87
99
  privateRoom: { link: { confirm: true }, unlink: { confirm: true } },
88
100
  keptAgent: { link: { confirm: true }, unlink: { confirm: true } },
@@ -1074,8 +1086,8 @@ export async function startVault(o = {}) {
1074
1086
  const summary = plan ? [
1075
1087
  'Members: ' + plan.emails.join(', '),
1076
1088
  'Domains: ' + ((plan.m.allow.domains || []).join(', ') || 'none'),
1077
- 'Owners: ' + (plan.want.owners.join(', ') || 'none'),
1078
- 'Admins: ' + (plan.want.admins.join(', ') || 'none'),
1089
+ 'Owners: ' + roleSummary(plan.want.owners, plan.want.ownerTags, plan.roleUsers),
1090
+ 'Admins: ' + roleSummary(plan.want.admins, plan.want.adminTags, plan.roleUsers),
1079
1091
  ...(plan.m.allow.users?.length ? ['Usernames: ' + plan.m.allow.users.map(u => u.handle).join(', ')] : []),
1080
1092
  ...(plan.m.allow.mh?.length ? ['Private membership entries: ' + plan.m.allow.mh.length] : []),
1081
1093
  ].join('\n') : ''
@@ -1191,7 +1203,7 @@ export async function startVault(o = {}) {
1191
1203
  'backup.newRecoveryCode': { title: 'Make a new recovery code?', text: 'Your current code stops working, and every other device is signed out. We email you a code to confirm, then show the new recovery code once.', ok: 'New code' },
1192
1204
  // a move already under way resumes in ITS saved mode, whatever this call asks (sdkBackupV2.js migrate) — the words say what it will do
1193
1205
  // (side sweep 2026-11-28: a resumed emailed-code move promised that devices could join, then signed them out)
1194
- 'backup.migrate': (sdk.backup._s?.v2?.moving ? (sdk.backup._s.v2.moveMode === 'signed' || sdk.backup._s.v2.svc?.silent === 'moved') : a?.silent === true) ? { title: 'Move this account with its signing key?', text: 'Your Spaces and recovery code stay the same. Other eligible devices can join using their existing account keys.', ok: 'Move account' } : { title: 'Move to the new account service?', text: 'Your Spaces and recovery code stay the same. Other devices are signed out and can restore on the new service. This legacy backup has no account key, so it moves with email-only trust; Advanced Backup remains unavailable.', ok: 'Move account' },
1206
+ 'backup.migrate': (sdk.backup._s?.v2?.moving ? (sdk.backup._s.v2.moveMode === 'signed' || sdk.backup._s.v2.svc?.silent === 'moved') : a?.silent === true) ? { title: 'Move this account with its signing key?', text: 'Your Spaces and recovery code stay the same. Other eligible devices can join using their existing account keys.', ok: 'Move account' } : { title: 'Move to the new account service?', text: 'Your Spaces and recovery code stay the same. Other devices are signed out and can restore on the new service. This legacy backup has no account key, so it moves using email alone. After the move, you can enroll security keys if Advanced Backup is available on this service.', ok: 'Move account' },
1195
1207
  'cloudDevice.enroll': { title: 'Sign the cloud device in?', text: 'We email a code so this secure cloud device can sign in to this app’s account. No Space is handed over yet.', ok: 'Send code' },
1196
1208
  'cloudDevice.register': { title: 'Add the cloud device to your account?', text: 'Register its public device key on the account service. You can sign it out later from Your devices. We email a code to confirm.', ok: 'Add device' },
1197
1209
  'cloudDevice.setBuilds': { title: 'Update the cloud device’s secure builds?', text: 'The cloud device will follow this account’s accepted secure-build list and automatic-acceptance choice.', ok: 'Update' },
@@ -1735,7 +1747,7 @@ export async function startVault(o = {}) {
1735
1747
  const config = await wop('getConfig', room, { plainMark: true })
1736
1748
  if (epoch === privacyEpoch && held(room) && (config?.help || config?.lane || config?.bridge)) return { excluded: true }
1737
1749
  const history = await readAllPages(since => wop('poll', room, undefined, since))
1738
- return epoch === privacyEpoch && held(room) && config && !config.help && !config.lane && !config.bridge && history.status === 200 && !history.incomplete ? { config, entries: history.entries, etag: history.etag, selfEntries: await ownAdmissionEntries(config, signedIn() && sdk.session.email, () => wop('state', room, ROSTER_DOC)), selfHash: signedIn() ? await memberHash(sdk.session.email, room) : null } : null
1750
+ return epoch === privacyEpoch && held(room) && config && !config.help && !config.lane && !config.bridge && history.status === 200 && !history.incomplete ? { config, entries: history.entries, etag: history.etag, selfEntries: await ownAdmissionEntries(config, signedIn() && sdk.session.email, () => wop('state', room, ROSTER_DOC), () => signedInRoomTags(sdk._client, room, sdk.session?.idToken)), selfHash: signedIn() ? await memberHash(sdk.session.email, room) : null } : null
1739
1751
  },
1740
1752
  forget: async room => { if (epoch === privacyEpoch && held(room)) { await base.forget(room); await dropRoom(room) } },
1741
1753
  }
@@ -1933,6 +1945,8 @@ export async function startVault(o = {}) {
1933
1945
  if (ns === 'a2a') return laneA2A(room, m, args)
1934
1946
  const sp = roomSpace(room)
1935
1947
  try {
1948
+ if (ns === 'roster' && m === 'sessionRole') return sessionRole(sp, await sp._gateConfig({ fresh: true, plainMark: true }))
1949
+ if (ns === 'roster' && (m === 'isOwner' || m === 'isAdmin')) return sp[m](args[0])
1936
1950
  if (ns === 'roster') return await (m === 'list' ? sp.roster() : sp.admission())
1937
1951
  if (ns === 'portable') {
1938
1952
  const { saveRoomExport } = await import('./sdkExports.js')
@@ -2148,7 +2162,9 @@ export async function startVault(o = {}) {
2148
2162
  if (op === 'getConfig') r = configForPage(r)
2149
2163
  if ((op === 'poll' || op === 'pollSealed') && r?.streamGrants) { const { streamGrants: _grants, ...visible } = r; r = visible }
2150
2164
  const lanes = op === 'getConfig' ? r && r.lanes : op === 'setConfig' && r && r.status === 200 && args[0] ? args[0].lanes : undefined
2151
- if (op === 'setConfig' && lanes === false) await disconnectRoomLanes(sdk, room)
2165
+ if (lanes === false && (op === 'setConfig' || sdk._heldLaneRooms(room).length ||
2166
+ sdk.backup.rooms.some(r => r.kind === 'lane' && r.shared === room) ||
2167
+ sdk.account.links.some(l => l.a === room || l.b === room))) await disconnectRoomLanes(sdk, room)
2152
2168
  if (typeof lanes === 'boolean') {
2153
2169
  const it = rooms.find((x) => x.room === room)
2154
2170
  if (it && it.link) { const url = new URL(it.link); url.searchParams.delete('lanes'); const hash = new URLSearchParams(url.hash.slice(1)); if (lanes) hash.set('lanes', '1'); else hash.delete('lanes'); url.hash = hash.toString(); const link = url.href; if (link !== it.link) { it.link = link; await saveRooms(); emit({ ev: 'rooms', rooms: publicRooms() }) } }
@@ -2157,13 +2173,26 @@ export async function startVault(o = {}) {
2157
2173
  return r
2158
2174
  },
2159
2175
  async create(cfg, opts) { // opts { enclave, split }: the confidential tier, a split-key room; anything else is refused, never ignored
2160
- if (opts !== undefined && opts !== null && (typeof opts !== 'object' || Object.keys(opts).some((k) => k !== 'enclave' && k !== 'split'))) throw Object.assign(new Error('vault: create takes { enclave, split } and nothing else'), { code: 'invalid_argument' })
2176
+ if (opts !== undefined && opts !== null && (typeof opts !== 'object' || Object.keys(opts).some((k) => k !== 'enclave' && k !== 'split' && k !== 'creator'))) throw Object.assign(new Error('vault: create takes { enclave, split } and nothing else'), { code: 'invalid_argument' })
2177
+ if (opts?.creator !== undefined && (opts.creator?.accountEpoch !== creationAccount() || opts.creator?.email !== who())) throw Object.assign(new Error('The creating account changed'), { code: 'account_changed' })
2161
2178
  return makeRoom(cfg, null, { enclave: !!(opts && opts.enclave === true), split: !!(opts && opts.split === true) })
2162
2179
  },
2163
2180
  }
2181
+ // An opaque revision lets the page bind a create to the current vault account without receiving its backup key.
2182
+ const creatorScopes = new WeakMap(), withoutBackup = {}
2183
+ let creatorRevision = 0
2184
+ function creationAccount() {
2185
+ const record = sdk.backup._s || withoutBackup
2186
+ const scope = JSON.stringify([privacyEpoch, sdk._archiveGeneration, who(), sdk.backup._restoreEpoch || 0])
2187
+ const previous = creatorScopes.get(record)
2188
+ if (previous?.scope === scope) return previous.revision
2189
+ const revision = ++creatorRevision
2190
+ creatorScopes.set(record, { scope, revision })
2191
+ return revision
2192
+ }
2164
2193
  async function makeRoom(cfg, lane, { enclave = false, split = false } = {}) {
2165
- const epoch = privacyEpoch, owner = who()
2166
- const current = () => { if (privacyEpoch !== epoch || who() !== owner) throw Object.assign(new Error('the account changed during creation'), { code: 'account_changed' }) }
2194
+ const revision = creationAccount()
2195
+ const current = () => { if (creationAccount() !== revision) throw Object.assign(new Error('the account changed during creation'), { code: 'account_changed' }) }
2167
2196
  // SPLIT: the room's key is two halves — the link holds one, the builder's app-half function (/api/appshare on THIS
2168
2197
  // origin; spaces/templates/appshare) the other. A vault that serves none cannot make one (`appShare: true` says it does).
2169
2198
  if (split && !o.appShare) throw Object.assign(new Error('vault: this vault serves no app-half function — a split-key Space needs one at /api/appshare (startVault({ appShare: true }))'), { code: 'vault_unsupported' })
@@ -2187,6 +2216,7 @@ export async function startVault(o = {}) {
2187
2216
  // Attest FIRST — loud on a configuration failure (no published claim: never mint a confidential room that pins
2188
2217
  // nothing), soft on a cold enclave (woken below) — then mint, wake, and hand the enclave its own sealed config.
2189
2218
  if (enclave) { await sdk._encAttestSoft(); pushEnclave() }
2219
+ current()
2190
2220
  const r = await wcall({ t: 'create', cfg, base: location.origin, ...(enclave && !split ? { enclave: true } : {}), ...(split ? { split: true, ...(sdk.backup.enabled ? { returnMk: true } : {}) } : {}), ...(sdk.backup.enabled ? { delAsk: true } : {}) })
2191
2221
  current()
2192
2222
  const mark = (l, m) => l + (l.includes('#') ? '&' : '#') + m
@@ -2370,7 +2400,7 @@ export async function startVault(o = {}) {
2370
2400
  if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
2371
2401
  await wipeSignedOut(); emit({ ev: 'signedOut' }); return { signedIn: false } },
2372
2402
  async enclaveAvailable() { return sdk._encClaimDoc().then(() => true, () => false) },
2373
- async whoami() { return signedIn() ? { signedIn: true, email: sdk.session.email, keyId: sessionKeyId() } : { signedIn: false } },
2403
+ async whoami(options) { return { ...(signedIn() ? { signedIn: true, email: sdk.session.email, keyId: sessionKeyId() } : { signedIn: false }), ...(options?.forCreate === true ? { accountEpoch: creationAccount() } : {}) } },
2374
2404
  async forget(room) {
2375
2405
  if (pendingForget.has(room)) { await purgeForgotten(room); return { forgotten: true } }
2376
2406
  if (!held(room)) return { forgotten: false }
package/vault-kit.mjs CHANGED
@@ -20,7 +20,7 @@ import { createHash } from 'node:crypto'
20
20
  import { join, dirname } from 'node:path'
21
21
 
22
22
  export const DEFAULTS = { endpoint: 'https://api.witbitz.chat/v1/space', loginBase: 'https://witbitz-spaces.pages.dev', from: 'https://witbitz.chat/sdk/latest/', enclaveClaim: 'https://witbitz-spaces.pages.dev/enclave-claim.json', accountService: 'https://api.witbitz.chat/v1' } // enclaveClaim: the confidential tier's published measurement (and its policy text, beside it)
23
- export const KIT_RELEASE = '4.7.0' // tools/sdk-release.mjs stamps the version here, so a downloaded copy builds from ITS release
23
+ export const KIT_RELEASE = '4.7.1' // tools/sdk-release.mjs stamps the version here, so a downloaded copy builds from ITS release
24
24
  export function stampSdkAuth(src) {
25
25
  return src.replaceAll('__' + 'SPACE_AUTH_BROKER' + '__', 'https://auth.witbitz.chat').replaceAll('__' + 'SPACE_AUTH_FORCE_BROKER' + '__', '0')
26
26
  }
package/witbitz-admin.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // Witbitz admin client — one file for your SERVER (https://witbitz.chat/docs/sdk#builder-calls). Never ship it in a page.
2
2
 
3
- // spaces/public/sdk/4.7.0/connCatalog.js
3
+ // spaces/public/sdk/4.7.1/connCatalog.js
4
4
  var GCAL_PROVIDER = "prov_XE5FdiPdAx881HKs";
5
5
  var CATALOG = [
6
6
  // AN AGENT YOU SEND JOBS TO, not a service you sign in to (the owner, 2026-10-15: "Doesn't grokbot have a connector like
@@ -154,7 +154,7 @@ var CATALOG = [
154
154
  { name: "Gmail", kind: "mail", host: "mail.google.com", desc: "Forward the mail you choose into a Space of your own \u2014 the assistant reads it when you ask.", cat: "Email" }
155
155
  ];
156
156
 
157
- // spaces/public/sdk/4.7.0/cbor.js
157
+ // spaces/public/sdk/4.7.1/cbor.js
158
158
  var MAX_LEN = 1 << 22;
159
159
  function decode(bytes) {
160
160
  const b = toBytes(bytes);
@@ -348,7 +348,7 @@ function concat(...parts) {
348
348
  return out;
349
349
  }
350
350
 
351
- // spaces/public/sdk/4.7.0/x509.js
351
+ // spaces/public/sdk/4.7.1/x509.js
352
352
  var TAG = { INT: 2, BITSTRING: 3, OID: 6, SEQ: 48, UTCTIME: 23, GENTIME: 24 };
353
353
  var SIG_OIDS = /* @__PURE__ */ new Map([
354
354
  ["1.2.840.10045.4.3.2", { hash: "SHA-256" }],
@@ -522,7 +522,7 @@ async function verifyChain(chainDer, { now = Date.now() } = {}) {
522
522
  return certs[certs.length - 1];
523
523
  }
524
524
 
525
- // spaces/public/sdk/4.7.0/nitroVerify.js
525
+ // spaces/public/sdk/4.7.1/nitroVerify.js
526
526
  var NITRO_ROOT_G1_B64 = "MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTELMAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYDVQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4MTQyODA1WjBJMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEGBSuBBAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSksfbb48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ3BABIeTPYwEoCWZEh8l5YoQwTcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkFR+eWw5b6cp3PmanfS5YwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPWrfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6NIwLz3/Y=";
527
527
  var COSE_ALG_ES384 = -35;
528
528
  var MAX_DOC = 1 << 20;
@@ -646,7 +646,7 @@ async function verifyAttestation(cose, { root, now = Date.now(), maxAgeMs = 0, e
646
646
  return { ok: true, ...doc, leaf };
647
647
  }
648
648
 
649
- // spaces/public/sdk/4.7.0/sentinelRelease.js
649
+ // spaces/public/sdk/4.7.1/sentinelRelease.js
650
650
  var BUILD_ENCLAVE_PCR0 = Object.freeze([
651
651
  "c6a8cbd0c05d8e003e75b266f1dde2a6426b7cd61f845e4b128e59063e40968b44f30d934bbe1925582fe33bbdd0b1d7",
652
652
  "f490096d57e4287146e8b8d7bf4c75f423984ca52199efab0ee8684fbee6cfe6ab82c72d54f05a38f24a0d4ad6e2f557",
@@ -794,7 +794,7 @@ async function recordPcrBy(r, subject, builders, verify = verifyAttestation) {
794
794
  return { pcr0, builder };
795
795
  }
796
796
 
797
- // spaces/public/sdk/4.7.0/sealShare.js
797
+ // spaces/public/sdk/4.7.1/sealShare.js
798
798
  var enc2 = new TextEncoder();
799
799
  var b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)));
800
800
  async function sealTo(enclaveKey, nonce, bundle) {
@@ -808,13 +808,13 @@ async function sealTo(enclaveKey, nonce, bundle) {
808
808
  return { epk: b64(epk), iv: b64(iv), ct: b64(ct), nonce: b64(nonce) };
809
809
  }
810
810
 
811
- // spaces/public/sdk/4.7.0/connDisp.js
811
+ // spaces/public/sdk/4.7.1/connDisp.js
812
812
  var enc3 = new TextEncoder();
813
813
  var dec = new TextDecoder();
814
814
  var SALT = enc3.encode("witbitz-sentinel-display-v1");
815
815
  var INFO = enc3.encode("sentinel-display");
816
816
 
817
- // spaces/public/sdk/4.7.0/connections.js
817
+ // spaces/public/sdk/4.7.1/connections.js
818
818
  var STANDING_SENTINEL_PCR0 = ["0e424db41977965bc6edf225229eae70fe162dd8264b1ac0b5670cb3f71bf8b923001341e85a665354b25cd8418ac6d3"];
819
819
  var b642 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)));
820
820
  var unb642 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
@@ -928,7 +928,7 @@ async function attestStandingSentinel({ post, auth = {}, pins = STANDING_SENTINE
928
928
  }
929
929
  var MCP_CURATED = CATALOG.filter((c) => c.url).map((c) => ({ label: c.name, url: c.url }));
930
930
 
931
- // spaces/public/sdk/4.7.0/sdkRedact.js
931
+ // spaces/public/sdk/4.7.1/sdkRedact.js
932
932
  var REDACTED = "[REDACTED]";
933
933
  var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
934
934
  function hide(obj, names) {
@@ -953,7 +953,7 @@ function redacted(proto, summary) {
953
953
  });
954
954
  }
955
955
 
956
- // spaces/public/sdk/4.7.0/witbitz-admin.js
956
+ // spaces/public/sdk/4.7.1/witbitz-admin.js
957
957
  var adminError = (code, message) => Object.assign(new Error(message), { code: String(code || "refused") });
958
958
  var DEFAULT_ENDPOINT = "https://api.witbitz.chat/v1/space";
959
959
  var ownerRetired = () => adminError("owner_rule_retired", "witbitz: the owner rule (rooms only your app may use) is retired \u2014 a web page cannot prove which app it is (sdk-changes.md, 4.0.0)");
package/witbitz-sdk.js CHANGED
@@ -22,7 +22,7 @@ import { memberHash } from './rosterHash.js'
22
22
  import { verifyAttestation } from './nitroVerify.js' // devRoot: the dev server's Sentinel, checked under its root
23
23
  import { AccountBackup } from './sdkBackup.js'
24
24
  import { linkLanes, laneLinkTool } from './sdkLaneLink.js' // lane.link(other): two of a member's assistants ask each other
25
- import { InviteAccount, adoptGrant as adoptRoomGrant, changeMembers as changeMembersInPlace, rotateKey as rotateKeyInPlace, relink } from './sdkRekey.js' // a verified room changes its members in place (https://witbitz.chat/docs/sdk-people.md#members)
25
+ import { InviteAccount, adoptGrant as adoptRoomGrant, changeMembers as changeMembersInPlace, rotateKey as rotateKeyInPlace, sessionRole, relink } from './sdkRekey.js' // a verified room changes its members in place (https://witbitz.chat/docs/sdk-people.md#members)
26
26
  import { TemporaryRooms } from './sdkTemporaryRooms.js'
27
27
  import { Computers } from './sdkComputers.js' // wb.computers: the person's cloud computers (docs/sdk-cloud-computers.md)
28
28
  import { opensEnvelopes, sealsIdentity } from './reqEnvelope.js' // the sealed request envelope: does a live enclave open it
@@ -51,7 +51,7 @@ import { Dictation, voiceForDictation } from './sdkDictation.js' // wb.dictation
51
51
  import { Protect } from './sdkProtect.js' // wb.protect: what the app keeps on the device, sealed under a passkey-derived key
52
52
  import { boxesHash, bareEC, jkey } from './spaceFork.js' // the membership fork's notice format, shared with the app
53
53
  import { preferredAddresses } from './addPreferred.js' // "Add me to Spaces as @username" (docs/spaces-usernames.md § 13)
54
- import { placeRoles, roleEmails, rolesOf, roleTagHolders } from './roomRoles.js' // owners and admins by @username tag (docs/spaces-usernames.md § 13.1)
54
+ import { signedInRoomTags, placeRoles, roleEmails, rolesOf, roleTagHolders } from './roomRoles.js' // owners and admins by @username tag (docs/spaces-usernames.md § 13.1)
55
55
  import { normAdmission, checkAdminCollections, judgeMove, newRoomKeepsGov } from './emailFork.js' // the gate's rules with the app; following a move an OLDER client made (a Space no longer moves: #members)
56
56
  import { deleteOwnRoom } from './roomDelete.js'
57
57
  import { sealTo, openBox, commit as keyCommit } from './e2ee.js'
@@ -201,7 +201,7 @@ const perTurn = (instructions) => (typeof instructions === 'string' && instructi
201
201
  /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
202
202
  export { isLaneCopy } from './roomName.js' // is this message a lane's copy of its shared room's line? (the app's own test, sdk-agents.md#lanes)
203
203
  export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
204
- export const SDK_VERSION = '4.7.0'
204
+ export const SDK_VERSION = '4.7.1'
205
205
  // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
206
206
  const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
207
207
  /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
@@ -1038,13 +1038,20 @@ export class Witbitz {
1038
1038
  if (this.vault) return this.vault._c.account('backup', 'exportArchive', recoveryKeys === true, rooms?.map(sp => sp.room), ...(destination === 'clipboard' ? [destination] : []))
1039
1039
  const { saveAccountArchive } = await import('./sdkExports.js')
1040
1040
  const session = this._session, generation = this._archiveGeneration, backup = this.backup._s
1041
- const selected = new Map((rooms === undefined ? this.backup.rooms : []).map(r => [r.room, r]))
1041
+ const savedLinks = new Map(this.backup.rooms.map(r => [r.room, r.link]))
1042
+ const selected = new Map((rooms === undefined ? this.backup.rooms : []).map(r => [r.room, { ...r }]))
1042
1043
  const opened = [...(this._archiveHandles || [])].filter(sp => sp._archiveGeneration === this._archiveGeneration && sp._archiveEmail === (session?.email || '') && sp._archiveMaster === (backup?.master || null))
1043
1044
  if (rooms?.some(sp => !opened.includes(sp))) throw sdkError('select Spaces opened for this account', 'invalid_argument')
1044
1045
  for (const sp of rooms ?? opened) {
1045
1046
  if (!sp || sp._wb !== this || sp._stopped || !sp.shareLink) throw sdkError('select open Spaces from this SDK client', 'invalid_argument')
1046
1047
  selected.set(sp.room, { room: sp.room, link: sp.shareLink, title: sp.title, held: sp })
1047
1048
  }
1049
+ const current = () => {
1050
+ if (this._archiveGeneration !== generation || (this._session?.email || '') !== (session?.email || '') || (this.backup._s?.master || null) !== (backup?.master || null)) return false
1051
+ const live = new Map(this.backup.rooms.map(r => [r.room, r.link]))
1052
+ return [...selected.values()].every(r => (!savedLinks.has(r.room) || live.get(r.room) === savedLinks.get(r.room)) &&
1053
+ (!r.held || (this._archiveHandles?.has(r.held) && !r.held._stopped && r.held.shareLink === r.link)))
1054
+ }
1048
1055
  return saveAccountArchive([...selected.values()], async (r, keysOnly, attachments) => {
1049
1056
  const { room, mk } = r.held?._mk ? { room: r.room, mk: r.held._mk } : await this._openLink(r.link)
1050
1057
  if (room !== r.room) throw sdkError('witbitz: a saved link opens another Space', 'wrong_room')
@@ -1052,7 +1059,7 @@ export class Witbitz {
1052
1059
  const saved = await this._client.exportSealed(room, mk, { attachments }) // + the stored attachments, sealed (sdkExports.js)
1053
1060
  if (saved?.status !== 200) throw sdkError('witbitz: this Space\u2019s history could not be read just now', 'unavailable')
1054
1061
  return { key: mk, ledger: saved.sealed, count: saved.count, attachments: saved.attachments }
1055
- }, recoveryKeys === true, () => this._archiveGeneration === generation && (this.backup._s?.master || null) === (backup?.master || null), destination)
1062
+ }, recoveryKeys === true, current, destination)
1056
1063
  }
1057
1064
  async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, usernames, safeMedia, lanes, owner } = {}) {
1058
1065
  // A TEMPORARY ROOM (docs/visitor-limits.md): a `tmp-` room the deployment wipes when it is idle — `true`: after about half
@@ -1314,7 +1321,7 @@ export class Witbitz {
1314
1321
  const config = await this._client.getConfig(room, mk, { plainMark: true })
1315
1322
  if (current() && (config?.help || config?.lane || config?.bridge)) return { excluded: true }
1316
1323
  const v = await readAllPages(since => this._client.poll(room, mk, undefined, since))
1317
- return current() && config && !config.help && !config.lane && !config.bridge && v.status === 200 && !v.incomplete ? { config, entries: v.entries, etag: v.etag, selfEntries: await ownAdmissionEntries(config, this.erasure._account(), () => this._client.state(room, mk, 'roster')), selfHash: this.erasure._account() ? await memberHash(this.erasure._account(), room) : null } : null
1324
+ return current() && config && !config.help && !config.lane && !config.bridge && v.status === 200 && !v.incomplete ? { config, entries: v.entries, etag: v.etag, selfEntries: await ownAdmissionEntries(config, this.erasure._account(), () => this._client.state(room, mk, 'roster'), () => signedInRoomTags(this._client, room, session?.idToken)), selfHash: this.erasure._account() ? await memberHash(this.erasure._account(), room) : null } : null
1318
1325
  },
1319
1326
  prepare: room => remove(room, { check: true, reviewPolicy: true }),
1320
1327
  deleteOnServer: (room, reviewedEtag, reviewedPolicy) => remove(room, { reviewedEtag, reviewedPolicy }),
@@ -2359,6 +2366,7 @@ export class Space {
2359
2366
  * connection. A non-admin's attempt is refused
2360
2367
  * with `code: 'not_admin'`. A room without admins has none (every member may do all of it, as before). */
2361
2368
  async isAdmin(email) {
2369
+ if (this._wb?.vault && String(email || '').trim().startsWith('@')) return this._wb.vault._c.roomAccount(this.room, 'roster', 'isAdmin', email)
2362
2370
  const e = String(email || '').trim().toLowerCase()
2363
2371
  const cfg = await this._gateConfig({ plainMark: true })
2364
2372
  const has = (o) => !!(o && Array.isArray(o.emails) && o.emails.some((x) => String(x).trim().toLowerCase() === e))
@@ -2377,6 +2385,7 @@ export class Space {
2377
2385
  /** Is `email` one of this room's OWNERS (a level above admins, enforced by the room)? An owner can do all an admin can,
2378
2386
  * and only an owner can change the owners or lower or remove an admin when the room is moved ({@link Space#fork}). */
2379
2387
  async isOwner(email) {
2388
+ if (this._wb?.vault && String(email || '').trim().startsWith('@')) return this._wb.vault._c.roomAccount(this.room, 'roster', 'isOwner', email)
2380
2389
  const e = String(email || '').trim().toLowerCase()
2381
2390
  const cfg = await this._gateConfig({ plainMark: true })
2382
2391
  return !!(cfg.owners && Array.isArray(cfg.owners.emails) && cfg.owners.emails.some((x) => String(x).trim().toLowerCase() === e)) || (await this._roleByTag(cfg, e)) === 'owner' // '@username': by its tag (§ 13.1)
@@ -2409,16 +2418,19 @@ export class Space {
2409
2418
  async _gateConfig({ fresh = false, plainMark = false } = {}) {
2410
2419
  const owner = this._wb?.vault ? this._wb._vaultGeneration : this._wb?._session
2411
2420
  const key = this._mk, epoch = this.epoch
2412
- if (!fresh && this._gateCfg && this._gateOwner === owner) return this._gateCfg
2421
+ if (!fresh && this._gateCfg && this._gateOwner === owner && (!this._gated || this._gateCfg.admission === 'email')) return this._gateCfg
2413
2422
  const cfg = typeof this._client.getConfig === 'function' ? await this._client.getConfig(this.room, this._mk, plainMark ? { plainMark: true } : undefined) : null
2414
2423
  if (key !== this._mk || epoch !== this.epoch || owner !== (this._wb?.vault ? this._wb._vaultGeneration : this._wb?._session)) throw sdkError('the room or account changed during the read', 'account_changed')
2415
2424
  if (cfg && typeof cfg.lanes === 'boolean') this._lanesSetting = cfg.lanes
2416
- if (!cfg || typeof cfg !== 'object') { const err = new Error("witbitz: could not read this Space's gate (its sealed config did not load) — try again"); err.code = 'config_unavailable'; throw err }
2417
2425
  // A gated room answers a caller who has not signed in with only { admission: 'email', gated: true } — not the config.
2418
2426
  // That stub is never cached, so the read after sign-in gets the real one.
2419
- if (cfg.gated === true && !cfg.allow) { if (!this._gated) { this._gated = true; if (this._announced) this._announce() } const me = await this._signedInEmail(); const e = new Error(me ? `witbitz: this Space is email-gated and ${me} is not on its list — only its members read its gate` : 'witbitz: this Space is email-gated — sign in (' + signInHow(this._wb) + ') to read its gate'); e.code = 'sign_in_required'; throw e } // signed in but not admitted: the server answers the same stub, and "sign in" was wrong there (sync sweep 11-14 P7: a signed-in vault)
2427
+ if (cfg?.gated === true && !cfg.allow) { if (!this._gated) { this._gated = true; if (this._announced) this._announce() } const me = await this._signedInEmail(); const e = new Error(me ? `witbitz: this Space is email-gated and ${me} is not on its list — only its members read its gate` : 'witbitz: this Space is email-gated — sign in (' + signInHow(this._wb) + ') to read its gate'); e.code = 'sign_in_required'; throw e } // signed in but not admitted: the server answers the same stub, and "sign in" was wrong there (sync sweep 11-14 P7: a signed-in vault)
2428
+ // A known email gate cannot become open on an incomplete policy read. Leave it uncached for the next lookup.
2429
+ if (!cfg || typeof cfg !== 'object' || (this._gated && cfg.admission !== 'email')) {
2430
+ throw sdkError("witbitz: could not read this Space's gate (its sealed config did not load) — try again", 'config_unavailable')
2431
+ }
2420
2432
  this._gateOwner = owner
2421
- this._gateCfg = cfg // the gate is sealed at creation and never changes in place (membership change = a new room)
2433
+ this._gateCfg = cfg // a membership rekey clears this cache
2422
2434
  if (cfg.admission === 'email' && !this._gated) { this._gated = true; if (this._announced) this._announce() } // a room that predates the link marker announces once its gate is read
2423
2435
  return cfg
2424
2436
  }
@@ -2740,7 +2752,9 @@ export class Space {
2740
2752
  const sess = this._wb && this._wb._session
2741
2753
  const me = this._wb && this._wb.vault ? String(((await this._wb.vault.whoami()) || {}).email || '') // in a vault, its signed-in member (sync sweep 10-15 #2)
2742
2754
  : sess && (!sess.exp || sess.exp > Date.now()) ? String(sess.email || '') : ''
2743
- const out = planChange(change, { cfg, me, lane: !!(this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)), activeLane: !!this._sharedRoom, checkData: checkDataSchema, gatedUnread, signIn: signInHow(this._wb) })
2755
+ const roles = rolesOf(cfg), tagged = !!(roles.ownerTags.length || roles.adminTags.length)
2756
+ const role = tagged && me ? (this._wb?.vault ? await this._wb.vault._c.roomAccount(this.room, 'roster', 'sessionRole') : await sessionRole(this, cfg, me)) : undefined
2757
+ const out = planChange(change, { cfg, me, role, lane: !!(this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)), activeLane: !!this._sharedRoom, checkData: checkDataSchema, gatedUnread, signIn: signInHow(this._wb) })
2744
2758
  if (out.how === 'in_place' && change.agent && change.agent.model && this._wb) { try { await this._wb._checkModel(change.agent.model) } catch (e) { return { how: 'refused', history: null, call: null, steps: out.steps, reason: String(e.message || e), code: e.code || 'invalid_model' } } }
2745
2759
  return out
2746
2760
  }
@@ -4055,12 +4069,18 @@ export class VaultSession {
4055
4069
  const enc = tierIsEnclave(tier) // the vault attests the enclave and keeps the key; the page only asks
4056
4070
  const split = splitKeyChoice(key) // the vault makes it through its app-half function (startVault({ appShare: true }))
4057
4071
  const wb = this._wb
4058
- if (direct !== undefined) { const who = await this._c.whoami(); admission = directAdmission(direct, admission, who && who.signedIn ? { email: who.email } : null, 'wb.vault.signIn') } // the vault's signed-in member
4072
+ let creator
4073
+ const readCreator = async () => {
4074
+ const who = await this._c.whoami({ forCreate: true })
4075
+ if (!who || typeof who.signedIn !== 'boolean' || !Number.isInteger(who.accountEpoch)) throw sdkError('The vault could not confirm the creating account. Update the vault and try again.', 'identity_unavailable')
4076
+ creator = { accountEpoch: who.accountEpoch, email: who.signedIn ? String(who.email).trim().toLowerCase() : '' }
4077
+ return who
4078
+ }
4079
+ if (direct !== undefined) { const who = await readCreator(); admission = directAdmission(direct, admission, who && who.signedIn ? { email: who.email } : null, 'wb.vault.signIn') } // the vault's signed-in member
4059
4080
  // THE CREATOR IS THE OWNER, as outside a vault (createSpace): the vault's signed-in member, when on the list and no owners given —
4060
4081
  // without it nobody could change the Space's members in place (changeMembers needs an owner or an admin)
4061
4082
  else if (admission && typeof admission === 'object' && Array.isArray(admission.emails) && !(Array.isArray(admission.owners) && admission.owners.length)) {
4062
- const who = await this._c.whoami()
4063
- if (!who || typeof who.signedIn !== 'boolean') throw sdkError('witbitz: the creating member could not be checked', 'identity_unavailable')
4083
+ const who = await readCreator()
4064
4084
  const me = who && who.signedIn ? String(who.email || '').trim().toLowerCase() : ''
4065
4085
  if (me && admission.emails.map((e) => String(e).trim().toLowerCase()).includes(me)) admission = { ...admission, owners: [me] }
4066
4086
  }
@@ -4075,7 +4095,7 @@ export class VaultSession {
4075
4095
  if (usernames === false && gate?.admission === 'email') cfg.usernames = false
4076
4096
  if (safeMedia === true) cfg.safeMedia = true // as outside a vault (sync sweep 2026-10-28: it was refused here while configure turned it on)
4077
4097
  if (lanes === true) cfg.lanes = true
4078
- const { room } = await this._c.create(cfg, enc || split ? { ...(enc ? { enclave: true } : {}), ...(split ? { split: true } : {}) } : undefined)
4098
+ const { room } = await this._c.create(cfg, enc || split || creator ? { ...(enc ? { enclave: true } : {}), ...(split ? { split: true } : {}), ...(creator ? { creator } : {}) } : undefined)
4079
4099
  if (enc) wb._enc.rooms.set(room, true)
4080
4100
  const made = refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, wb, gated: !!gate, lanes: lanes === true }))
4081
4101
  made.safeMedia._learn(safeMedia === true, 0) // a new room's setting is what it was made with, as outside a vault (sync sweep 2026-10-28…11-02: it read null)
@@ -4427,18 +4447,20 @@ class SiriAccount {
4427
4447
  // change is made again on top of what landed and that is pushed — at most a few times, then the latest state stands.
4428
4448
  // `guard`: the Spaces this edit is about — when another device changed one of them while this edit was out, the edit is not made
4429
4449
  // again over it (a rename must not overwrite a newer rename; the app's siri.js editShows): `siri_conflict`
4430
- _change(fn, { guard } = {}) {
4450
+ _change(fn, { guard, guardDefault = false } = {}) {
4431
4451
  const generation = this._wb._archiveGeneration
4432
4452
  const run = async () => {
4433
4453
  if (generation !== this._wb._archiveGeneration) throw sdkError('Account changed before Siri setup', 'account_changed')
4434
4454
  let out
4435
- const guarded = (st) => JSON.stringify((guard || []).map((room) => st.rooms[room] || null))
4455
+ const guarded = (st) => JSON.stringify([guardDefault ? st.defaultRoom || '' : '', ...(guard || []).map(room => st.rooms[room] || null)])
4436
4456
  const began = guarded(this._wb._siri)
4457
+ const stagedRemovals = new Set()
4437
4458
  for (let i = 0; i < 4; i++) {
4438
4459
  const account = await this._wb._account(), base = this._wb._siri
4439
4460
  const conflict = !!(i && guard && guarded(base) !== began) // pushed as it now stands (the Sentinel took this edit's copy), then said
4440
4461
  const next = siriStateOf(JSON.parse(JSON.stringify(base)))
4441
- const pending = next.pendingRemovals || []
4462
+ // A restore can carry this attempt's local retry marker along with the newer room.
4463
+ const pending = (next.pendingRemovals || []).filter(id => !conflict || !stagedRemovals.has(id))
4442
4464
  const priorSetup = next.pendingSetup, rotation = next.pendingRotation
4443
4465
  delete next.pendingRotation
4444
4466
  delete next.pendingSetup
@@ -4463,7 +4485,10 @@ class SiriAccount {
4463
4485
  const stageLocal = !this._stageInbox && (removed.length || added.length || priorSetup || next.token !== base.token) && this._wb._siri === base
4464
4486
  if (stageLocal) {
4465
4487
  if (next.token !== base.token && (base.token || !added.length)) base.pendingRotation = { from: base.token, to: next.token }
4466
- if (removed.length) base.pendingRemovals = removed
4488
+ if (removed.length) {
4489
+ for (const id of removed) if (!pending.includes(id)) stagedRemovals.add(id)
4490
+ base.pendingRemovals = removed
4491
+ }
4467
4492
  if (added.length) base.pendingSetup = siriStateOf({ token: next.token, rooms: Object.fromEntries(added), defaultRoom: next.defaultRoom })
4468
4493
  else delete base.pendingSetup
4469
4494
  this._changed()
@@ -4537,6 +4562,8 @@ class SpaceSiri {
4537
4562
  const requested = normSiriAlias(alias)
4538
4563
  if (alias !== undefined && !requested) throw sdkError('witbitz: an alias is needed — the word you will say to Siri', 'invalid_argument')
4539
4564
  if (/[,:;]/.test(requested)) throw sdkError('witbitz: an alias cannot contain , : or ;', 'invalid_argument')
4565
+ const lane = includeAssistant && this._assistantRoom()
4566
+ const guardDefault = makeDefault || wb._siri.defaultRoom === sp.room
4540
4567
  return wb.siri._change(async (st) => { // kept only once the Sentinel took it (pass 9, K#5)
4541
4568
  const a = requested || st.rooms[sp.room]?.alias || uniqueAlias(label || sp.title || 'Space', new Set(Object.values(st.rooms).map(r => r.alias)))
4542
4569
  for (const [rm, r] of Object.entries(st.rooms)) if (rm !== sp.room && r.alias === a) throw sdkError(`witbitz: "${a}" already names another Space`, 'invalid_argument')
@@ -4544,15 +4571,14 @@ class SpaceSiri {
4544
4571
  const cur = st.rooms[sp.room]
4545
4572
  if (cur) st.rooms[sp.room] = { ...cur, alias: a, label: label || cur.label, at: Date.now() } // the newer copy wins a merge (sync sweep 2026-11-15 #7)
4546
4573
  else { const kp = await genRecipientKey(); st.rooms[sp.room] = { alias: a, label: String(label || ''), pub: { x: kp.publicJwk.x, y: kp.publicJwk.y }, priv: kp.privateJwk, at: Date.now() } }
4547
- const lane = includeAssistant && this._assistantRoom()
4548
4574
  if (lane && !st.rooms[lane]) {
4549
4575
  const taken = new Set(Object.values(st.rooms).map(r => r.alias))
4550
4576
  const assistantAlias = uniqueAlias(a.slice(0, 22) + ' assistant', taken), kp = await genRecipientKey()
4551
4577
  st.rooms[lane] = { alias: assistantAlias, label: (label || a) + ' · assistant', pub: { x: kp.publicJwk.x, y: kp.publicJwk.y }, priv: kp.privateJwk, at: Date.now() }
4552
4578
  }
4553
- if (makeDefault) st.defaultRoom = sp.room; else if (st.defaultRoom === sp.room) st.defaultRoom = ''
4579
+ if (makeDefault) st.defaultRoom = sp.room; else if (guardDefault && st.defaultRoom === sp.room) st.defaultRoom = ''
4554
4580
  return { key: st.token, endpoint: SIRI_ENDPOINT, alias: a }
4555
- }, { guard: [sp.room] })
4581
+ }, { guard: [sp.room, lane].filter(Boolean), guardDefault })
4556
4582
  }
4557
4583
  /** Disable Siri for this Space (other Spaces keep theirs). A push that fails rejects and keeps it on, here as at the Sentinel. */
4558
4584
  async disable({ includeAssistant = false } = {}) {
@@ -4563,7 +4589,7 @@ class SpaceSiri {
4563
4589
  for (const id of targets) delete st.rooms[id]
4564
4590
  if (targets.includes(st.defaultRoom)) st.defaultRoom = ''
4565
4591
  return true
4566
- })
4592
+ }, { guard: targets, guardDefault: true })
4567
4593
  return { disabled: r === true }
4568
4594
  }
4569
4595
  /** Collect: pull the account's drops, open the ones for THIS Space with its inbox key, post each as you (🎙-marked),