@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/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:
@@ -131,6 +132,10 @@ const originBase = () => (typeof location !== 'undefined' && location.origin) ||
131
132
  // can't tamper with (the verifiable-client property). `{ relay, keyConfig }` = the direct mode: the app encapsulates
132
133
  // in-process (simpler; used by tests / the non-framed path). Unset ⇒ plain JSON POST (behaviour-neutral).
133
134
  let _ohttp = null
135
+ let relayRequired = false
136
+ export function requireOhttp(on) { relayRequired = !!on }
137
+ export function ohttpRequired() { return relayRequired }
138
+ const relayUnavailable = () => ({ status: 0, error: 'privacy_relay_unavailable' })
134
139
  export function configureOhttp(cfg) { _ohttp = (cfg && (typeof cfg.send === 'function' || (cfg.relay && cfg.keyConfig))) ? cfg : null }
135
140
  export async function readSealedArchive(read) {
136
141
  const first = await read(0)
@@ -156,8 +161,8 @@ export function ohttpActive() { return !!_ohttp }
156
161
  // bought that guarantee by AWAITing setup in boot — which held the whole UI hostage for the full setup (seconds, and up
157
162
  // to the 25s timeout on a bad network), the "blank for 30s then the app appears" bug. Instead: boot marks OHTTP pending
158
163
  // SYNCHRONOUSLY (before op one) and stops awaiting, so views resolve instantly; each network op below awaits this gate,
159
- // so it still never fires before OHTTP is up (success ⇒ routed oblivious) or has definitively given up (failure ⇒ direct,
160
- // the unchanged fail-open-to-direct posture). Untouched when OHTTP is off: _ohttpPending stays null → zero added latency.
164
+ // so it waits for setup, then uses the active relay
165
+ // or returns an offline result when the device requires the relay.
161
166
  let _ohttpPending = null // a Promise (with its resolver stapled on) while setup is in flight; null otherwise
162
167
  export function markOhttpPending() { let done; _ohttpPending = new Promise((r) => { done = r }); _ohttpPending._done = done }
163
168
  export function resolveOhttpPending() { const p = _ohttpPending; _ohttpPending = null; if (p && p._done) p._done() }
@@ -170,8 +175,8 @@ async function awaitOhttpReady() { const p = _ohttpPending; if (p) { try { await
170
175
  // leak — fail-closed on IP exactly like call().
171
176
  export async function ohttpSend(body, fetchImpl = (typeof fetch !== 'undefined' ? fetch : null)) {
172
177
  await awaitOhttpReady() // hold until "Hide my IP" setup settles, so this never picks the direct path while OHTTP is still coming up
173
- if (!_ohttp) return null
174
- try { return _ohttp.send ? await _ohttp.send(body) : await ohttpCall(body, fetchImpl) }
178
+ if (!_ohttp) return relayRequired ? relayUnavailable() : null
179
+ try { return (await (_ohttp.send ? _ohttp.send(body) : ohttpCall(body, fetchImpl))) || relayUnavailable() }
175
180
  catch (e) { return { status: 0, error: 'ohttp: ' + String((e && e.message) || e).slice(0, 120) } }
176
181
  }
177
182
 
@@ -198,22 +203,27 @@ export async function verifyAndEnableOhttp(relayBase, expect = {}, gateway = { a
198
203
  let _ohttpMod = null
199
204
  const ohttpMod = async () => (_ohttpMod || (_ohttpMod = await import('./ohttp.js')))
200
205
 
201
- async function ohttpCall(body, fetchImpl) {
206
+ async function ohttpCall(body, fetchImpl, config = _ohttp) {
202
207
  const O = await ohttpMod()
203
208
  const inner = O.encodeRequest({
204
- method: 'POST', scheme: 'https', authority: _ohttp.gatewayAuthority, path: _ohttp.gatewayPath || '/',
209
+ method: 'POST', scheme: 'https', authority: config.gatewayAuthority, path: config.gatewayPath || '/',
205
210
  headers: { 'content-type': 'application/json' }, body: new TextEncoder().encode(JSON.stringify(body)),
206
211
  })
207
- const { encRequest, ks, enc } = await O.encapsulateRequest(_ohttp.keyConfig, inner)
212
+ const { encRequest, ks, enc } = await O.encapsulateRequest(config.keyConfig, inner)
208
213
  // Send the encapsulated request THROUGH the relay as { op:'ohttp', enc:<base64> } — the relay forwards this opaque
209
214
  // envelope to the gateway verbatim (it can't read enc: ciphertext) and returns { res:<base64> }. Relay sees our IP
210
215
  // but not the room; the gateway decrypts the room but sees the relay's IP, not ours.
211
216
  const b64 = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s) }
212
217
  const ub64 = (s) => { const bin = atob(s); const u = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u }
213
- const res = await fetchImpl(_ohttp.relay, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'ohttp', enc: b64(encRequest) }) })
214
- if (!res.ok) return { status: res.status }
215
- let env = {}; try { env = await res.json() } catch { return { status: res.status } }
216
- if (!env.res) return { status: env.status || res.status, ...(env.error ? { error: env.error } : {}) }
218
+ const packet = { op: 'ohttp', enc: b64(encRequest) }
219
+ let env
220
+ if (config.forward) env = await config.forward(packet.enc)
221
+ else {
222
+ const res = await fetchImpl(config.relay, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(packet) })
223
+ if (!res.ok) return { status: res.status }
224
+ env = await res.json()
225
+ }
226
+ if (!env?.res) return { status: env?.status >= 400 ? env.status : 0, error: 'privacy_relay_unavailable' }
217
227
  const respBhttp = await O.decapsulateResponse(ks, enc, ub64(env.res))
218
228
  const resp = O.decodeResponse(respBhttp)
219
229
  let data = {}
@@ -221,9 +231,21 @@ async function ohttpCall(body, fetchImpl) {
221
231
  return { status: resp.status, ...data }
222
232
  }
223
233
 
234
+ // The worker seals to the gateway independently of the page carrying its envelope. Refresh this PUBLIC pin
235
+ // alongside gateway key rotations. A stale pin fails closed. The existing attested shim carries the outer request.
236
+ export function workerEnvelopeTransport(forward) {
237
+ const pub = 'BIfFQos1TNEVvDa0Njw4XvMqwHRMFix92888qJBRatoRaUvGpzQVgYEMeH0ij8rudN5IAtbB04GLscfRchfmc5c'
238
+ const config = { gatewayAuthority: 'api.witbitz.chat', gatewayPath: '/v1/space',
239
+ keyConfig: { keyId: 1, publicKey: Uint8Array.from(atob(pub.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)) } }
240
+ config.forward = forward
241
+ return { send: body => ohttpCall(body, null, config) }
242
+ }
243
+
224
244
  async function call(endpoint, body, fetchImpl) {
225
- await awaitOhttpReady() // hold until "Hide my IP" setup settles, so an op never leaks direct while OHTTP is still coming up
226
- if (_ohttp) { try { return _ohttp.send ? await _ohttp.send(body) : await ohttpCall(body, fetchImpl) } catch (e) { return { status: 0, error: 'ohttp: ' + String((e && e.message) || e).slice(0, 120) } } }
245
+ if (isSealedAppRoom(body?.room) || isSealedAppRoom(body?.bridgeRoom) || (Array.isArray(body?.rooms) && body.rooms.some(isSealedAppRoom))) throw new Error('sealed room transport required')
246
+ const routed = await ohttpSend(body, fetchImpl)
247
+ if (routed !== null) return routed
248
+ if (relayRequired) return relayUnavailable() // the choice can change at the await above
227
249
  const res = await fetchImpl(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
228
250
  let data = {}
229
251
  try { data = await res.json() } catch { /* non-JSON → status only */ }
@@ -329,10 +351,30 @@ const VOICE_OPS = new Set(['stt', 'tts'])
329
351
  // 5xx, no network. Jittered ×0.5–1.5. After the last, the room is "could not tell" for TIER_RETRY_MS.
330
352
  const TIER_PROBE_WAITS = [500, 1500] // spread wide: a burst of rooms probing together must not retry together into the same limit
331
353
  const tierFault = (r) => !r || !r.status || r.status === 429 || r.status >= 500
332
- 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 } = {}) {
333
357
  const tenantHint = tenant ? { tid: String(tenant).slice(0, 64) } : {}
334
358
  const f = fetchImpl || (typeof fetch !== 'undefined' ? fetch : null)
335
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
+ }
336
378
  // ENCLAVE TIER. `enclave` and `mkPub` may EACH be a value OR a per-room function (room) => …, so ONE client can run
337
379
  // some rooms in the enclave and others normally (a room's tier is fixed at creation). For an enclave room, post()
338
380
  // marks the op enclave:true (the backend relays it to the Nitro enclave) and keyFields() seals mk to the room's
@@ -389,6 +431,21 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
389
431
  try { const t = typeof userToken === 'function' ? await userToken() : userToken; return typeof t === 'string' ? t : '' } catch { return '' }
390
432
  }
391
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
+ }
392
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
393
450
  // In a CONFIDENTIAL room the token rides SEALED to the attested enclave (turn.mjs opens it; docs/tenant-billing.md
