@witbitz/sdk 0.0.0-stage → 4.3.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -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/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
@@ -0,0 +1,28 @@
1
+ import { browseKey, channelFor, sealCtl, open, readCtl, KIND_CTL } from './browseSeal.js'
2
+ import { RELAY_URL } from './codeRelay.js'
3
+
4
+ const fail = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
5
+ /** The owner's existing encrypted browser control channel; resolves only after the publisher reports the requested state. */
6
+ export async function setSessionPrivate(cloud, session, on, { WebSocket: Socket = globalThis.WebSocket, timeoutMs = 10_000 } = {}) {
7
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(String(session || '')) || typeof on !== 'boolean') throw fail('invalid_argument', 'private browsing needs a session id and a boolean')
8
+ if (!cloud || !cloud.browse || !Socket) throw fail('not_supported', 'this computer has no browser control channel')
9
+ const key = await browseKey(cloud.browse), channel = await channelFor(cloud.browse)
10
+ const relay = new URL(cloud.relay || RELAY_URL)
11
+ if (!['ws:', 'wss:'].includes(relay.protocol)) throw fail('invalid_argument', 'the browser relay must use WebSocket')
12
+ return new Promise((resolve, reject) => {
13
+ let ws, done = false, sent = false
14
+ const finish = (e) => { if (done) return; done = true; clearTimeout(timer); if (ws) { ws.onclose = null; ws.onerror = null; ws.onmessage = null; try { ws.close() } catch {} } e ? reject(e) : resolve(true) }
15
+ const timer = setTimeout(() => finish(fail('timeout', 'the browser did not confirm session privacy; its state is unknown')), timeoutMs)
16
+ try {
17
+ ws = new Socket(relay.href.replace(/\/$/, '') + '/c/' + channel)
18
+ ws.binaryType = 'arraybuffer'
19
+ ws.onopen = async () => { try { const msg = await sealCtl(key, { wb: 'private', session, on }); if (!done) { sent = true; ws.send(msg) } } catch { finish(fail('offline', 'the browser control channel failed')) } }
20
+ ws.onmessage = async (event) => {
21
+ if (!sent || done) return
22
+ const msg = await open(key, event.data), ctl = msg && msg.kind === KIND_CTL && readCtl(msg.bytes)
23
+ if (ctl && ctl.wb === 'session' && ctl.session === session && ctl.private === on) finish()
24
+ }
25
+ ws.onerror = ws.onclose = () => finish(fail('offline', 'the browser control channel disconnected'))
26
+ } catch { finish(fail('offline', 'the browser control channel could not connect')) }
27
+ })
28
+ }
package/sdkBuilds.js ADDED
@@ -0,0 +1,208 @@
1
+ // sdkBuilds.js — `wb.builds`: WHICH ENCLAVE BUILD THIS PERSON ACCEPTS, in a builder's app (the owner's build-later list,
2
+ // 2026-10-28, item 3; "Sync the sdk", 2026-11-07). The Witbitz app seals a confidential room's key only to a build that is
3
+ // (1) published by Witbitz and (2) on the PERSON's own list of accepted builds (trustedBuilds.js; the owner, 2026-10-11:
4
+ // "Accept this build should be only from the user perspective. It is a per user choice."). The SDK sealed to any published
5
+ // build — the person had no say. Now a builder chooses:
6
+ //
7
+ // new Witbitz({ builds: 'published' }) — as before: any build Witbitz publishes (the default; nothing changes)
8
+ // new Witbitz({ builds: 'mine' }) — the person's own list, the app's rules:
9
+ // · FIRST USE: an account that has accepted nothing accepts the first published build it meets;
10
+ // · AUTOMATIC (on unless the person turns it off): every published build is accepted when met — still checked
11
+ // against what Witbitz published, still attested;
12
+ // · off: a new build BLOCKS the person's confidential rooms (`enclave_not_accepted`, with the verdict) until
13
+ // `wb.builds.accept(room)`.
14
+ // The list rides the account (a sealed `builds` document in this app's account index — every device of the account
15
+ // sees an acceptance), and `state` / `onState` for a page without one. The pure rules are enclaveAccept.js's, the
16
+ // app's own.
17
+ import { deviceLacksBuilds } from './cloudDeviceBuilds.js'
18
+ import { mergeTrusted, parseTrusted, trustBuild, userVerdict, gatedKey, publishedKey } from './enclaveAccept.js'
19
+ import { sealDoc, openDoc } from './accountSeal.js'
20
+ import { roomRegion, DEFAULT_REGION } from './regions.js'
21
+
22
+ export const BUILDS_DOC = 'builds' // the app's TRUSTED_DOC (trustedBuilds.js) — the same document name, sealed the same way
23
+ const fail = (code, message, extra = {}) => Object.assign(new Error('witbitz: ' + message), { code, ...extra })
24
+ const parseAuto = (a) => (a && typeof a === 'object' && typeof a.on === 'boolean' && Number.isFinite(+a.at) ? { on: a.on, at: +a.at } : null)
25
+ const stateOf = (s) => (s && typeof s === 'object' ? { builds: parseTrusted(s.builds), ...(parseAuto(s.auto) ? { auto: parseAuto(s.auto) } : {}) } : null)
26
+
27
+ export class Builds {
28
+ /** @param {object} wb the Witbitz client @param {object} o { mode: 'published' | 'mine', state? } */
29
+ constructor (wb, { mode = 'published', state = null } = {}) {
30
+ if (!['published', 'mine'].includes(mode)) throw fail('invalid_argument', "builds is 'published' or 'mine'")
31
+ this._wb = wb
32
+ this._epoch = 0
33
+ this._mode = mode
34
+ const s = stateOf(state)
35
+ this._list = s ? s.builds : []
36
+ this._auto = s && s.auto ? s.auto : null
37
+ this._ready = !!s // a list this page was handed is known — for a page with NO account (_known: with one, its list is read first)
38
+ this._accountRead = false // the account's own list has been read on this page (review 2026-11-07: until then nothing is "known")
39
+ this._pending = new Map() // region → { attested, platform } met before the list was known
40
+ this._syncing = null
41
+ /** Called with the new state whenever it changes — persist it there (a page without an account). */
42
+ this.onState = null
43
+ }
44
+
45
+ _resetAccount () {
46
+ this._epoch++
47
+ this._list = []; this._auto = null; this._ready = false; this._accountRead = false
48
+ this._pending.clear(); this._syncing = null
49
+ }
50
+ _checkAccount (epoch) {
51
+ if (epoch !== this._epoch) throw fail('account_changed', 'the account changed while reading trusted builds')
52
+ }
53
+
54
+ /** 'published' (any build Witbitz publishes) | 'mine' (the person's own list). */
55
+ get mode () { return this._mode }
56
+ /** JSON-safe state to persist: { builds, auto? }. */
57
+ get state () { return { builds: this._list.map((e) => ({ ...e })), ...(this._auto ? { auto: { ...this._auto } } : {}) } }
58
+ /** The builds this person accepted: [{ kernel, payload?, policy?, at }]. */
59
+ list () { return this._list.map((e) => ({ ...e })) }
60
+ /** Is "accept new Witbitz builds automatically" on? On unless the person turned it off. */
61
+ get automatic () { return !this._auto || this._auto.on }
62
+
63
+ /** Turn automatic acceptance on or off — for the account (every device). */
64
+ async setAutomatic (on) {
65
+ const epoch = this._epoch
66
+ if (this._mode === 'mine' && !this._known()) await this.sync()
67
+ this._checkAccount(epoch)
68
+ this._auto = { on: !!on, at: Date.now() }
69
+ this._changed()
70
+ await this._push()
71
+ return this.automatic
72
+ }
73
+
74
+ /** Does this person accept the enclave serving `room`? → { ok, reason?, live } — reason: no_attestation · kernel ·
75
+ * payload · policy (not published by Witbitz) · unknown (the list is not read yet) · not_accepted. null before the
76
+ * room's enclave has attested. In 'published' mode, any published build is ok. */
77
+ verdict (room) {
78
+ const k = this._live(room)
79
+ if (!k) return null
80
+ if (this._mode === 'published') { const v = userVerdict([], k.attested, k.platform); return v.reason === 'not_accepted' ? { ok: true, matched: v.live, live: v.live } : v } // published = accepted
81
+ return userVerdict(this._known() ? this._list : undefined, k.attested, k.platform)
82
+ }
83
+
84
+ /** The person accepts the build serving `room` (its region's enclave). → the list. */
85
+ async accept (room) {
86
+ if (this._mode !== 'mine') throw fail('invalid_argument', "accepting a build is for new Witbitz({ builds: 'mine' })")
87
+ const epoch = this._epoch
88
+ if (!this._known()) await this.sync()
89
+ this._checkAccount(epoch) // the account's list (and its automatic choice) first: never a partial list taken as whole
90
+ const k = this._live(room)
91
+ if (!k || !k.attested) throw fail('not_attested', 'that room\'s enclave has not attested yet — open the room first')
92
+ const pub = userVerdict([], k.attested, k.platform)
93
+ if (pub.reason !== 'not_accepted' && !pub.ok) throw fail('not_published', 'this build is not one Witbitz publishes — it cannot be accepted', { verdict: pub })
94
+ this._list = trustBuild(this._list, k.attested)
95
+ this._changed()
96
+ await this._push()
97
+ return this.list()
98
+ }
99
+
100
+ /** Read the account's list and fold it in (union; the newest automatic choice wins), writing back what it lacks. */
101
+ async sync () {
102
+ if (this._syncing) return this._syncing
103
+ const epoch = this._epoch
104
+ this._syncing = (async () => {
105
+ const store = await this._store()
106
+ this._checkAccount(epoch)
107
+ if (!store) { this._ready = true; this._first(); return this.list() } // no account: this page's list is the only one (an account turned on later is read then: _known)
108
+ const doc = await store.get()
109
+ this._checkAccount(epoch)
110
+ const remote = doc && typeof doc === 'object' ? doc : null
111
+ const next = mergeTrusted(this._list, remote && remote.builds)
112
+ const ra = parseAuto(remote && remote.auto)
113
+ if (ra && (!this._auto || ra.at > this._auto.at)) this._auto = ra
114
+ const lacks = next.length > parseTrusted(remote && remote.builds).length || (this._auto && (!ra || this._auto.at > ra.at))
115
+ this._list = next; this._ready = true; this._accountRead = true
116
+ this._changed()
117
+ if (lacks) { try { await store.put(this.state) } catch { /* the next acceptance writes it */ } }
118
+ this._checkAccount(epoch)
119
+ this._first()
120
+ return this.list()
121
+ })().finally(() => { if (epoch === this._epoch) this._syncing = null })
122
+ return this._syncing
123
+ }
124
+
125
+ // ── the SDK's own hooks ────────────────────────────────────────────────────────────────────────────────────────────
126
+ /** @private the seal gate (Witbitz `mkPub`): the key iff this person accepts the live build; throws `enclave_not_accepted`. */
127
+ _key ({ key, attested, platform, room }) {
128
+ if (this._mode === 'published') return publishedKey({ key, attested, platform, room })
129
+ const known = this._known()
130
+ if (key && !known) this.sync().catch(() => {}) // the list is read in the background; this call says `unknown` meanwhile
131
+ return gatedKey({ key, trusted: known ? this._list : undefined, attested, platform, room })
132
+ }
133
+ /** Is the person's list KNOWN here? With an account: only once ITS list was read on this page — a handed or local list may be
134
+ * partial, and first use / automatic must never be decided on one. Without an account: the list this page holds. */
135
+ _known () { const acc = this._wb.account; return acc && acc.enabled ? this._accountRead : true }
136
+ /** @private an enclave attested (Witbitz `_encAttest`): first use / automatic, the app's rule (trustedBuilds.autoAccept). */
137
+ _attested (region, attested, platform) {
138
+ if (this._mode !== 'mine' || !attested) return
139
+ if (!this._known()) { this._pending.set(region, { attested, platform }); this.sync().catch(() => {}); return }
140
+ this._auto1(attested, platform)
141
+ }
142
+ _first () { for (const [r, p] of this._pending) { this._pending.delete(r); this._auto1(p.attested, p.platform) } }
143
+ _auto1 (attested, platform) {
144
+ if (!this._known()) return false
145
+ if (this._list.length && !this.automatic) return false
146
+ const v = userVerdict([], attested, platform)
147
+ if (v.reason !== 'not_accepted') return false // not published (or not attested): nothing is accepted for them
148
+ if (userVerdict(this._list, attested, platform).ok) return false // already
149
+ this._list = trustBuild(this._list, attested); this._changed(); this._push().catch(() => {})
150
+ return true
151
+ }
152
+ _live (room) {
153
+ const enc = this._wb._enc
154
+ if (!enc) return null
155
+ const reg = roomRegion(room)
156
+ return enc.byRegion.get(reg) || (reg === DEFAULT_REGION && enc.attested ? { attested: enc.attested, platform: enc.platform } : null)
157
+ }
158
+ async _store () {
159
+ const acc = this._wb.account
160
+ if (!acc || !acc.enabled || typeof acc._where !== 'function') return null
161
+ const loc = await acc._where(), c = acc._client()
162
+ let v = null // the version get() read: put() lands only over it (another device's write in between → 409 → read and merge again)
163
+ return {
164
+ get: async () => {
165
+ const r = await c.state(loc.room, loc.mk, BUILDS_DOC)
166
+ if (!r || r.status !== 200) throw fail('unreadable', 'the account could not be read just now', { status: r && r.status })
167
+ v = Number.isInteger(r.v) ? r.v : null
168
+ const st = r.state
169
+ return st == null || (typeof st === 'object' && !Object.keys(st).length) ? null : openDoc(loc.key, st)
170
+ },
171
+ put: async (doc) => {
172
+ const w = await c.state(loc.room, loc.mk, BUILDS_DOC, await sealDoc(loc.key, { ...doc, at: Date.now() }), BUILDS_DOC, 'device', v ?? undefined)
173
+ if (w && w.status === 409) throw fail('moved', 'another device changed the account just now')
174
+ if (!w || w.status !== 200) throw fail('save_failed', 'the account could not be saved just now', { status: w && w.status })
175
+ },
176
+ }
177
+ }
178
+ async _push () {
179
+ const epoch = this._epoch
180
+ const store = await this._store().catch(() => null)
181
+ this._checkAccount(epoch)
182
+ if (!store) return
183
+ // read, merge, write ONLY over what was read — another device's write in between is read and merged again, never written
184
+ // over (sync sweep 11-08 #32; the app's accountStores ifV)
185
+ for (let i = 0; ; i++) {
186
+ const remote = await store.get() // a read that fails ABORTS the write: a whole-doc put over an unread copy would drop other devices' acceptances (review 2026-11-07)
187
+ this._checkAccount(epoch)
188
+ const merged = mergeTrusted(this._list, remote && remote.builds)
189
+ const ra = parseAuto(remote && remote.auto)
190
+ if (ra && (!this._auto || ra.at > this._auto.at)) this._auto = ra
191
+ this._list = merged
192
+ try { await store.put(this.state); return } catch (e) { if (!(e && e.code === 'moved') || i >= 4) throw e }
193
+ }
194
+ }
195
+ _changed () {
196
+ if (this._mode === 'mine' && this._wb.cloudDevice && !this._wb.vault && this._wb._session) {
197
+ const epoch = this._epoch, session = this._wb._session, backup = this._wb.backup?._s
198
+ const send = async () => {
199
+ const current = () => this._epoch === epoch && this._wb._session === session && this._wb.backup?._s === backup
200
+ if (!current()) return
201
+ const cloud = await this._wb.cloudDevice.status()
202
+ const ours = this.state
203
+ if (current() && cloud.email && cloud.email.toLowerCase() === session.email?.toLowerCase() && cloud.rooms?.length && deviceLacksBuilds(cloud.builds, ours)) await this._wb.cloudDevice.setBuilds(ours)
204
+ }
205
+ this._cloudSync = (this._cloudSync || Promise.resolve()).then(send).catch(() => {})
206
+ }
207
+ if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback must not break the gate */ } } }
208
+ }
@@ -0,0 +1,215 @@
1
+ import { sealDoc } from './accountSeal.js'
2
+ import { disconnectKeptSpace, keptAgentSpaceIds } from './sdkKeptAgent.js'
3
+
4
+ const fail = (code, text, status) => Object.assign(new Error('witbitz: ' + text), { code, ...(status ? { status } : {}) })
5
+ const current = (wb, session, state) => { if (wb._session !== session || wb.backup._s !== state) throw fail('account_changed', 'the account changed during the cloud-device operation') }
6
+
7
+ /** A kept Space remains solo and has no private lane of its own, on every SDK/vault device. */
8
+ export async function assertNotKept(space) {
9
+ if (space._wb?.vault) return space._wb.vault._c.roomAccount(space.room, 'alwaysOn', 'assertNotKept')
10
+ if (await isKeptSpace(space)) throw fail('kept_space', 'stop keeping this Space always on before adding people or private lanes')
11
+ }
12
+
13
+ export async function isKeptSpace(space) {
14
+ const w = space._wb, a = w && w.account
15
+ if (!a?.enabled || typeof a._read !== 'function') {
16
+ if (!w?._session?.email || space._sharedRoom) return false
17
+ if (!w.cloudDevice) throw fail('index_unavailable', 'the Space’s always-on status could not be checked')
18
+ try { return (await w.cloudDevice.status()).rooms.some((r) => r.room === space.room) }
19
+ catch (e) { if (['not_available', 'cloud_device_unavailable', 'not_enrolled', 'not_in_dev_server'].includes(e.code)) return false; throw e } // cloud_device_unavailable: this deployment runs no cloud device (agent/cloudDeviceRoute.mjs, 501), so nothing here is kept
20
+ }
21
+ const session = w._session, state = w.backup._s, loc = await a._where()
22
+ current(w, session, state)
23
+ const r = await a._read(loc, 'xindex', loc.app)
24
+ current(w, session, state)
25
+ if (!r.ok) throw fail('index_unavailable', 'the account’s always-on mark could not be read')
26
+ return !!r.doc?.rooms?.[space.room]?.alwaysOn
27
+ }
28
+
29
+ export async function disconnectRoomLanes(w, room) {
30
+ if (!w) return
31
+ for (const lane of w._openLanes || []) if (lane._sharedRoom === room) lane._detachShared()
32
+ const session = w._session, state = w.backup?._s
33
+ const sync = async () => {
34
+ const result = await w.account.sync()
35
+ current(w, session, state)
36
+ if (!result?.ok) throw fail('index_unavailable', 'the disconnected lanes could not be synced')
37
+ }
38
+ if (w.account?.enabled) await sync()
39
+ const held = w._heldLaneRooms?.(room) || []
40
+ const children = new Set([...held, ...(w.backup?.rooms || []).filter(r => r.kind === 'lane' && r.shared === room).map(r => r.room)])
41
+ const links = (w.account?.links || []).filter(l => l.a === room || l.b === room)
42
+ for (const link of links) w.account._dropLink(link.a, link.b)
43
+ for (const child of children) w.backup?._detachLane(child, room)
44
+ if (held.length) { await w._detachHeldLanes(room); current(w, session, state) }
45
+ if (w.account?.enabled && (links.length || children.size)) await sync()
46
+ }
47
+
48
+ /** Requests use the attested, encrypted cloud-device channel. */
49
+ export class CloudDevice {
50
+ constructor(wb) { this._wb = wb }
51
+ async _ask(t, body = {}) {
52
+ const w = this._wb, auth = w._auth('the cloud device belongs to an account')
53
+ const session = w._session, state = w.backup._s
54
+ const opts = typeof w._cloudDeviceOpts === 'function' ? await w._cloudDeviceOpts() : undefined // devRoot: the dev server's device, under its root
55
+ if (typeof (w._client && w._client.cloudDevice) !== 'function') throw fail('not_available', 'this client has no cloud device') // a builder's own client, a test's: no device here (isKeptSpace reads that as not kept)
56
+ const r = await w._client.cloudDevice({ t, ...body }, auth.idToken, opts)
57
+ current(w, session, state)
58
+ if (!r || r.status !== 200 || r.ok === false) throw fail((r && r.error) || 'offline', (r && (r.message || r.reason)) || 'the cloud device did not answer', r && r.status)
59
+ return r
60
+ }
61
+ async status() {
62
+ const w = this._wb
63
+ if (w.vault) return w.vault._c.account('cloudDevice', 'status')
64
+ const h = await this._ask('hello')
65
+ return { email: h.email || null, registered: !!h.registered, rooms: Array.isArray(h.rooms) ? h.rooms : [], builds: h.builds || null }
66
+ }
67
+ async enroll({ getCode } = {}) {
68
+ const w = this._wb
69
+ if (w.vault) return w.vault._c.account('cloudDevice', 'enroll')
70
+ if (typeof getCode !== 'function') throw fail('no_screen', 'cloud-device sign-in needs an emailed code')
71
+ const session = w._session, state = w.backup._s
72
+ await this._ask('enrol')
73
+ const code = await getCode(); current(w, session, state)
74
+ await this._ask('code', { code: String(code || '').trim() })
75
+ return this.status()
76
+ }
77
+ async register({ getCode } = {}) {
78
+ const w = this._wb
79
+ if (w.vault) return w.vault._c.account('cloudDevice', 'register')
80
+ if (!w.backup._v2 || w.backup.service !== 'account') throw fail('not_on_service', 'register the cloud device from an account on the account service')
81
+ const session = w._session, state = w.backup._s
82
+ const { spk } = await this._ask('devkey'); current(w, session, state)
83
+ const registration = await w.backup._v2.enrolCloudDevice(w.backup, { spk, getCode })
84
+ current(w, session, state)
85
+ await this._ask('devready', { base: registration.base })
86
+ return this.status()
87
+ }
88
+ async setBuilds(state) {
89
+ const w = this._wb
90
+ if (w.vault) return w.vault._c.account('cloudDevice', 'setBuilds', state)
91
+ return this._ask('builds', { state })
92
+ }
93
+ async forget() {
94
+ const w = this._wb
95
+ if (w.vault) return w.vault._c.account('cloudDevice', 'forget')
96
+ const session = w._session, state = w.backup._s, h = await this.status()
97
+ current(w, session, state)
98
+ let cleanupError
99
+ const links = await keptAgentSpaceIds(w)
100
+ let marked = []
101
+ if (w.account?.enabled && typeof w.account._read === 'function') {
102
+ const loc = await w.account._where()
103
+ const entry = await w.account._read(loc, 'xindex', loc.app)
104
+ current(w, session, state)
105
+ if (!entry.ok) throw fail('index_unavailable', 'the account’s always-on marks could not be read')
106
+ marked = Object.entries(entry.doc?.rooms || {}).filter(([, r]) => r?.alwaysOn).map(([id]) => id)
107
+ }
108
+ const rooms = [...new Set([...h.rooms.map((r) => r.room), ...links])]
109
+ current(w, session, state)
110
+ for (const room of rooms) {
111
+ const r = { room }
112
+ let sp
113
+ try {
114
+ if (w._agentRoom) sp = w._agentRoom(r.room)
115
+ else { const rec = w.backup.rooms.find((x) => x.room === r.room); if (!rec) throw fail('not_in_account', 'restore the kept Space to finish unlinking it'); sp = await w.openSpace(rec.link, { live: false }) }
116
+ await disconnectKeptSpace(sp)
117
+ } catch (e) { cleanupError = cleanupError || e }
118
+ finally { if (sp) sp.close() }
119
+ current(w, session, state)
120
+ }
121
+ try { await this._ask('forget') } catch (e) { if (e.code !== 'not_enrolled') throw e }
122
+ current(w, session, state)
123
+ for (const room of new Set([...rooms, ...marked])) { current(w, session, state); await markKept(w, room, false) }
124
+ if (cleanupError) throw cleanupError
125
+ return { forgotten: true }
126
+ }
127
+ }
128
+
129
+ /** The app's per-room always-on mark, over a versioned read; links to a stopped kept assistant are tombstoned. */
130
+ async function markKept(w, room, on) {
131
+ const a = w.account
132
+ if (!a || !a.enabled) return
133
+ const s = w.backup._s, session = w._session
134
+ if (!on) for (const l of a.links) if (l.a === room || l.b === room) a._dropLink(l.a, l.b)
135
+ const synced = await a.sync(); current(w, session, s)
136
+ if (!synced || !synced.ok) throw fail('index_unavailable', 'the device changed, but its account mark could not sync; check its status')
137
+ for (let i = 0; i < 5; i++) {
138
+ const loc = await a._where(), got = await a._read(loc, 'xindex', loc.app); current(w, session, s)
139
+ if (!got.ok) throw fail('index_unavailable', 'the account mark could not be read')
140
+ const doc = got.doc || {}, entry = (doc.rooms || {})[room]
141
+ if (!entry) throw fail('not_in_account', 'the cloud device changed, but this Space is absent from the account index')
142
+ const at = Math.max(Date.now(), (Number(entry.alwaysOnAt) || 0) + 1)
143
+ const next = { ...doc, rooms: { ...(doc.rooms || {}), [room]: { ...entry, alwaysOn: !!on, alwaysOnAt: at } } }
144
+ const r = await a._client().state(loc.room, loc.mk, 'xindex', await sealDoc(loc.app, next), 'always on', 'device', got.v)
145
+ current(w, session, s)
146
+ if (r && r.status === 409) continue
147
+ if (!r || r.status !== 200) throw fail('save_failed', 'the cloud-device account mark could not be saved')
148
+ return
149
+ }
150
+ throw fail('version_conflict', 'the account kept changing; check the cloud-device status and retry')
151
+ }
152
+
153
+ export class SpaceAlwaysOn {
154
+ constructor(space) { this._sp = space }
155
+ _client() { const w = this._sp._wb; if (!w) throw fail('no_client', 'open this Space through a Witbitz client'); return w }
156
+ async status() {
157
+ const w = this._client(), s = this._sp
158
+ if (w.vault) return w.vault._c.roomAccount(s.room, 'alwaysOn', 'status')
159
+ const h = await w.cloudDevice.status(), entry = h.rooms.find((r) => r.room === s.room)
160
+ return { on: !!entry, registered: h.registered, ...(entry && entry.waiting ? { waiting: entry.waiting } : {}) }
161
+ }
162
+ async enable({ disconnectLanes = false } = {}) {
163
+ const w = this._client(), s = this._sp
164
+ if (w.vault) return w.vault._c.roomAccount(s.room, 'alwaysOn', 'enable', { disconnectLanes: !!disconnectLanes })
165
+ if (s._sharedRoom || String(s.room).startsWith('tmp-')) throw fail('not_supported', 'private lanes and temporary Spaces cannot be kept always on')
166
+ if (!w.account.enabled) throw fail('not_enabled', 'enable the account backup before keeping a Space always on')
167
+ const session = w._session, state = w.backup._s
168
+ const synced = await w.account.sync()
169
+ current(w, session, state)
170
+ if (!synced?.ok) throw fail('index_unavailable', 'the account’s linked rooms could not be checked')
171
+ const cfg = await s._gateConfig({ fresh: true })
172
+ current(w, session, state)
173
+ const linked = w.account.links?.some((l) => l.a === s.room || l.b === s.room)
174
+ const children = new Set((w.backup.rooms || []).filter((r) => r.kind === 'lane' && r.shared === s.room).map((r) => r.room))
175
+ for (const room of w._heldLaneRooms?.(s.room) || []) children.add(room)
176
+ if (linked || children.size || cfg.lanes === true || s.lanes) {
177
+ if (!disconnectLanes) throw fail('lanes_enabled', 'turn private assistants off, or pass disconnectLanes: true')
178
+ await s.configure({ lanes: false })
179
+ current(w, session, state)
180
+ await disconnectRoomLanes(w, s.room)
181
+ current(w, session, state)
182
+ }
183
+ if (!s.shareLink) throw fail('no_link', 'this device does not hold the Space’s current link')
184
+ if (w.builds && w.builds.mode === 'mine') {
185
+ await w.builds.sync()
186
+ current(w, session, state)
187
+ await w.cloudDevice.setBuilds(w.builds.state)
188
+ current(w, session, state)
189
+ }
190
+ await w.cloudDevice._ask('room', { link: s.shareLink })
191
+ current(w, session, state)
192
+ await markKept(w, s.room, true)
193
+ return { on: true }
194
+ }
195
+ async disable() {
196
+ const w = this._client(), s = this._sp
197
+ if (w.vault) return w.vault._c.roomAccount(s.room, 'alwaysOn', 'disable')
198
+ const session = w._session, state = w.backup._s
199
+ let cleanupError
200
+ try { await disconnectKeptSpace(s) } catch (e) { cleanupError = e }
201
+ current(w, session, state)
202
+ try { await w.cloudDevice._ask('unroom', { room: s.room }) } catch (e) { if (e.code !== 'not_enrolled') throw e }
203
+ current(w, session, state)
204
+ await markKept(w, s.room, false)
205
+ if (cleanupError) throw cleanupError
206
+ return { on: false }
207
+ }
208
+ async run(text) {
209
+ const w = this._client(), s = this._sp
210
+ if (typeof text !== 'string' || !text.trim() || text.length > 8000) throw fail('invalid_argument', 'run needs 1–8000 characters')
211
+ if (w.vault) return w.vault._c.roomAccount(s.room, 'alwaysOn', 'run', text)
212
+ const r = await w.cloudDevice._ask('run', { room: s.room, text })
213
+ return { started: r.started === true }
214
+ }
215
+ }