@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/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
+ }
@@ -10,6 +10,7 @@ import { derSigToRaw } from './x509.js'
10
10
 
11
11
  /** The build-enclave images whose verdicts count — infra/build-enclave/pins.json `buildEnclave` (held equal by a test). */
12
12
  export const BUILD_ENCLAVE_PCR0 = Object.freeze([
13
+ "5efd30e7333e33104dcc238d6d876b4019ee7cb0c80ee423786473199225de8bb11eb5edbb60b787b1f87741e8876e34",
13
14
  "c6a8cbd0c05d8e003e75b266f1dde2a6426b7cd61f845e4b128e59063e40968b44f30d934bbe1925582fe33bbdd0b1d7",
14
15
  "f490096d57e4287146e8b8d7bf4c75f423984ca52199efab0ee8684fbee6cfe6ab82c72d54f05a38f24a0d4ad6e2f557",
15
16
  "41ec7e0e54beac5759fba7efa06c48081dbd96c7299c29c92a9c619036ce057cec357ad4ad71a165d7f881df120b043b",