394
451
  // § 12.2) — the relay must neither read nor swap who pays. A seal that cannot be made sends no token at all.
@@ -419,7 +476,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
419
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
420
477
  // read needs no sign-in: it goes plain WITHOUT it for a short while — the sign-in never goes outside an envelope.
421
478
  const idOnly = sealedWay === true && PLAIN_OPS.has(body.op) && !gatedRooms.has(body.room)
422
- 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) }
423
480
  if (idOnly && (asleepPlain.get(body.room) || 0) > Date.now()) return plainNoId()
424
481
  if (sealedWay === true) {
425
482
  const pub = mkPubFor(body.room) // fail CLOSED: an enclave that opens envelopes but no attested key here → nothing is sent
@@ -461,7 +518,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
461
518
  if (typeof body.mk === 'string' && body.mk) { const no = await keyFor(body.room); if (no) return no }
462
519
  if (typeof body.bridgeMk === 'string' && body.bridgeMk && typeof body.bridgeRoom === 'string' && body.bridgeRoom) { const no = await keyFor(body.bridgeRoom); if (no) return no }
463
520
  }
464
- return call(endpoint, body, f)
521
+ return sendRoomRequest(body)
465
522
  }
466
523
  let r = await send()
467
524
  // A KEYLESS REQUEST REFUSED AS CONFIDENTIAL (agent/tierGuard.mjs: `409 confidential_room` — the refused request ran nothing): this
