@witbitz/sdk 4.8.0 → 4.9.0

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/roomPass.js CHANGED
@@ -29,6 +29,63 @@ export const psigBytes = ({ op, room, ts, nonce, ph, sk }) => enc.encode(REQ_PUR
29
29
  /** The pass's own fields (unverified here: the server is the judge) → { email, exp, sessionPub } | null. */
30
30
  export const passFields = (pass) => { try { const p = JSON.parse(unb64uText(pass.p)); return p && typeof p === 'object' ? p : null } catch { return null } }
31
31
 
32
+ // One instance belongs to one approved account session and one room set from its
33
+ // encrypted backup. Its private signing key and passes are kept only in memory.
34
+ export const ACCOUNT_ROOM_ASK = '#account-room:'
35
+ export const isAccountRoomAsk = name => typeof name === 'string' && name.length <= 2048 && name.startsWith(ACCOUNT_ROOM_ASK)
36
+ export async function answerAccountRoomAsk(name, issue) {
37
+ if (!isAccountRoomAsk(name)) throw new Error('bad account room request')
38
+ const { room, pub, kind, proofs } = JSON.parse(name.slice(ACCOUNT_ROOM_ASK.length))
39
+ if (['index', 'pipes', 'msgs'].includes(kind) && typeof room === 'string' && /^sp-(?:us-)?[a-z0-9]{1,12}$/.test(room)) return issue(room, pub, kind, proofs)
40
+ if (typeof room !== 'string' || !/^sp-ar2-[a-f0-9]{40}$/.test(room)) throw new Error('bad account room')
41
+ return issue(room, pub)
42
+ }
43
+ export function makeAccountRoomAccess({ issue, issueRoom, setId, now = Date.now }) {
44
+ const byKind = new Map(), byRoom = new Map()
45
+ let key
46
+ async function credential(kind, legacyKind) {
47
+ const prior = byKind.get(kind)
48
+ if (prior) {
49
+ const value = await prior
50
+ if (value.exp * 1000 > now() + RENEW_BEFORE_S * 1000) return value
51
+ if (byKind.get(kind) !== prior) return credential(kind, legacyKind)
52
+ }
53
+ const pending = (async () => {
54
+ key ||= subtle().generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify'])
55
+ const pair = await key
56
+ const pub = await subtle().exportKey('jwk', pair.publicKey)
57
+ const proof = issueRoom ? await issueRoom(kind, pub, legacyKind) : await issue(kind, setId, pub)
58
+ if (!proof || (legacyKind ? proof.room !== kind : !/^sp-ar2-[0-9a-f]{40}$/.test(proof.room)) || !Number.isFinite(proof.exp) ||
59
+ proof.exp * 1000 <= now() || !proof.pass || !proof.sig) throw new Error('invalid account room pass')
60
+ byRoom.set(proof.room, kind)
61
+ return proof
62
+ })()
63
+ byKind.set(kind, pending)
64
+ try { return await pending } catch (err) {
65
+ if (byKind.get(kind) === pending) byKind.delete(kind)
66
+ throw err
67
+ }
68
+ }
69
+ return {
70
+ async room(kind) { return (await credential(kind)).room },
71
+ async sign(body, legacyKind) {
72
+ const kind = byRoom.get(body.room) || (issueRoom && body.room)
73
+ if (!kind) throw new Error('unknown account room')
74
+ const proof = await credential(kind, legacyKind)
75
+ if (proof.room !== body.room) throw new Error('account room changed')
76
+ const { op, pass: ignoredPass, psig: ignoredSig, ...fields } = body
77
+ const payload = legacyKind ? body : { ...fields, op: 'account-room', action: op }
78
+ const pass = { p: proof.pass, s: proof.sig }
79
+ const ts = now(), nonce = randNonce()
80
+ const signed = psigBytes({ op: payload.op, room: payload.room, ts, nonce,
81
+ ph: await sha256hex(pass.p), sk: await sha256hex(JSON.stringify(payload)) })
82
+ const bytes = await subtle().sign({ name: 'ECDSA', hash: 'SHA-256' }, (await key).privateKey, signed)
83
+ const psig = { ts, nonce, sig: b64u(new Uint8Array(bytes)) }
84
+ return legacyKind ? { ...payload, accountDeviceProof: { pass, psig } } : { ...payload, pass, psig }
85
+ },
86
+ }
87
+ }
88
+
32
89
  /** The sign-in a request body carries (top level, or the turn's message) → { email, spk } | null. */
33
90
  export function signInOf (body) {
34
91
  const m = body && body.message && typeof body.message === 'object' ? body.message : null
@@ -69,19 +69,24 @@ export function frameReader () {
69
69
  export function openRoomStream ({ mk, grants = null, tag = '', onEvent = () => {}, onState = () => {}, relay = RELAY_URL, path = 'c', WebSocketImpl = globalThis.WebSocket, now = () => Date.now(), heartbeatMs = HEARTBEAT_MS, pongWaitMs = PONG_WAIT_MS } = {}) {
70
70
  if (!mk || typeof WebSocketImpl !== 'function') return { up: () => false, sync () {}, setGrants () {}, stop () {} }
71
71
  const reader = frameReader()
72
- let ws = null, up = false, stopped = false, backoff = 1000, retry = null, beat = null, pongTimer = null, epochTimer = null, key = null, gs = grants
72
+ let ws = null, up = false, stopped = false, backoff = 1000, retry = null, beat = null, pongTimer = null, epochTimer = null, gs = grants
73
+ let connectAttempt = 0
73
74
  const setUp = (v) => { if (v !== up) { up = v; try { onState(v) } catch { /* */ } } }
74
75
  const drop = () => { clearInterval(beat); clearTimeout(pongTimer); clearTimeout(epochTimer); beat = pongTimer = epochTimer = null; setUp(false); if (ws) { try { ws.onclose = ws.onerror = ws.onmessage = null; ws.close() } catch { /* */ } } ws = null }
75
76
  const schedule = () => { if (stopped || retry) return; retry = setTimeout(() => { retry = null; connect() }, backoff); backoff = Math.min(backoff * 2, 30_000) }
76
77
  async function connect () {
77
78
  if (stopped || ws) return
79
+ const attempt = ++connectAttempt
78
80
  const grant = gs ? currentGrant(gs, now()) : ''
79
81
  if (gs && !grant) return // a gated room with no current grant: wait for the next poll's
80
- key = await streamKey(mk, grant)
81
- let s
82
- // path 's': a page on ANY origin (the SDK) — the relay's /s/ namespace (relay/relay.mjs); the app keeps 'c'
83
- try { s = new WebSocketImpl(String(relay).replace(/\/+$/, '') + '/' + path + '/' + await streamChannel(mk, grant) + (tag ? '?v=' + encodeURIComponent(tag) : '')) } catch { schedule(); return } // tag: THIS device is viewing (spaceClient viewingTag)
84
- if (stopped) { try { s.close() } catch { /* */ } return }
82
+ let s, key
83
+ try {
84
+ key = await streamKey(mk, grant)
85
+ const channel = await streamChannel(mk, grant)
86
+ if (stopped || attempt !== connectAttempt) return
87
+ // The SDK uses /s/; the app uses /c/. The optional tag marks this device as viewing.
88
+ s = new WebSocketImpl(String(relay).replace(/\/+$/, '') + '/' + path + '/' + channel + (tag ? '?v=' + encodeURIComponent(tag) : ''))
89
+ } catch { if (attempt === connectAttempt) schedule(); return }
85
90
  ws = s
86
91
  s.onopen = () => {
87
92
  backoff = 1000; setUp(true)
package/sdkAccount.js CHANGED
@@ -407,8 +407,12 @@ export class AccountIndex {
407
407
  _schedule() { if (!this.enabled) return; clearTimeout(this._pushT); this._pushT = setTimeout(() => { this._pushT = null; this.sync().catch((e) => { this.lastError = e }) }, 300) }
408
408
 
409
409
  async _where() {
410
- const master = this._backup._s.master
411
- if (!this._loc || this._loc.master !== master) this._loc = { master, ...(await indexRoomOf(master)), app: await appStoreKey(ub64(master)) }
410
+ const { master, v2 } = this._backup._s
411
+ const dir = v2?.accountRooms
412
+ if (dir?.phase === 'preparing') throw fail('room_setup_pending', 'Account room setup is in progress')
413
+ if (!this._loc || this._loc.master !== master || this._loc.setId !== dir?.setId) {
414
+ this._loc = { master, ...(await indexRoomOf(master)), ...dir?.index, setId: dir?.setId, app: await appStoreKey(ub64(master)) }
415
+ }
412
416
  return this._loc
413
417
  }
414
418
  _me() {
@@ -429,7 +433,9 @@ export class AccountIndex {
429
433
  }
430
434
  async _ensureRoom(loc) {
431
435
  if (loc.made) return
432
- try { await this._client().create({ room: loc.room, mk: loc.mk }, { base: this._viewer || undefined }) } catch (e) { if (!/409|exists/.test(String(e && e.message))) throw e }
436
+ // sync sweep 2026-12-04 O10: named as the account's INDEX room (the app's twin sends roomKind too) — a row stamped 'space' is never
437
+ // recognised as an account room (agent/accountRoomGrace.mjs existingAccountKind), so its device proof could never be set up
438
+ try { await this._client().create({ room: loc.room, mk: loc.mk }, { base: this._viewer || undefined, roomKind: 'index' }) } catch (e) { if (!/409|exists/.test(String(e && e.message))) throw e }
433
439
  loc.made = true
434
440
  }
435
441
  // Read → merge → write ONLY IF the index has not moved since the read (ifV); another device that wrote in between makes
@@ -457,7 +463,7 @@ export class AccountIndex {
457
463
  // CREATE BEFORE THE FIRST READ, once per device (an existing room answers 409). A read of an unknown room is not
458
464
  // refused — the server adopts it with no owner — so waiting for a 404 would leave the index outside the app's tenant.
459
465
  const me0 = this._me()
460
- if (!me0.made) {
466
+ if (!me0.made && !loc.setId) {
461
467
  try { await this._ensureRoom(loc) } catch (e) { this.lastError = e; return { ok: false, rooms: this.rooms, devices: this.devices } }
462
468
  if (moved()) return stopped()
463
469
  this._backup._s.device = { ...me0, made: true }; this._backup._changed()
package/sdkBackup.js CHANGED
@@ -22,6 +22,7 @@ import { newRecoveryCode, codeSecret, gateParams, emailCommit, seal, unseal } fr
22
22
  import { recordFromRooms, roomsOfRecord, roomPin, tombOfRecord, keyInLink, vaultOwner, LEGACY_SDK_KIND, SDK_APP } from './accountRecord.js' // one account record for the app and the SDK; this module's original is LEGACY
23
23
  import { applyPlan } from './backupRecord.js' // the Spaces app's restore rules, pure (docs/sdk-account-format-plan.md phase 1)
24
24
  import { normUsageKey } from './usageReceipts.js'
25
+ import { protectedRoomPointers } from './accountRoomPointers.js'
25
26
  import { indexRoomOf, mergeIndex } from './sdkAccount.js' // the account's derived index room — published in the record as the app's `indexRoom` pointer
26
27
  import { newMasterSecret, backupLocation, wrapperLocation, enrollCredential, openWrapper } from './backupVault.js'
27
28
 
@@ -50,6 +51,7 @@ export function v2Of(x) {
50
51
  o.svc = { acct: sv.acct, base: String(sv.base || '').slice(0, 300), at: Number(sv.at) || 0, trust: sv.trust == null ? null : String(sv.trust).slice(0, 40),
51
52
  ...(sv.setup === 'pending' ? { setup: 'pending' } : {}), ...(typeof sv.address === 'string' && sv.address ? { address: sv.address.slice(0, 254) } : {}) }
52
53
  }
54
+ if (x.accountRooms) o.accountRooms = protectedRoomPointers(x)
53
55
  if (is32(x.bm)) o.bm = x.bm
54
56
  if (x.pending && is32(x.pending.master)) o.pending = { master: x.pending.master, rid: typeof x.pending.rid === 'string' ? x.pending.rid.slice(0, 200) : null, at: Number(x.pending.at) || 0 }
55
57
  if (typeof x.dk === 'string' && /^[A-Za-z0-9]{8,32}$/.test(x.dk)) o.dk = x.dk
package/sdkBackupV2.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { applyProtectedRoomPointers, protectedRoomPointers, mergeProtectedRoomPointers, roomDirectoryTag } from './accountRoomPointers.js'
1
2
  // sdkBackupV2.js — A BUILDER'S ACCOUNT ON THE NEW ACCOUNT SERVICE (account recovery v2, docs/account-recovery-protocol.md), run
2
3
  // in the builder's VAULT (vault-core.js), where the master never leaves. The owner, 2026-11-16: "Yes. Do the sdk." — the SDK
3
4
  // follows our own two apps (2026-11-15): a NEW account made in a vault that names its tenant starts on the new service; an
@@ -123,7 +124,7 @@ export function restoreBridge(run, { waitMs = 15 * 60_000 } = {}) {
123
124
  * onRevoked() (a request was refused as signed out: run the status check now), afterSignOut?(address) (the other devices were just
124
125
  * signed out: the room pass renews at once — vault-core.js) }
125
126
  */
126
- export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...a) => globalThis.fetch(...a), keyStore, label = () => deviceLabel(), persistNow, legacyRecovery, onRevoked = () => {}, afterSignOut = null, pushEndpoint = null, withdrawPush = null } = {}) {
127
+ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...a) => globalThis.fetch(...a), keyStore, label = () => deviceLabel(), persistNow, legacyRecovery, onRevoked = () => {}, afterSignOut = null, pushEndpoint = null, pushSubscription = null, withdrawPush = null } = {}) {
127
128
  if (!TENANT_ID.test(String(tenant || '')) || !base || !keyStore) return null
128
129
  const headers = { 'x-acct-tenant': tenant }
129
130
  const fetchWatched = async (...args) => {
@@ -155,14 +156,15 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
155
156
 
156
157
  /** The SDK's account record for state `s` (rooms, tombstones, email, invite key, index pointer) + the identity master. */
157
158
  async function recordOf(s, rooms = s.rooms) {
158
- return { ...recordFromRooms({ rooms, tomb: s.tomb, email: s.email, inviteKey: s.invite, indexRoom: await indexRoomOf(s.master) }), sdkMaster: s.master }
159
+ return applyProtectedRoomPointers({ ...recordFromRooms({ rooms, tomb: s.tomb, email: s.email, inviteKey: s.invite, indexRoom: await indexRoomOf(s.master) }), sdkMaster: s.master }, protectedRoomPointers(s.v2))
159
160
  }
160
161
  /** The rooms another device wrote into the head, kept beside this device's (never one this device forgot). */
161
162
  async function recordOverHead(s, key, head) {
162
163
  const remote = head?.blob ? await openRecord(key, head.blob) : null
163
164
  if (!remote) throw fail('unopenable', 'the current backup could not be opened')
164
165
  const { rooms, tomb } = mergeIndex(s, { rooms: roomsOfRecord(remote), tomb: tombOfRecord(remote) })
165
- return recordOf({ ...s, tomb }, rooms)
166
+ const local = await recordOf({ ...s, tomb }, rooms)
167
+ return mergeProtectedRoomPointers(local, local, remote)
166
168
  }
167
169
  const openRecord = async (key, sealed) => { try { const d = await unseal(key, sealed); return vaultOwner(d) === 'sdk' ? d : null } catch { return null } }
168
170
 
@@ -215,7 +217,7 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
215
217
  const deviceKey = async () => { const rec = await ensureKeyRecord(ks); return rec && rec.priv && rec.spk ? { priv: rec.priv, pub: rec.pub, spk: rec.spk } : null }
216
218
  async function sealed(payload, newCode, newMaster) {
217
219
  const cs = codeSecret(newCode), loc = await backupLocation(newMaster)
218
- return { newCode, newMaster, backupId: loc.id, wrapperId: (await wrapperLocation(cs)).id, backupBlob: utf8(await seal(loc.key, payload)), wrapperBlob: utf8(await sealWrapper(cs, newMaster)) }
220
+ return { newCode, newMaster, roomDir: roomDirectoryTag(payload), backupId: loc.id, wrapperId: (await wrapperLocation(cs)).id, backupBlob: utf8(await seal(loc.key, payload)), wrapperBlob: utf8(await sealWrapper(cs, newMaster)) }
219
221
  }
220
222
  return makeAcctV2({
221
223
  base, fetch: hooks.beforeFetch ? async (...a) => { await hooks.beforeFetch(); return fetchWatched(...a) } : fetchWatched, headers, storage, // beforeFetch: a restore's "finish sent" mark is on disk before the finish goes
@@ -226,6 +228,15 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
226
228
  codeBytesOf: codeSecret,
227
229
  beforeLegacyCommit: hooks.beforeLegacyCommit,
228
230
  legacyAborted: hooks.legacyAborted,
231
+ // sync sweep 2026-12-04 O10: from the account's IDENTITY master (`s.master`) — the one sdkErase.js _commitFor made the room's
232
+ // delete commitment with at its create. `saved` is the BACKUP master (`v2.bm`, a fresh secret at setup and at every new code),
233
+ // so the proof it gave never matched the commitment and the account room's device binding was refused.
234
+ accountCreatorProof: async (saved, room) => {
235
+ if (!s.master) return null
236
+ const { eraseKeyOf } = await import('./sdkErase.js')
237
+ const { delSecretFor } = await import('./roomDelete.js')
238
+ return delSecretFor(await eraseKeyOf(s.master), room)
239
+ },
229
240
  backupIdOf: async (m) => (await backupLocation(m)).id,
230
241
  wrapperIdOf: async (c) => (await wrapperLocation(c)).id,
231
242
  acctKey: () => hooks.legacy?.acctKey || null,
@@ -272,6 +283,8 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
272
283
  sealId: async () => (s.v2 && s.v2.bm ? [...new Uint8Array(await crypto.subtle.digest('SHA-256', utf8('push-seal|' + s.v2.bm)))].slice(0, 8).map((x) => x.toString(16).padStart(2, '0')).join('') : ''),
273
284
  // undefined = NOT KNOWN YET (the subscription is still loading — Codex sweep 2026-11-16 #2): syncPush then sends nothing
274
285
  pushEndpoint: async () => { try { const e = await pushEndpoint(); return e === undefined ? undefined : (e || null) } catch { return undefined } },
286
+ // sync sweep 2026-12-04 O8: with its encryption keys, so the email-move security notice can reach this device (acctV2App.syncPush)
287
+ ...(typeof pushSubscription === 'function' ? { pushSubscription: async () => { try { const v = await pushSubscription(); return v === undefined ? undefined : (v || null) } catch { return undefined } } } : {}),
275
288
  sealPush: async (endpoint) => { const d = await sealDoc(await pushKey(s), { e: endpoint }); return (d.z ? '1.' : '0.') + d.s },
276
289
  openPush: async (sealed) => { // the current master, then the kept previous ones (#1)
277
290
  const [z, x] = String(sealed).split('.')
@@ -537,7 +550,7 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
537
550
  const plan = applyPlan(payload, {}, { app: SDK_APP })
538
551
  done = { master: identity, rooms: roomsOfRecord(plan ? { ...payload, recents: plan.add } : payload), tomb: tombOfRecord(payload),
539
552
  ...(payload.email ? { email: payload.email } : {}), ...((plan ? plan.inviteKey : payload.inviteKey) ? { invite: plan ? plan.inviteKey : payload.inviteKey } : {}),
540
- format: 'account', v2: { ...s1.v2, bm: b64(bm) } }
553
+ format: 'account', v2: { ...s1.v2, bm: b64(bm), ...(payload.accountRooms ? { accountRooms: protectedRoomPointers(payload) } : {}) } }
541
554
  return done.rooms.length
542
555
  },
543
556
  })
@@ -563,11 +576,13 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
563
576
  let head
564
577
  try { head = await a.readBackup(loc.id) } catch (e) { throw fail('save_failed', 'the backup could not be read', { status: e && e.status, reason: e && e.code }) }
565
578
  if (b._s !== s0) return
566
- const blob = await seal(loc.key, await recordOverHead(s0, loc.key, head))
579
+ const payload = await recordOverHead(s0, loc.key, head)
580
+ const blob = await seal(loc.key, payload)
567
581
  if (b._s !== s0) return
568
582
  let r
569
- try { r = await a.writeBackup(loc.id, blob, head) } catch (e) { throw fail('save_failed', 'the backup could not be saved', { status: e && e.status, reason: e && e.code }) }
583
+ try { r = await a.writeBackup(loc.id, blob, head, roomDirectoryTag(payload)) } catch (e) { throw fail('save_failed', 'the backup could not be saved', { status: e && e.status, reason: e && e.code }) }
570
584
  if (r === 'conflict') { await new Promise((res) => setTimeout(res, 100 + Math.floor(Math.random() * 300))); continue }
585
+ if (b._s === s0 && payload.accountRooms) s0.v2.accountRooms = protectedRoomPointers(payload)
571
586
  b.lastError = null
572
587
  return
573
588
  }
@@ -611,6 +626,7 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
611
626
  },
612
627
  /** docs/device-gate-design.md: this ACTIVE device's ten-minute room pass for its session key (roomPass.js) → { pass, sig, exp } —
613
628
  * in this vault's tenant's scope (x-acct-tenant). A signed-out device is refused (`revoked`), and onRevoked runs the status check. */
629
+ async accountRoomPassFor(b, room, pub, kind, proofs) { return client(onService(b)).accountRoomPassFor(room, pub, kind, proofs) },
614
630
  async roomPass(b, email, sessionPub) {
615
631
  const s = onService(b)
616
632
  return client(s).roomPass(email, sessionPub)
package/sdkPlan.js CHANGED
@@ -19,10 +19,10 @@ const RANK = { none: 0, in_place: 1, fork: 2, new_room: 3 }
19
19
 
20
20
  /**
21
21
  * @param change { agent?: { name?, instructions?, model? }, data?, platformTools?, framing?, dataWrites?, admission?, tier?, key?, tools?, immediateTools? }
22
- * @param room { cfg (the room's sealed config, or null), me (the signed-in email, or ''), lane (bool), checkData?(data) }
22
+ * @param room { cfg (the room's sealed config, or null), me (the signed-in email, or ''), lane (bool), checkData?(data), cfgUnread? (the read failed) }
23
23
  * → { how: 'none'|'in_place'|'new_room'|'refused', history: 'kept'|'not_carried'|null, call, steps, reason? }
24
24
  */
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
+ export function planChange (change = {}, { cfg = null, me = '', role = roleFor(cfg, { email: me }), lane = false, activeLane = lane, checkData = null, gatedUnread = false, cfgUnread = false, signIn = 'wb.signIn' } = {}) { // cfgUnread: the settings read failed (not an open room) // signIn: the call that signs in here ('wb.vault.signIn' in a vault) // gatedUnread: a gated room answered only its stub (not signed in)
26
26
  const steps = []
27
27
  let members = false // the change includes a member list (in place: space.changeMembers)
28
28
  let how = 'none', refusal = null
@@ -63,6 +63,7 @@ export function planChange (change = {}, { cfg = null, me = '', role = roleFor(c
63
63
  if (change.admission !== undefined) {
64
64
  if (lane) refuse('lane', "a lane is one member's own room — change its Space's members instead")
65
65
  else if (gatedUnread && !cfg) { need('in_place'); refuse('sign_in_required', 'a member change needs a signed-in member (' + signIn + ')') } // a gated room read signed out: it IS gated, its gate unread
66
+ else if (cfgUnread && !cfg) refuse('config_unavailable', "this Space's settings could not be read — try again (a member change keeps the room and its history)") // sync sweep 2026-12-04 O27: a failed read is not an open room (it planned a new room and lost history)
66
67
  else if (!cfg || cfg.admission !== 'email') { need('new_room'); steps.push("admission: an open room's link IS its membership — gate a new room (createSpace({ admission })); the history does not come along") }
67
68
  else {
68
69
  // A gate fork() would refuse is a refusal here, never a throw (sync sweep, 2026-10-12: normAdmission throws).
@@ -86,6 +87,11 @@ export function planChange (change = {}, { cfg = null, me = '', role = roleFor(c
86
87
  const old = rolesOf(cfg)
87
88
  const ownerTags = change.admission.ownerTags ?? old.ownerTags, adminTags = change.admission.adminTags ?? old.adminTags
88
89
  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' })
90
+ // sync sweep 2026-12-04 O28: a STATED role tag must name someone — a role held now or a tag on the list — as changeMembers
91
+ // refuses it (sdkRekey.js planMembers); the plan said "in place" for a change the call then refused
92
+ const knownTags = new Set([...(Array.isArray(cfg.allow?.mh) ? cfg.allow.mh : []), ...old.ownerTags, ...old.adminTags])
93
+ const stray = [...(change.admission.ownerTags || []), ...(change.admission.adminTags || [])].find(t => !knownTags.has(t))
94
+ if (stray) throw Object.assign(new Error('a role tag must be one admission() reports, or name someone on the list (' + String(stray).slice(0, 8) + '…)'), { code: 'invalid_argument' })
89
95
  if (role !== 'owner' && (old.owners.length || old.ownerTags.length) &&
90
96
  (ownerTags.length !== old.ownerTags.length || old.ownerTags.some(t => !ownerTags.includes(t)) || old.adminTags.some(t => !adminTags.includes(t) && !ownerTags.includes(t)))) {
91
97
  throw Object.assign(new Error('Only an owner can change the owners or lower an admin'), { code: 'not_owner' })
@@ -0,0 +1,68 @@
1
+ // Single-room pilot wire format. Callers supply deployment and region from verified configuration.
2
+ import { roomRegion, REGIONS } from './regions.js'
3
+
4
+ const fields = {
5
+ 'app-challenge': [],
6
+ 'app-request': ['packet', 'proof'],
7
+ challenge: ['mk'],
8
+ pending: ['mk', 'readAttestation'],
9
+ poll: ['mk', 'readAttestation', 'sinceCount'],
10
+ turn: ['mk', 'message'],
11
+ }
12
+
13
+ export function validRoomHeader (h, destination) {
14
+ return h?.version === 2 && h.tier === 'confidential' &&
15
+ typeof h.deployment === 'string' && h.deployment.length > 0 && h.deployment === destination.deployment &&
16
+ Object.hasOwn(REGIONS, h.region) && h.region === destination.region &&
17
+ Object.hasOwn(fields, h.op) && Number.isSafeInteger(h.ts) &&
18
+ typeof h.nonce === 'string' && /^[A-Za-z0-9_-]{16}$/.test(h.nonce)
19
+ }
20
+
21
+ // JSON-array encoding is positional and unambiguous even when a deployment name contains punctuation.
22
+ export function roomWireContext (h, purpose) {
23
+ return JSON.stringify(['witbitz-sealed-room', 2, purpose, h.deployment, h.region, h.tier, h.op, h.ts, h.nonce])
24
+ }
25
+
26
+ export const hardwareTicketPurpose = 'witbitz:sealed-room:hardware-ticket:v1'
27
+ export function hardwareChallengeBinding (deployment, keyId, nonce) {
28
+ return JSON.stringify([hardwareTicketPurpose, 'issue', deployment, 'ios', keyId, nonce])
29
+ }
30
+
31
+ // Both hardware and account keys sign the same fresh, room-bound request. The
32
+ // account service sees only its digest and the account's public session key.
33
+ export function accountRequestSubject(packet, deployment, keyId, identity) {
34
+ return ['witbitz-sealed-account-request-v1', deployment, keyId, packet, identity.idToken, identity.spk, identity.sessionPub]
35
+ }
36
+
37
+ // A distinct grammar survives a restore or a lost local tier mark.
38
+ export const isSealedAppRoom = room => typeof room === 'string' && /^sp-s2-[0-9a-f]{32}$/.test(room)
39
+ export const sealedAppHref = room => isSealedAppRoom(room) ? '/space#sealedRoom=' + room : null
40
+ export function sealedAppRoomFromHash (hash) {
41
+ const room = new URLSearchParams(String(hash).replace(/^#/, '')).get('sealedRoom')
42
+ return isSealedAppRoom(room) ? room : null
43
+ }
44
+ export function newSealedAppRoom () {
45
+ return 'sp-s2-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), b => b.toString(16).padStart(2, '0')).join('')
46
+ }
47
+
48
+ export function validRoomPayload (req, h) {
49
+ return req && typeof req === 'object' && !Array.isArray(req) &&
50
+ typeof req.room === 'string' && (isSealedAppRoom(req.room) || /^(?:sp|tmp)-(?:[a-z]{2}-)?[a-z0-9]{1,12}$/.test(req.room)) &&
51
+ roomRegion(req.room) === h.region && req.op === h.op &&
52
+ Object.keys(req).every(k => k === 'room' || k === 'op' || k === 'deviceTicket' || fields[h.op].includes(k))
53
+ }
54
+
55
+ // This pilot serves hardware-only rooms in EU. The receiver chooses the pinned
56
+ // service locally. An invite can never select a URL, policy or trust root.
57
+ export function validPilotHandoff (value) {
58
+ return !!value && typeof value === 'object' && (Object.keys(value).length === 2 || (Object.keys(value).length === 3 && isSealedAppRoom(value.room) && value.gate === 'email')) &&
59
+ Object.hasOwn(value, 'room') && typeof value.room === 'string' &&
60
+ (isSealedAppRoom(value.room) || /^(?:sp|tmp)-(?:eu-)?[a-z0-9]{1,12}$/.test(value.room)) && roomRegion(value.room) === 'eu' &&
61
+ Object.hasOwn(value, 'mk') && typeof value.mk === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value.mk)
62
+ }
63
+
64
+ // Bind a hosted-origin assertion to the vault that alone can read the answer.
65
+ export async function hostedAnswerBinding(key) {
66
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', key))
67
+ return btoa(String.fromCharCode(...digest)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
68
+ }
package/spaceClient.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { isSealedAppRoom } from './sealedRoomWire.js'
1
2
  // witz/public/spaceClient.js — the THIN async-Space client (docs/async-spaces-m2.md).
2
3
  //
3
4
  // The client holds `mk` (reconstructed LOCALLY from the link fragment). TWO read paths exist:
@@ -241,8 +242,10 @@ export function workerEnvelopeTransport(forward) {
241
242
  }
242
243
 
243
244
  async function call(endpoint, body, fetchImpl) {
245
+ if (isSealedAppRoom(body?.room) || isSealedAppRoom(body?.bridgeRoom) || (Array.isArray(body?.rooms) && body.rooms.some(isSealedAppRoom))) throw new Error('sealed room transport required')
244
246
  const routed = await ohttpSend(body, fetchImpl)
245
247
  if (routed !== null) return routed
248
+ if (relayRequired) return relayUnavailable() // the choice can change at the await above
246
249
  const res = await fetchImpl(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
247
250
  let data = {}
248
251
  try { data = await res.json() } catch { /* non-JSON → status only */ }
@@ -348,10 +351,30 @@ const VOICE_OPS = new Set(['stt', 'tts'])
348
351
  // 5xx, no network. Jittered ×0.5–1.5. After the last, the room is "could not tell" for TIER_RETRY_MS.
349
352
  const TIER_PROBE_WAITS = [500, 1500] // spread wide: a burst of rooms probing together must not retry together into the same limit
350
353
  const tierFault = (r) => !r || !r.status || r.status === 429 || r.status >= 500
351
- export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl, auth, mkPub, app, enclave = false, envelope = false, identity = false, tenant, userToken, delCommit, roomPass = null, renewSignIn = null, onConfidential = null, tierWaits = TIER_PROBE_WAITS } = {}) {
354
+ // the writes after which a room's shared config read (getConfig, policyForConfig) is stale: what the `policy` op answers moves
355
+ const CONFIG_WRITES = new Set(['config', 'rekey', 'create', 'owner-policy', 'leave', 'purge', 'drop', 'toolrules', 'carry', 'grant'])
356
+ export function makeSpaceClient({ sealedAppRequest, sealedAccount = false, endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl, auth, mkPub, app, enclave = false, envelope = false, identity = false, tenant, userToken, delCommit, roomPass = null, accountRoomAccess = null, renewSignIn = null, onConfidential = null, tierWaits = TIER_PROBE_WAITS } = {}) {
352
357
  const tenantHint = tenant ? { tid: String(tenant).slice(0, 64) } : {}
353
358
  const f = fetchImpl || (typeof fetch !== 'undefined' ? fetch : null)
354
359
  if (!f) throw new Error('no fetch available — pass { fetch }')
360
+ const existingRoles = new Map(), retryProofAfter = new Map()
361
+ async function sendRoomRequest(body, retryUpgrade = true) {
362
+ const room = body.room, kind = existingRoles.get(room)
363
+ let wire = body
364
+ if (accountRoomAccess && kind && body.op !== 'intakedrop' && !(retryProofAfter.get(room) > Date.now())) {
365
+ try { wire = await accountRoomAccess.sign(body, kind) } catch {
366
+ // Old vaults and accounts without a creator proof continue syncing during grace.
367
+ retryProofAfter.set(room, Date.now() + 60_000)
368
+ }
369
+ }
370
+ const result = await call(endpoint, wire, f)
371
+ if (typeof room === 'string' && /^sp-(?:us-)?[a-z0-9]{1,12}$/.test(room) &&
372
+ [200, 426].includes(result.status) && ['index', 'pipes', 'msgs'].includes(result.accountRoomKind)) {
373
+ existingRoles.set(room, result.accountRoomKind)
374
+ if (accountRoomAccess && !kind && retryUpgrade && result.status === 426) return sendRoomRequest(body, false)
375
+ }
376
+ return result
377
+ }
355
378
  // ENCLAVE TIER. `enclave` and `mkPub` may EACH be a value OR a per-room function (room) => …, so ONE client can run
356
379
  // some rooms in the enclave and others normally (a room's tier is fixed at creation). For an enclave room, post()
357
380
  // marks the op enclave:true (the backend relays it to the Nitro enclave) and keyFields() seals mk to the room's
@@ -408,6 +431,21 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
408
431
  try { const t = typeof userToken === 'function' ? await userToken() : userToken; return typeof t === 'string' ? t : '' } catch { return '' }
409
432
  }
410
433
  const post = async (body, billingToken) => {
434
+ if (body && typeof body.room === 'string' && CONFIG_WRITES.has(body.op)) cfgReads.delete(body.room) // getConfig's shared read (below) is stale now
435
+ if (typeof body?.room === 'string' && /^sp-ar2-[0-9a-f]{40}$/.test(body.room) && body.op !== 'intakedrop') {
436
+ if (!accountRoomAccess) return { status: 403, error: 'account_room_device_required' }
437
+ return call(endpoint, await accountRoomAccess.sign(body), f)
438
+ }
439
+ if (isSealedAppRoom(body?.room)) {
440
+ if (!sealedAppRequest) throw new Error('sealed room transport unavailable')
441
+ const sendSealed = async () => sealedAppRequest(body.readAttestation || ATTEST_OWN_OPS.has(body.op) ? body : { ...body, ...await readAttestFor(body.room) })
442
+ let response = await sendSealed()
443
+ if (response?.error === 'attest_required' && typeof response.challenge === 'string' && !body.readAttestation && !ATTEST_OWN_OPS.has(body.op)) {
444
+ attestReadRooms.set(body.room, response.challenge)
445
+ response = await sendSealed()
446
+ }
447
+ return response
448
+ }
411
449
  const tok = typeof billingToken === 'string' ? billingToken : body && !body.userToken ? await tokenFor(body.op) : '' // a token the caller passed (the SDK's user) is never replaced
412
450
  // In a CONFIDENTIAL room the token rides SEALED to the attested enclave (turn.mjs opens it; docs/tenant-billing.md
413
451
  // § 12.2) — the relay must neither read nor swap who pays. A seal that cannot be made sends no token at all.
@@ -438,7 +476,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
438
476
  // confidential room showed nothing to a signed-in SDK (sweep 11-07 #4; the app sends no sign-in for an open room). The
439
477
  // read needs no sign-in: it goes plain WITHOUT it for a short while — the sign-in never goes outside an envelope.
440
478
  const idOnly = sealedWay === true && PLAIN_OPS.has(body.op) && !gatedRooms.has(body.room)
441
- const plainNoId = () => { const { idToken: _t, spk: _s, pass: _p, psig: _q, ...rest } = body; return call(endpoint, rest, f) }
479
+ const plainNoId = () => { const { idToken: _t, spk: _s, pass: _p, psig: _q, ...rest } = body; return sendRoomRequest(rest) }
442
480
  if (idOnly && (asleepPlain.get(body.room) || 0) > Date.now()) return plainNoId()
443
481
  if (sealedWay === true) {
444
482
  const pub = mkPubFor(body.room) // fail CLOSED: an enclave that opens envelopes but no attested key here → nothing is sent
@@ -480,7 +518,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
480
518
  if (typeof body.mk === 'string' && body.mk) { const no = await keyFor(body.room); if (no) return no }
481
519
  if (typeof body.bridgeMk === 'string' && body.bridgeMk && typeof body.bridgeRoom === 'string' && body.bridgeRoom) { const no = await keyFor(body.bridgeRoom); if (no) return no }
482
520
  }
483
- return call(endpoint, body, f)
521
+ return sendRoomRequest(body)
484
522
  }
485
523
  let r = await send()
486
524
  // A KEYLESS REQUEST REFUSED AS CONFIDENTIAL (agent/tierGuard.mjs: `409 confidential_room` — the refused request ran nothing): this
@@ -555,7 +593,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
555
593
  try {
556
594
  let r = null
557
595
  for (let i = 0; ; i++) {
558
- try { r = await call(endpoint, { op: 'policy', room, ...(await authFor(room)) }, f) } catch { r = { status: 0 } }
596
+ try { r = await sendRoomRequest({ op: 'policy', room, ...(await authFor(room)) }) } catch { r = { status: 0 } }
559
597
  if (saysTier(r) || i >= tierWaits.length || !tierFault(r)) break
560
598
  await new Promise((res) => setTimeout(res, tierWaits[i] * (0.5 + Math.random())))
561
599
  }
@@ -641,6 +679,10 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
641
679
  return out
642
680
  }
643
681
  const keyFields = async (room, op, mk) => {
682
+ if (isSealedAppRoom(room)) {
683
+ if (!sealedAppRequest) throw new Error('sealed room transport unavailable')
684
+ return { mk }
685
+ }
644
686
  const pub = mkPubFor(room)
645
687
  if (enclaveFor(room) && !pub) throw new Error('enclave key unavailable for this room — refusing to send the room key to the relay')
646
688
  if (!pub || !mk) return { mk }
@@ -674,7 +716,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
674
716
  const healEnclaveConfig = async (room, mk) => {
675
717
  if (!mk || !enclaveFor(room)) return null
676
718
  let s = null
677
- try { s = await call(endpoint, { op: 'policy', room }, f) } catch { return null }
719
+ try { s = await sendRoomRequest({ op: 'policy', room }) } catch { return null }
678
720
  if (!s || typeof s.configSealed !== 'string' || !s.configSealed) return null
679
721
  let cfg = null
680
722
  try { cfg = JSON.parse(await open(JSON.parse(s.configSealed), { mk })) } catch { cfg = null }
@@ -683,7 +725,25 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
683
725
  try { r = await post({ op: 'config', room, ...(await keyFields(room, 'config', mk)), configSealed: s.configSealed, ...(await authFor(room)) }) } catch { r = null }
684
726
  return { cfg, configSealed: s.configSealed, saved: !!(r && r.status === 200) }
685
727
  }
686
- const policyPost = async (room, mk) => post({ op: 'policy', room, ...(mk ? await keyFields(room, 'policy', mk) : {}), ...(await authFor(room)) })
728
+ // CONFIG READS ASKED TOGETHER SHARE ONE REQUEST (the owner, 2026-12-03: a launch's ~1,600 requests in a minute; measured with
729
+ // spaces/test/members/launchLoad.mjs: the open room's `policy` read 21 times a minute, 18 of them from getConfig — the move button,
730
+ // the safe-media check, the lane's inheritance, Help … each asks the worker on its own, often at the same moment). getConfig alone
731
+ // shares the read IN FLIGHT, per room and key; nothing is kept once it answers. ⛔ NOT A TIME WINDOW: the page, its key worker and
732
+ // the vault each hold a client, and a write through one never reaches another's copy — a 1.5 s cache already left a new private
733
+ // lane on a stale config (spaces/test/members/topology.test.mjs failed). The reads that must see the server now — setConfig,
734
+ // rekey, the key chain, governance, attestedRoom — call policyPost itself.
735
+ // sync sweep 2026-12-04 N4: per room, key AND sign-in — the server answers a gated room by WHO asks too, so a read sent before
736
+ // the sign-in (the gated stub) must not answer a call made after it (an admitted member lost settings and lanes on that open).
737
+ const cfgReads = new Map() // room → { mk, who, p }
738
+ const policyForConfig = async (room, mk) => {
739
+ const a = await authFor(room), who = a.idToken || ''
740
+ const c = cfgReads.get(room)
741
+ if (c && c.mk === mk && c.who === who) return c.p
742
+ const p = policyPost(room, mk, a).finally(() => { if (cfgReads.get(room)?.p === p) cfgReads.delete(room) })
743
+ cfgReads.set(room, { mk, who, p })
744
+ return p
745
+ }
746
+ const policyPost = async (room, mk, a) => post({ op: 'policy', room, ...(mk ? await keyFields(room, 'policy', mk) : {}), ...(a || await authFor(room)) })
687
747
  const linksFields = async (room, op, links) => (await sealField(room, op + ':links', JSON.stringify(links), 'links')) || { links }
688
748
 
689
749
  // reconstruct mk from the pieces carried in a set of links (a share `#s=` each, or `#mk=` for solo)
@@ -710,6 +770,10 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
710
770
  const sealedRead = async (room, mk, op, fields, { proveKey = false, sent = null } = {}) => {
711
771
  // the enclave ASLEEP with no attested key here: the keyed retry cannot go (keyFields fails closed) — it threw, the poll swallowed
712
772
  // it and no banner showed until a wake (sync sweep 11-08/11-09). Answer what it is instead: the enclave is starting, nothing sent.
773
+ if (isSealedAppRoom(room)) {
774
+ if (sent) sent.keyed = !!mk
775
+ return post({ op, room, ...fields, ...(mk ? { mk } : {}), ...await authFor(room), ...await attestFor(room, op, fields) })
776
+ }
713
777
  const keyed = async () => { if (enclaveFor(room) && !mkPubFor(room)) return { status: 503, ok: false, error: 'enclave_warming', retry: true, reason: 'this confidential Space\'s enclave is asleep — nothing was sent' }; if (sent) sent.keyed = true; const k = await post({ op, room, ...fields, ...(await keyFields(room, op, mk)), ...(await authFor(room)), ...(await attestFor(room)) }); if (k && k.status === 200) keyedOk.add(room); return k }
714
778
  if (mk && (proveKey || (gatedRooms.has(room) && (enclaveFor(room) || keyFirstNow(room))))) return keyed()
715
779
  const r = await post({ op, room, ...fields, ...(await authFor(room)), ...(await attestFor(room, op, fields)) })
@@ -930,11 +994,18 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
930
994
  return { blobs, stats }
931
995
  }
932
996
  const api = {
997
+ async reopenSealedInvite ({ room, mk, gate }) {
998
+ if (!isSealedAppRoom(room) || !sealedAppRequest) return false
999
+ const reply = await sealedAppRequest({ op: 'reopen', room, mk })
1000
+ return reply.status === 200 && reply.opened === true && (reply.gated === true) === (gate === 'email')
1001
+ },
933
1002
  _openAny: openAny, // internal: a box opened with the room's key or, after an in-place change, an earlier one (tests)
934
1003
  /** Mint a Space from a config, register its PUBLIC record (commit + config) with the server, and return
935
1004
  * { room, mk, commit, links, keyModel }. `mk` is reconstructed locally from the minted pieces — it is NEVER sent
936
1005
  * to the server (only its commitment is). The `links` are what you hand to members. */
937
- async create(config = {}, { base = originBase(), gk, enclave: enclaveOpt, split = false, via = null, lapseDays } = {}) {
1006
+ async create(config = {}, { base = originBase(), gk, enclave: enclaveOpt, split = false, via = null, lapseDays, reservedUserShare, roomKind } = {}) {
1007
+ if (reservedUserShare !== undefined && (!isSealedAppRoom(config.room) || !split || !/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(reservedUserShare))) throw Error('invalid reserved room share')
1008
+ if (isSealedAppRoom(config.room) && (via || (split && (!sealedAccount || config.admission !== 'email')) || tenant || (config.admission === 'email' && !sealedAccount) || !enclaveOpt || config.requireApp !== 'app')) throw new Error('unsupported sealed room creation path')
938
1009
  const space = await createConfiguredSpace(config, { base })
939
1010
  const mk = await mkFromLinks(space.links, config, space.commit)
940
1011
  // Prepare the email allow-list for sealing. Co-members hold mk and can decrypt the config, so HIDDEN addresses are
@@ -987,13 +1058,15 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
987
1058
  // SPLIT (docs/sdk-split-key.md): mk = userShare ⊕ appShare. The RAW app half rides this create once; the server seals
988
1059
  // it under the page's tenant's K_eco (platform custody) and never stores it in the clear. userShare goes back to the
989
1060
  // caller for the room's #us= link and is never sent.
990
- const sp = split ? splitKey(mk) : null
1061
+ const sp = reservedUserShare ? { shareA: reservedUserShare, shareB: combineShares(mk, reservedUserShare) } : split ? splitKey(mk) : null
991
1062
  // `via` (2026-10-02): a BUILDER-HOSTED app-half function. The create goes to the builder's own function, which seals
992
1063
  // the half under ITS K_eco and registers the room through the tenant door with its tenant key — the same path our
993
1064
  // vault's /api/appshare takes. Witbitz then stores a half it cannot open. Absent ⇒ this endpoint, as before.
994
1065
  const send = typeof via === 'function' ? via : post
995
1066
  const dc = typeof delCommit === 'function' ? await delCommit(space.room).catch(() => null) : null // only the creating account can later delete this room (docs/user-erasure.md)
996
- const r = await send({ op: 'create', ...(app ? { app } : {}), room: space.room, commit: space.commit, configSealed, invite: invitePad(), ...(Number.isInteger(lapseDays) && lapseDays >= 1 && lapseDays <= 7 ? { lapseDays } : {}) /* a temporary room kept days after its last question (docs/visitor-limits.md) — beside the sealed config, never in it */, ...ownerFields, ...(dc ? { delCommit: dc } : {}), ...(sp ? { appShare: sp.shareB } : {}), ...embedAttribution(), ...tenantHint, ...(config.admission === 'email' ? { gated: true } : {}), ...(config.requireVerifiedClient ? { requireVerifiedClient: true } : {}), ...(gk ? { gk } : {}), ...(enclaveOpt ? { enclave: true } : {}), ...(config.help === true && config.install === true ? { installHelp: true } : {}) }) // installHelp: the front marks the room's record — its turns get the front's ticket (docs/install-help.md)
1067
+ const r = await send({ op: 'create', ...(isSealedAppRoom(space.room) ? { mk } : {}), ...(app ? { app } : {}), ...(typeof roomKind === 'string' && /^[a-z]{1,16}$/.test(roomKind) ? { roomKind } : {}) /* the room's TYPE on a tenant's row (an account's index: 'index'; sync sweep 12-04 O10) */, room: space.room, commit: space.commit, configSealed, invite: invitePad(), ...(Number.isInteger(lapseDays) && lapseDays >= 1 && lapseDays <= 7 ? { lapseDays } : {}) /* a temporary room kept days after its last question (docs/visitor-limits.md) — beside the sealed config, never in it */, ...ownerFields, ...(dc ? { delCommit: dc } : {}), ...(sp ? { appShare: sp.shareB } : {}), ...embedAttribution(), ...tenantHint, ...(config.admission === 'email' ? { gated: true } : {}), ...(config.requireVerifiedClient ? { requireVerifiedClient: true } : {}), ...(gk ? { gk } : {}), ...(enclaveOpt ? { enclave: true } : {}), ...(config.help === true && config.install === true ? { installHelp: true } : {}) }) // installHelp: the front marks the room's record — its turns get the front's ticket (docs/install-help.md)
1068
+ if (isSealedAppRoom(space.room) && r.status === 200 && r.created !== true) throw new Error('sealed room creation was not confirmed')
1069
+ if (/^sp-ar2-[0-9a-f]{40}$/.test(space.room) && r.status === 200 && r.accountRoom !== true) throw new Error('server did not confirm protected account room')
997
1070
  if (r.status !== 200) throw Object.assign(new Error(`create failed: ${r.status} ${r.error || ''}${r.reason ? ' — ' + r.reason : ''}`), { status: r.status, ...(r.error ? { code: String(r.error) } : {}), ...(r.reason ? { reason: r.reason } : {}) }) // the server's code on the error (config_too_large, tenant_required, …) — sync sweep, 2026-10-10
998
1071
  if (config.admission === 'email') { gatedRooms.add(space.room); if (config.ownerPolicy) keyFirst.set(space.room, Infinity) } // owner-governed: its reads carry the key (sweep 11-07 #5)
999
1072
  if (config.requireVerifiedClient) verifiedRooms.add(space.room)
@@ -1002,7 +1075,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1002
1075
  // agent). The app does this inline; the SDK needs it too, and re-sealing outside would be a second source of truth.
1003
1076
  // `enclaveCreated`: the CONFIDENTIAL create was answered `created: true` — by the enclave, whose create keeps configSealed in
1004
1077
  // the room's record (agent/spaceRoom.mjs). The SDK then skips handing it over a second time (witbitz-sdk _encSealConfig).
1005
- return { room: space.room, mk, commit: space.commit, links: space.links, keyModel: space.keyModel, configSealed, ...(sp ? { userShare: sp.shareA } : {}), ...(enclaveOpt && r.created === true ? { enclaveCreated: true } : {}) }
1078
+ return { room: space.room, mk, commit: space.commit, links: sp && isSealedAppRoom(space.room) ? [] : space.links, keyModel: space.keyModel, configSealed, ...(sp ? { userShare: sp.shareA } : {}), ...(enclaveOpt && r.created === true ? { enclaveCreated: true } : {}) }
1006
1079
  },
1007
1080
  /** The app half of a SPLIT room, for a page on an origin the room's tenant declared (op:'appshare-page'). → { status, appShare, commit } */
1008
1081
  appSharePage: async (room) => post({ op: 'appshare-page', room }),
@@ -1083,6 +1156,10 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1083
1156
  const { sig } = await signEntry(identity.sign.priv, { room, author: identity.name, ts, kind: 'text', id, text, ...(message && message.chal ? { chal: message.chal } : {}) })
1084
1157
  m = { ...message, from: identity.name, ts, id, kind: 'text', sig, spk: identity.sign.pub }
1085
1158
  }
1159
+ if (isSealedAppRoom(room)) {
1160
+ if (bridgeRoom || bridgeMk || links?.length || run || call || schema) throw Error('This private room supports messages in this room only')
1161
+ return post({ op: 'turn', room, mk, message: m, ...(mode ? { mode } : {}) })
1162
+ }
1086
1163
  return post({ op: 'turn', room, ...(await keyFields(room, 'turn', mk)), message: m, ...(viewSource ? { viewSource } : {}), ...(pushSelf() ? { pushSelf: pushSelf() } : {}), ...(await pushAcctField(room)), ...(await crossingPush(bridgeRoom)), ...(bridgeMk ? await bridgeFields(room, 'turn', bridgeMk) : {}), ...(bridgeRoom ? { bridgeRoom } : {}), ...(m && m.idToken ? {} : await otherAuth([bridgeRoom, ...(Array.isArray(links) ? links.map((l) => l && l.room) : [])])), ...(mode ? { mode } : {}), ...(Array.isArray(links) && links.length ? await linksFields(room, 'turn', links) : {}), ...(context ? { context } : {}), ...(instructions ? { instructions: String(instructions) } : {}), ...(Array.isArray(clientTools) && clientTools.length ? { clientTools } : {}), ...(clientGuidance ? { clientGuidance } : {}), ...(call ? { call: 1 } : {}), ...(stopKey ? { stopKey } : {}), ...(model ? { model } : {}), ...(receipt && receipt.drop ? { receipt } : {}), ...(showPrompt === true ? { showPrompt: true } : {}), ...(run === true ? { run: true } : {}), ...(run === true && schema ? { schema } : {}) }, billingToken) // model: the composer's per-room pick ({catalog, wire}), taken over the create-time model server-side // clientTools/clientGuidance: the device's on-device tools for this turn (calendar, …); call:1 flags a "started a call" turn so the room tickle opens the meeting link; stopKey: the prompter's per-turn cancel nonce (op:'stop' matches it — docs/spaces-stop-turn.md)
1087
1164
  },
1088
1165
  // USAGE RECEIPTS (docs/usage-receipts.md): this account's sealed receipts in a room, at its per-room drop, and the trim
@@ -1129,7 +1206,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1129
1206
  // opts.changeInbox — THE CHANGE INBOX (docs/change-inbox.md): this device's inbox id rides the room's first poll of a
1130
1207
  // session, and the server follows the room for it only if this poll succeeds and proves the key. Plain, outside
1131
1208
  // the sealed fields — a confidential room's relaying Lambda needs it, and it names no content.
1132
- const ci = opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {}
1209
+ const ci = !isSealedAppRoom(room) && opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {}
1133
1210
  // ⛔ A CONFIDENTIAL ROOM IS NEVER READ IN PLAINTEXT (docs/confidential-path-sweep-2026-11-05.md, finding B): the server
1134
1211
  // answers `poll` with the whole DECRYPTED history, and that answer crosses the Lambda and the enclave's parent host in
1135
1212
  // the clear. Read it sealed and open it here. Every caller (the room loop, the unread sweep, lanes, mail, pins…) comes
@@ -1152,7 +1229,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1152
1229
  * and the caller's render path is unchanged. A key that doesn't fit surfaces as the same 422/'undecodable' the
1153
1230
  * server used to return, except now the CLIENT proves it rather than being told. */
1154
1231
  async pollSealed(room, mk, sinceEtag, sinceCount = 0, opts = {}) {
1155
- const ci = opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {} // ONLY the inbox id: a plain op carries nothing a caller hands it by mistake (confidentialWire.test.mjs) // ci: { changeInbox } when poll() reads a confidential room sealed — the drawer's follow rides it (agent/changeFeed.mjs pollSubscribeIntent takes both ops)
1232
+ const ci = !isSealedAppRoom(room) && opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {} // ONLY the inbox id: a plain op carries nothing a caller hands it by mistake (confidentialWire.test.mjs) // ci: { changeInbox } when poll() reads a confidential room sealed — the drawer's follow rides it (agent/changeFeed.mjs pollSubscribeIntent takes both ops)
1156
1233
  // the key rides only as sealedRead says (proveKey: a regular room's read that registers the change inbox)
1157
1234
  const sent = { keyed: false }
1158
1235
  const send = async () => sealedRead(room, mk, 'pollsealed', { sinceEtag, sinceCount, ...ci, ...editField(opts) }, { proveKey: !!(opts && opts.proveKey && mk && !enclaveFor(room)), sent })
@@ -1290,7 +1367,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1290
1367
  // with room ids from the device's OWN recents list — no mk, no content — so the server never learns which rooms are
1291
1368
  // whose (the client does the fan-out; the server just pushes each `lapsesAt` out). Bounded here and again server-side;
1292
1369
  // best-effort by contract → a Space's life must never hinge on this succeeding. → { ok, rooms }.
1293
- touch: async (rooms) => post({ op: 'touch', rooms: (Array.isArray(rooms) ? rooms : [rooms]).filter((r) => typeof r === 'string' && r).slice(0, 200) }),
1370
+ touch: async (rooms) => post({ op: 'touch', rooms: (Array.isArray(rooms) ? rooms : [rooms]).filter((r) => typeof r === 'string' && r && !isSealedAppRoom(r)).slice(0, 200) }),
1294
1371
 
1295
1372
  // §APP STORE Stage 2: the PUBLIC registry-backed app catalog (no room/mk/auth) → { status, apps:[…] }.
1296
1373
  apps: async () => post({ op: 'apps' }),
@@ -1410,7 +1487,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1410
1487
  // `{ plainMark: true }`: a PLAIN room (a read that worked, nothing sealed, no lanes bit) answers `{ plain: true }`, so null
1411
1488
  // means only that the read failed — a private lane waits on that, never inherits "nothing" (sync sweep 2026-11-03)
1412
1489
  getConfig: async (room, mk, o) => {
1413
- const r = await policyPost(room, mk)
1490
+ const r = await policyForConfig(room, mk)
1414
1491
  if (!r || r.status !== 200 || r.error || r.ok === false) return null // a refusal is not a plain room (sweep 11-06 #1: an envelope refusal read as { plain: true } → an OPEN lane)
1415
1492
  if (!r.configSealed && r.gated === true) { gatedRooms.add(room); return { admission: 'email', gated: true } } // a gated room before sign-in: that it is gated, and nothing else
1416
1493
  if (!r.configSealed) { const h = await healEnclaveConfig(room, mk); if (h) return h.cfg }