@witbitz/sdk 0.0.0-stage → 4.4.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.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/sdkProtect.js ADDED
@@ -0,0 +1,228 @@
1
+ // sdkProtect.js — wb.protect: DEVICE STORAGE PROTECTION for what an app keeps on the device (https://witbitz.chat/docs/sdk-accounts.md#protect). The owner, 2026-10-06: "Build it and then use it in spaces".
2
+ //
3
+ // The SDK hands an app JSON to persist — the sign-in session, room snapshots (they carry room keys), the Siri / A2A /
4
+ // backup state (private keys) — and an infostealer copies localStorage along with the rest of the profile. With
5
+ // protection on, every value the app writes through `save()` / `seal()` is AES-GCM ciphertext under a key a PLATFORM
6
+ // passkey derives (Windows Hello → TPM, Touch ID → Secure Enclave, Android → StrongBox): PRF, or a secret stored in the
7
+ // credential's largeBlob. That key is nowhere on disk; this object holds it in memory while unlocked and drops it on lock.
8
+ //
9
+ // const p = wb.protect
10
+ // p.available() → can this browser hold such a passkey at all
11
+ // await p.enable({ label }) one passkey; everything already saved through save() is sealed in place
12
+ // await p.save(name, value) / load(name) / remove(name) a Storage (localStorage by default), sealed while on
13
+ // await p.seal(value) / open(stored) for a store of the app's own; both pass values through while protection is off
14
+ // p.lock() / await p.unlock() drop the key / a user-verified passkey assertion brings it back
15
+ // p.autoLock(minutes) lock when the page comes back after being hidden longer than this
16
+ // await p.disable() write what save() wrote back in the clear, forget the protection
17
+ // p.on('locked' | 'unlocked' | 'change', cb) → unsubscribe
18
+ //
19
+ // ⚑ A LOST PASSKEY LOSES THE SEALED STATE. `enable()` refuses unless the account backup is on (wb.backup) or the app says
20
+ // `withoutBackup: true` — the backup is what brings the rooms back on a new device.
21
+ // ⚑ The Spaces app takes its passkey → key step from here too (enrollProtectKey / unlockProtectKey): one derivation, and
22
+ // the protection passkey under its OWN user handle, so it never replaces the account's recovery passkey (spacePasskey.js).
23
+ import { deriveSealRaw, importRaw, seal as sealWith, open as openWith, isSealed } from './deviceSeal.js'
24
+ import { passkeyPossible, enrollPasskey, unlockPasskey, describePasskey } from './spacePasskey.js'
25
+
26
+ export const PROTECT_CFG = 'witbitz:protect'
27
+ /** The protection passkey's own user handle (spacePasskey.js keys one handle per purpose). A shared handle REPLACED the
28
+ * account's recovery passkey: an authenticator keeps one credential per (site, user handle). */
29
+ export const PROTECT_USER_KEY = 'space:pkuser:protect'
30
+ const CHECK = 'witbitz-protect-check-v1' // sealed into the config at enable: an unlock knows it has the right key before it opens anything
31
+ const fail = (code, msg) => Object.assign(new Error('witbitz: ' + msg), { code })
32
+
33
+ /** The browser's WebAuthn as a passkey for protection: { possible, enroll(label) → { credId, secret, mode },
34
+ * unlock(credId) → { credId, secret, mode, secrets } }. `rpId` / `rpName` default to this page's host. */
35
+ export function webauthnPasskey ({ rpId, rpName, userName = 'Device protection', userKey = PROTECT_USER_KEY } = {}) {
36
+ return {
37
+ // A SECURE CONTEXT, not only https: a builder developing on http://localhost has WebAuthn too (passkeyPossible() asks https).
38
+ possible: () => { try { return passkeyPossible() || !!(typeof window !== 'undefined' && window.isSecureContext && window.PublicKeyCredential && navigator.credentials && navigator.credentials.create) } catch { return false } },
39
+ enroll: (label) => enrollPasskey(label, rpId, { rpName: rpName || (typeof location !== 'undefined' ? location.hostname : ''), userName, userKey }),
40
+ unlock: (credId) => unlockPasskey(credId, rpId),
41
+ }
42
+ }
43
+
44
+ /** The secret an assertion answered for this mode — a credential can answer both (a PRF and a largeBlob), and only the one
45
+ * protection was enabled with opens what it sealed. */
46
+ const secretsOf = (r, mode) => {
47
+ const all = (r && Array.isArray(r.secrets) && r.secrets.length ? r.secrets : (r && r.secret ? [{ secret: r.secret, mode: r.mode }] : []))
48
+ return [...all.filter((s) => s.mode === mode), ...all.filter((s) => s.mode !== mode)]
49
+ }
50
+
51
+ /** THE SHARED STEP, for an app with stores of its own (the Spaces app): a new protection passkey → { credId, mode, raw },
52
+ * `raw` being the 32 device-key bytes (deviceSeal.importRaw makes the key). */
53
+ export async function enrollProtectKey (label, { rpId, passkey } = {}) {
54
+ const pk = passkey || webauthnPasskey({ rpId, rpName: 'Witbitz Spaces', userName: describePasskey('Spaces device protection') }) // purpose · device · date in the keychain
55
+ const r = await pk.enroll(label)
56
+ if (!r || !r.secret) throw fail('prf_unsupported', 'this passkey cannot hold a key')
57
+ return { credId: r.credId, mode: r.mode || 'prf', raw: await deriveSealRaw(r.secret) }
58
+ }
59
+ /** …and an unlock with it → { credId, mode, raw }. `mode` picks the secret protection was enabled with. */
60
+ export async function unlockProtectKey (credId, mode, { rpId, passkey } = {}) {
61
+ const pk = passkey || webauthnPasskey({ rpId })
62
+ const r = await pk.unlock(credId)
63
+ const [s] = secretsOf(r, mode)
64
+ if (!s) throw fail('wrong_passkey', 'the passkey answered no key')
65
+ return { credId: r.credId || credId, mode: s.mode || mode, raw: await deriveSealRaw(s.secret) }
66
+ }
67
+
68
+ export class Protect {
69
+ /** @param {object} o { storage?, storeKey?, passkey?, backup?, rpId?, rpName?, doc?, now? } — `storage` is a Storage
70
+ * (localStorage by default), `backup` the account backup (wb.backup), `passkey` replaces WebAuthn (tests, a native shell). */
71
+ constructor ({ storage, storeKey = PROTECT_CFG, passkey, backup = null, rpId, rpName, doc, now } = {}) {
72
+ const hidden = (k, v) => Object.defineProperty(this, k, { value: v, writable: true, enumerable: false, configurable: true })
73
+ hidden('_storage', storage || (typeof localStorage !== 'undefined' ? localStorage : null))
74
+ hidden('_storeKey', storeKey)
75
+ hidden('_pk', passkey || webauthnPasskey({ rpId, rpName }))
76
+ hidden('_backup', backup)
77
+ hidden('_doc', doc || (typeof document !== 'undefined' ? document : null))
78
+ hidden('_now', typeof now === 'function' ? now : () => Date.now())
79
+ hidden('_key', null) // the AES-GCM key — in memory only, and only while unlocked
80
+ hidden('_ls', { locked: new Set(), unlocked: new Set(), change: new Set() })
81
+ hidden('_away', null)
82
+ if (this._cfg().auto) this._watch()
83
+ }
84
+
85
+ _cfg () { try { return JSON.parse((this._storage && this._storage.getItem(this._storeKey)) || 'null') || {} } catch { return {} } }
86
+ _setCfg (c) { if (!this._storage) return; if (c) this._storage.setItem(this._storeKey, JSON.stringify(c)); else this._storage.removeItem(this._storeKey) }
87
+ _emit (ev) { for (const f of [...this._ls[ev], ...(ev === 'change' ? [] : this._ls.change)]) { try { f(this.state) } catch { /* a listener must not break the lock */ } } }
88
+
89
+ /** { on, locked, mode, auto } — `locked` is true while protection is on and the key is not in memory. */
90
+ get state () { const c = this._cfg(); return { on: !!c.on, locked: !!c.on && !this._key, mode: c.on ? c.mode || null : null, auto: +c.auto || 0 } }
91
+ toJSON () { return { protect: this.state } }
92
+
93
+ /** Can this browser hold a protection passkey (WebAuthn on https)? PRF / largeBlob support is only known at enable. */
94
+ available () {
95
+ try {
96
+ const policy = globalThis.document?.permissionsPolicy || globalThis.document?.featurePolicy
97
+ if (globalThis.window && window.parent !== window && policy?.allowsFeature &&
98
+ (!policy.allowsFeature('publickey-credentials-create') || !policy.allowsFeature('publickey-credentials-get'))) return false
99
+ return !!this._pk.possible()
100
+ } catch { return false }
101
+ }
102
+
103
+ on (ev, cb) { const s = this._ls[ev]; if (!s || typeof cb !== 'function') throw fail('bad_event', 'protect events are locked, unlocked and change'); s.add(cb); return () => s.delete(cb) }
104
+
105
+ async enable ({ label = '', withoutBackup = false } = {}) {
106
+ if (this._cfg().on) throw fail('already_enabled', 'protection is already on for this app on this device')
107
+ if (!this.available()) throw fail('unavailable', 'this browser cannot hold a passkey for storage protection')
108
+ // No backup to check (a Protect made before its client, or alone) is no backup: never a silently skipped guard (code review).
109
+ if (!withoutBackup && !(this._backup && this._backup.enabled)) throw fail('backup_required', 'turn on the account backup (wb.backup) first: a lost passkey would lose everything sealed under it (or pass withoutBackup: true)')
110
+ const r = await this._pk.enroll(label || 'Device protection')
111
+ if (!r || !r.secret) throw fail('prf_unsupported', 'this passkey cannot hold a key')
112
+ const mode = r.mode || 'prf'
113
+ const key = await importRaw(await deriveSealRaw(r.secret))
114
+ // pass 7, F#7: the check is sealed BEFORE the config is read — a name save() added while it was awaited (the config read
115
+ // before it) was dropped from `keys` by the write below, and its value stayed clear for good
116
+ const check = await sealWith(key, CHECK)
117
+ const prev = this._cfg()
118
+ // RECORD THE SWITCH FIRST, the key held — then seal what was saved while off. A crash in between leaves clear values,
119
+ // which read as they are and are sealed at the next unlock (_sealPending). The other order (seal, then record) left
120
+ // sealed values behind an "off" config with no passkey recorded: unopenable for good (code review, 2026-10-06).
121
+ this._key = key
122
+ this._setCfg({ on: true, credId: r.credId, mode, at: this._now(), check, keys: Array.isArray(prev.keys) ? prev.keys : [], auto: +prev.auto || 0 })
123
+ await this._sealPending()
124
+ this._emit('unlocked')
125
+ return this.state
126
+ }
127
+
128
+ async unlock () {
129
+ const c = this._cfg()
130
+ if (!c.on) throw fail('not_enabled', 'protection is off')
131
+ if (this._key) return this.state
132
+ const r = await this._pk.unlock(c.credId)
133
+ for (const s of secretsOf(r, c.mode)) {
134
+ let key = null
135
+ try { key = await importRaw(await deriveSealRaw(s.secret)); if (await openWith(key, c.check) !== CHECK) key = null } catch { key = null }
136
+ if (key) { this._key = key; try { await this._sealPending() } catch { /* a full disk must not cost the unlock */ } this._emit('unlocked'); return this.state }
137
+ }
138
+ throw fail('wrong_passkey', 'that passkey does not open this device\'s protected storage')
139
+ }
140
+
141
+ /** Seal every value save() wrote that is still clear — what an interrupted enable() left behind. */
142
+ async _sealPending () {
143
+ if (!this._key) return
144
+ for (const k of Array.isArray(this._cfg().keys) ? this._cfg().keys : []) { const v = this._read(k); if (v !== undefined && !isSealed(v)) this._write(k, await sealWith(this._key, v)) }
145
+ }
146
+
147
+ lock () { const was = !!this._key; this._key = null; if (was && this._cfg().on) this._emit('locked'); return this.state }
148
+
149
+ // ONE AT A TIME (state machines pass 7, F#8): disable() opens and rewrites every saved value across awaits, and a save() that
150
+ // finished in between left a sealed value behind the "off" it then wrote — load() deletes those. The two run in order.
151
+ _serial (fn) { const run = (this._chain || Promise.resolve()).then(fn, fn); this._chain = run.catch(() => {}); return run }
152
+
153
+ async disable () { return this._serial(() => this._disable()) }
154
+ async _disable () {
155
+ const c = this._cfg()
156
+ if (!c.on) return this.state
157
+ if (!this._key) await this.unlock() // the passkey confirms it, and its key writes the values back
158
+ const key = this._key
159
+ // a value sealed by an EARLIER setup (another passkey) never opens: dropped, not a throw that leaves protection half off (sync sweep backlog P3)
160
+ for (const k of Array.isArray(c.keys) ? c.keys : []) { const v = this._read(k); if (isSealed(v)) { let clear; try { clear = await openWith(key, v) } catch { this._storage.removeItem(k); continue } this._write(k, clear) } }
161
+ this._key = null
162
+ this._setCfg(c.auto || (c.keys && c.keys.length) ? { on: false, keys: c.keys || [], auto: +c.auto || 0 } : null)
163
+ this._emit('change')
164
+ return this.state
165
+ }
166
+
167
+ /** Seal a value for a store of the app's own — the value itself while protection is off. Refuses while locked. */
168
+ async seal (value) {
169
+ if (!this._cfg().on) return value
170
+ if (!this._key) throw fail('locked', 'protected storage is locked — wb.protect.unlock() first')
171
+ return sealWith(this._key, value)
172
+ }
173
+ /** Open what seal() returned — a clear value passes through. Refuses a sealed one while locked. */
174
+ async open (stored) {
175
+ if (!isSealed(stored)) return stored
176
+ if (!this._key) throw fail('locked', 'protected storage is locked — wb.protect.unlock() first')
177
+ return openWith(this._key, stored)
178
+ }
179
+
180
+ _read (name) { const s = this._storage && this._storage.getItem(name); if (s == null) return undefined; try { return JSON.parse(s) } catch { return s } }
181
+ _write (name, v) { this._storage.setItem(name, JSON.stringify(v)) }
182
+ /** Persist `value` under `name` in the Storage — sealed while protection is on, and resealed / written back clear when it changes. */
183
+ async save (name, value) { return this._serial(() => this._save(name, value)) }
184
+ async _save (name, value) {
185
+ if (!this._storage) throw fail('no_storage', 'no Storage to save into (pass storage to wb.protect)')
186
+ const c = this._cfg()
187
+ if (c.on && !this._key) throw fail('locked', 'protected storage is locked — wb.protect.unlock() first')
188
+ const keys = Array.isArray(c.keys) ? c.keys : []
189
+ if (!keys.includes(name)) this._setCfg({ ...c, keys: [...keys, String(name)] })
190
+ if (!c.on) { this._write(name, value); return }
191
+ const sealed = await sealWith(this._key, value)
192
+ // pass 7, F#8: disable() ran while it was sealed — a sealed value behind an "off" config is what load() deletes; write it clear
193
+ this._write(name, this._cfg().on ? sealed : value)
194
+ }
195
+ /** The value saved under `name` (undefined if none). Refuses a sealed one while locked. */
196
+ async load (name) {
197
+ const v = this._read(name)
198
+ if (v === undefined) return undefined
199
+ if (!isSealed(v)) return v
200
+ // sealed while protection is OFF, or sealed under another key: an earlier setup's leftover, which nothing can open — it
201
+ // reads as absent and goes, never a throw (sync sweep backlog P3). Sealed under THIS key while locked still refuses.
202
+ if (!this._cfg().on) { this._storage.removeItem(name); return undefined }
203
+ if (!this._key) throw fail('locked', 'protected storage is locked — wb.protect.unlock() first')
204
+ try { return await openWith(this._key, v) } catch { this._storage.removeItem(name); return undefined }
205
+ }
206
+ remove (name) {
207
+ if (this._storage) this._storage.removeItem(name)
208
+ const c = this._cfg(); if (Array.isArray(c.keys) && c.keys.includes(name)) this._setCfg({ ...c, keys: c.keys.filter((k) => k !== name) })
209
+ }
210
+
211
+ /** Lock when the page returns after being hidden longer than `minutes` (0 = only an explicit lock() or a new launch). */
212
+ autoLock (minutes) {
213
+ const m = Math.max(0, +minutes || 0)
214
+ const c = this._cfg(); this._setCfg({ ...c, auto: m, keys: c.keys || [] })
215
+ if (m) this._watch()
216
+ return this.state
217
+ }
218
+ _watch () {
219
+ if (this._away || !this._doc || !this._doc.addEventListener) return
220
+ this._away = { at: 0 }
221
+ this._doc.addEventListener('visibilitychange', () => {
222
+ const auto = +this._cfg().auto || 0
223
+ if (this._doc.hidden) { this._away.at = this._now(); return }
224
+ if (auto && this._away.at && this._now() - this._away.at > auto * 60000) this.lock()
225
+ this._away.at = 0
226
+ })
227
+ }
228
+ }
package/sdkRedact.js ADDED
@@ -0,0 +1,36 @@
1
+ // sdkRedact.js — keep a room's key out of a builder's logs (https://witbitz.chat/docs/sdk-roadmap.md, item 1, measured 2026-10-05).
2
+ //
3
+ // A Space's link and key ARE the admission: whoever holds them is a member. `console.log(space)` printed both (`_mk`,
4
+ // `shareLink` were plain enumerable properties), and an error reporter that walks objects (`Sentry.setContext('space',
5
+ // space)`) would have sent them to a third party. Two layers, so either habit is covered:
6
+ // 1. hide() — the credential-bearing properties become NON-ENUMERABLE: still readable and writable by name (the SDK's
7
+ // own code and `space.shareLink` / `space.key` are unchanged), invisible to Object.keys, for…in, spread, JSON and
8
+ // every walker that follows enumerable keys.
9
+ // 2. redacted() — `toJSON()` and Node's `inspect.custom` print a short summary with `[REDACTED]` in place of each secret.
10
+ // Browsers' consoles show non-enumerable properties greyed out when an object is EXPANDED by hand; that is the developer
11
+ // opening the object on their own screen, not a log leaving it.
12
+
13
+ export const REDACTED = '[REDACTED]'
14
+ export const INSPECT = Symbol.for('nodejs.util.inspect.custom')
15
+
16
+ /** Make `names` on `obj` non-enumerable, keeping their values and writability. Missing names are created undefined. */
17
+ export function hide(obj, names) {
18
+ for (const n of names) {
19
+ const d = Object.getOwnPropertyDescriptor(obj, n)
20
+ Object.defineProperty(obj, n, { value: d ? d.value : undefined, writable: true, configurable: true, enumerable: false })
21
+ }
22
+ return obj
23
+ }
24
+
25
+ /** Install toJSON + inspect.custom on a class prototype. `summary(self)` returns the plain object to show. */
26
+ export function redacted(proto, summary) {
27
+ Object.defineProperty(proto, 'toJSON', { value: function toJSON() { return summary(this) }, writable: true, configurable: true })
28
+ Object.defineProperty(proto, INSPECT, {
29
+ value: function inspect(depth, options, nodeInspect) {
30
+ const s = summary(this)
31
+ const name = (this && this.constructor && this.constructor.name) || 'Object'
32
+ return typeof nodeInspect === 'function' ? `${name} ${nodeInspect(s, options)}` : { [name]: s }
33
+ },
34
+ writable: true, configurable: true,
35
+ })
36
+ }
package/sdkRekey.js ADDED
@@ -0,0 +1,340 @@
1
+ // sdkRekey.js — A VERIFIED ROOM CHANGES ITS MEMBERS IN PLACE, in a builder's app (https://witbitz.chat/docs/sdk-people.md#members;
2
+ // docs/key-rotation-design.md § (b)). The Spaces app's rule (rekeyMembers.js), with the key held by the Space itself:
3
+ // • wb.invite — the account's INVITE KEY for this app: an ECDH box whose public half is in the directory under the app's own
4
+ // scope ('app:<origin>', the sign-in's app — the server refuses any other app writing it). A member change seals the room's
5
+ // new key to it. The builder keeps `wb.invite.state` as it keeps `wb.a2a.state` (it holds a private key) and hands it back
6
+ // as `new Witbitz({ invite })`; a second device without it never takes over the slot (it would cut the first one off).
7
+ // • space.changeMembers({ emails, … }) / space.rotateKey() — a new key, the config with the old key in its chain, one grant
8
+ // per remaining member (spaceClient.rekey); the same room, link, history and lanes.
9
+ // • a device holding the old key meets `stale_key` → fetches its grant (op 'grant'), opens it with the invite key, checks it
10
+ // against the room's commitment, takes it → 'rekeyed'. No grant → 'removed'; on the list but nothing sealed → 'pending'.
11
+ // One scope per app: a member reached only in another app (or only in the Spaces app) gets 'pending' — "ask for a fresh link".
12
+ import { enroll, resolveHandle } from './inviteEnroll.js'
13
+ import { genRecipientKey, openBox, commit, combineShares } from './e2ee.js'
14
+ import { tokenApp, tokenClaims } from './accountScope.js'
15
+ import { GATE_DOMAIN } from './emailFork.js'
16
+ import { EMAIL, normalizeDomains, lc, recipientsFor, membersAfter, unseenHidden, stillOnList, dropsForUsers } from './memberChange.js'
17
+ import { ROSTER_DOC } from './roomRoster.js'
18
+ import { hide } from './sdkRedact.js'
19
+ import { assertNotKept } from './sdkCloudDevice.js'
20
+ import { memberHash } from './rosterHash.js'
21
+
22
+ const sdkError = (message, code) => Object.assign(new Error(message), { code })
23
+
24
+ /** The directory scope a sign-in enrols under: 'app:<the app it speaks for>'; '' for a first-party sign-in (the Spaces app's own). */
25
+ export function inviteScope (idToken) {
26
+ const app = tokenApp(tokenClaims(idToken))
27
+ return app == null ? '' : 'app:' + app
28
+ }
29
+
30
+ const validState = (s) => !!(s && typeof s === 'object' && s.boxPub && s.boxPriv && typeof s.inbox === 'string' && s.inbox)
31
+
32
+ /** wb.invite — this account's invite key for this app (see the header). */
33
+ export class InviteAccount {
34
+ constructor (wb, { state = null } = {}) {
35
+ this._wb = wb
36
+ this._state = validState(state) ? { ...state } : null
37
+ this._enrolling = null
38
+ this._waiting = new Set() // Spaces told 'pending' for want of this key (adoptGrant) — woken by restore()
39
+ this.status = this._state ? 'held' : 'none' // 'none' | 'held' | 'enrolled' | 'held_elsewhere' | 'failed'
40
+ hide(this, ['_wb', '_state', '_waiting'])
41
+ }
42
+ /** What to persist (it holds a private key — keep it as you keep the session), or null. */
43
+ get state () { const k = this._key(); return k ? { ...k } : null }
44
+ // the state handed in, else the account backup's (a restored device), else none
45
+ _key () {
46
+ if (this._state) return this._state
47
+ const b = this._wb && this._wb.backup && this._wb.backup.invite
48
+ if (validState(b)) { this._state = { ...b }; this.status = 'held' }
49
+ return this._state
50
+ }
51
+ /** Hand back a persisted state (also `new Witbitz({ invite })`). */
52
+ restore (state) {
53
+ if (!validState(state)) throw sdkError('witbitz: invite.restore needs a state from wb.invite.state', 'invalid_argument')
54
+ this._state = { ...state }; this.status = 'held'
55
+ for (const sp of [...this._waiting]) { this._waiting.delete(sp); try { sp._keyAt = 0; sp._keyMiss = null; sp._kick() } catch { /* */ } } // a Space waiting for a key it could not open tries at once — its grant backoff too (pass 6, K#5: the kicked poll's adoption was refused by it, up to 60 s)
56
+ try { if (typeof this._onRestore === 'function') this._onRestore() } catch { /* the vault's */ }
57
+ return this
58
+ }
59
+ /** Publish this account's invite key for this app (after signIn / refreshSession — the SDK runs it). Idempotent. A slot that
60
+ * already holds ANOTHER key (another device of this account, without this state) is left as it is: status 'held_elsewhere'
61
+ * — restore that device's state here, or from the account backup. → the status. */
62
+ async enroll () {
63
+ if (this._enrolling) return this._enrolling
64
+ this._enrolling = this._enroll().finally(() => { this._enrolling = null })
65
+ return this._enrolling
66
+ }
67
+ async _enroll () {
68
+ const wb = this._wb, s = wb && wb._session
69
+ if (!s || !s.idToken || !s.email) return this.status
70
+ const client = wb._client
71
+ if (!client || typeof client.dirPut !== 'function' || typeof client.oprf !== 'function') return this.status
72
+ const scope = inviteScope(s.idToken)
73
+ const email = lc(s.email)
74
+ try {
75
+ // NEVER TAKE OVER ANOTHER DEVICE'S SLOT: the box published under this account's handle wins. This device publishes only when
76
+ // the slot is empty or already holds the key this device holds (read AFTER the lookup: a restore may land meanwhile)
77
+ const handle = await resolveHandle(email, client, scope)
78
+ const g = handle ? await client.dirGet(handle, { idToken: s.idToken, ...(scope ? { scope } : {}) }) : null // as its owner: a slot hidden from lookups still answers
79
+ const mine = this._key()
80
+ const usable = mine && (mine.scope == null || mine.scope === scope) && (mine.email == null || lc(mine.email) === email)
81
+ const published = g && g.status === 200 && g.entry && g.entry.boxPub
82
+ const held = usable && published && JSON.stringify(g.entry.boxPub) === JSON.stringify(mine.boxPub)
83
+ if (published && !held) { this.status = 'held_elsewhere'; return this.status }
84
+ if (!g || (g.status !== 200 && g.status !== 404)) throw new Error('directory_unavailable: ' + ((g && (g.error || g.status)) || 'no answer')) // unknown is not empty: never mint over a slot that may exist
85
+ const next = await enroll({ email, idToken: s.idToken, client, genRecipientKey, scope, load: () => (usable ? mine : null), save: () => {} })
86
+ if (next) { this._state = { boxPub: next.boxPub, boxPriv: next.boxPriv, inbox: next.inbox, handle: next.handle, scope, email }; this.status = 'enrolled' }
87
+ try { if (wb.backup && this._state) wb.backup.setInvite(this._state) } catch { /* the backup is best-effort */ }
88
+ } catch (e) { this._error = String((e && e.message) || e); this.status = this._state ? 'held' : 'failed' }
89
+ return this.status
90
+ }
91
+ }
92
+
93
+ // THE LINK FOLLOWS THE KEY: `#mk=` (or a split room's `#us=…&spc=…`) is replaced; every other mark (gate, tier) stays.
94
+ export function relink (link, { mk = null, userShare = null, commit: spc = null } = {}) {
95
+ const s = String(link || '')
96
+ const i = s.indexOf('#')
97
+ if (i < 0) return s
98
+ const keep = s.slice(i + 1).split('&').filter((p) => p && !/^(mk|s|us|spc)=/.test(p))
99
+ const key = userShare ? ['us=' + encodeURIComponent(userShare), ...(spc ? ['spc=' + encodeURIComponent(spc)] : [])] : mk ? ['mk=' + mk] : []
100
+ return s.slice(0, i) + '#' + [...key, ...keep].join('&')
101
+ }
102
+ const fragParam = (link, k) => { const m = new RegExp('[#&]' + k + '=([^&]*)').exec(String(link)); return m ? decodeURIComponent(m[1]) : '' }
103
+
104
+ // ON THE LIST, BUT NO KEY THIS DEVICE CAN TAKE: 'pending' once per reason (the poll slows meanwhile) — send this member the link again
105
+ function waiting (space, reason) {
106
+ const was = space._keyWait
107
+ space._keyWait = reason
108
+ try { if (space._wb && space._wb.invite) space._wb.invite._waiting.add(space) } catch { /* */ }
109
+ if (was !== reason) space._emit('pending', { room: space.room, reason })
110
+ return null
111
+ }
112
+
113
+ /** The answer to op 'grant', opened with this account's invite key and checked against the room's commitment — one reading for a
114
+ * Space (below) and a vault (vault-core.js, whose worker holds the key). → { mk, epoch } | { userShare, commit, epoch } (a split
115
+ * room's new user half) | { removed:true } | { wait: reason } */
116
+ export async function openGrant (r, room, invite, { gated: markGated = true } = {}) {
117
+ const gated = (r && r.gated === true) || markGated // the server says so (spaceRoom op grant, only ever true); else the link's mark
118
+ // A LINK SPACE (not email-gated) changed in place seals its key to its members' SIGNING keys, which only the Spaces app holds
119
+ // (rekeyMembers linkProof) — an account has no grant there, so "no grant" is not "removed": ask for the link again
120
+ // (sweep 10-23 #17: the SDK and the vault said 'removed', or waited for ever)
121
+ if (!gated && (!r || r.status === 404 || r.status === 401)) return { wait: 'link_changed' }
122
+ // a VERIFIED room answering 401: the sign-in lapsed — say so (the app asks for one, rekeyMembers.js signInNeeded); it was a silent
123
+ // 'grant_unavailable' (sync sweep 2026-11-14 #6)
124
+ if (gated && r && r.status === 401) return { wait: 'sign_in_required' }
125
+ if (!r || r.status !== 200 || !r.grant) return r && r.status === 404 ? { removed: true } : { wait: 'grant_unavailable' }
126
+ if (r.grant === 'pending') return { wait: 'pending' }
127
+ if (!invite || !invite.boxPriv) return { wait: 'no_invite_key' }
128
+ let g = null
129
+ try { g = JSON.parse(await openBox(JSON.parse(r.grant), invite.boxPriv)) } catch { g = null }
130
+ if (!g || g.room !== room) return { wait: 'grant_unopenable' }
131
+ const epoch = Number(r.epoch) || Number(g.epoch) || 0
132
+ if (g.kind === 'room-split-key' && typeof g.userShare === 'string' && g.userShare && g.commit === r.commit) return { userShare: g.userShare, commit: g.commit, epoch }
133
+ if (g.kind !== 'room-key' || typeof g.mk !== 'string' || (await commit(g.mk)) !== r.commit) return { wait: 'grant_not_current' }
134
+ return { mk: g.mk, epoch }
135
+ }
136
+
137
+ /** This Space met its room's new key: fetch the grant sealed to this account, open it, take it. → { mk } | null (and 'removed' /
138
+ * 'pending' is emitted). */
139
+ export async function adoptGrant (space) {
140
+ const wb = space._wb
141
+ const r = await space._client.grant(space.room).catch(() => null)
142
+ const o = await openGrant(r, space.room, wb && wb.invite && wb.invite._key(), { gated: !!space._gated })
143
+ if (o.removed) { if (space._keyWait !== 'removed') { space._keyWait = 'removed'; space._emit('removed', { room: space.room }) } return null }
144
+ if (o.wait) return o.wait === 'grant_unavailable' ? null : waiting(space, o.wait)
145
+ if (o.userShare) {
146
+ // a split room: the grant is the new USER half; the app's half did not change — mk ⊕ old user half
147
+ const oldShare = fragParam(space.shareLink, 'us')
148
+ const app = oldShare && space._mk ? combineShares(space._mk, oldShare) : null
149
+ const mk = app ? combineShares(o.userShare, app) : null
150
+ if (!mk || (await commit(mk)) !== o.commit) return waiting(space, 'split_unpaired')
151
+ space._setKey(mk, o.epoch, { userShare: o.userShare, commit: o.commit })
152
+ return { mk }
153
+ }
154
+ space._setKey(o.mk, o.epoch)
155
+ return { mk: o.mk }
156
+ }
157
+
158
+ // Who the room has now: the advertised addresses, and the members whose email the guest book shows (a hidden address is only
159
+ // its hash in the config — the book is where a removed hidden member can still be named)
160
+ async function currentMembers (space, cfg) {
161
+ const al = (cfg && cfg.allow) || {}
162
+ // ⛔ A FAILED READ IS NOT AN EMPTY BOOK (state machines pass 7, F#6; the app's V#6): read as "nobody has joined", a member the
163
+ // book alone names (a hidden address, a domain, an @username) fell out of the list — a change removed them with no word, and
164
+ // rotateKey left them out of the new key while it reported success. The read failing fails the call; nothing changes.
165
+ const book = await space._client.state(space.room, space._mk, ROSTER_DOC).catch(() => null)
166
+ if (!book || (book.status !== undefined && book.status !== 200)) throw sdkError('witbitz: who has joined this Space could not be read — nothing has changed; try again', 'book_unavailable')
167
+ const seen0 = Object.values(book.seen || {}).filter((x) => x && !x.left).map((x) => x.email).filter((e) => typeof e === 'string' && e)
168
+ // a room changed in place keeps its guest book — those already removed are still in it; only the people on the list count
169
+ // (the app's rule, memberChange.stillOnList; sweep 10-23 #5: the SDK gave them the new key back)
170
+ const onList = await stillOnList(cfg, space.room, Object.values(book.seen || {}).filter((x) => x && x.email && !x.left)).catch(() => null) // the records: a person in by @username is on by the entry they came in by (sync sweep 11-23 #2)
171
+ const seen = onList ? seen0.filter((e) => onList(e, '')) : seen0
172
+ const emails = [...new Set([...(Array.isArray(al.emails) ? al.emails : []), ...seen].map(lc))]
173
+ return { book, emails, owners: ((cfg.owners && cfg.owners.emails) || []).map(lc), admins: ((cfg.admins && cfg.admins.emails) || []).map(lc) }
174
+ }
175
+
176
+ const epochOf = (cfg) => (Array.isArray(cfg && cfg.keyChain) ? cfg.keyChain.length : 0) // the epoch a config was read at (= the app's rekeyToWant)
177
+ async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null, book }) {
178
+ const me = lc(space._wb && space._wb._session && space._wb._session.email)
179
+ const wb = space._wb
180
+ const scope = inviteScope(wb._session.idToken)
181
+ if (!wb.invite._key()) await wb.invite.enroll()
182
+ const people = Object.values(book.seen || {})
183
+ const retained = await stillOnList({ keyChain: [{ epoch: expectEpoch }], allow: allowAfter }, space.room, people)
184
+ const domains = new Set(normalizeDomains(allowAfter?.domains))
185
+ const joined = people.filter(p => p && !p.left && p.email && retained(p.email) &&
186
+ (domains.has(lc(p.email).split('@')[1]) || p.entries?.some(e => typeof e === 'string' && e.startsWith('u:')))).map(p => lc(p.email))
187
+ const { recipients, unreachable, pending } = await recipientsFor(space.room, [...stay, ...joined], wb._client || space._client, { scope, allow: allowAfter, people }) // include observed retained legacy handles, never arbitrary roster emails
188
+ if (!recipients.some((x) => x.email === me)) throw sdkError('witbitz: this account has no invite key for this app yet (wb.invite.status: ' + wb.invite.status + ') — restore wb.invite.state from the device that has it', 'no_invite_key')
189
+ const split = space._split ? { userShare: fragParam(space.shareLink, 'us') } : null
190
+ if (space._split && !split.userShare) throw sdkError('witbitz: this split Space was not opened from its link — its user half is unknown here', 'invalid_argument')
191
+ const r = await space._client.rekey(space.room, space._mk, { ...(members ? { members } : {}), recipients: recipients.map(({ mh, boxPub }) => ({ mh, boxPub })), pending: [...pending, ...unseenHidden(allowAfter, recipients, pending)], by: me, ...(split ? { split } : {}), ...(Number.isInteger(expectEpoch) ? { expectEpoch } : {}) }).catch(() => null) // ONE SNAPSHOT (docs/state-machines.md V#5, the SDK's twin K#1): the change was planned at this epoch — a key adopted on the way (the healing client's retry) must not apply it to another
192
+ if (!r || r.status !== 200 || !(r.newMk || r.newShare)) { // a split room in a vault: the worker keeps the key and answers only the new share (sweep 10-23 #3; the app's rekeyMembers takes it too)
193
+ if (!r || !r.status || r.status >= 500 || r.status === 200) throw sdkError('The service did not confirm the new key. Refresh this Space to check its current membership before trying again.', 'rekey_unknown')
194
+ const code = r && r.error === 'stale_epoch' ? 'changed_meanwhile' : (r && r.error) || 'rekey_failed'
195
+ throw Object.assign(new Error('witbitz: the key was not changed — nothing has changed' + (r && r.reason ? ` (${r.reason})` : '')), { code, status: r && r.status })
196
+ }
197
+ space._setKey(r.newMk || null, r.epoch, r.newShare ? { userShare: r.newShare, commit: r.newCommit } : null)
198
+ return { epoch: r.epoch, unreachable: unreachable.filter((e) => e !== me) }
199
+ }
200
+
201
+ /** May this session change this Space (`what`: 'changeMembers' | 'rotateKey')? Throws the refusal; → { cfg, me }. Exported so a
202
+ * vault checks BEFORE it asks the person (sweep 10-23 #21). */
203
+ export async function changeable (space, what) {
204
+ const wb = space._wb
205
+ if (!wb || !wb._session || !wb._session.email) throw sdkError(`witbitz: ${what} needs a signed-in session (wb.signIn)`, 'sign_in_required')
206
+ if (typeof space._client.rekey !== 'function' || typeof space._client.grant !== 'function') throw sdkError(`witbitz: ${what} is not available on this client`, 'not_supported')
207
+ const read = () => space._client.getConfig(space.room, space._mk).catch(() => null)
208
+ let cfg = await read()
209
+ // A SLEEPING CONFIDENTIAL SPACE (sweep 10-24 #3): a config read does not wake its enclave, so it fails — wake it, read again
210
+ if (!cfg && wb._enc && wb._enc.rooms && wb._enc.rooms.has(space.room) && typeof wb._encWake === 'function') {
211
+ try { await wb._encWake(space.room, { tries: 8 }) } catch { /* the read below says it */ }
212
+ cfg = await read()
213
+ }
214
+ if (!cfg) throw sdkError(`witbitz: couldn’t read this Space’s members — try ${what} again shortly`, 'config_unavailable')
215
+ if (cfg.admission !== 'email') throw sdkError(`witbitz: only an email-gated Space changes ${what === 'rotateKey' ? 'its key' : 'its members'}`, 'invalid_argument')
216
+ const me = lc(wb._session.email)
217
+ const owners = ((cfg.owners && cfg.owners.emails) || []).map(lc), admins = ((cfg.admins && cfg.admins.emails) || []).map(lc)
218
+ if (!owners.length && !admins.length) throw sdkError('witbitz: this Space has no owners or admins — only the Spaces app can change it (its creator)', 'not_admin')
219
+ if (!owners.includes(me) && !admins.includes(me)) throw sdkError('witbitz: only an owner or an admin changes this Space', 'not_admin')
220
+ return { cfg, me }
221
+ }
222
+
223
+ // the same people on the list (emails, hashes, domains, advertised usernames) — whatever the order
224
+ const sameList = (a, b) => { const k = (x) => JSON.stringify(['emails', 'mh', 'domains'].map((f) => [...((x && Array.isArray(x[f])) ? x[f] : [])].map(String).sort()).concat([((x && Array.isArray(x.users)) ? x.users : []).map((u) => String(u && u.handle)).sort()])); return k(a) === k(b) }
225
+ /** THE LIST A CHANGE ENDS WITH, in the config's own shape (the app's rule, rekeyMembers + memberChange; sweep 10-23 #6):
226
+ * membersAfter's list; someone removed who is also on it by @username loses exactly those entries — the ones the server
227
+ * recorded at their sign-in (roster_seen `entries`) and their tag; every other hashed entry stays (replacing `mh` with the
228
+ * stated emails' hashes dropped every member added by @username); a NEW hidden member (stated, not shown) is admitted by
229
+ * its hash. `book()` → the guest book read ({ seen }); `tagOf(username)` → its tag for this room. */
230
+ export async function listAfter (cfg, room, want, { book, tagOf } = {}) {
231
+ // A tag-only member's email is visible in the guest book, but is not part of the SDK's email-list contract.
232
+ // Keep them unless the caller can actually name their admission entry; do not silently drop their tag.
233
+ const al = cfg.allow || {}, hashes = new Set(al.mh || [])
234
+ const known = []
235
+ for (const e of want.known || []) {
236
+ if ((al.emails || []).map(lc).includes(lc(e)) || hashes.has(await memberHash(lc(e), room))) known.push(e)
237
+ }
238
+ want = { ...want, known }
239
+ let m = await membersAfter(cfg, want, room)
240
+ if (m.removed.length) {
241
+ const b = typeof book === 'function' ? await book() : null
242
+ const gone = new Set(m.removed.map(lc)), recs = Object.values((b && b.seen) || {}).filter((x) => x && gone.has(lc(x.email)))
243
+ const drop = await dropsForUsers(room, recs.map((x) => x.user).filter(Boolean), { tagOf })
244
+ for (const x of recs) for (const k of (Array.isArray(x.entries) ? x.entries : [])) if (typeof k === 'string' && k.startsWith('mh:')) drop.mh.push(k.slice(3))
245
+ m = await membersAfter(cfg, { ...want, drop }, room)
246
+ }
247
+ const shownSet = new Set((m.allow.emails || []).map(lc))
248
+ const newHidden = await Promise.all([...new Set([...(want.emails || []), ...(want.owners || []), ...(want.admins || [])].map(lc))].filter((e) => !shownSet.has(e)).map((e) => memberHash(e, room)))
249
+ const mh = [...new Set([...(Array.isArray(m.allow.mh) ? m.allow.mh : []), ...newHidden])]
250
+ if (mh.length) m.allow.mh = mh; else delete m.allow.mh
251
+ return m
252
+ }
253
+
254
+ /** WHAT changeMembers(admission) WILL DO, before it does it: the list after (listAfter — hidden members counted) and `roles`, true
255
+ * when nobody's access changes (only who manages it; the key stays). One rule for the SDK's change and the vault's question
256
+ * (sync sweep 10-26 #3: the vault compared only the shown addresses). `cfg`: the config changeable() read, else it is read. */
257
+ export async function planMembers (space, admission = {}, cfg = null) {
258
+ if (admission.domains !== undefined && (!Array.isArray(admission.domains) || admission.domains.some(d => typeof d !== 'string' || !GATE_DOMAIN.test(lc(d).replace(/^@/, ''))))) throw sdkError('witbitz: invalid admission domain', 'invalid_argument')
259
+ if (!cfg) cfg = (await changeable(space, 'changeMembers')).cfg
260
+ const emails = [...new Set((Array.isArray(admission.emails) ? admission.emails : []).map(lc).filter(Boolean))]
261
+ if (!emails.length) throw sdkError('witbitz: changeMembers needs admission.emails (the whole list)', 'invalid_argument')
262
+ // An @username is not an email: the SDK cannot add one (intended.md) — say so instead of reporting it unreachable (sync sweep 2026-11-23)
263
+ const handle = [...emails, ...(Array.isArray(admission.owners) ? admission.owners : []), ...(Array.isArray(admission.admins) ? admission.admins : [])].find(e => !EMAIL.test(lc(e)))
264
+ if (handle !== undefined) throw sdkError(`witbitz: changeMembers takes email addresses only (${handle})`, 'invalid_argument')
265
+ const cur = await currentMembers(space, cfg)
266
+ const want = {
267
+ emails,
268
+ ...(Array.isArray(admission.domains) ? { domains: admission.domains } : {}),
269
+ owners: Array.isArray(admission.owners) ? admission.owners.map(lc) : cur.owners,
270
+ admins: Array.isArray(admission.admins) ? admission.admins.map(lc) : cur.admins,
271
+ shown: admission.advertise === true ? emails : admission.advertise === false ? [] : Array.isArray(admission.advertise) ? admission.advertise : ((cfg.allow && cfg.allow.emails) || []).map(lc).filter((e) => emails.includes(e)),
272
+ }
273
+ const c = (space._wb && space._wb._client) || space._client
274
+ const tagOf = async (u) => { const t = typeof c.userTag === 'function' ? await c.userTag(u, space.room).catch(() => null) : null; return t && t.status === 200 ? t.tag : '' }
275
+ const domains = normalizeDomains(want.domains ?? cfg.allow?.domains)
276
+ const admitted = address => emails.includes(address) || domains.includes(address.split('@')[1])
277
+ for (const role of ['owners', 'admins']) {
278
+ if (Array.isArray(admission[role])) {
279
+ const outside = want[role].find(address => !admitted(address))
280
+ if (outside) throw sdkError('A manager must already be admitted by email or domain: ' + outside, 'invalid_argument')
281
+ } else {
282
+ const retained = []
283
+ for (const address of want[role]) {
284
+ if (admitted(address) || (!cur.emails.includes(address) && cfg.allow?.mh?.includes(await memberHash(address, space.room)))) retained.push(address)
285
+ }
286
+ want[role] = retained
287
+ }
288
+ }
289
+ const m = await listAfter(cfg, space.room, { ...want, known: cur.emails }, { book: () => cur.book, tagOf })
290
+ // ⛔ NOT YOURSELF, SILENTLY (second review, 2026-11-27): a manager the new list does not admit is dropped (545f3a97f, so a role cannot
291
+ // admit anyone) — a manager who leaves THEIR OWN address off the whole list would lose the Space with no word. Refused by name
292
+ // instead: they add it, or leave the Space. Asked of the change itself (`m.removed`), so a manager who stays by a domain, a
293
+ // hidden-member hash or an @username tag is not refused.
294
+ const actor = lc(space._wb?._session?.email)
295
+ if (actor && (cur.owners.includes(actor) || cur.admins.includes(actor)) && (m.removed || []).map(lc).includes(actor)) {
296
+ throw sdkError('witbitz: your own address is not on the new list — add it, or leave the Space instead', 'invalid_argument')
297
+ }
298
+ return { emails, cur, want, m, epoch: epochOf(cfg), actor: lc(space._wb?._session?.email), roles: !m.removed.length && sameList(cfg.allow, m.allow) }
299
+ }
300
+
301
+ /** space.changeMembers(admission) — `admission`: { emails, domains?, admins?, owners?, advertise? }, the list stated in FULL,
302
+ * as fork() takes it. → { inPlace:true, epoch, link, removed, added, unreachable } */
303
+ export async function changeMembers (space, admission = {}, approved = null) {
304
+ await assertNotKept(space)
305
+ const { cfg, me } = await changeable(space, 'changeMembers')
306
+ const plan = await planMembers(space, admission, cfg)
307
+ const approvalFields = p => {
308
+ const { book, ...cur } = p.cur
309
+ const admissions = Object.values(book?.seen || {}).filter(x => x && !x.left).map(x => JSON.stringify([lc(x.email), x.user || '', [...(x.entries || [])].sort()])).sort()
310
+ return JSON.stringify({ ...p, cur, admissions })
311
+ }
312
+ if (approved && approvalFields(plan) !== approvalFields(approved)) throw sdkError('Space membership changed during confirmation. Review it again.', 'config_changed')
313
+ const { emails, cur, want, m, roles } = plan
314
+ // A ROLE CHANGE NEEDS NO NEW KEY (the app's decision 4, verifiedMove.js; sweep 10-23 #16): nobody's access changes, so the
315
+ // room keeps its key and the config changes in place (op 'config'). A server that does not take it yet answers
316
+ // config_immutable / not_enabled: then the change is made as before, by a re-key.
317
+ if (roles && typeof space._client.setConfig === 'function') {
318
+ const r = await space._client.setConfig(space.room, space._mk, { admins: m.admins, owners: m.owners }, space._who ? space._who() : 'An admin').catch(() => null)
319
+ if (r && r.status === 200) return { inPlace: true, roles: true, epoch: space.epoch, link: space.shareLink, removed: [], added: [], unreachable: [] }
320
+ if (!r || !r.status || r.status >= 500) throw sdkError('The service did not confirm the role change. Refresh the membership list before trying again.', 'config_unknown')
321
+ if (!(r && (r.error === 'config_immutable' || r.error === 'not_enabled'))) throw Object.assign(new Error('witbitz: the roles were not changed — nothing has changed' + (r && r.reason ? ` (${r.reason})` : '')), { code: (r && r.error) || 'config_failed', status: r && r.status })
322
+ }
323
+ const stay = [...new Set([...want.emails, ...want.owners, ...want.admins, me])]
324
+ const { epoch, unreachable } = await rekeyNow(space, { members: { allow: m.allow, owners: m.owners, admins: m.admins }, stay, allowAfter: m.allow, expectEpoch: epochOf(cfg), book: cur.book })
325
+ // added = on neither list before: not an address the room showed or its book knew, and not a hidden address's hash
326
+ const hidden = new Set(Array.isArray(cfg.allow && cfg.allow.mh) ? cfg.allow.mh : [])
327
+ const before = new Set(cur.emails)
328
+ const added = []
329
+ for (const e of emails) if (!before.has(e) && !hidden.has(await memberHash(e, space.room))) added.push(e)
330
+ return { inPlace: true, epoch, link: space.shareLink, removed: m.removed, added, unreachable }
331
+ }
332
+
333
+ /** space.rotateKey() — the same members, a new key (a lost phone, a link sent to the wrong place). → { inPlace:true, rotated:true, epoch, link, unreachable } */
334
+ export async function rotateKey (space) {
335
+ const { cfg, me } = await changeable(space, 'rotateKey')
336
+ const cur = await currentMembers(space, cfg)
337
+ const stay = [...new Set([...cur.emails, ...cur.owners, ...cur.admins, me])]
338
+ const { epoch, unreachable } = await rekeyNow(space, { members: null, stay, allowAfter: cfg.allow || {}, expectEpoch: epochOf(cfg), book: cur.book })
339
+ return { inPlace: true, rotated: true, epoch, link: space.shareLink, unreachable }
340
+ }