@@ -536,7 +593,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
536
593
  try {
537
594
  let r = null
538
595
  for (let i = 0; ; i++) {
539
- 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 } }
540
597
  if (saysTier(r) || i >= tierWaits.length || !tierFault(r)) break
541
598
  await new Promise((res) => setTimeout(res, tierWaits[i] * (0.5 + Math.random())))
542
599
  }
@@ -622,6 +679,10 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
622
679
  return out
623
680
  }
624
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
+ }
625
686
  const pub = mkPubFor(room)
626
687
  if (enclaveFor(room) && !pub) throw new Error('enclave key unavailable for this room — refusing to send the room key to the relay')
627
688
  if (!pub || !mk) return { mk }
@@ -655,7 +716,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
655
716
  const healEnclaveConfig = async (room, mk) => {
656
717
  if (!mk || !enclaveFor(room)) return null
657
718
  let s = null
658
- try { s = await call(endpoint, { op: 'policy', room }, f) } catch { return null }
719
+ try { s = await sendRoomRequest({ op: 'policy', room }) } catch { return null }
659
720
  if (!s || typeof s.configSealed !== 'string' || !s.configSealed) return null
660
721
  let cfg = null
661
722
  try { cfg = JSON.parse(await open(JSON.parse(s.configSealed), { mk })) } catch { cfg = null }
@@ -664,7 +725,25 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
664
725
  try { r = await post({ op: 'config', room, ...(await keyFields(room, 'config', mk)), configSealed: s.configSealed, ...(await authFor(room)) }) } catch { r = null }
665
726
  return { cfg, configSealed: s.configSealed, saved: !!(r && r.status === 200) }
666
727
  }
