@witbitz/sdk 4.7.1 → 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/README.md CHANGED
@@ -16,6 +16,6 @@ The guide: https://witbitz.chat/docs/sdk
16
16
 
17
17
  ## The same bytes as the hosted release
18
18
 
19
- Version 4.7.1 of this package is the release folder https://witbitz.chat/sdk/4.7.1/ unchanged (from commit
20
- `00dd61d7a078a10492a7f464b2734f66d0a92287`), plus this README, `package.json` and `LICENSE`. Its `manifest.json` lists the sha384 of every file; each file in the
19
+ Version 4.9.0 of this package is the release folder https://witbitz.chat/sdk/4.9.0/ unchanged (from commit
20
+ `cc0d7d7f0a2ebb3550ea65a0179128b5d33a5645`), plus this README, `package.json` and `LICENSE`. Its `manifest.json` lists the sha384 of every file; each file in the
21
21
  package matches it.
@@ -0,0 +1,54 @@
1
+ import { pointerToPublish } from './accountIndexDoc.js'
2
+
3
+ export const accountRoomKinds = Object.freeze(['index', 'pipes', 'msgs'])
4
+ const roomId = /^sp-ar2-[a-f0-9]{40}$/
5
+ export const isProtectedAccountRoom = room => typeof room === 'string' && roomId.test(room)
6
+ const roomKey = /^[A-Za-z0-9_-]{43}$/
7
+ const field = kind => kind + 'Room'
8
+
9
+ // Protected pointers travel in the authenticated backup. An outstanding index
10
+ // write can still target a link room while this device adopts the new directory.
11
+ export function publishedAccountPointer(local, remote) {
12
+ return isProtectedAccountRoom(local?.room) || isProtectedAccountRoom(remote?.room) ? null : pointerToPublish(local, remote)
13
+ }
14
+
15
+ export function protectedRoomPointers(record) {
16
+ const manifest = record?.accountRooms
17
+ if (manifest == null) return null
18
+ if (manifest.v !== 1 || typeof manifest.setId !== 'string' || !/^[a-f0-9]{32}$/.test(manifest.setId) ||
19
+ !['preparing', 'active'].includes(manifest.phase) ||
20
+ !accountRoomKinds.every(k => isProtectedAccountRoom(manifest[k]?.room) && typeof manifest[k]?.mk === 'string' && roomKey.test(manifest[k].mk)) ||
21
+ new Set(accountRoomKinds.map(k => manifest[k].room)).size !== accountRoomKinds.length) throw new Error('invalid account room manifest')
22
+ return manifest
23
+ }
24
+
25
+ // Local edits already live in each device's persistent Space list and lane registry.
26
+ // Resolve the signed directory on reconnect, then run their ordinary merge/CAS writers.
27
+ export async function replayAccountRoomEdits(record, { adopt, pushIndex, pushLanes, current }) {
28
+ const directory = protectedRoomPointers(record)
29
+ if (directory?.phase !== 'active' || !current()) return false
30
+ adopt(directory)
31
+ if (current()) await pushIndex()
32
+ if (current()) await pushLanes()
33
+ return true
34
+ }
35
+
36
+ export function applyProtectedRoomPointers(record, manifest) {
37
+ if (!manifest) return record
38
+ const out = { ...record, accountRooms: manifest }
39
+ if (manifest.phase === 'active') for (const kind of accountRoomKinds) out[field(kind)] = manifest[kind]
40
+ return out
41
+ }
42
+
43
+ // A previously published manifest wins over the device's cached link-room pointers.
44
+ // Competing room sets are a conflict, not a reason to guess which data to overwrite.
45
+ export function mergeProtectedRoomPointers(record, local, remote) {
46
+ const a = protectedRoomPointers(local), b = protectedRoomPointers(remote)
47
+ if (a && b && (a.setId !== b.setId || accountRoomKinds.some(k => a[k].room !== b[k].room || a[k].mk !== b[k].mk))) throw new Error('conflicting account room manifests')
48
+ return applyProtectedRoomPointers(record, b?.phase === 'active' ? b : a || b)
49
+ }
50
+
51
+ export function roomDirectoryTag(record) {
52
+ const m = protectedRoomPointers(record)
53
+ return m ? m.phase + '.' + m.setId : undefined
54
+ }
@@ -0,0 +1,79 @@
1
+ // Provision the three account rooms in the trusted client that owns the v2 backup.
2
+ // The pending manifest and its random keys are encrypted in the same backup as
3
+ // the active pointers. Publishing and resuming use the backup's versioned write.
4
+ import { newKey } from './e2ee.js'
5
+ import { backupLocation } from './backupVault.js'
6
+ import { seal, unseal } from './recovery.js'
7
+ import { makeAccountRoomAccess } from './roomPass.js'
8
+
9
+ import { accountRoomKinds as kinds, protectedRoomPointers, applyProtectedRoomPointers, roomDirectoryTag } from './accountRoomPointers.js'
10
+ const field = kind => kind + 'Room'
11
+
12
+ // Normal setup is limited to backups without predecessor rooms.
13
+ export function initializeAccountRooms(options) {
14
+ return provisionRooms(options)
15
+ }
16
+
17
+ // The isolated staging runner supplies proof for its own three sources and verifies
18
+ // their contents and retirement before this client can publish replacement pointers.
19
+ export function migrateStagingAccountRooms(options, migration) {
20
+ if (options.base !== 'https://preview.witbitz-spaces.pages.dev' || typeof migration?.verifySources !== 'function' ||
21
+ typeof migration?.copyAndRetire !== 'function') throw new Error('staging migration controller required')
22
+ return provisionRooms(options, migration)
23
+ }
24
+
25
+ async function provisionRooms({ api, master, makeClient, base, split = false, hasLocalPredecessor = () => false, current = () => true }, migration) {
26
+ const loc = await backupLocation(master)
27
+ const guard = () => { if (!current()) throw new Error('account changed during room setup') }
28
+ for (let attempt = 0; attempt < 6; attempt++) {
29
+ guard()
30
+ const head = await api.readBackup(loc.id)
31
+ if (!head?.blob || !head.ver) throw new Error('account backup unavailable')
32
+ const record = await unseal(loc.key, head.blob)
33
+ if (record?.v !== 1 || !Array.isArray(record.recents)) throw new Error('invalid account backup')
34
+ let manifest = protectedRoomPointers(record)
35
+ guard()
36
+ if (manifest?.phase === 'active') return manifest
37
+ if (migration) {
38
+ await migration.verifySources(record)
39
+ guard()
40
+ }
41
+ else if (hasLocalPredecessor() || kinds.some(k => record[field(k)])) throw new Error('existing account rooms require migration')
42
+ const setId = manifest?.setId || [...crypto.getRandomValues(new Uint8Array(16))].map(b => b.toString(16).padStart(2, '0')).join('')
43
+ const access = makeAccountRoomAccess({ setId, issue: (kind, set, pub) => { guard(); return api.accountRoomPass(kind, set, pub) } })
44
+ let rooms
45
+ try { rooms = await Promise.all(kinds.map(k => access.room(k))) }
46
+ catch (err) {
47
+ if (err?.code === 'unknown_account_room' && (await api.readBackup(loc.id)).ver !== head.ver) continue
48
+ throw err
49
+ }
50
+ guard()
51
+ if (!manifest) {
52
+ manifest = { v: 1, setId, phase: 'preparing' }
53
+ kinds.forEach((k, i) => { manifest[k] = { room: rooms[i], mk: newKey() } })
54
+ } else {
55
+ const client = makeClient(access)
56
+ for (const [i, kind] of kinds.entries()) {
57
+ guard()
58
+ const { room, mk } = manifest[kind]
59
+ if (room !== rooms[i]) throw new Error('account room issuer changed')
60
+ try { await client.create({ room, mk, kind, agentReplies: false, ...(kind === 'msgs' ? { retention: 'purgeable' } : {}) }, { base, split }) }
61
+ catch (e) { if (e?.status !== 409 || e.code !== 'exists') throw e }
62
+ const check = await client.state(room, mk, 'accountsetup')
63
+ if (check?.status !== 200) throw new Error('could not open protected account room')
64
+ }
65
+ if (migration) {
66
+ guard()
67
+ await migration.copyAndRetire(record, manifest, client)
68
+ guard()
69
+ }
70
+ manifest = { ...manifest, phase: 'active' }
71
+ }
72
+ const blob = await seal(loc.key, applyProtectedRoomPointers(record, manifest))
73
+ guard()
74
+ const result = await api.writeBackup(loc.id, blob, head, roomDirectoryTag({ accountRooms: manifest }))
75
+ if (result === 'ok' && manifest.phase === 'active') return manifest
76
+ if (result !== 'ok' && result !== 'conflict') throw new Error('account backup write failed')
77
+ }
78
+ throw new Error('account backup changed during room setup')
79
+ }
package/accountStores.js CHANGED
@@ -73,6 +73,16 @@ export function carryMissing (mine, cur, name = '') {
73
73
  return out
74
74
  }
