@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
@@ -0,0 +1,232 @@
1
+ // sdkDictation.js — wb.dictation(): press-to-talk for a builder's page, the same engine the Spaces app runs (sttCloud.js).
2
+ //
3
+ // const mic = wb.dictation()
4
+ // await mic.start({ onPartial: (t) => (input.value = t) }) // on press: asks for the mic, the words stream in
5
+ // input.value = await mic.stop() // on release: the final text (~0.5 s)
6
+ // mic.cancel() // a press thrown away (its audio dropped server-side too)
7
+ //
8
+ // The microphone streams STRAIGHT from the page to Tinfoil's confidential realtime enclave (Voxtral Mini 4B Realtime) —
9
+ // never through Witbitz. Witbitz only mints the page a short-lived, capped key (op:'stt', agent/sttKey.mjs), and only for
10
+ // a signed-in person (wb.signIn) or a user the tenant's backend vouched for (wb.useUserToken). One connection is kept
11
+ // across presses and closed after 15 quiet minutes ($0.002 per connection, whatever is said on it). https://witbitz.chat/docs/sdk-assistant.md#dictation.
12
+ // ⚑ 13 languages, NOT Hebrew. ⚑ The page's own CSP must allow `connect-src wss://inference.tinfoil.sh` and the worklet
13
+ // script from this origin; the microphone needs a secure context and the browser's permission.
14
+
15
+ import { voicePayload } from './voiceCert.js'
16
+
17
+ const certifications = new WeakMap()
18
+ export function voiceForDictation(result, room) {
19
+ const held = certifications.get(result)
20
+ if (!held || held.room !== room) throw err('dictation_room_mismatch', 'use the dictation result from this room')
21
+ return voicePayload(room, held.stt)
22
+ }
23
+
24
+ const err = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
25
+
26
+ export class Dictation {
27
+ constructor(wb, { WebSocketImpl, getUserMedia } = {}) {
28
+ this._wb = wb
29
+ this._WS = WebSocketImpl
30
+ this._gum = getUserMedia || ((c) => navigator.mediaDevices.getUserMedia(c))
31
+ this._engine = null // sttCloud's engine, made on the first press
32
+ this._mod = null
33
+ this._stream = null
34
+ this._capture = null
35
+ this._live = false
36
+ }
37
+
38
+ /** true between start() and stop()/cancel(). */
39
+ get listening() { return this._live }
40
+
41
+ /** @private who the key is for: a signed-in session first (the person), else the tenant's user token. */
42
+ async _who() {
43
+ const wb = this._wb
44
+ const sess = wb._session
45
+ const idToken = sess && sess.idToken && !(sess.exp && sess.exp <= Date.now()) ? sess.idToken : ''
46
+ let userToken = ''
47
+ try { const t = typeof wb._userToken === 'function' ? await wb._userToken() : wb._userToken; userToken = typeof t === 'string' ? t : '' } catch { userToken = '' }
48
+ if (!idToken && !userToken && !wb.vault) throw err('sign_in_required', 'dictation needs a signed-in user (wb.signIn) or a user token (wb.useUserToken)') // in a vault, the vault's sign-in mints the key
49
+ return { idToken, userToken }
50
+ }
51
+
52
+ /** @private the page's key (op:'stt'). */
53
+ async _key() {
54
+ const epoch = this._payerEpoch
55
+ const { idToken, userToken } = this._cloudRun?.auth || await this._who()
56
+ const wb = this._wb
57
+ const r = await wb._client.stt(idToken, userToken)
58
+ if (epoch !== this._payerEpoch) throw err('account_changed', 'the voice payer changed')
59
+ if (r && r.status === 200 && r.key) {
60
+ this._stt = r.cert?.bundle ? { model: r.model, cert: structuredClone(r.cert), bundleGz: r.bundleGz } : null
61
+ return r
62
+ } // the endpoint itself is pinned in sttCloud.js, never taken from here
63
+ const raw = (r && r.error) || 'stt_unavailable'
64
+ const code = raw === 'signin_required' ? 'sign_in_required' : raw // the SDK's one spelling (sync sweep, 2026-10-10; the server says signin_required)
65
+ throw err(code, code === 'sign_in_required' ? 'the sign-in or user token was refused — sign in again'
66
+ : code === 'stt_rate_limited' ? `too many voice keys this hour — try again in ${(r && r.retryAfterS) || 60} s`
67
+ : 'the voice service could not issue a key')
68
+ }
69
+
70
+ async _load() {
71
+ if (!this._mod) this._mod = await import('./sttCloud.js')
72
+ if (!this._engine) this._engine = this._mod.createCloudStt({ getKey: () => this._key(), ...(this._WS ? { WebSocketImpl: this._WS } : {}) })
73
+ return this._engine
74
+ }
75
+
76
+ /** Begin a press. Resolves once the microphone is live and the connection is up (audio said meanwhile is queued).
77
+ * @param {{ onPartial?: (text:string)=>void, onLevel?: (rms:number)=>void }} [opts] */
78
+ async start({ onPartial, onLevel, room, engine: choice = 'cloud' } = {}) {
79
+ if (this._live) throw err('already_listening', 'dictation is already listening — stop() or cancel() first')
80
+ if (choice === 'device') return this._startDevice(room, onPartial, onLevel)
81
+ if (choice !== 'cloud') throw err('invalid_argument', 'choose cloud or device dictation')
82
+ const run = { partial: '', error: null }
83
+ this._cloudRun = run
84
+ this._interrupted = null
85
+ this._live = true
86
+ this._room = typeof room === 'string' ? room : null
87
+ const current = () => this._cloudRun === run
88
+ const interrupted = error => {
89
+ if (!current()) return
90
+ run.error = error
91
+ this.cancel()
92
+ this._interrupted = { text: run.partial, room: this._room, stt: this._stt }
93
+ }
94
+ try {
95
+ run.auth = await this._who()
96
+ if (!current()) return
97
+ const payer = run.auth.userToken || this._wb._session?.email || ''
98
+ if (this._payer !== undefined && payer !== this._payer) {
99
+ this._engine?.close(); this._engine = null; this._stt = null
100
+ }
101
+ this._payer = payer
102
+ const engine = await this._load()
103
+ if (!current()) return
104
+ let stream
105
+ try { stream = await this._gum({ audio: { channelCount: 1, echoCancellation: true, autoGainControl: true, noiseSuppression: true } }) }
106
+ catch (e) { throw err('mic_denied', String(e?.message || e)) }
107
+ if (!current()) { stream.getTracks().forEach(t => t.stop()); return }
108
+ this._stream = stream
109
+ const ready = engine.begin({ onPartial: text => {
110
+ if (current()) { run.partial = text; try { onPartial?.(text) } catch {} }
111
+ }, onError: interrupted })
112
+ await Promise.all([ready, (async () => {
113
+ const capture = await this._mod.startCapture(stream, ({ pcm, rms }) => {
114
+ if (!current()) return
115
+ engine.append(pcm)
116
+ try { onLevel?.(rms) } catch {}
117
+ }, { onError: interrupted })
118
+ if (current()) this._capture = capture
119
+ else capture.stop()
120
+ })()])
121
+ } catch (error) {
122
+ if (!current() && !run.error) return
123
+ if (current()) this.cancel()
124
+ throw error?.code ? error : err('stt_unavailable', String(error?.message || error))
125
+ }
126
+ }
127
+
128
+ async _startDevice(room, onPartial, onLevel) {
129
+ const run = { committed: '', partial: '', transcriber: null }
130
+ this._deviceRun = run; this._interrupted = null; this._live = true; this._room = room || null
131
+ const text = () => [run.committed, run.partial].filter(Boolean).join(' ').trim()
132
+ const update = () => { if (this._deviceRun === run) { try { onPartial?.(text()) } catch {} } }
133
+ try {
134
+ const M = await (this._deviceSdk ? this._deviceSdk() : import(new URL('/vendor/moonshine.web.mjs', globalThis.location.href).href))
135
+ if (this._deviceRun !== run) return
136
+ Object.assign(M.Settings.BASE_ASSET_PATH, { MOONSHINE: '/vendor/ms/', ONNX_RUNTIME: '/vendor/ms/ort/', SILERO_VAD: '/vendor/ms/vad/' })
137
+ const t = new M.Transcriber('model/tiny', {
138
+ onSpeechStart: () => { if (run.partial) { run.committed = text(); run.partial = '' } },
139
+ onTranscriptionUpdated: value => { run.partial = value || ''; update() },
140
+ onTranscriptionCommitted: value => { run.committed = [run.committed, value].filter(Boolean).join(' '); run.partial = ''; update() },
141
+ onError: e => { run.error = e || new Error('voice model failed') },
142
+ }, false)
143
+ run.transcriber = t
144
+ const stream = await this._gum({ audio: { channelCount: 1, echoCancellation: true, sampleRate: 16000 } })
145
+ if (this._deviceRun !== run) { for (const track of stream.getTracks()) track.stop(); return }
146
+ this._stream = stream
147
+ t.attachStream(stream)
148
+ await t.start()
149
+ if (this._deviceRun !== run) { this._endDevice(run); return }
150
+ if (onLevel && t.audioContext) {
151
+ const ctx = t.audioContext
152
+ const meter = ctx.createAnalyser()
153
+ meter.fftSize = 256
154
+ run.source = ctx.createMediaStreamSource(stream)
155
+ run.source.connect(meter)
156
+ const samples = new Float32Array(meter.fftSize)
157
+ run.timer = setInterval(() => {
158
+ meter.getFloatTimeDomainData(samples)
159
+ let square = 0
160
+ for (const sample of samples) square += sample * sample
161
+ try { onLevel(Math.sqrt(square / samples.length)) } catch {}
162
+ }, 50)
163
+ }
164
+ } catch (error) {
165
+ if (this._deviceRun !== run) return
166
+ this.cancel()
167
+ throw err(/permission|denied|notallowed/i.test(String(error)) ? 'mic_denied' : 'stt_unavailable', String(error?.message || error))
168
+ }
169
+ }
170
+
171
+ _endDevice(run) {
172
+ const t = run.transcriber
173
+ clearInterval(run.timer)
174
+ try { run.source?.disconnect() } catch {}
175
+ try { t?.stop() } catch {}
176
+ try { const context = t?.audioContext; if (context && context.state !== 'closed') context.close().catch(() => {}) } catch {}
177
+ }
178
+
179
+ /** End the press. → the final text ('' if nothing was said). */
180
+ async stop() {
181
+ if (!this._live) { const interrupted = this._interrupted; this._interrupted = null; return interrupted?.text || '' }
182
+ this._live = false
183
+ this._cloudRun = null
184
+ this._release()
185
+ if (this._deviceRun) {
186
+ const run = this._deviceRun; this._deviceRun = null
187
+ this._endDevice(run)
188
+ if (run.error) throw err('stt_unavailable', String(run.error.message || run.error))
189
+ return [run.committed, run.partial].filter(Boolean).join(' ').trim()
190
+ }
191
+ return this._engine?.commit() || ''
192
+ }
193
+
194
+ /** Finish room-bound dictation and return the public certificate alongside the transcript. */
195
+ async stopCertified() {
196
+ if ((!this._live && !this._interrupted) || !this._room) throw err('dictation_room_required', 'start dictation with the destination room')
197
+ const room = this._room, stt = this._deviceRun ? null : (this._interrupted?.stt || this._stt)
198
+ const text = await this.stop()
199
+ const result = Object.freeze({ text, room, certificate: stt?.cert ? structuredClone(stt.cert) : null })
200
+ certifications.set(result, { room, stt })
201
+ return result
202
+ }
203
+
204
+ /** Throw the press away. */
205
+ cancel() {
206
+ if (!this._live) return
207
+ this._live = false
208
+ this._cloudRun = null
209
+ this._release()
210
+ if (this._deviceRun) { const run = this._deviceRun; this._deviceRun = null; this._endDevice(run); return }
211
+ try { this._engine.cancel() } catch { /* */ }
212
+ }
213
+
214
+ /** Close the connection now (otherwise it closes itself after 15 quiet minutes). */
215
+ close() {
216
+ this.cancel()
217
+ try { this._engine && this._engine.close() } catch { /* */ }
218
+ }
219
+
220
+ _resetPayer() {
221
+ this._payerEpoch = (this._payerEpoch || 0) + 1
222
+ this.close()
223
+ this._engine = null; this._stt = null; this._payer = undefined; this._interrupted = null
224
+ }
225
+
226
+ _release() {
227
+ try { this._capture && this._capture.stop() } catch { /* */ }
228
+ this._capture = null
229
+ try { this._stream && this._stream.getTracks().forEach((t) => t.stop()) } catch { /* */ }
230
+ this._stream = null
231
+ }
232
+ }
package/sdkErase.js ADDED
@@ -0,0 +1,288 @@
1
+ // sdkErase.js — `wb.erasure`: A BUILDER'S USERS' ROOMS CAN BE DELETED WHEN THE USER IS ERASED (https://witbitz.chat/docs/sdk-builder.md#user-erasure; a
2
+ // builder, 2026-10-07: "users.erase finds 0 rooms for a user of ours"). The tenant's erase (`wb.users.erase(email)` on its
3
+ // server → agent/eraseUser.mjs) runs ONLY the list the account FILED with the attested standing Sentinel, and deletes only
4
+ // a room whose create carried a deletion commitment and that nobody else marked. The Witbitz app does all three
5
+ // (roomDelete.js, accountUsage.js, eraseFile.js); the SDK did none. Now, for every room the SDK creates or opens:
6
+ // 1. a CREATE carries delCommit = sha256(HMAC(erase key, 'witbitz-room-delete:' + room)) — only this account can later
7
+ // prove it created the room (the server keeps the commitment, never the secret);
8
+ // 2. the room gets this account's MEMBERSHIP MARK (HMAC(erase key, 'witbitz-usage-drop:' + room)) — so another account's
9
+ // delete of a room this account used is refused (409 shared), and this account's own delete is not;
10
+ // 3. the account's list — per room, the delete secret and the drop — is FILED, sealed to the standing Sentinel, under
11
+ // the app's tenant and the signed-in email (eraseFile.js, unchanged). Automatic, a few seconds after a room is
12
+ // created or opened, and only when the list changed; `wb.erasure.file()` does it on demand.
13
+ // THE ERASE KEY comes from the BACKUP MASTER (wb.backup), which every device of the account restores: the Sentinel keeps one
14
+ // list per account and a filing REPLACES it, so every device must derive the same secrets. No backup → no shared secret →
15
+ // nothing is committed, marked or filed (a room created then can be deleted only by the tenant: wb.rooms.delete(room)).
16
+ // The mark works on rooms created before this, the commitment does not (it is set at create, never after).
17
+ import { delSecretFor, delCommitOf } from './roomDelete.js'
18
+ import { dropFor } from './usageReceipts.js'
19
+ import { fileEraseList } from './eraseFile.js'
20
+ import { attestStandingSentinel } from './connections.js'
21
+ import { sealTo as sealToEnclave } from './sealShare.js'
22
+ import { eraseAccount, stepDone, readAllEntries } from './accountErase.js' // the app's Delete my account — its order and rules, and its one rule for "done"
23
+ import { deleteOwnRoom, leaveAndMaybeDelete, leaveHandover, deleteHandedOver } from './roomDelete.js'
24
+ import { inviteScope } from './sdkRekey.js'
25
+
26
+ const enc = new TextEncoder()
27
+ const ub64 = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
28
+ const b64u = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
29
+ const TENANT = /^t_[0-9a-f]{32}$/ // the Sentinel's (erase.mjs)
30
+ const memStorage = () => { const m = new Map(); return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, v) => { m.set(k, String(v)) } } }
31
+
32
+ /** The erase key every device of the account derives from its backup master: { secret } (43-char base64url). */
33
+ export async function eraseKeyOf (masterB64) {
34
+ const km = await crypto.subtle.importKey('raw', ub64(masterB64), 'HKDF', false, ['deriveBits'])
35
+ const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: enc.encode('witbitz-sdk-account-v1'), info: enc.encode('erase-key') }, km, 256)
36
+ return { secret: b64u(new Uint8Array(bits)) }
37
+ }
38
+
39
+ export class Erasure {
40
+ /** @param {object} wb the Witbitz client */
41
+ constructor (wb) {
42
+ this._wb = wb
43
+ this._k = { master: null, key: null }
44
+ this._marked = new Set()
45
+ this._opened = [] // rooms this page created or opened, newest last
46
+ this._debounceMs = 4000
47
+ this._timer = null
48
+ this._deps = null // tests: { post, auth, attest, seal }
49
+ let ls = null; try { ls = globalThis.localStorage || null; if (ls) ls.getItem('witbitz:probe') } catch { ls = null }
50
+ this._ls = ls || memStorage() // where eraseFile.js remembers what it filed (skips an unchanged list for 6 h)
51
+ }
52
+
53
+ async _key () {
54
+ const st = this._wb.backup && this._wb.backup.state
55
+ const m = st && st.master
56
+ if (!m) return null
57
+ if (this._k.master !== m) this._k = { master: m, key: await eraseKeyOf(m) }
58
+ return this._k.key
59
+ }
60
+ /** @private the account's USAGE keys (wb.account): its turns' receipts carry drops made with them, so a delete and the
61
+ * filed list present those too — else the server reads this account's own receipts as another's (409 shared; sync sweep 11-08 #3) */
62
+ _dropKeys () { try { const a = this._wb.account; return a && typeof a._usageKeys === 'function' ? a._usageKeys() : [] } catch { return [] } }
63
+ _account () { const s = this._wb._session; return s && s.email && !(s.exp && s.exp <= Date.now()) ? String(s.email).toLowerCase() : '' }
64
+ _tenant () { return TENANT.test(this._wb._tenant || '') ? this._wb._tenant : '' }
65
+
66
+ /** True when this page can file: a tenant app, a live sign-in and a backup (the shared key). */
67
+ get available () { return !!(this._tenant() && this._account() && this._wb.backup && this._wb.backup.enabled) }
68
+
69
+ /** @private the create hook (spaceClient `delCommit`): the commitment for `room`, or null with no backup */
70
+ async _commitFor (room) { const k = await this._key(); return k ? delCommitOf(await delSecretFor(k, room)) : null }
71
+
72
+ /** @private every room the SDK hands back (Witbitz#_backedUp): mark it once per page, and refile soon. Never throws. */
73
+ _seen (sp) {
74
+ if (!sp || !sp.room) return
75
+ if (!this._opened.includes(sp.room)) this._opened.push(sp.room)
76
+ ;(async () => {
77
+ const k = await this._key()
78
+ if (!k || this._marked.has(sp.room) || !sp._mk) return
79
+ this._marked.add(sp.room)
80
+ // A refusal is ANSWERED, not thrown (mark is email-gated: a sign-in may be needed) — so it is let go too, and the room
81
+ // is marked again the next time it is handed back, as the app's accountUsage does (sync sweep, 2026-10-10).
82
+ try { const r = await this._wb._client.mark(sp.room, sp._mk, await dropFor(k, sp.room)); if (!r || r.status !== 200) this._marked.delete(sp.room) } catch { this._marked.delete(sp.room) }
83
+ })().catch(() => {})
84
+ if (this.available) {
85
+ clearTimeout(this._timer)
86
+ this._timer = setTimeout(() => { this.file().catch(() => {}) }, this._debounceMs)
87
+ if (this._timer && typeof this._timer.unref === 'function') this._timer.unref()
88
+ }
89
+ }
90
+
91
+ _rooms () {
92
+ const st = this._wb.backup && this._wb.backup.state
93
+ const kept = (st && Array.isArray(st.rooms) ? st.rooms : []).slice().sort((a, b) => (b.at || 0) - (a.at || 0)).map((r) => r.room)
94
+ return [...new Set([...this._opened.slice().reverse(), ...kept])] // newest first: the Sentinel keeps what fits
95
+ }
96
+ _d () {
97
+ if (this._deps) return this._deps
98
+ const wb = this._wb
99
+ return { post: wb._sentinelPost(), auth: wb._auth('the erase list belongs'), attest: (o) => attestStandingSentinel({ ...o, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow }), seal: sealToEnclave }
100
+ }
101
+
102
+ /** File this account's delete list with the standing Sentinel, for this app's tenant, so `wb.users.erase(email)` on the
103
+ * tenant's server can delete the rooms this account created. Automatic after a room is created or opened; call it after
104
+ * a sign-in or a backup restore to file at once. → `{ filed, rooms?, skipped? }`
105
+ * @param {object} [opts] { force? } — refile even when the list is unchanged */
106
+ async file ({ force = false } = {}) {
107
+ if (!this._tenant()) return { filed: false, skipped: 'not a tenant app: new Witbitz({ tenant })' }
108
+ if (!this._account()) return { filed: false, skipped: 'signed out: ' + (this._wb && this._wb.vault ? 'wb.vault.signIn' : 'wb.signIn') + ' first' }
109
+ const key = await this._key()
110
+ if (!key) return { filed: false, skipped: 'no backup: enable wb.backup so every device of the account shares the erase key' }
111
+ const d = this._d()
112
+ const backup = this._wb.backup
113
+ const stillOurs = backup && typeof backup._checkErased === 'function' ? async () => !(await backup._checkErased()) : null // pass 7, F#10
114
+ return fileEraseList({ tenant: this._tenant(), account: this._account(), rooms: this._rooms(), keys: [key], dropKeys: this._dropKeys(), post: d.post, auth: d.auth, attest: d.attest, seal: d.seal, ls: this._ls, force, stillOurs })
115
+ }
116
+
117
+ /** DELETE MY ACCOUNT — the Witbitz app's Settings → Delete my account (accountErase.js), for a builder's user (the owner's
118
+ * build-later list, 2026-10-28; "Sync the sdk", 2026-11-07). In this order, every step safe to run again:
119
+ * 0. the backup FIRST (its email gate is the step that can refuse — nothing else is deleted until it is through);
120
+ * 1. every room of the account (the backup's list and the rooms this page opened): one ONLY this account used is DELETED
121
+ * — the server checks this account's creation secret; a room someone else used is LEFT (what they wrote with you
122
+ * stays theirs too); an older room with no creation secret lapses when idle;
123
+ * 2. the username (a sign-in made in your app has none — nothing to release) and the directory entry; the app's filed
124
+ * erase list is withdrawn;
125
+ * 3. the account's index LAST, only when every step before it worked; then this client forgets the account
126
+ * (wb.backup.onState(null), signed out).
127
+ * Needs a live sign-in (for 2) and the backup (its key proves which rooms this account created). Billing: a builder's
128
+ * user is the APP's user — your server erases it (`wb.users.erase(email)` with the admin key).
129
+ * → { deleted:[room], left:[room], lapsing:[room], failed:[{room|what, why}], account:{ username, directory, backup } }
130
+ * `failed` not empty: nothing was forgotten here — fix the cause (often a sign-in) and call it again.
131
+ * @param {object} [opts] { onStep?(text) — progress lines to show; names? — the display names this person posts under in
132
+ * your app (`send(text, { from })`): a room whose every message is theirs (by email, or by one of these names) counts as
133
+ * only theirs. Without them a room with a named message is LEFT, never deleted unchecked (the server also refuses a
134
+ * room another account marked); code, ticket, emailCode — a backup set up with an email (wb.backup.gated) is deleted
135
+ * only with its emailed code, as a restore: the first call (with the recovery `code`) mails it and throws
136
+ * `email_code_required` with a `ticket` BEFORE anything is deleted; call again with { code, ticket, emailCode };
137
+ * getCode(address) → the emailed code — an account on the Witbitz account service is deleted there with it (as
138
+ * wb.backup.deleteAccount), as the run's backup step. In a vault the vault runs all of this itself, with its own screens. } */
139
+ async deleteAccount ({ onStep, names = [], code, ticket, emailCode, getCode } = {}) {
140
+ const wb = this._wb
141
+ // IN A VAULT the vault holds the keys and runs the whole erase itself, asking the person on its own screens (vault-core.js
142
+ // backup.deleteAccount; the owner, 2026-11-24) — it answers with the same report
143
+ if (wb.vault) { const r = await wb.backup.deleteAccount({ names }); return (r && r.report) || r }
144
+ const sess = wb._session
145
+ if (!sess || !sess.idToken || (sess.exp && sess.exp <= Date.now())) throw Object.assign(new Error('witbitz: sign in first — deleting the account needs a live sign-in'), { code: 'sign_in_required' })
146
+ const backup = wb.backup
147
+ const key = await this._key()
148
+ if (!key) throw Object.assign(new Error('witbitz: deleting the account needs its backup (wb.backup) — its key proves which rooms this account created'), { code: 'no_backup' })
149
+ // the backup's email gate FIRST: nothing is deleted until the release is in hand (sync sweep 11-08 #1). Asked only while the
150
+ // server still holds a gated backup — a re-run after the backup went (its gate with it) needs no new emailed code; and the
151
+ // backup is the run's FIRST step (accountErase.js), so the 120 s release is spent seconds after it was made, however many
152
+ // rooms follow (sync sweep 11-09 #15).
153
+ let token = null, gone = null
154
+ // AN ACCOUNT ON THE WITBITZ ACCOUNT SERVICE (sync sweep 2026-11-23 follow-up): its backup is the account there — deleted with an
155
+ // emailed code, as the run's backup step. The old store answered "on the account service" and every such run stopped at step 1.
156
+ const onService = !!(backup._s && backup._s.v2 && backup._v2)
157
+ if (onService && !backup._s.erased && typeof getCode !== 'function' && !(this._deleteDeps && this._deleteDeps.deleteBackup)) throw Object.assign(new Error('witbitz: this account is on the Witbitz account service — pass getCode(address) for the emailed code'), { code: 'invalid_argument' })
158
+ if (!onService && backup.gated && !(this._deleteDeps && this._deleteDeps.deleteBackup)) {
159
+ const probe = await backup._deleteRemote(null)
160
+ if (probe.ok || probe.status !== 403) gone = probe // already gone / not enforced (deleted now), or why it could not be asked
161
+ else token = await backup._release({ code, ticket, emailCode })
162
+ }
163
+ const dropKeys = this._dropKeys()
164
+ const st = backup.state || {}
165
+ const kept = Array.isArray(st.rooms) ? st.rooms : []
166
+ // a room's key: the whole key kept for a split room, else the link's own (a plain room's link IS its key — sync sweep 11-08
167
+ // #2: only split rooms had one here, so every plain Space read as shared and was left)
168
+ const keysBefore = new Map(kept.map((r) => [r.room, backup.keyFor(r.room)])) // read now: the service's erase may end the backup's state
169
+ const keyOf = async (room) => {
170
+ const kk = keysBefore.get(room) || backup.keyFor(room); if (kk) return kk
171
+ const r = kept.find((x) => x.room === room)
172
+ if (!r || !r.link || /[#&]us=/.test(r.link)) return null
173
+ try { const o = await wb._client.open(r.link); return o && o.room === room ? o.mk : null } catch { return null }
174
+ }
175
+ const isTemp = (r) => String(r).startsWith('tmp-')
176
+ let indexRoom = null
177
+ try { if (wb.account && wb.account.enabled && typeof wb.account._where === 'function') indexRoom = (await wb.account._where()).room } catch { indexRoom = null }
178
+ const d = this._deleteDeps || {}
179
+ const client = wb._client
180
+ const temporaryScope = wb.temporaryRooms?._scope()
181
+ const rep = await eraseAccount({
182
+ me: { email: this._account(), names: (Array.isArray(names) ? names : []).map((n) => String(n || '').trim()).filter(Boolean).slice(0, 20) },
183
+ indexRoom,
184
+ rooms: {
185
+ all: [...new Set([...kept.filter((r) => r.kind !== 'lane').map((r) => r.room), ...this._opened])].filter((r) => r && !isTemp(r)),
186
+ account: kept.filter((r) => r.kind === 'lane').map((r) => r.room), // a lane is the account's own: deleted without a read
187
+ },
188
+ read: d.read || (async (room) => {
189
+ const mk = await keyOf(room)
190
+ if (!mk) return null // a room this client cannot open is treated as shared: never deleted unchecked
191
+ const entries = await readAllEntries((since) => client.poll(room, mk, undefined, since)) // every page, not the first (sync sweep 2026-11-09)
192
+ if (!entries) return null
193
+ let config = null; try { config = await client.getConfig(room, mk) } catch { config = null }
194
+ return { entries, config }
195
+ }),
196
+ deleteRoom: d.deleteRoom || ((room) => deleteOwnRoom(room, { url: wb._roomDeleteEndpoint(), keys: [key], dropKeys, fetchImpl: (...a) => wb._fetch(...a) })),
197
+ // a queued delete is CONFIRMED (this secret's tombstone is down) before the account key goes — asked, never re-queued (state machines pass 9, S#1)
198
+ confirmDeleted: d.confirmDeleted || (d.deleteRoom ? undefined : ((room) => deleteOwnRoom(room, { url: wb._roomDeleteEndpoint(), keys: [key], dropKeys, fetchImpl: (...a) => wb._fetch(...a), check: true }))),
199
+ // a VERIFIED room: hand over this account's marks and delete secrets as it leaves; the last one out deletes it (agent/roomLeave.mjs).
200
+ // What they wrote stays part of the room while anyone who joined is still in it.
201
+ // WHAT THE ACCOUNT KEEPS OUTSIDE ITS ROOMS, as the app's Delete my account takes it (accountEraseUi.js eraseCleanups; sync sweep
202
+ // 2026-11-18 #2: the SDK passed none, and the builder docs promised the app's behaviour) — from this SDK's own handles.
203
+ cleanups: d.cleanups || sdkEraseCleanups(wb),
204
+ // …and the account's OTHER devices: each is signed out through the index before it goes (the app's signOutOthersForErase);
205
+ // one offline meanwhile clears itself on the index's 410s (sdkAccount.js / devices.js indexGoneVerdict).
206
+ signOutOthers: d.signOutOthers || (async () => {
207
+ const a = wb.account; if (!a || !a.enabled) return { ok: true }
208
+ for (const x of a.devices || []) if (x && !x.current && !x.signedOut) { try { a.signOut(x.id, { reason: 'erased' }) } catch { /* gone meanwhile */ } }
209
+ const r = await a.sync().catch(() => null)
210
+ return r && r.ok ? { ok: true } : { ok: false, why: 'the other devices could not be told — they clear themselves when they next find the account gone' }
211
+ }),
212
+ leaveRoom: d.leaveRoom || (async (room) => {
213
+ const mk = await keyOf(room); if (!mk || typeof client.leave !== 'function') return { left: false }
214
+ return leaveAndMaybeDelete(room, { post: (h) => client.leave(room, mk, h), handover: (r) => leaveHandover(r, { keys: [key], dropKeys }), del: (r, h, opts) => deleteHandedOver(r, h, { ...opts, url: wb._roomDeleteEndpoint(), fetchImpl: (...a) => wb._fetch(...a) }) })
215
+ }),
216
+ idToken: async () => sess.idToken,
217
+ // ONE rule for "done" (accountErase.stepDone — sync sweep 11-09 #14); a builder's sign-in owns no @username: the server's
218
+ // first_party_required is nothing to release (#4 — it ended every run here, after the rooms and the backup were gone)
219
+ releaseUsername: d.releaseUsername || (async (t) => stepDone(await client.userRelease(t), { nothing: ['first_party_required'] })),
220
+ eraseDirectory: d.eraseDirectory || (async (t) => { const sc = inviteScope(t); return stepDone(await client.dirErase(t, sc || undefined)) }),
221
+ eraseBilling: async () => ({ ok: true }), // the app's user: the builder's server erases it (wb.users.erase)
222
+ deleteBackup: d.deleteBackup || (onService
223
+ ? async () => { if (backup._s && backup._s.erased) return { ok: true }; try { await backup._v2.deleteAccount(backup, { getCode, keep: true }); return { ok: true } } catch (e) { return { ok: false, reason: (e && (e.code || e.message)) || 'failed' } } }
224
+ : () => (gone || backup._deleteRemote(token))),
225
+ backupGone: () => { if (backup._s) { clearTimeout(backup._timer); backup._timer = null; backup._s.erased = true; backup._changed() } }, // pass 7, F#2: no write re-creates it, even if a later step fails
226
+ withdrawFiled: d.withdrawFiled || (this._tenant() ? async () => { const dd = this._d(); const r = await fileEraseList({ tenant: this._tenant(), account: this._account(), rooms: [], keys: [key], dropKeys, post: dd.post, auth: dd.auth, attest: dd.attest, seal: dd.seal, ls: this._ls, force: true }).catch(() => null); return { ok: !!(r && r.filed) } } : null),
227
+ wipe: async () => {
228
+ try {
229
+ if (temporaryScope) wb.temporaryRooms._erase(temporaryScope)
230
+ } finally {
231
+ this._opened = []; this._marked.clear(); this._k = { master: null, key: null }
232
+ try { if (wb.account && typeof wb.account.stop === 'function') wb.account.stop() } catch { /* */ }
233
+ backup._drop() // onState(null): the builder persists that this client holds no account any more
234
+ wb.signOut()
235
+ }
236
+ },
237
+ onStep,
238
+ })
239
+ delete rep.account.billing
240
+ return rep
241
+ }
242
+
243
+ /** Is a list filed for this account in this app, and how many rooms? Never the secrets. → `{ ok, filed, rooms?, updated? }` */
244
+ async status () {
245
+ if (!this._tenant() || !this._account()) return { ok: true, filed: false }
246
+ const d = this._d()
247
+ return d.post({ op: 'sentinel', sentinel: { mode: 'erasestatus', tenant: this._tenant() }, ...d.auth })
248
+ }
249
+ }
250
+
251
+ /** The SDK's half of the app's eraseCleanups (accountEraseUi.js): connections, Siri, outside agents, cloud computers, then what is left
252
+ * at the Sentinel. Room funding and mail addresses are the app's own (a builder bills through its tenant; mail is app-only). */
253
+ export function sdkEraseCleanups (wb) {
254
+ const why = (e) => String((e && e.message) || e)
255
+ return [
256
+ { what: 'connections', run: async () => { for (const c of await wb.connections.list()) if (c && c.id) await wb.connections.detach(c.id); return { ok: true } } },
257
+ { what: 'your Siri setup', run: async () => { await wb.siri.revoke(); return { ok: true } } },
258
+ { what: 'outside agents', run: async () => { if (wb.a2a && typeof wb.a2a.revoke === 'function') await wb.a2a.revoke(); return { ok: true } } },
259
+ { what: 'the cloud device', run: async () => {
260
+ if (!wb.cloudDevice) return { ok: true }
261
+ try {
262
+ const status = await wb.cloudDevice.status()
263
+ if (status.email || status.registered || status.rooms?.length) await wb.cloudDevice.forget()
264
+ return { ok: true }
265
+ } catch (e) {
266
+ if (['not_enrolled', 'not_available', 'not_in_dev_server', 'cloud_device_unavailable'].includes(e.code)) return { ok: true }
267
+ return { ok: false, why: why(e) }
268
+ }
269
+ } },
270
+ { what: 'your cloud computers', run: async (t) => { // every object of each (controller destroy) — not remove(), which keeps them for a key file
271
+ if (!wb.computers || typeof wb.computers._read !== 'function') return { ok: true }
272
+ const { destroyCloud } = await import('./codeCloud.js')
273
+ const { cloud } = await wb.computers._read()
274
+ for (const [id, e] of Object.entries((cloud && cloud.cloud) || {})) {
275
+ if (!e || e.removed || !e.workspace) continue
276
+ const r = await destroyCloud({ id, cloud: e }, { token: t })
277
+ if (!r.ok) return r
278
+ }
279
+ return { ok: true }
280
+ } },
281
+ { what: 'your account at the Sentinel', run: async (t) => {
282
+ const r = await wb._sentinelPost()({ op: 'sentinel', sentinel: { mode: 'forgetaccount' }, idToken: t }).catch((e) => ({ error: why(e) }))
283
+ if (r && r.ok) return { ok: true }
284
+ if (/unknown op forgetaccount|not an op this front forwards|bad_mode/.test(String((r && r.error) || ''))) return { ok: true } // an older Sentinel (accountEraseUi.js FORGET_UNSUPPORTED): the steps above took every record it keeps
285
+ return { ok: false, why: String((r && r.error) || 'no answer') }
286
+ } },
287
+ ].map((c) => ({ ...c, run: (t) => c.run(t).catch((e) => ({ ok: false, why: why(e) })) }))
288
+ }
package/sdkExports.js ADDED
@@ -0,0 +1,71 @@
1
+ import { exportSpace, recreateSpace } from './spaceExport.js'
2
+ import { makeBundle, sealSpaceMeta, keysFileText } from './offlineBundle.js'
3
+
4
+ // Downloads stay in the document doing the export. A vault never returns the
5
+ // contents or a recovery key to its embedding page.
6
+ export function saveExport(name, contents, type) {
7
+ const url = URL.createObjectURL(new Blob([contents], { type }))
8
+ const a = document.createElement('a')
9
+ a.href = url; a.download = name
10
+ document.body.appendChild(a); a.click(); a.remove()
11
+ setTimeout(() => URL.revokeObjectURL(url), 4000)
12
+ }
13
+
14
+ export async function saveOfflineReader() {
15
+ const response = await fetch(new URL('./decrypt.html', import.meta.url))
16
+ if (!response.ok) throw new Error('The offline reader could not be downloaded.')
17
+ saveExport('witbitz-offline-decryptor.html', await response.text(), 'text/html;charset=utf-8')
18
+ }
19
+
20
+ export async function saveRoomExport(sp, tier, current = () => true, title = sp.title) {
21
+ const reader = Object.fromEntries(['poll', 'getConfig', 'blob', 'state'].map((op) => [
22
+ op, (room, ...args) => sp._client[op](room, sp._mk, ...args),
23
+ ]))
24
+ const bundle = await exportSpace(sp.room, reader, { title })
25
+ if (!current()) throw new Error('account_changed')
26
+ bundle.tier = tier
27
+ saveExport('witbitz-space-' + sp.room + '.json', JSON.stringify(bundle), 'application/json')
28
+ return { count: bundle.count }
29
+ }
30
+
31
+ export async function recreateExport(wb, bundle, { tier = bundle?.tier || (bundle?.device?.confidential === false ? 'standard' : 'enclave') } = {}) {
32
+ const email = wb.vault ? (await wb.vault.whoami())?.email : wb.session?.email
33
+ if (!email) throw Object.assign(new Error('Sign in to recreate a Space for yourself.'), { code: 'sign_in_required' })
34
+ let space
35
+ const result = await recreateSpace(bundle, {
36
+ createSpace: async (cfg) => {
37
+ space = await wb.createSpace({
38
+ agent: { name: cfg.agentName, instructions: cfg.persona }, model: cfg.model, tools: cfg.tools,
39
+ clientTools: cfg.clientTools, agentReplies: cfg.agentReplies,
40
+ immediateTools: cfg.immediateTools, data: cfg.dataSchema, platformTools: cfg.platformTools,
41
+ framing: cfg.framing, dataWrites: cfg.dataWrites, admission: { emails: [email], admins: [email] }, tier,
42
+ })
43
+ return { room: space.room, mk: space._mk, keyless: !!wb.vault }
44
+ },
45
+ mirror: (_room, _mk, entries) => space._client.mirror(space.room, space._mk, entries),
46
+ })
47
+ let titleWarning
48
+ if (bundle.title) { try { await space.rename(bundle.title) } catch { titleWarning = 'The room was copied, but its title could not be saved.' } }
49
+ return { space, carried: result.carried, total: result.total, ...(titleWarning ? { titleWarning } : {}) }
50
+ }
51
+
52
+ export async function saveAccountArchive(rooms, resolveRoom, recoveryKeys, current, destination = 'download') {
53
+ if (!['download', 'clipboard'].includes(destination) || (destination === 'clipboard' && !recoveryKeys)) throw Object.assign(new Error('Invalid archive destination'), { code: 'invalid_argument' })
54
+ const spaces = [], keys = [], unavailable = []
55
+ for (const r of rooms) {
56
+ if (!current()) throw new Error('account_changed')
57
+ try {
58
+ const { key, ledger, count } = await resolveRoom(r, recoveryKeys)
59
+ if (!key || (!recoveryKeys && !ledger)) throw new Error('room_unavailable')
60
+ if (recoveryKeys) keys.push({ room: r.room, title: r.label || r.title || '', key })
61
+ else spaces.push({ meta: await sealSpaceMeta(key, { room: r.room, title: r.label || r.title || '', count }), ledger })
62
+ } catch { unavailable.push(r.room) }
63
+ }
64
+ if (!current()) throw new Error('account_changed')
65
+ const saved = recoveryKeys ? keys.length : spaces.length
66
+ if (!saved) throw Object.assign(new Error('No rooms could be exported.'), { code: 'archive_empty', unavailable })
67
+ if (destination === 'clipboard') await navigator.clipboard.writeText(keysFileText(keys))
68
+ else if (recoveryKeys) saveExport('witbitz-room-keys.txt', keysFileText(keys), 'text/plain')
69
+ else saveExport('witbitz-spaces.json', JSON.stringify(makeBundle(spaces)), 'application/json')
70
+ return { saved, unavailable }
71
+ }
@@ -0,0 +1,34 @@
1
+ import { sendInvite } from './inviteSend.js'
2
+ import { inviteScope } from './sdkRekey.js'
3
+ import { validUsername } from './address.js'
4
+ import { EMAIL } from './memberChange.js'
5
+ import { boxApp } from './attestedBox.js'
6
+
7
+ const fail = (code, text) => Object.assign(new Error('witbitz: ' + text), { code })
8
+ export async function resendInvitation(sp, { email, username } = {}) {
9
+ if (sp._sharedRoom) throw fail('lane', 'a private lane cannot invite another member')
10
+ if (!!email === !!username || (email && !EMAIL.test(email)) || (username && !validUsername(username))) throw fail('invalid_argument', 'name one recipient by email or username')
11
+ const wb = sp._wb, client = wb && wb._client
12
+ if (!client || !wb._session || !wb._session.idToken) throw fail('sign_in_required', 'sign in before sending an invitation')
13
+ // Never downgrade an attested invitation to a bearer link in a normal directory box.
14
+ let attested
15
+ try { attested = await client.attestedRoom(sp.room, sp._mk) } catch { throw fail('policy_unreadable', 'the device policy could not be read') }
16
+ const cfg = await sp._gateConfig()
17
+ if (cfg.admission === 'email') {
18
+ if (!(await sp.isAdmin(wb._session.email)) && !(await sp.isOwner(wb._session.email))) throw fail('not_admin', 'only an owner or admin may resend an invitation')
19
+ }
20
+ if (attested) {
21
+ if ((sp._client && sp._client.keyless) || typeof client.verifyGovernance !== 'function') throw fail('attested', 'resend this invitation from the attested app that holds its key')
22
+ let verified
23
+ try { verified = await client.verifyGovernance(sp.room, sp._mk, null) } catch { throw fail('policy_unreadable', 'the signed native-app policy could not be read') }
24
+ const platforms = verified && verified.ok && verified.governed && verified.policy && verified.policy.requireAttestation && verified.policy.requireAttestation.platforms
25
+ const kind = Array.isArray(platforms) && platforms.length && platforms.every((p) => ['ios', 'android', 'macos'].includes(p)) ? 'attested' : Array.isArray(platforms) && platforms.length && platforms.every((p) => p === 'windows') ? 'windows' : null
26
+ if (!kind) throw fail('policy_unreadable', 'the signed native-app policy could not be verified')
27
+ const fragment = new URLSearchParams(String(sp.shareLink || '').split('#')[1] || '')
28
+ const us = sp._split ? fragment.get('us') : null, spc = us ? fragment.get('spc') || '' : ''
29
+ if ((sp._split && !us) || (!sp._split && !sp._mk)) throw fail('no_key', 'this device does not hold this attested Space’s key or user share')
30
+ return sendInvite({ email, username, room: sp.room, ...(us ? { us, spc } : { mk: sp._mk }), title: sp.title, from: sp._who(), gate: cfg.admission === 'email' ? 'email' : undefined, client, kind, app: boxApp(kind), scope: '' })
31
+ }
32
+ if (!sp.shareLink) throw fail('no_link', 'this device does not hold the current invitation link')
33
+ return sendInvite({ email, username, room: sp.room, link: sp.shareLink, title: sp.title, from: sp._who(), gate: cfg.admission === 'email' ? 'email' : undefined, client, scope: inviteScope(wb._session.idToken) })
34
+ }