667
- 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)) })
668
747
  const linksFields = async (room, op, links) => (await sealField(room, op + ':links', JSON.stringify(links), 'links')) || { links }
669
748
 
670
749
  // reconstruct mk from the pieces carried in a set of links (a share `#s=` each, or `#mk=` for solo)
@@ -691,6 +770,10 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
691
770
  const sealedRead = async (room, mk, op, fields, { proveKey = false, sent = null } = {}) => {
692
771
  // the enclave ASLEEP with no attested key here: the keyed retry cannot go (keyFields fails closed) — it threw, the poll swallowed
693
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
+ }
694
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 }
695
778
  if (mk && (proveKey || (gatedRooms.has(room) && (enclaveFor(room) || keyFirstNow(room))))) return keyed()
696
779
  const r = await post({ op, room, ...fields, ...(await authFor(room)), ...(await attestFor(room, op, fields)) })
@@ -911,11 +994,18 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
911
994
  return { blobs, stats }
912
995
  }
913
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
+ },
914
1002
  _openAny: openAny, // internal: a box opened with the room's key or, after an in-place change, an earlier one (tests)
915
1003
  /** Mint a Space from a config, register its PUBLIC record (commit + config) with the server, and return
916
1004
  * { room, mk, commit, links, keyModel }. `mk` is reconstructed locally from the minted pieces — it is NEVER sent
917
1005
  * to the server (only its commitment is). The `links` are what you hand to members. */
918
- 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')
919
1009
  const space = await createConfiguredSpace(config, { base })
920
1010
  const mk = await mkFromLinks(space.links, config, space.commit)
921
1011
  // Prepare the email allow-list for sealing. Co-members hold mk and can decrypt the config, so HIDDEN addresses are
@@ -968,13 +1058,15 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
968
1058
  // SPLIT (docs/sdk-split-key.md): mk = userShare ⊕ appShare. The RAW app half rides this create once; the server seals
969
1059
  // it under the page's tenant's K_eco (platform custody) and never stores it in the clear. userShare goes back to the
970
1060
  // caller for the room's #us= link and is never sent.
971
- const sp = split ? splitKey(mk) : null
1061
+ const sp = reservedUserShare ? { shareA: reservedUserShare, shareB: combineShares(mk, reservedUserShare) } : split ? splitKey(mk) : null
972
1062
  // `via` (2026-10-02): a BUILDER-HOSTED app-half function. The create goes to the builder's own function, which seals
973
1063
  // the half under ITS K_eco and registers the room through the tenant door with its tenant key — the same path our
974
1064
  // vault's /api/appshare takes. Witbitz then stores a half it cannot open. Absent ⇒ this endpoint, as before.
975
1065
  const send = typeof via === 'function' ? via : post
976
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)
977
- 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')
978
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
979
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)
980
1072
  if (config.requireVerifiedClient) verifiedRooms.add(space.room)
@@ -983,7 +1075,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
983
1075
  // agent). The app does this inline; the SDK needs it too, and re-sealing outside would be a second source of truth.
984
1076
  // `enclaveCreated`: the CONFIDENTIAL create was answered `created: true` — by the enclave, whose create keeps configSealed in
985
1077
  // the room's record (agent/spaceRoom.mjs). The SDK then skips handing it over a second time (witbitz-sdk _encSealConfig).
986
- 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 } : {}) }
987
1079
  },