75
75
 
76
+ // Compare logical documents across encrypted retries. Only the outer sync timestamp
77
+ // is regenerated. Entry timestamps, arrays, removals and key changes all count.
78
+ export function sameDoc(a, b) {
79
+ if (!a || !b || typeof b !== 'object') return false
80
+ const ordered = v => Array.isArray(v) ? v.map(ordered) : v && typeof v === 'object'
81
+ ? Object.fromEntries(Object.keys(v).sort().map(k => [k, ordered(v[k])])) : v
82
+ const content = ({ at, ...rest }) => JSON.stringify(ordered(rest))
83
+ return content(a) === content(b)
84
+ }
85
+
76
86
  export function makeAccountStore ({ call, key, oldKeys = async () => [] }) {
77
87
  // A NEW ACCOUNT KEY (account recovery v2: starting on the new service and every new recovery code make a new master;
78
88
  // the owner's iPhone, 2026-11-15): documents sealed under a PREVIOUS master open with `oldKeys` (the device that changed
@@ -161,13 +171,14 @@ export function makeAccountStore ({ call, key, oldKeys = async () => [] }) {
161
171
  const sr = await read(room, mk, SEALED(name))
162
172
  if (!(sr && sr.status === 200)) return { status: (sr && sr.status) || 0, error: 'unread' } // unknown is not empty
163
173
  if (pinned && (isSealedDoc(sr.state) || Number.isInteger(sr.v)) && sr.v !== ifV) return { status: 409, error: 'moved' } // written since the caller's read (the first sealing too: side sweep 2026-11-28)
164
- let body = obj
174
+ let body = obj, alreadyStored = false
165
175
  if (isSealedDoc(sr.state)) {
166
176
  const opened = await openAny(k, sr.state) // a previous key's document is merged and written under this one
167
177
  if (!opened) return { status: 0, error: 'unopenable' }
168
178
  body = carryMissing(obj, opened.st, name)
179
+ alreadyStored = !opened.old && ['index', 'index2', 'pipes'].includes(name) && sameDoc(body, opened.st)
169
180
  }
170
- const r = await call(room, mk, SEALED(name), await sealDoc(k, body), summary, by, Number.isInteger(sr.v) ? sr.v : 0)
181
+ const r = alreadyStored ? { status: 200 } : await call(room, mk, SEALED(name), await sealDoc(k, body), summary, by, Number.isInteger(sr.v) ? sr.v : 0)
171
182
  const status = (r && r.status) || 0
172
183
  if (status === 409 && pinned) return { status: 409, error: 'moved' }
173
184
  if (status === 409) { await new Promise((res) => setTimeout(res, 20 + Math.floor(Math.random() * 80) * (i + 1))); continue } // another device wrote first: re-read, re-merge
package/acctV2App.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // injected (makeAcctV2), so the whole flow is tested against the service code in-process (spaces/test/acctV2App.test.mjs).
9
9
  import { accountClient } from './acctV2Client.js'
10
10
  import { possessionKey, backupWriteKey, gateValues, webCryptoSigner, webCryptoSignerFromSpk } from './acctV2Keys.js'
11
- import { rawToDer, b64u, hexOf } from './acctV2Wire.js'
11
+ import { rawToDer, b64u, hexOf, sealMoveSubscription } from './acctV2Wire.js'
12
12
  import { transcriptForLegacy, transcriptForJoin, transcriptForSilent, transcriptForJoinAsk } from './acctV2Legacy.js'
13
13
 
14
14
  export const STATE_KEY = 'space:acctv2' // { acct, base, at, address? } — an account id, the service's address and the account's email; no key
@@ -126,6 +126,15 @@ export function makeAcctV2(deps) {
126
126
  return {
127
127
  enabled: () => !!client,
128
128
  state,
129
+ roomPilotEnabled: () => !!deps.roomPilot?.(),
130
+ async finishRoomPilot() {
131
+ if (!this.roomPilotEnabled()) throw new Error('account room pilot unavailable')
132
+ const { makeClient, base, hasLocalPredecessor, adopt } = await deps.roomPilotOptions()
133
+ const account = state()?.acct, master = deps.vault()?.master
134
+ const manifest = await this.initializeAccountRooms({ makeClient, base, hasLocalPredecessor })
135
+ if (!account || state()?.acct !== account || deps.vault()?.master !== master) throw new Error('account changed during room setup')
136
+ adopt(manifest)
137
+ },
129
138
 
130
139
  /** § 12.2 — move this account. `typedCode` only when this device has no escrowed copy of the recovery code. */
131
140
  async migrate({ address, getCode, typedCode = null, label = myLabel() }) {
@@ -237,6 +246,10 @@ export function makeAcctV2(deps) {
237
246
  confirmSaved: (at) => keepPending(prep, at, showCode) })
238
247
  deps.adoptRotation(prep)
239
248
  setState({ acct: s.acct, base: deps.base, at: Date.now(), trust: null, address })
249
+ if (this.roomPilotEnabled()) {
250
+ try { await this.finishRoomPilot() }
251
+ catch { return { acct: s.acct, ...r, roomSetup: 'pending' } }
252
+ }
240
253
  return { acct: s.acct, ...r }
241
254
  },
242
255
 
@@ -516,12 +529,12 @@ export function makeAcctV2(deps) {
516
529
  },
517
530
 
518
531
  /** § 8.4 — a new version over `head` (as readBackup returned it). → 'ok' | 'conflict' */
519
- async writeBackup(id, sealed, head) {
532
+ async writeBackup(id, sealed, head, roomDir) {
520
533
  need()
521
534
  const s = state(), v = deps.vault()
522
535
  const master = Uint8Array.from(atob(v.master), (c) => c.charCodeAt(0))
523
536
  try {
524
- await client.writeBackup({ device: await signer(), acct: s.acct, id, blob: new TextEncoder().encode(sealed), prev: head.ver, master, rg: head.rg, epoch: head.epoch })
537
+ await client.writeBackup({ device: await signer(), acct: s.acct, id, blob: new TextEncoder().encode(sealed), prev: head.ver, master, rg: head.rg, epoch: head.epoch, roomDir })
525
538
  return 'ok'
526
539
  } catch (e) { if (e && e.code === 'conflict') return 'conflict'; throw e }
527
540
  },
@@ -541,7 +554,7 @@ export function makeAcctV2(deps) {
541
554
  const r = await client.rotate({
542
555
  acct: s.acct, device: await signer(), address, getCode,
543
556
  newCode: deps.codeBytesOf(prep.newCode), newMaster: prep.newMaster, backupId: prep.backupId, wrapperId: prep.wrapperId,
544
- backupBlob: prep.backupBlob, wrapperBlob: prep.wrapperBlob, keys: deps.keys || null,
557
+ backupBlob: prep.backupBlob, wrapperBlob: prep.wrapperBlob, roomDir: prep.roomDir, keys: deps.keys || null,
545
558
  confirmSaved: (at) => keepPending(prep, at, showCode), // kept (and read back) before the activation is sent
546
559
  })
547
560
  deps.adoptRotation(prep)
@@ -619,6 +632,42 @@ export function makeAcctV2(deps) {
619
632
  return { statement: r.statement, sig: r.sig }
620
633
  },
621
634
 
635
+ async accountRoomPassFor(room, pub, kind, proofs) {
636
+ need()
637
+ const device = await signer()
638
+ try { return await client.accountRoomPassFor(device, room, pub, kind) } catch (error) {
639
+ if (!kind || error.code !== 'room_owner_unconfirmed') throw error
640
+ const saved = deps.vault()?.master
641
+ if (!saved) throw error
642
+ const master = Uint8Array.from(atob(saved), c => c.charCodeAt(0))
643
+ const head = await client.syncRead(device, await deps.backupIdOf(master))
644
+ const record = head.blob?.length && await deps.openBackup(master, new TextDecoder().decode(head.blob))
645
+ if (record?.[kind + 'Room']?.room !== room || deps.vault()?.master !== saved) throw error
646
+ const extra = deps.accountCreatorProof ? await deps.accountCreatorProof(saved, room) : null
647
+ const candidates = [...new Set([extra, ...(proofs || [])].filter(Boolean))].slice(0, 16)
648
+ if (!candidates.length) throw error
649
+ return client.accountRoomPassFor(device, room, pub, kind, candidates)
650
+ }
651
+ },
652
+
653
+ async initializeAccountRooms({ makeClient, base, hasLocalPredecessor }) {
654
+ need()
655
+ const account = state()?.acct, master = deps.vault()?.master
656
+ if (!account || !master) throw new Error('account backup unavailable')
657
+ const { initializeAccountRooms } = await import('./accountRooms.js')
658
+ return initializeAccountRooms({ api: this, master: Uint8Array.from(atob(master), ch => ch.charCodeAt(0)), makeClient, base, hasLocalPredecessor,
659
+ current: () => state()?.acct === account && deps.vault()?.master === master })
660
+ },
661
+
662
+ async accountRoomPass(kind, setId, sessionPub) {
663
+ need()
664
+ return client.accountRoomPass(await signer(), kind, setId, sessionPub)
665
+ },
666
+ async sealedRoomBinding(email, sessionPub, binding) {
667
+ need()
668
+ return client.sealedRoomBinding(await signer(), email, sessionPub, binding)
669
+ },
670
+
622
671
  /** docs/device-gate-design.md: this ACTIVE device's ten-minute room pass for its session key (roomPass.js) → { pass, sig, exp }.
623
672
  * A signed-out device is refused (`revoked`), and the bridge's fetch runs the status check at once. */
624
673
  async roomPass(email, sessionPub) {
@@ -632,7 +681,9 @@ export function makeAcctV2(deps) {
632
681
  * hash — when it changed (or none any more). → 'registered' | 'removed' | 'same' | 'off' */
633
682
  async syncPush() {
634
683
  if (!client || !state() || !deps.pushEndpoint || !deps.sealPush) return 'off'
635
- const endpoint = await deps.pushEndpoint()
684
+ const target = deps.pushSubscription ? await deps.pushSubscription() : await deps.pushEndpoint()
685
+ const subscription = target && typeof target === 'object' && target.keys ? { endpoint: target.endpoint, keys: { p256dh: target.keys.p256dh, auth: target.keys.auth } } : undefined
686
+ const endpoint = target && typeof target === 'object' ? target.endpoint : target
636
687
  // NOT KNOWN YET is not "none" (Codex sweep 2026-11-16 #2: a builders' vault whose subscription was still loading sent an empty
637
688
  // record, and another device could no longer find this one's address to revoke it) — nothing is sent; the change resyncs it
638
689
  if (endpoint === undefined) return 'unknown'
@@ -641,9 +692,24 @@ export function makeAcctV2(deps) {
641
692
  const seal = deps.sealId ? await deps.sealId() : ''
642
693
  let prev = null
643
694
  try { prev = deps.storage.getItem(k) } catch { /* */ }
644
- if (prev === state().acct + '|' + mark + '|' + seal) return 'same'
645
- await client.devicePush(await signer(), endpoint ? { sealed: await deps.sealPush(endpoint), hash: mark } : {})
646
- try { deps.storage.setItem(k, state().acct + '|' + mark + '|' + seal) } catch { /* */ }
695
+ const device = await signer()
696
+ const legacyMarker = state().acct + '|' + mark + '|' + seal
697
+ const marker = legacyMarker + (subscription ? '|' + device.spk + '|' + await sha256Hex(JSON.stringify(subscription)) : '')
698
+ if (prev === marker) return 'same'
699
+ let noticePush
700
+ if (subscription) {
701
+ const { notice_key } = await client.deviceStatus(device, { noticeKey: true })
702
+ if (notice_key) noticePush = await sealMoveSubscription(notice_key, subscription, mark)
703
+ else if (prev === legacyMarker) return 'same' // an older service; keep the existing room-pruning registration
704
+ }
705
+ const registration = {}
706
+ if (endpoint) {
707
+ registration.hash = mark
708
+ if (!noticePush || !deps.sealId || seal) registration.sealed = await deps.sealPush(endpoint)
709
+ if (noticePush) registration.notice_push = noticePush
710
+ }
711
+ await client.devicePush(device, registration)
712
+ try { deps.storage.setItem(k, noticePush ? marker : legacyMarker) } catch { /* */ }
647
713
  return endpoint ? 'registered' : 'removed'
648
714
  },
649
715
 
package/acctV2Client.js CHANGED
@@ -83,7 +83,7 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
83
83
  if (!keys) throw Object.assign(new Error('need_security_key'), { code: 'need_security_key' })
84
84
  const allow = (c.keys || []).filter((k) => k.id !== except)
85
85
  if (!allow.length) throw Object.assign(new Error('no_other_key'), { code: 'no_other_key' })
86
- return { hwkey: await keys.get({ challenge: await sha256(Tb), allow }) }
86
+ return { hwkey: await keys.get({ challenge: await sha256(Tb), allow, rpId: c.rpId }) }
87
87
  }
88
88
  const fail = (code) => { throw Object.assign(new Error(code), { code }) }
89
89
  /** A new code's parameters (§ 8.2): every value derived HERE from the new code and master, before anything is sent. */
@@ -112,9 +112,9 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
112
112
  return {
113
113
  req,
114
114
  /** § 8.5 — this device's status; an answer that does not name this key AND echo this request's nonce is refused. */
115
- async deviceStatus(device) {
115
+ async deviceStatus(device, { noticeKey = false } = {}) {
116
116
  const nonce = b64u(rand(9))
117
- const r = await req('GET', '/v2/account/device', { query: { nonce }, signer: device })
117
+ const r = await req('GET', '/v2/account/device', { query: { nonce, ...(noticeKey ? { notice_key: '1' } : {}) }, signer: device })
118
118
  if (r.spk !== device.spk || r.nonce !== nonce) throw Object.assign(new Error('status_mismatch'), { code: 'status_mismatch' })
119
119
  return r
120
120
  },
@@ -225,19 +225,20 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
225
225
  syncRead: async (device, id) => { const r = await req('GET', `/v2/account/backup/${id}/head`, { signer: device }); return { ...r, blob: unb64u(r.blob) } },
226
226
 
227
227
  /** § 8.4 — upload and commit a new version over `prev`. `master` makes the write key; rg/epoch from the device's view. */
228
- async writeBackup({ device, acct, id, blob, prev, master, rg, epoch }) {
228
+ async writeBackup({ device, acct, id, blob, prev, master, rg, epoch, roomDir }) {
229
229
  const wk = await backupWriteKey(master)
230
230
  const up = await req('POST', `/v2/account/backup/${id}/upload`, { body: { blob: b64u(blob) }, signer: device })
231
231
  const nonce = b64u(rand(9)), ts = now()
232
- const write_sig = b64u(wk.sign(writeProofBytes({ acct, id, ver: up.ver, digest: up.digest, prev, rg, epoch, nonce, ts })))
233
- return req('POST', `/v2/account/backup/${id}/commit`, { body: { ver: up.ver, prev, nonce, ts, write_sig }, signer: device })
232
+ const write_sig = b64u(wk.sign(writeProofBytes({ acct, id, ver: up.ver, digest: up.digest, prev, rg, epoch, nonce, ts, ...(roomDir ? { room_dir: roomDir } : {}) })))
233
+ return req('POST', `/v2/account/backup/${id}/commit`, { body: { ver: up.ver, prev, nonce, ts, write_sig, room_dir: roomDir }, signer: device })
234
234
  },
235
235
 
236
236
  /** § 8.2 — a new recovery code. The caller has made the new code and master and sealed both blobs under them
237
237
  * (`backupBlob` under the new master, `wrapperBlob` under the new code); `confirmSaved` shows the code and resolves
238
238
  * once the person has saved it. Every new value is derived HERE, before authorising. */
239
- async rotate({ acct, device, address, getCode, newCode, newMaster, backupId, wrapperId, backupBlob, wrapperBlob, confirmSaved, keys = null }) {
239
+ async rotate({ acct, device, address, getCode, newCode, newMaster, backupId, wrapperId, backupBlob, wrapperBlob, confirmSaved, keys = null, roomDir }) {
240
240
  const params = await codeParams({ device, address, newCode, newMaster, backupId, wrapperId })
241
+ if (roomDir) params.room_dir = roomDir
241
242
  const c = await req('POST', '/v2/account/challenge', { body: { op: 'rotation_authorize', acct, params } })
242
243
  const ticket = await emailProof(c, address, getCode)
243
244
  const Tr = T(c, 'rotation_authorize', params)
@@ -327,7 +328,13 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
327
328
  /** § 8.8: an active device's approval of the person's next AWS key (the mint requires it once a sign-out gated it). */
328
329
  awsStatement: (device, signPub) => req('POST', '/v2/account/aws_statement', { body: { signPub }, signer: device }),
329
330
  /** docs/device-gate-design.md: an active device's ten-minute room pass for its session key → { pass, sig, exp }. */
331
+ sealedRoomBinding: (device, email, sessionPub, binding) =>
332
+ req('POST', '/v2/account/sealed_room_binding', { body: { email, sessionPub, binding }, signer: device }),
330
333
  roomPass: (device, email, sessionPub) => req('POST', '/v2/account/room_pass', { body: { email, sessionPub }, signer: device }),
334
+ accountRoomPassFor: (device, room, sessionPub, kind, proofs) => kind
335
+ ? req('POST', '/v2/account/existing_room_pass', { body: { room, sessionPub, kind, proofs }, signer: device })
336
+ : req('POST', '/v2/account/account_room_pass', { body: { room, sessionPub }, signer: device }),
337
+ accountRoomPass: (device, kind, setId, sessionPub) => req('POST', '/v2/account/account_room_pass', { body: { kind, setId, sessionPub }, signer: device }),
331
338
 
332
339
  /** The account's mode and active keys (an active device only). */
333
340
  security: (device) => req('GET', '/v2/account/security', { signer: device }),
@@ -360,11 +367,11 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
360
367
  const assertions = []
361
368
  for (const [i, m] of made.entries()) {
362
369
  onStep({ step: 'confirm', index: i, of: made.length })
363
- assertions.push(await keys.get({ challenge: ch, allow: [m] }))
370
+ assertions.push(await keys.get({ challenge: ch, allow: [m], rpId: f.rpId }))
364
371
  }
365
372
  if (purpose === 'key_add') {
366
373
  onStep({ step: 'existing' })
367
- assertions.push(await keys.get({ challenge: ch, allow: (f.active || []).filter((k) => !creds.includes(k.id)) }))
374
+ assertions.push(await keys.get({ challenge: ch, rpId: f.rpId, allow: (f.active || []).filter((k) => !creds.includes(k.id)) }))
368
375
  }
369
376
  return req('POST', `/v2/account/enrol/${eid}/finish`, { body: { device_sig: await sigOf(device, Tf), assertions, idem: b64u(rand(16)) }, signer: device })
370
377
  },
package/acctV2Switch.js CHANGED
@@ -20,6 +20,11 @@ export const PROD_SERVICE = 'https://api.witbitz.chat/v1'
20
20
  // its CSP already allows; the staging vault (it frames the staging app) to the staging service.
21
21
  export const PROD_VAULT = 'spaces.witbitz.chat'
22
22
  export const STAGING_VAULT = 'vault.witbitz-spaces.pages.dev'
23
+ // A developer opts a disposable preview profile into the account-room pilot before setup.
24
+ export function accountRoomPilot(loc = globalThis.location, storage = globalThis.localStorage) {
25
+ try { return loc?.hostname === STAGING_APP && baseOf(storage.getItem(BASE_KEY), loc.hostname) === STAGING_SERVICE && storage.getItem('space:account-room-pilot') === '1' }
26
+ catch { return false }
27
+ }
23
28
  const SERVICE_OF = { [STAGING_APP]: STAGING_SERVICE, [PROD_APP]: PROD_SERVICE, [STAGING_VAULT]: STAGING_SERVICE, [PROD_VAULT]: PROD_SERVICE }
24
29
 
25
30
  export function stagingSwitch(loc = globalThis.location, storage = globalThis.localStorage) {
package/acctV2UiCore.js CHANGED
@@ -42,6 +42,7 @@ const MESSAGES = {
42
42
  already_migrated: 'This device already has an account on the new service.',
43
43
  need_security_key: 'This needs one of your security keys, and this device can’t ask for one.',
44
44
  key_cancelled: 'The security key didn’t answer — the prompt was closed, timed out, or a key that isn’t on this account was touched. Nothing changed.',
45
+ key_domain_mismatch: 'Open the vault on the website where you set up your security keys.',
45
46
  key_wrong_site: 'Security keys can’t be used in this app yet.', // accounts are per app (sync sweep 11-16 #17): never sent to another app's address
46
47
  webauthn_unavailable: 'This browser can’t use security keys.',
47
48
  key_already_registered: 'That key is already on this account. Use a different key.',
@@ -306,6 +307,17 @@ export function renderAcctV2Section(box, rerender, { devicesBox = null } = {}) {
306
307
  // different card"): the devices and "Sign out all other devices now" go to the caller's box; the recovery code stays here
307
308
  if (devicesBox) { b.style.marginTop = '10px'; devicesBox.replaceChildren(serviceDevicesBlock(a, address, rerender), b); sec.append(t, d, nc) }
308
309
  else sec.append(t, d, serviceDevicesBlock(a, address, rerender), b, nc)
310
+ if (a.roomPilotEnabled?.()) {
311
+ const setup = document.createElement('button')
312
+ setup.type = 'button'; setup.className = 'dev-out'; setup.textContent = 'Set up protected account rooms'
313
+ setup.onclick = async () => {
314
+ setup.disabled = true
315
+ try { await a.finishRoomPilot(); await notice('The three account rooms are protected.') }
316
+ catch (err) { await notice(String(err?.message || 'Account room setup failed.')) }
317
+ finally { setup.disabled = false }
318
+ }
319
+ sec.append(setup)
320
+ }
309
321
  const mw = moveWarningBlock(rerender) // § 11.5, 3a: a move of this account's address under way — above everything else
310
322
  if (mw) sec.prepend(mw)
311
323
  box.append(sec)
@@ -701,8 +713,10 @@ async function startFresh(a, address0, rerender) {
701
713
  }
702
714
  if (!(await confirmSheet({ message: `Start an account on the new service from this device?\n\nWe’ll send a code to ${address}, then show you a new recovery code to save. This device’s current backup and recovery code are replaced by the new ones.`, confirmLabel: 'Start', destructive: false }))) return
703
715
  try {
704
- await a.startFresh({ address, getCode: emailCode(address, 'new'), showCode })
705
- await notice('Done. This device has an account on the new account service, with your new recovery code.')
716
+ const result = await a.startFresh({ address, getCode: emailCode(address, 'new'), showCode })
717
+ await notice(result?.roomSetup === 'pending'
718
+ ? 'Your account and recovery code are ready. To retry room setup, open Back up & recovery and choose Set up protected account rooms.'
719
+ : 'Done. This device has an account on the new account service, with your new recovery code.')
706
720
  } catch (e) {
707
721
  if (e && e.code === 'restore_instead') return restoreHere(a, address, rerender) // the email already has an account: restore it
708
722
  if (!(e && e.code === 'cancelled')) await notice(messageFor(e))
package/acctV2WebAuthn.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // acctV2WebAuthn.js — the security-key ceremonies of account recovery v2 (docs/account-recovery-protocol.md § 10), as the
2
2
  // small adapter the client takes (acctV2Client.js `keys`): create(options) → the registration, get({challenge, allow}) →
3
3
  // an assertion, everything in base64url. This file is the BROWSER's adapter (navigator.credentials); the tests pass a
4
- // simulated key with the same shape. The relying party is always witbitz.chat: one credential per key, for every app (§ 10.2).
4
+ // simulated key with the same shape. The service chooses the verified vault's RP (§ 10.2). Older responses use the shared Spaces RP.
5
5
  import { b64u, unb64u } from './acctV2Wire.js'
6
6
 
7
7
  export const RP_ID = 'witbitz.chat'
@@ -21,7 +21,7 @@ const rethrow = (e) => { throw (e && e.code === 'cancelled' ? e : why(e)) }
21
21
  function why(e) {
22
22
  if (e && e.name === 'NotAllowedError') return err('key_cancelled') // closed, timed out, or no matching key touched
23
23
  if (e && e.name === 'InvalidStateError') return err('key_already_registered') // excludeCredentials matched
24
- if (e && e.name === 'SecurityError') return err('key_wrong_site') // this origin may not use witbitz.chat (§ 10.2)
24
+ if (e && e.name === 'SecurityError') return err('key_wrong_site') // this origin may not use the requested RP (§ 10.2)
25
25
  return err('key_failed')
26
26
  }
27
27
 
@@ -45,11 +45,11 @@ export function browserKeys({ rpId = RP_ID } = {}) {
45
45
  return { attestationObject: ab(r.attestationObject), clientDataJSON: ab(r.clientDataJSON), transports: (r.getTransports && r.getTransports()) || [] }
46
46
  },
47
47
  /** An assertion over `challenge` (bytes) by one of `allow` ([{ id, transports }]). */
48
- async get({ challenge, allow }) {
48
+ async get({ challenge, allow, rpId: requestRpId = rpId }) {
49
49
  if (!available()) throw err('webauthn_unavailable')
50
50
  let a
51
51
  const publicKey = {
52
- rpId, challenge, userVerification: 'required', timeout: 120000,
52
+ rpId: requestRpId, challenge, userVerification: 'required', timeout: 120000,
53
53
  allowCredentials: (allow || []).map((c) => ({ type: 'public-key', id: unb64u(c.id), transports: c.transports || [] })),
54
54
  }
55
55
  try { a = await ceremony('get', () => navigator.credentials.get({ publicKey })) } catch (e) { rethrow(e) }
package/acctV2Wire.js CHANGED
@@ -5,6 +5,22 @@
5
5
 
6
6
  const enc = new TextEncoder()
7
7
 
8
+ /** Only the notice worker can open the subscription. Bind the ciphertext to its registered
9
+ * endpoint fingerprint and purpose, separate from the worker's encrypted email addresses. */
10
+ export async function sealMoveSubscription(publicKey, subscription, hash) {
11
+ const alg = { name: 'ECDH', namedCurve: 'P-256' }
12
+ const peer = await crypto.subtle.importKey('raw', unb64u(publicKey), alg, false, [])
13
+ const own = await crypto.subtle.generateKey(alg, true, ['deriveBits'])
14
+ const eph = new Uint8Array(await crypto.subtle.exportKey('raw', own.publicKey))
15
+ const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, own.privateKey, 256)
16
+ const base = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey'])
17
+ const info = enc.encode('witbitz-move-push-v1:' + hash)
18
+ const key = await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: eph, info }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt'])
19
+ const iv = crypto.getRandomValues(new Uint8Array(12))
20
+ const cipher = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: info }, key, enc.encode(JSON.stringify(subscription)))
21
+ return ['v2', b64u(eph), b64u(iv), b64u(new Uint8Array(cipher))].join('.')
22
+ }
23
+
8
24
  /** RFC 8785 for the value types the protocol signs (strings, safe integers, booleans, null, arrays, plain objects). */
9
25
  export function jcs(v) {
10
26
  if (v === null) return 'null'
@@ -49,7 +65,11 @@ export async function deviceRequestBytes({ method, path, query = '', body = new
49
65
  }
50
66
 
51
67
  /** § 8.4 — the bytes the backup write key signs. */
52
- export const writeProofBytes = (o) => framed('witbitz-backup-write-v1', ['acct', 'id', 'ver', 'digest', 'prev', 'rg', 'epoch', 'nonce', 'ts'], o)
68
+ export function writeProofBytes(o) {
69
+ const fields = ['acct', 'id', 'ver', 'digest', 'prev', 'rg', 'epoch', 'nonce', 'ts']
70
+ if (Object.hasOwn(o, 'room_dir')) return framed('witbitz-backup-write-rooms-v1', [...fields, 'room_dir'], o)
71
+ return framed('witbitz-backup-write-v1', fields, o)
72
+ }
53
73
 
54
74
  /** WebCrypto signs ECDSA as raw r‖s (64 bytes); the service verifies DER. */
55
75
  export function rawToDer(raw) {
package/backupRecord.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { protectedRoomPointers } from './accountRoomPointers.js'
1
2
  // backupRecord.js — THE BACKUP RECORD'S RULES, pure (docs/sdk-account-format-plan.md, phase 1). The account's backup is one
2
3
  // sealed record in the vault (accountRecord.js says whose it is); these are the rules that build what a device puts in it and
3
4
  // what a restore takes back out. They lived inside backup.js's gatherBackup and applyBackup, next to the page's storage; here
@@ -94,13 +95,16 @@ export function applyPlan (p, local = {}, { app = 'spaces' } = {}) {
94
95
  else { fill(rm, 'mk', e.mk) }
95
96
  fill(rm, 'model', e.model); fill(rm, 'gate', e.gate); fill(rm, 'id', e.id); fill(rm, 'sign', e.sign)
96
97
  }
97
- const ptr = (x, held) => (x && x.room && x.mk && !held ? x : null) // a room minted on another device is adopted, never over this one's
98
+ const manifest = protectedRoomPointers(p)
99
+ const ptr = (kind, x, held) => manifest?.phase === 'active'
100
+ ? (held?.room === manifest[kind].room && held?.mk === manifest[kind].mk ? null : manifest[kind])
101
+ : (x && x.room && x.mk && !held ? x : null) // a room minted on another device is adopted, never over this one's
98
102
  return {
99
103
  tombstones: tomb, newTombstones: Object.keys(tomb).length > Object.keys(mine).length,
100
104
  add, recents: add.length || cur.some(r => tomb[r.room]) ? cur.filter(r => !tomb[r.room]).concat(add).sort((a, b) => (b.at || 0) - (a.at || 0)) : null,
101
105
  fills,
102
106
  name: p.name && !L.myName ? p.name : '', // a name typed here is never replaced; a waiting name prompt is answered
103
- msgsRoom: ptr(p.msgsRoom, L.msgsRoom), pipesRoom: ptr(p.pipesRoom, L.pipesRoom), indexRoom: ptr(p.indexRoom, L.indexRoom),
107
+ msgsRoom: ptr('msgs', p.msgsRoom, L.msgsRoom), pipesRoom: ptr('pipes', p.pipesRoom, L.pipesRoom), indexRoom: ptr('index', p.indexRoom, L.indexRoom),
104
108
  acctKey: p.acctKey && p.acctKey.priv && !L.acctKey ? p.acctKey : null, // the account signing key: adopted, never clobbering a local one
105
109
  inviteKey: p.inviteKey && p.inviteKey.boxPriv && !L.inviteKey ? p.inviteKey : null, // invites sealed to your boxPub open here too
106
110
  code: typeof p.code === 'string' && p.code && !L.code ? p.code : '', // the escrowed recovery code → a passkey/link recovery can Show it
package/changePush.js CHANGED
@@ -52,8 +52,11 @@ export function startChangePush ({ inbox, onHint = () => {}, onState = () => {},
52
52
  async function connect () {
53
53
  if (stopped || ws) return
54
54
  let s
55
- try { s = new WebSocketImpl(String(relay).replace(/\/+$/, '') + '/' + path + '/' + await hintChannel(inbox)) } catch { schedule(); return }
56
- if (stopped) { try { s.close() } catch { /* */ } return }
55
+ try {
56
+ const channel = await hintChannel(inbox)
57
+ if (stopped || ws) return
58
+ s = new WebSocketImpl(String(relay).replace(/\/+$/, '') + '/' + path + '/' + channel)
59
+ } catch { schedule(); return }
57
60
  ws = s
58
61
  s.onopen = () => { backoff = MIN_BACKOFF; setUp(true); beat = setInterval(() => probe(), heartbeatMs) }
59
62
  s.onmessage = async (ev) => {
@@ -30,4 +30,4 @@
30
30
  // cd17 (2026-11-25, 28779188 — PASS Rekor 4111966802): the device's trail reaches the `logs` op. cd18 (2026-11-25, 234eed2e — PASS on a
31
31
  // fresh build-enclave boot, Rekor 4112152120): a hosted sign-in acts on the hosted app's own Sentinel account (an own agent's report
32
32
  // came back). cd19 runs and KMS opens for cd19. Devices on an older release follow it by its record (followImage FOLLOW_WINDOW).
33
- export const CLOUD_DEVICE_PCR0 = Object.freeze(['d89c0daf2290536038265b116f4e66fd350c342203c6e6624153596d63c96ebcc57e8e9482afd274a6e0c260f2f22829']) // cd20
33
+ export const CLOUD_DEVICE_PCR0 = Object.freeze(['a0f3672263bda321087b7d2ce2a5a41561cc84d4166be04b9c2441320f2fc9bb450437d020cd807e57f1533261977123', 'd89c0daf2290536038265b116f4e66fd350c342203c6e6624153596d63c96ebcc57e8e9482afd274a6e0c260f2f22829']) // Privacy logging rollout and cd20