988
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 } */
989
1081
  appSharePage: async (room) => post({ op: 'appshare-page', room }),
@@ -1064,6 +1156,10 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1064
1156
  const { sig } = await signEntry(identity.sign.priv, { room, author: identity.name, ts, kind: 'text', id, text, ...(message && message.chal ? { chal: message.chal } : {}) })
1065
1157
  m = { ...message, from: identity.name, ts, id, kind: 'text', sig, spk: identity.sign.pub }
1066
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
+ }
1067
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)
1068
1164
  },
1069
1165
  // USAGE RECEIPTS (docs/usage-receipts.md): this account's sealed receipts in a room, at its per-room drop, and the trim
@@ -1110,7 +1206,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1110
1206
  // opts.changeInbox — THE CHANGE INBOX (docs/change-inbox.md): this device's inbox id rides the room's first poll of a
1111
1207
  // session, and the server follows the room for it only if this poll succeeds and proves the key. Plain, outside
1112
1208
  // the sealed fields — a confidential room's relaying Lambda needs it, and it names no content.
1113
- const ci = opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {}
1209
+ const ci = !isSealedAppRoom(room) && opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {}
1114
1210
  // ⛔ A CONFIDENTIAL ROOM IS NEVER READ IN PLAINTEXT (docs/confidential-path-sweep-2026-11-05.md, finding B): the server
1115
1211
  // answers `poll` with the whole DECRYPTED history, and that answer crosses the Lambda and the enclave's parent host in
1116
1212
  // the clear. Read it sealed and open it here. Every caller (the room loop, the unread sweep, lanes, mail, pins…) comes
@@ -1133,7 +1229,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1133
1229
  * and the caller's render path is unchanged. A key that doesn't fit surfaces as the same 422/'undecodable' the
1134
1230
  * server used to return, except now the CLIENT proves it rather than being told. */
1135
1231
  async pollSealed(room, mk, sinceEtag, sinceCount = 0, opts = {}) {
1136
- 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)
1137
1233
  // the key rides only as sealedRead says (proveKey: a regular room's read that registers the change inbox)
1138
1234
  const sent = { keyed: false }
1139
1235
  const send = async () => sealedRead(room, mk, 'pollsealed', { sinceEtag, sinceCount, ...ci, ...editField(opts) }, { proveKey: !!(opts && opts.proveKey && mk && !enclaveFor(room)), sent })
@@ -1271,7 +1367,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1271
1367
  // with room ids from the device's OWN recents list — no mk, no content — so the server never learns which rooms are
1272
1368
  // whose (the client does the fan-out; the server just pushes each `lapsesAt` out). Bounded here and again server-side;
1273
1369
  // best-effort by contract → a Space's life must never hinge on this succeeding. → { ok, rooms }.
1274
- 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) }),
1275
1371
 
1276
1372
  // §APP STORE Stage 2: the PUBLIC registry-backed app catalog (no room/mk/auth) → { status, apps:[…] }.
1277
1373
  apps: async () => post({ op: 'apps' }),
@@ -1391,7 +1487,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1391
1487
  // `{ plainMark: true }`: a PLAIN room (a read that worked, nothing sealed, no lanes bit) answers `{ plain: true }`, so null
1392
1488
  // means only that the read failed — a private lane waits on that, never inherits "nothing" (sync sweep 2026-11-03)
1393
1489
  getConfig: async (room, mk, o) => {
1394
- const r = await policyPost(room, mk)
1490
+ const r = await policyForConfig(room, mk)
1395
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)
1396
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
1397
1493
  if (!r.configSealed) { const h = await healEnclaveConfig(room, mk); if (h) return h.cfg }
package/spaceConfig.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { sealedAppHref, sealedAppRoomFromHash } from './sealedRoomWire.js'
1
2
  // M3 — Configurable Space: build a Space from a CONFIG (docs/configurable-space-m3.md). Generalizes the shared-presence
2
3
  // KEY MODEL — 1-of-1 (solo) / 2-of-2 (couple) / k-of-n (team) — so ONE engine serves any small private AI Space, not
3
4
  // just couples. The config is to a Space what the manifest is to an agent: { keyModel, agent(persona), tools,
@@ -31,7 +32,8 @@ export async function createConfiguredSpace(config = {}, { base = '' } = {}) {
31
32
  // in the default region. Never sealed into the config — it is in the id.
32
33
  const room = config.room || newRoomId(config.region)
33
34
  const c = await commit(mk)
34
- const link = (frag) => `${String(base).replace(/\/+$/, '')}/space?room=${enc(room)}#${frag}`
35
+ const sealedPath = sealedAppHref(room)
36
+ const link = (frag) => sealedPath ? String(base).replace(/\/+$/, '') + sealedPath + '&' + frag : `${String(base).replace(/\/+$/, '')}/space?room=${enc(room)}#${frag}`
35
37
  let links
36
38
  if (n === 1) {
37
39
  links = [link(`mk=${enc(mk)}`)] // solo: the single member's link carries mk (like the gift today)
@@ -74,7 +76,7 @@ export function parseConfiguredLink(url) {
74
76
  const raw = (u.hash || '').replace(/^#/, '')
75
77
  const q = raw.indexOf('?')
76
78
  const frag = new URLSearchParams(q >= 0 ? raw.slice(0, q) : raw)
77
- return { room: u.searchParams.get('room') || '', share: frag.get('s') || '', mk: frag.get('mk') || '' }
79
+ return { room: sealedAppRoomFromHash(raw) || u.searchParams.get('room') || '', share: frag.get('s') || '', mk: frag.get('mk') || '' }
78
80
  } catch {
79
81
  return { room: '', share: '', mk: '' }
80
82
  }
package/splitKeyClient.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { isSealedAppRoom } from './sealedRoomWire.js'
1
2
  // splitKeyClient.js — the CLIENT half of the tenant split-key model (docs/tenant-split-key-design.md).
2
3
  //
3
4
  // mk = userShare ⊕ appShare. The user's kernel keeps `userShare` (a normal keyring entry — custody/recovery unchanged,
@@ -22,6 +23,7 @@ export async function wrapKEco(K_eco, originPubs = {}) {
22
23
  * Returns { room, mk, userShare, commit }. The caller persists `userShare` on the user keyring; the tenant keeps K_eco.
23
24
  * `extra` folds in the normal create fields (configSealed, gk, …). `originPubs` seeds the per-origin K_eco wraps. */
24
25
  export async function createSplitRoom({ room, mk, K_eco, originPubs = {}, extra = {}, tenantPost }) {
26
+ if (isSealedAppRoom(room) || isSealedAppRoom(extra?.room)) throw new Error('sealed share transport required')
25
27
  if (!K_eco) throw new Error('createSplitRoom needs K_eco')
26
28
  if (typeof tenantPost !== 'function') throw new Error('createSplitRoom needs an authed tenantPost')
27
29
  mk = mk || newKey()
@@ -40,6 +42,7 @@ export async function createSplitRoom({ room, mk, K_eco, originPubs = {}, extra
40
42
  * { room, mk, userShare, commit }; the caller persists `userShare` (space:us:) + `commit` (space:spc:), NEVER `mk`. */
41
43
  export async function createSplitViaBackend({ room, mk, config, gk, roomKind, split = true, gated, tenantPost, delCommit, owner = null }) { // owner: { ownerPolicy, roomAuth, attestAccept? } — a room that requires an app (space.js createSplitLocal)
42
44
  if (!room) throw new Error('createSplitViaBackend needs a room id')
45
+ if (isSealedAppRoom(room)) throw new Error('sealed share transport required')
43
46
  if (typeof tenantPost !== 'function') throw new Error('createSplitViaBackend needs an authed tenantPost')
44
47
  mk = mk || newKey()
45
48
  const c = await commit(mk)
@@ -72,6 +75,7 @@ export async function reconstructMk({ userShare, appShare, expectedCommit }) {
72
75
  * `userShare` → mk; verify commit(mk) against the room's registered commitment (§6.4). `origin` = { id, privateJwk }.
73
76
  * Returns { room, mk } on success, or { room, mk:null, error } — a null mk is always fail-closed (never a wrong key). */
74
77
  export async function openSplitRoom({ room, userShare, origin, tenantPost }) {
78
+ if (isSealedAppRoom(room)) return { room, mk: null, error: 'sealed_transport_required' }
75
79
  if (typeof tenantPost !== 'function') throw new Error('openSplitRoom needs an authed tenantPost')
76
80
  const r = await tenantPost('appshare-get', { room })
77
81
  if (!r || r.status !== 200) return { room, mk: null, error: (r && (r.error || r.status)) || 'appshare_get_failed' }
package/sw-notif-core.js CHANGED
@@ -191,6 +191,23 @@ self.wbxWaitingNotice = async (p) => {
191
191
  // stashTap — stash the tapped room to idb so the page's foreground re-check routes it even when iOS drops the
192
192
  // SW→client postMessage to a resuming PWA. Both apps set it: the vault reads it in vault-loader.js, the
193
193
  // regular app in notifTap.js (2026-10-01 — before that the regular app opened the LAST room on iOS).
194
+ async function openAccountReview(client) {
195
+ await client.focus()
196
+ const channel = new MessageChannel()
197
+ let timer
198
+ try {
199
+ return await new Promise(resolve => {
200
+ timer = setTimeout(() => resolve(false), 900)
201
+ channel.port1.onmessage = () => resolve(true)
202
+ client.postMessage({ ch: 'account-security-review' }, [channel.port2])
203
+ })
204
+ } finally {
205
+ clearTimeout(timer)
206
+ channel.port1.close()
207
+ channel.port2.close()
208
+ }
209
+ }
210
+
194
211
  self.wbxWireNotifClick = (cfg) => {
195
212
  const coldUrl = cfg.coldUrl
196
213
  const stashTap = !!cfg.stashTap
@@ -199,6 +216,20 @@ self.wbxWireNotifClick = (cfg) => {
199
216
  self.addEventListener('notificationclick', (e) => {
200
217
  e.notification.close()
201
218
  const data = e.notification.data || {}
219
+ if (data.accountSecurity === 1) {
220
+ e.waitUntil((async () => {
221
+ const url = new URL(coldUrl(''), self.location.origin)
222
+ url.searchParams.set('accountSecurity', '1')
223
+ const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true })
224
+ const current = windows.find((c) => c.frameType !== 'nested' && new URL(c.url).pathname === url.pathname)
225
+ if (current) {
226
+ try { if (await openAccountReview(current)) return } catch { /* an older page uses the cold URL */ }
227
+ try { const opened = await current.navigate(url.href); if (opened) { await opened.focus(); return } } catch { /* open from cold */ }
228
+ }
229
+ await self.clients.openWindow(url.href)
230
+ })())
231
+ return
232
+ }
202
233
  const room = data.room || ''
203
234
  const isCall = !!data.call // §CALL: a "started a call" tickle — also open the room's meeting link
204
235
  const card = typeof data.card === 'string' ? data.card : '' // a "waiting for your approval" reminder: the card to show
@@ -271,10 +302,22 @@ self.wbxQuietIfViewing = async (room, tag) => {
271
302
  // rooms it shows as unread under 'badge'; a push for a room NOT on screen adds it here, so the number rises while the app is
272
303
  // closed, and the page's next count replaces the list. No badge API, or no permission: nothing happens.
273
304
  // ⚑ A PROTECTED device keeps nothing under a room's name in the clear (idbSeal.js §NAMES), and this worker holds no key: there
274
- // it leaves the number alone — the page, unlocked, sets it from its own count.
305
+ // count distinct room alerts still in Notification Center. The page restores its exact unread count when opened.
275
306
  self.wbxBadgeAdd = async (room) => {
276
307
  try {
277
- if (await self.wbxIdbGet('protectedNames')) return 0
308
+ if (await self.wbxIdbGet('protectedNames')) {
309
+ if (typeof self.navigator?.setAppBadge !== 'function') return 0
310
+ const rooms = new Set([room])
311
+ try {
312
+ for (const notice of await self.registration.getNotifications()) {
313
+ // Only ordinary message alerts use the room ID itself as their tag.
314
+ if (notice.tag && notice.tag === notice.data?.room) rooms.add(notice.tag)
315
+ }
316
+ } catch { /* The current push still represents one room. */ }
317
+ const count = Math.min(rooms.size, 200)
318
+ await self.navigator.setAppBadge(count)
319
+ return count
320
+ }
278
321
  const rec = await self.wbxIdbGet('badge')
279
322
  const rooms = rec && Array.isArray(rec.rooms) ? rec.rooms.filter((r) => typeof r === 'string') : []
280
323
  if (!rooms.includes(room) && rooms.length < 200) rooms.push(room)
@@ -309,6 +352,9 @@ self.wbxWirePush = (cfg) => self.addEventListener('push', (e) => {
309
352
  const art = { icon: '/icon-192.png', badge: '/icon-192.png' }
310
353
  const idFor = (tag) => tag + ':' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6) // THIS showing's mark: ghosts share tags, never ids
311
354
  e.waitUntil((async () => {
355
+ if (p.accountSecurity === 1) return self.registration.showNotification('Account security alert', {
356
+ body: 'Open Spaces to review.', tag: 'account-security', data: { accountSecurity: 1 }, ...art, renotify: true,
357
+ })
312
358
  if (p.remind || p.code) { // "WAITING FOR YOUR APPROVAL" — a room's card or a Code ask (wbxWaitingNotice)
313
359
  await self.wbxNoteSw('push remind ' + (p.code ? 'code' : room.slice(0, 10)))
314
360
  const w = (await self.wbxWaitingNotice(p)) || { title: 'Waiting for your approval', body: 'Open the app to answer.', tag: 'remind', data: {} }
@@ -353,7 +399,9 @@ self.wbxWirePush = (cfg) => self.addEventListener('push', (e) => {
353
399
  // A LOCKED CHAT (chatLockSw.js; docs/chat-lock-plan.md): the plain line only — no name, no words, no read of its own
354
400
  const locked = room ? await self.wbxChatLocked(room) : false
355
401
  const carried = allowed && !locked ? opened : null
356
- const fetched = carried || !room || locked ? null : await cfg.describe(room)
402
+ // Until the app has mirrored an explicit permission (including after an upgrade), show the notice offline.
403
+ const directAllowed = await self.wbxIdbGet('pushDirectAllowed').catch(() => false) === true
404
+ const fetched = carried || !room || locked || !directAllowed ? null : await cfg.describe(room)
357
405
  const d = allowed && !locked ? (carried || fetched) : null
358
406
  // ALERT or update quietly ("don't notify" is not an option on iOS — "don't buzz" is). Stamped only on an alert, or a
359
407
  // continuous conversation keeps pushing the window forward and never alerts again.
@@ -372,7 +420,7 @@ self.wbxWirePush = (cfg) => self.addEventListener('push', (e) => {
372
420
  else if (room) await self.wbxBadgeAdd(room) // the number on the app's icon counts it until it is read (appBadge.js)
373
421
  // The push carried the preview, so describe() did not run: run it now for its PREFETCH — after the notification is up,
374
422
  // so a slow or refused fetch never delays or blanks what is shown.
375
- if (carried && room && !tailKept) { try { await cfg.describe(room) } catch { /* the tap's prefetch is best-effort */ } }
423
+ if (directAllowed && carried && room && !tailKept) { try { await cfg.describe(room) } catch { /* the tap's prefetch is best-effort */ } }
376
424
  })())
377
425
  })
378
426