@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,255 @@
1
+ // sdkSafeMedia.js — `space.safeMedia`: SAFE MEDIA from a builder's page (docs/safe-media.md; the owner, 2026-10-27: "Do 1+2").
2
+ // The same engine as the Spaces app (safeMedia.js makeSafe / verifySafe, safeMediaRoom.js): in a room with `safeMedia: true`,
3
+ // a photo or a PDF is made safe ONCE — sent, sealed to the tools enclave's ATTESTED key, through the Space server (which sees
4
+ // ciphertext only), and given back as JPEGs our enclave encoded from pixels a keyless one-shot parser produced, with the
5
+ // hardware's attestation over exactly those bytes. The copies are stored beside the original (op 'safe', a hidden entry
6
+ // `{ kind: 'safe', safeFor: { id, at, i }, safe }`), and a reader draws one only after checking that attestation itself.
7
+ //
8
+ // space.safeMedia.on → true | false | null (not known yet: call refresh())
9
+ // await space.safeMedia.refresh() → boolean, from the room's sealed settings
10
+ // await space.safeMedia.set(on, { from }) → { changed } — the admins' where the room names some, any member's otherwise
11
+ // await space.safeMedia.copy(message, ref) → { ok, versions: [{ w, h, b64 }], statement, att } | { ok: false, why } — VERIFIED here, or ok:false
12
+ // await space.safeMedia.make(message, ref) → { ok, error? } — make the copy for everyone (needs a signed-in session)
13
+ // await space.safeMedia.isOriginal(copy, b64) → boolean — the original is the file the copy was made from
14
+ // events on the Space: 'safeMedia' { on, from, ts } (the setting moved) · 'safeCopy' { for: { id, at, i } } (a copy arrived)
15
+ //
16
+ // `ref` = { at: 'images' | 'files', i } — which attachment of the message (default: its first image, else its first file).
17
+ // While the setting is on, send() makes the copies of what it sends by itself, as the app does (best effort: signed out,
18
+ // offline or too large, the message goes anyway and anyone may make() it later).
19
+
20
+ import { makeSafe, verifySafe, isTheOriginal, firstVerifiedCopy, safeMediaReady, SAFE_MAX_INPUT } from './safeMedia.js'
21
+
22
+ const fail = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
23
+ const stdB64 = (b) => { let s = ''; for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000)); return btoa(s) }
24
+ const fromB64 = (s) => Uint8Array.from(atob(String(s || '').replace(/^data:[^,]*,/, '')), (c) => c.charCodeAt(0))
25
+ const isPdf = (a) => !!a && (a.mime === 'application/pdf' || /\.pdf$/i.test(a.name || ''))
26
+ export const isImg = (a) => !!a && (a.kind === 'image' || /^image\//i.test(String(a.mime || ''))) // = media.js isImageAtt, COPIED: media.js loads the app's idb and key worker, which the SDK must not (isImgCopy.test holds them equal) — a photo sent as a file is a photo
27
+ const slotKey = (f) => `${f.id}|${f.at}|${f.i}`
28
+ // the assistant's photos (_autoAgent): the app's numbers, COPIED — messageRender.js and safeMediaRoom.js load the app's shell
29
+ // (sdkAppParityMore.test holds them equal)
30
+ export const AUTO_SAFE_MS = 30 * 60_000 // a photo younger than this gets its copy made by the first device that draws it
31
+ export const AUTO_SAFE_WAIT_MS = 2500 // …after this wait, for a copy another device may be making
32
+ /** What send() matches its own stored message by — the app's echo signature (space.js echoSig). */
33
+ export const sigOf = (m) => `${String((m && m.text) || '').trim()}|${((m && m.images) || []).length}|${((m && m.files) || []).length}`
34
+
35
+ export class SpaceSafeMedia {
36
+ /** @param {object} space the Space; @param {object} [deps] injectable engine (tests): { makeSafe, verifySafe, pins, root, now } */
37
+ constructor (space, deps = {}) {
38
+ this._s = space
39
+ this._d = { makeSafe, verifySafe, pins: undefined, root: undefined, ...deps }
40
+ this._on = null; this._at = -1 // what is known, as of `_at` (a settings read: now; a line: its ts) — an older word never wins
41
+ this._copies = new Map() // slotKey → [copy entries], oldest first
42
+ this._sent = [] // { sig, made: [{ at, i, p }] } — copies being made for messages this handle sent, waiting for their ids
43
+ this._autoTried = new Set() // the assistant's photos this handle has made (or tried to make) a copy of — once each
44
+ }
45
+
46
+ /** The setting as this handle knows it: true / false, or null before the room's settings or a line said. A private lane
47
+ * follows its Space's (sync sweep 2026-10-27 #1: the mirror copies the Space's photos into the lane, and there they were
48
+ * read as plain attachments) — draw a lane's photos through copy() as the Space's. */
49
+ get on () {
50
+ // a lane's OWN value is ignored: before 2026-10-30 a lane could be turned on alone, and nothing can turn that off now — it
51
+ // stayed on after its Space turned it off (sync sweep 2026-10-31 #3)
52
+ if (this._isLane()) { const sh = this._lane(); return sh && sh.safeMedia ? sh.safeMedia.on : null } // without its Space's handle: not known here
53
+ return this._on
54
+ }
55
+ /** @private the Space this handle's lane follows, or null for a Space (or a lane opened without its Space's handle) */
56
+ _lane () { const sh = this._s && this._s._sharedSpace; return sh && sh !== this._s ? sh : null }
57
+ /** @private IS this handle a private lane? ONE check (sync sweep P7: `configure` asked `_sharedRoom`, this file `_sharedSpace`, and
58
+ * a Lane built without its Space's handle — the app's and the vault's — read as a Space here: its own value, `set` allowed). */
59
+ _isLane () { return !!(this._s && this._s._sharedRoom) }
60
+ /** Is there an accepted safe-media build in this release at all? (safeMediaPins.js) — false: nothing verifies yet. */
61
+ get available () { return safeMediaReady(this._d.pins) }
62
+
63
+ /** @private learn the setting as of `at`; tells listeners when it moved. */
64
+ _learn (on, at, from = '') {
65
+ if (at < this._at) return
66
+ const was = this._on
67
+ this._on = !!on; this._at = at
68
+ // a LANE's own value is kept but never said: the lane follows its Space, and relays the Space's moves (sweep 11-07 #12)
69
+ if (was !== this._on && was !== null && !this._isLane()) this._s._emit('safeMedia', { on: this._on, from, ts: at })
70
+ }
71
+
72
+ /** Read the room's sealed settings → boolean. */
73
+ async refresh () {
74
+ const sh = this._lane()
75
+ if (sh && sh.safeMedia) return sh.safeMedia.refresh() // a lane follows its Space: read the Space's
76
+ if (this._isLane()) throw fail('lane_follows_space', 'a private lane follows its Space’s Safe media — read it on the Space (open the lane with its Space)')
77
+ const c = this._s._client
78
+ if (!c || typeof c.getConfig !== 'function') throw fail('unavailable', 'this Space cannot read its settings here')
79
+ let cfg = await c.getConfig(this._s.room, this._s._mk)
80
+ // a SLEEPING confidential Space reads nothing: wake it and read once more, as the vault does (sweep P2: a lane's refresh,
81
+ // which reads its Space's, failed until something else woke it)
82
+ const wb = this._s._wb
83
+ if (!cfg && wb && typeof wb._encWake === 'function' && typeof this._s._isEnclave === 'function' && this._s._isEnclave()) {
84
+ try { await wb._encWake(this._s.room, { tries: 8 }); cfg = await c.getConfig(this._s.room, this._s._mk) } catch { /* said below */ }
85
+ }
86
+ // "sign in" only where it is the reason — a gated room's settings before sign-in; a sleeping enclave or a failed read is not
87
+ // (sweep 11-07 #8: a vault, signed in, was told to sign in)
88
+ if (!cfg || typeof cfg !== 'object') throw fail('config_unavailable', 'the room’s settings could not be read just now — try again')
89
+ if (cfg.gated === true && !cfg.allow) throw fail('config_unavailable', 'the room’s settings could not be read (sign in to a verified Space first)')
90
+ this._learn(cfg.safeMedia === true, Date.now())
91
+ return this.on === true // a private lane follows its Space (sync sweep 2026-10-29 #7: refresh() answered false while `on` was true)
92
+ }
93
+
94
+ /** Turn Safe media on or off for everyone — a line every member sees says who did. */
95
+ async set (on, { from } = {}) {
96
+ if (typeof on !== 'boolean') throw fail('invalid_argument', 'safeMedia.set takes true or false')
97
+ // A private lane follows its Space: its own setting could turn it on for the lane alone and never off (sync sweep
98
+ // 2026-10-30 #4) — the Space's admins set it, for everyone, on the Space.
99
+ if (this._isLane()) throw fail('lane_follows_space', 'a private lane follows its Space’s Safe media — set it on the Space')
100
+ if (on && !this.available) throw fail('safe_media_unavailable', 'no safe-media enclave is accepted in this release yet')
101
+ return this._s.configure({ safeMedia: on, ...(from ? { from } : {}) })
102
+ }
103
+
104
+ /** @private one ledger entry, from the poll: a copy (kept, never a message) or the line that moved the setting. → true if consumed. */
105
+ _note (e) {
106
+ if (!e || typeof e !== 'object') return false
107
+ if (e.kind === 'safe') {
108
+ if (!e.safeFor || !e.safe) return true
109
+ const k = slotKey(e.safeFor), list = this._copies.get(k) || []
110
+ if (!list.some((x) => x.id === e.id)) { this._copies.set(k, [...list, e]); this._s._emit('safeCopy', { for: { id: e.safeFor.id, at: e.safeFor.at, i: e.safeFor.i } }) }
111
+ return true
112
+ }
113
+ if (e.sys && e.safeMedia && typeof e.safeMedia === 'object') this._learn(e.safeMedia.on === true, Number(e.ts) || 0, e.name || e.from || '')
114
+ return false
115
+ }
116
+
117
+ /** @private which attachment of a message → { at, i, att, kind } */
118
+ _slot (message, ref) {
119
+ if (!message || typeof message !== 'object' || message.id == null) throw fail('invalid_argument', 'safeMedia takes a stored message (from "message" or space.messages)')
120
+ let at = ref && ref.at, i = ref && Number.isInteger(ref.i) ? ref.i : 0
121
+ if (!at) at = Array.isArray(message.images) && message.images.length ? 'images' : 'files'
122
+ if (at !== 'images' && at !== 'files') throw fail('invalid_argument', "ref.at is 'images' or 'files'")
123
+ const att = Array.isArray(message[at]) ? message[at][i] : null
124
+ if (!att) throw fail('invalid_argument', `the message has no ${at}[${i}]`)
125
+ if (at === 'files' && !isPdf(att) && !isImg(att)) throw fail('invalid_argument', 'only photos and PDFs have safe copies')
126
+ return { at, i, att, kind: at === 'images' || isImg(att) ? 'image' : 'pdf' }
127
+ }
128
+
129
+ /** The first copy of that attachment that VERIFIES on this device, every version checked → { ok, versions, statement, att } | { ok: false, why }. */
130
+ async copy (message, ref) {
131
+ const s = this._slot(message, ref)
132
+ const list = (this._copies.get(slotKey({ id: message.id, at: s.at, i: s.i })) || []).map((c) => ({ c, via: this._s }))
133
+ // a private lane's MIRRORED entry (`sh:<the Space's id>`) is drawn from its Space's copies — the same bytes; the original
134
+ // check below still holds (sync sweep: the Space's verified copies were never seen in the lane). Its COPIES are the Space's
135
+ // stored blobs, read through the SPACE's handle — the lane's room has none (sync sweep 11-08 #13); its ORIGINAL is the
136
+ // lane's own: the mirror stored the photo's bytes again in the lane, so the entry's ref is under the lane's key (sync
137
+ // sweep 11-09: read through the Space, it was a 404)
138
+ const m = /^sh:(.+)$/.exec(String(message.id || '')), sh = this._lane()
139
+ const shared = !!(m && sh && sh.safeMedia)
140
+ if (shared) list.push(...(sh.safeMedia._copies.get(slotKey({ id: m[1], at: s.at, i: s.i })) || []).map((c) => ({ c, via: sh.safeMedia._s })))
141
+ if (!list.length) return { ok: false, why: 'no safe copy yet' }
142
+ const origVia = this._s // the entry's own room holds its original — the lane's, for a mirrored one
143
+ // every version fetched and checked; the loop, the verify and the "made from THIS file" check are safeMedia.js firstVerifiedCopy,
144
+ // the app's too (sync sweep 2026-10-29 #1: a copy must be OF this file)
145
+ const r = await firstVerifiedCopy(list, {
146
+ fetch: async ({ via }, vs) => ({ bytes: await Promise.all(vs.map(async (v) => fromB64((await via.attachment({ ...v, mime: 'image/jpeg' })).b64))) }),
147
+ verify: (safe, bytes) => this._d.verifySafe(safe, bytes, { pins: this._d.pins, root: this._d.root }),
148
+ original: async () => fromB64((await origVia.attachment(s.att)).b64),
149
+ })
150
+ if (!r.ok) return r
151
+ const c = r.cand.c, vs = c.safe.versions
152
+ return { ok: true, versions: vs.map((x, k) => ({ w: x.w, h: x.h, b64: stdB64(r.bytes[k]) })), statement: c.safe.statement, att: c.safe.att }
153
+ }
154
+
155
+ /** Does `b64` (the original's bytes, from space.attachment) hash to what `copy` was made from? Check before opening it. */
156
+ async isOriginal (copy, b64) {
157
+ let st; try { st = JSON.parse(copy && copy.statement) } catch { return false }
158
+ return isTheOriginal(st, fromB64(b64))
159
+ }
160
+
161
+ /** @private the sign-in a make needs, or a clear error */
162
+ _idToken () {
163
+ const wb = this._s._wb
164
+ if (!wb || typeof wb._auth !== 'function') throw fail('sign_in_required', 'sign in first — making a file safe is counted to an account')
165
+ return wb._auth('making a file safe is counted').idToken
166
+ }
167
+
168
+ /** @private bytes → the enclave → a verified result (throws with a reason) */
169
+ async _made (bytes, kind, mime, idToken) {
170
+ if (!bytes.length || bytes.length > SAFE_MAX_INPUT) throw fail('too_large', 'this file is too large to make safe')
171
+ return this._d.makeSafe({ bytes, kind, mime }, { client: this._s._client, idToken, pins: this._d.pins, root: this._d.root, ...(this._d.now ? { now: this._d.now } : {}) })
172
+ }
173
+
174
+ /** @private post one made copy beside its original */
175
+ async _post (ref, made, from) {
176
+ const safe = { for: { id: ref.id, at: ref.at, i: ref.i }, statement: made.statement, att: made.att, versions: made.versions.map((v) => ({ w: v.w, h: v.h, b64: stdB64(v.bytes) })) }
177
+ // A sleeping confidential Space answers 'warming' (a copy wakes nothing), and one whose enclave key is not known yet throws
178
+ // before sending: wake it, then post once more — as the app does (sync sweep 2026-10-29 #6).
179
+ const post = () => Promise.resolve().then(() => this._s._client.safeCopy(this._s.room, this._s._mk, safe, from || this._s._who()))
180
+ .catch((e) => (/enclave key unavailable/.test(String((e && e.message) || e)) ? { status: 503, error: 'enclave_warming' } : Promise.reject(e)))
181
+ let r = await post()
182
+ const wb = this._s._wb
183
+ if (r && (r.status === 503 || r.error === 'enclave_warming') && wb && typeof wb._encWake === 'function' && typeof this._s._isEnclave === 'function' && this._s._isEnclave()) {
184
+ try { await wb._encWake(this._s.room, { tries: 8 }); r = await post() } catch { /* the enclave did not come up: say the first answer */ }
185
+ }
186
+ if (!r || r.status !== 200) return { ok: false, error: String((r && (r.reason || r.error)) || 'the room did not take it') }
187
+ this._s._kick()
188
+ return { ok: true }
189
+ }
190
+
191
+ /** Make the safe copy of an attachment already in the room, for everyone. Never throws for a refusal: { ok, error? }. */
192
+ async make (message, ref, { from } = {}) {
193
+ this._s._needKey('safe media')
194
+ const s = this._slot(message, ref)
195
+ if (!this.available) return { ok: false, error: 'safe_media_unavailable' }
196
+ const idToken = this._idToken()
197
+ try {
198
+ const got = await this._s.attachment(s.att)
199
+ const made = await this._made(fromB64(got.b64), s.kind, s.att.mime || got.mime || '', idToken)
200
+ return await this._post({ id: message.id, at: s.at, i: s.i }, made, from)
201
+ } catch (e) { return { ok: false, error: String((e && (e.code === 'too_large' ? 'too_large' : e.message)) || e) } }
202
+ }
203
+
204
+ /** @private at send: start making the copies of a message's photos and PDFs (only while the setting is on, signed in). */
205
+ async _prepare (msg) {
206
+ if (!(msg.images || []).length && !(msg.files || []).some((a) => isPdf(a) || isImg(a))) return
207
+ if (this.on === false || !this.available) return // `on`, not `_on`: a lane follows its Space (sync sweep 2026-10-29 #7)
208
+ const c = this._s._client
209
+ if (!c || c.keyless || typeof c.safeCopy !== 'function') return
210
+ if (this.on === null) { try { await this.refresh() } catch { return } } // once per handle: the first photo sent asks the room
211
+ if (this.on !== true) return
212
+ let idToken; try { idToken = this._idToken() } catch { return } // signed out: the message goes, anyone may make() later
213
+ const made = []
214
+ const start = (at, i, a, kind) => {
215
+ if (!a || typeof a.b64 !== 'string') return
216
+ let bytes; try { bytes = fromB64(a.b64) } catch { return }
217
+ made.push({ at, i, p: this._made(bytes, kind, a.mime || '', idToken).catch(() => null) })
218
+ }
219
+ ;(msg.images || []).forEach((a, i) => start('images', i, a, 'image'))
220
+ ;(msg.files || []).forEach((a, i) => { if (isPdf(a)) start('files', i, a, 'pdf'); else if (isImg(a)) start('files', i, a, 'image') })
221
+ if (made.length) this._sent.push({ sig: sigOf(msg), made, at: Date.now() })
222
+ }
223
+
224
+ /** @private THE ASSISTANT'S PHOTOS TOO (the app's messageRender.js autoSafe + safeMediaRoom.js `auto`; docs/safe-media.md § 11;
225
+ * sync sweep 2026-11-13): show_photo and fetch_url put pictures from web pages into its replies, and no device sent them, so
226
+ * nobody made their copy at send. A RECENT one with no copy after a short wait (another member's device may be making it) is
227
+ * made here — the bytes go to the tools enclave, nothing is decoded on this device. Once per photo per handle; signed out, a
228
+ * keyless client (a vault) or a failure: it waits for make(), as before. Its PDFs are left alone (write_pdf's are our own). */
229
+ _autoAgent (m) {
230
+ if (this.on !== true || !this.available || /^sh:/.test(String(m.id))) return // a lane's copy of its Space's line: the Space's handle makes it
231
+ const c = this._s._client
232
+ if (!c || c.keyless || typeof c.safeCopy !== 'function' || !(Number(m.ts) > Date.now() - AUTO_SAFE_MS)) return
233
+ const todo = (Array.isArray(m.images) ? m.images : []).map((_a, i) => i).filter((i) => !this._autoTried.has(slotKey({ id: m.id, at: 'images', i })))
234
+ if (!todo.length) return
235
+ for (const i of todo) this._autoTried.add(slotKey({ id: m.id, at: 'images', i }))
236
+ const t = setTimeout(async () => {
237
+ for (const i of todo) {
238
+ if ((this._copies.get(slotKey({ id: m.id, at: 'images', i })) || []).length || this._s._stopped) continue // a copy came meanwhile
239
+ try { await this.make(m, { at: 'images', i }) } catch { /* signed out: Make safe stays the way */ }
240
+ }
241
+ }, this._d.autoWaitMs ?? AUTO_SAFE_WAIT_MS)
242
+ try { t.unref?.() } catch { /* a browser timer */ }
243
+ }
244
+
245
+ /** @private a stored message arrived: if this handle sent it, its copies go beside it; the assistant's recent photos get theirs. */
246
+ _arrived (m) {
247
+ if (m && m.self && !m.sys && m.id != null) { this._autoAgent(m); return }
248
+ if (!this._sent.length || !m || m.self || m.sys || m.id == null) return
249
+ this._sent = this._sent.filter((x) => Date.now() - x.at < 10 * 60_000) // a message the room never gave back is let go
250
+ const k = this._sent.findIndex((x) => x.sig === sigOf(m))
251
+ if (k < 0) return
252
+ const [x] = this._sent.splice(k, 1)
253
+ ;(async () => { for (const y of x.made) { const made = await y.p; if (made) await this._post({ id: m.id, at: y.at, i: y.i }, made).catch(() => null) } })()
254
+ }
255
+ }
@@ -0,0 +1,39 @@
1
+ import { SCHEDULES_DOC, ALWAYSON_DOC, alwaysOnNow, jobsOf, withJob, withoutJob, withPaused, summaryOf } from './schedulesDoc.js'
2
+
3
+ const fail = (code, message, status) => Object.assign(new Error('witbitz: ' + message), { code, ...(status ? { status } : {}) })
4
+
5
+ /** The same sealed schedule document edited by the app and executed by the cloud device. */
6
+ export class SpaceSchedules {
7
+ constructor(space) { this._sp = space }
8
+ async _read(name) {
9
+ const s = this._sp, r = await s._client.state(s.room, s._mk, name)
10
+ if (!r || r.status !== 200 || !Number.isInteger(r.v)) throw fail((r && r.error) || 'unreadable', 'the schedule document could not be read', r && r.status)
11
+ return r
12
+ }
13
+ async list() { const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'list'); return jobsOf(await this._read(SCHEDULES_DOC)) }
14
+ async _edit(fn, needsDevice = false) {
15
+ const s = this._sp
16
+ if (needsDevice && !alwaysOnNow(await this._read(ALWAYSON_DOC))) throw fail('not_always_on', 'this Space needs an active cloud device for schedules')
17
+ for (let i = 0; i < 5; i++) {
18
+ const cur = await this._read(SCHEDULES_DOC), jobs = fn(jobsOf(cur))
19
+ const r = await s._client.state(s.room, s._mk, SCHEDULES_DOC, { jobs }, summaryOf(jobs), s._who(), cur.v)
20
+ if (r && r.status === 409) continue
21
+ if (!r || r.status !== 200) throw fail((r && r.error) || 'save_failed', 'the schedules could not be saved', r && r.status)
22
+ s._kick()
23
+ if (s._wb && s._wb.cloudDevice) s._wb.cloudDevice._ask('sched', { room: s.room }).catch(() => {})
24
+ return jobs
25
+ }
26
+ throw fail('version_conflict', 'the schedules kept changing; try again', 409)
27
+ }
28
+ async add({ when, text } = {}) {
29
+ const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'add', { when, text })
30
+ let id
31
+ const jobs = await this._edit((jobs) => { const next = withJob(jobs, { when, text, by: this._sp._who() }); id = next.at(-1).id; return next }, true)
32
+ return jobs.find((j) => j.id === id)
33
+ }
34
+ async remove(id) { const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'remove', id); return this._edit((jobs) => withoutJob(jobs, id)) }
35
+ async pause(id, paused = true) {
36
+ const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'pause', id, !!paused)
37
+ return this._edit((jobs) => { if (!jobs.some((j) => j.id === id)) throw fail('not_found', 'that schedule does not exist'); return withPaused(jobs, id, !!paused) }, !paused)
38
+ }
39
+ }
package/sdkSpeech.js ADDED
@@ -0,0 +1,54 @@
1
+ // sdkSpeech.js — wb.speak(text): text read aloud on a builder's page, the same player the Spaces app's "Play aloud" uses
2
+ // (speechOut.js).
3
+ //
4
+ // await wb.speak('Your table is booked for 8.') // resolves when it has finished playing
5
+ // wb.speech.stop() // stop what is playing
6
+ // wb.speech.playing // true while it plays
7
+ //
8
+ // The text goes STRAIGHT from the page to Tinfoil's attested speech model — never through Witbitz. Witbitz only mints the
9
+ // page a short-lived, capped key (op:'tts', agent/sttKey.mjs), and only for a signed-in person (wb.signIn) or a user the
10
+ // tenant's backend vouched for (wb.useUserToken), as dictation does. A long text is cut at sentence ends; each request is
11
+ // $0.002 whatever its length. https://witbitz.chat/docs/sdk-assistant.md#speak.
12
+ // ⚑ No Hebrew: Hebrew-dominant text is refused (`no_hebrew`) before anything is spent. ⚑ The page's own CSP must allow
13
+ // `connect-src https://inference.tinfoil.sh` and `media-src blob:`; playback needs a user gesture on most browsers.
14
+ import { createTtsPlayer } from './speechOut.js'
15
+
16
+ const err = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
17
+
18
+ export class Speech {
19
+ constructor (wb, { fetchImpl, AudioImpl, URLImpl, checkKey } = {}) { // checkKey: a test seam — the page's own evidence check (voiceAttest.js) by default
20
+ this._wb = wb
21
+ this._player = createTtsPlayer({ getKey: () => this._key(), ...(checkKey ? { checkKey } : {}), ...(fetchImpl ? { fetchImpl } : {}), ...(AudioImpl ? { AudioImpl } : {}), ...(URLImpl ? { URLImpl } : {}) })
22
+ }
23
+
24
+ /** true while something is playing. */
25
+ get playing () { return this._player.playing }
26
+
27
+ /** @private the page's key (op:'tts'): a signed-in session first (the person), else the tenant's user token. */
28
+ async _key () {
29
+ const wb = this._wb, sess = wb._session
30
+ const idToken = sess && sess.idToken && !(sess.exp && sess.exp <= Date.now()) ? sess.idToken : ''
31
+ let userToken = ''
32
+ try { const t = typeof wb._userToken === 'function' ? await wb._userToken() : wb._userToken; userToken = typeof t === 'string' ? t : '' } catch { userToken = '' }
33
+ if (!idToken && !userToken && !wb.vault) throw err('sign_in_required', 'speak needs a signed-in user (wb.signIn) or a user token (wb.useUserToken)') // in a vault, the vault's sign-in mints the key
34
+ const r = await wb._client.tts(idToken, userToken)
35
+ if (!r || r.status !== 200 || !r.key) {
36
+ const code = (r && r.error === 'signin_required') ? 'sign_in_required' : (r && r.status === 429) ? 'tts_rate_limited' : 'tts_unavailable'
37
+ throw Object.assign(err(code, 'reading aloud is unavailable: ' + String((r && (r.reason || r.error)) || 'HTTP ' + (r && r.status))), { status: r && r.status })
38
+ }
39
+ return r
40
+ }
41
+
42
+ /** Read `text` aloud → resolves when it has played. Rejects with `code`: `no_hebrew`, `empty`, `sign_in_required`,
43
+ * `tts_rate_limited`, `tts_unavailable`, `http_<status>`, `audio` / `play` (the browser would not play it). A new call
44
+ * stops the one playing. */
45
+ async play (text) {
46
+ try { await this._player.play(String(text == null ? '' : text)) } catch (e) {
47
+ if (e && e.code && !String(e.message || '').startsWith('witbitz:')) e.message = 'witbitz: ' + e.message
48
+ throw e
49
+ }
50
+ }
51
+
52
+ /** Stop what is playing (its promise resolves). */
53
+ stop () { this._player.stop() }
54
+ }
package/sdkTurn.js ADDED
@@ -0,0 +1,117 @@
1
+ // sdkTurn.js — a turn you can hold (https://witbitz.chat/docs/sdk-roadmap.md, item 6, 2026-10-05).
2
+ //
3
+ // `space.send()` keeps the room's semantics: it posts a message, and whatever the room does next (the assistant replies,
4
+ // stays quiet, someone else speaks) arrives on `on('message')`. Builders asked for the other shape too — "I sent this,
5
+ // tell me when ITS answer is done" — and wired it by hand from three events. `space.turn(text)` is that shape:
6
+ //
7
+ // const t = space.turn('Plan the trip', { timeoutMs: 120_000 })
8
+ // t.on('partial', ({ text }) => draw(text)) // the reply as it streams (this turn only)
9
+ // const { status, reply } = await t.finished // 'done' | 'silent' | 'failed' | 'aborted' | 'timeout'
10
+ // t.abort() // stop it: the text streamed so far is kept as the reply
11
+ //
12
+ // HOW THE REPLY IS FOUND. The turn request returns when the server has finished the turn (with the reply's text), or is
13
+ // cut at ~30 s by the API front door while the server goes on (`pending`). The reply MESSAGE arrives through the poll. A
14
+ // room runs one reply at a time (the server answers `busy` and the SDK resends), so the first assistant message that
15
+ // lands after the attempt that actually ran is this turn's — matched by its text when the server gave it, else by order.
16
+ // `finished` never rejects: the status says what happened, and `error` carries the server's code when there is one.
17
+ import { turnVerdict, QUEUE_MAX_TRIES, QUEUE_RETRY_MS } from './turnVerdict.js'
18
+
19
+ /** A turn's usage as a builder reads it (Tomer, 2026-10-10: "tokens in/out/cached and the cost, so we can measure a turn
20
+ * without waiting for daily billing"), from the record the server keeps on the reply (agent/turnUsage.mjs). `costMicros`
21
+ * is the PROVIDER's figure in millionths of a dollar; `source` 'provider-partial'/'none' = some calls reported no cost
22
+ * (the total then counts only the priced ones). null when the turn made no model call. */
23
+ export function turnUsage (rec) {
24
+ if (!rec || typeof rec !== 'object' || !Number.isFinite(rec.in)) return null
25
+ const n = (v) => (Number.isFinite(v) ? v : 0)
26
+ return {
27
+ tokensIn: n(rec.in), tokensOut: n(rec.out), tokensCached: n(rec.cached),
28
+ costMicros: n(rec.costMicros), costUsd: n(rec.costMicros) / 1e6,
29
+ calls: n(rec.calls), models: Array.isArray(rec.models) ? rec.models.slice() : [],
30
+ source: typeof rec.source === 'string' ? rec.source : 'none',
31
+ ...(rec.estimated ? { estimated: true } : {}), ...(rec.funded ? { funded: true } : {}),
32
+ }
33
+ }
34
+
35
+ // THE APP'S WAIT (docs sync, 2026-11-22): the Spaces app holds a send for QUEUE_MAX_TRIES × QUEUE_RETRY_MS (~16 min, turnVerdict.js),
36
+ // longer than the longest turn the server runs (13 min, under the 900 s Lambda, since 2026-11-18). This was 180 s — the old hold —
37
+ // so a long, healthy turn timed out here and was STOPPED (`_stop`). One constant now; spaces/test/sdkTurnWait.test.mjs holds it.
38
+ export const TURN_TIMEOUT_MS = QUEUE_MAX_TRIES * QUEUE_RETRY_MS
39
+
40
+ const randStopKey = () => {
41
+ const a = new Uint8Array(18); crypto.getRandomValues(a)
42
+ return btoa(String.fromCharCode(...a)).replace(/[^A-Za-z0-9]/g, '').slice(0, 24)
43
+ }
44
+ const isReply = (m) => !!(m && m.self && !m.sys)
45
+
46
+ export class Turn {
47
+ /** Use `space.turn(text, opts)`. */
48
+ constructor(space, text, { timeoutMs = TURN_TIMEOUT_MS, ...sendOpts } = {}) {
49
+ this._space = space
50
+ this._subs = {}
51
+ this._stopKey = randStopKey()
52
+ this._mark = null // messages.length when the attempt that RAN was posted
53
+ this._replyText = null // the server's word on the reply, when it gave one
54
+ /** 'running' until it settles; then 'done' | 'silent' | 'failed' | 'aborted' | 'timeout'. */
55
+ this.status = 'running'
56
+ /** The reply as it has streamed so far ('' before the first token). */
57
+ this.text = ''
58
+ /** The send() result, once the server answered. */
59
+ this.result = null
60
+ this.finished = new Promise((res) => { this._resolve = res })
61
+ this._onPartial = (p) => { if (this.status !== 'running' || p.text == null) return; this.text = p.text; this._emit('partial', p) }
62
+ this._onMessage = () => this._look()
63
+ space.on('partial', this._onPartial)
64
+ space.on('message', this._onMessage)
65
+ this._timer = timeoutMs > 0 ? setTimeout(() => { this._settle('timeout'); this._stop() }, timeoutMs) : null
66
+ space.send(text, { ...sendOpts, stopKey: this._stopKey, _onAttempt: () => { this._mark = space.messages.length }, _aborted: () => this.status !== 'running' }) // aborted OR timed out: a held message is never resent after the turn settled
67
+ .then((r) => this._answered(r), (e) => this._settle('failed', { error: (e && e.code) || String((e && e.message) || e) }))
68
+ }
69
+
70
+ /** Listen: 'partial' ({ text, step }) while it streams, 'done' (the settled result). Returns an unsubscribe function. */
71
+ on(event, cb) { (this._subs[event] ||= []).push(cb); return () => { this._subs[event] = (this._subs[event] || []).filter((x) => x !== cb) } }
72
+ _emit(event, arg) { for (const cb of (this._subs[event] || [])) { try { cb(arg) } catch { /* a listener must not break the turn */ } } }
73
+
74
+ /** Stop the reply. The server keeps what streamed so far as the reply; `finished` settles as 'aborted'. */
75
+ async abort() {
76
+ if (this.status !== 'running') return false
77
+ this._settle('aborted')
78
+ await this._stop()
79
+ return true
80
+ }
81
+ async _stop() { try { await this._space._client.stop(this._space.room, this._stopKey) } catch { /* a stop that cannot be sent leaves the turn to finish */ } }
82
+
83
+ _answered(r) {
84
+ this.result = r
85
+ const v = turnVerdict(r)
86
+ if (v.kind === 'silent') return this._settle('silent')
87
+ if (v.kind === 'ok') { this._replyText = typeof r.reply === 'string' ? r.reply : null; if (this._replyText === '') return this._settle('silent'); return this._look() }
88
+ if (r && r.pending) return this._look() // cut at the front door; the reply still comes on the poll
89
+ // NO ANSWER at all (status 0) settles as failed with its code — it MAY have posted (sdk.md): read the room before resending
90
+ this._settle('failed', { error: (r && r.error) || v.code || v.kind, reason: (r && r.reason) || v.reason }) // the server's sentence too (sweep 11-04 P3: TurnResult had no reason)
91
+ }
92
+
93
+ // Is this turn's reply in `messages` yet?
94
+ _look() {
95
+ if (this.status !== 'running' || this._mark === null) return
96
+ if (this.result === null) return // the request is still out: a reply that lands now may be a previous turn's
97
+ const list = this._space.messages
98
+ const after = list.slice(this._mark).filter(isReply)
99
+ const m = (this._replyText ? after.find((x) => String(x.text || '') === this._replyText) : null) || after[0]
100
+ if (m) this._settle(m.stopped ? 'aborted' : 'done', { reply: m })
101
+ }
102
+
103
+ _settle(status, extra = {}) {
104
+ if (this.status !== 'running') return
105
+ this.status = status
106
+ clearTimeout(this._timer)
107
+ this._space.off('partial', this._onPartial)
108
+ this._space.off('message', this._onMessage)
109
+ const reply = extra.reply || null
110
+ if (reply && typeof reply.text === 'string') this.text = reply.text
111
+ // usage: from the turn's answer, else (a turn cut at the 30 s front door) from the stored reply, which carries it too
112
+ const usage = (this.result && this.result.usage) || turnUsage(reply && reply.usage)
113
+ const out = { status, reply, text: this.text, proposed: (this.result && Array.isArray(this.result.proposed)) ? this.result.proposed : [], ...(usage ? { usage } : {}), ...(extra.error ? { error: String(extra.error) } : {}), ...(extra.reason ? { reason: String(extra.reason).slice(0, 500) } : {}) }
114
+ this._emit('done', out)
115
+ this._resolve(out)
116
+ }
117
+ }
package/sdkVault.js ADDED
@@ -0,0 +1,124 @@
1
+ // sdkVault.js — the SDK's side of a BUILDER-HOSTED VAULT (docs/sdk-vault-mode.md).
2
+ //
3
+ // A builder's page runs framed by a vault on another origin the builder also serves. The vault (vault-core.js) holds the
4
+ // room keys in its own worker; this page never does. Every room operation goes up as a message and its answer comes
5
+ // back — the page sends the room id and the operation, never a key, and gets back what the operation returns.
6
+ //
7
+ // The wire, on the `wbvault` channel, origin-pinned BOTH ways:
8
+ // page → vault { ch:'wbvault', t:'hello', v } the handshake; the vault answers { t:'welcome', v, tenant, endpoint, signedIn, email, rooms }
9
+ // page → vault { ch:'wbvault', t:'call', id, op, args } one request; the vault answers { t:'res', id, result } or { t:'res', id, error, code }
10
+ // vault → page { ch:'wbvault', t:'event', ev, ... } rooms changed / joined / signed in or out / a room's stream
11
+ // vault → page { ch:'wbvault', t:'ask', id, kind, ... } the vault needs the page's answer (a Siri drop for its deliver);
12
+ // the page replies with the call `answer(id, { result } | { error })`
13
+ // The page posts ONLY to the pinned vault origin (never '*') and accepts ONLY messages from that origin AND from the
14
+ // window that frames it — a page we did not write must not broadcast, and nothing else on the page may answer for the vault.
15
+ import { WORKER_OPS } from './workerClient.js'
16
+
17
+ export const VAULT_PROTOCOL = 1
18
+ const HELLO_MS = 8000 // the vault's welcome; past it the page is not in a vault (or the vault is not answering)
19
+ const CALL_MS = 120_000 // one operation; a turn can run a while — the vault answers when the server does
20
+ // …but a call that HOLDS A SCREEN for the person (a code from their mail, writing the recovery code down, a confirm) waits for
21
+ // them: at 120 s the page gave up with vault_timeout while the vault went on — a retried fork made a second room (sync sweep 10-22 #8)
22
+ const PERSON_MS = 15 * 60_000
23
+ const PERSON_OPS = new Set(['signIn', 'signOut', 'fork', 'follow', 'share', 'forget', 'changeMembers', 'rotateKey', 'account', 'roomAccount', 'lockSettings', 'notifications'])
24
+ // …and a call that may WAKE a confidential Space's enclave: a confidential create waits up to 45 × 8 s for it, a lane's create may
25
+ // wake it twice — past 120 s the page gave up while the vault went on, and a retry made a second room (sync sweep 11-04 P7)
26
+ const WAKE_MS = 15 * 60_000
27
+ const WAKE_OPS = new Set(['create', 'createLane'])
28
+
29
+ const isOrigin = (s) => typeof s === 'string' && /^https?:\/\/[^/?#]+$/.test(s)
30
+
31
+ /** Connect to the vault that frames this page. Resolves to a KEYLESS client the SDK's Space runs on, plus the vault's own
32
+ * calls (create, rooms, share, signIn, signOut). Rejects with `not_in_vault` when the page is not framed by that origin. */
33
+ export function connectVault({ vault, win = (typeof window !== 'undefined' ? window : null), helloMs = HELLO_MS } = {}) {
34
+ const origin = String(vault || '').replace(/\/+$/, '')
35
+ if (!isOrigin(origin)) return Promise.reject(Object.assign(new Error('witbitz: `vault` must be the vault\'s origin, e.g. https://vault.example.com'), { code: 'invalid_argument' }))
36
+ if (!win || win.top === win) return Promise.reject(Object.assign(new Error('witbitz: this page is not framed by a vault — open the vault (' + origin + '), which opens this page inside it'), { code: 'not_in_vault' }))
37
+ const top = win.top
38
+ const waiting = new Map()
39
+ const listeners = new Set()
40
+ const askers = new Map() // kind → room → the page's handler for the vault's question
41
+ const streams = new Map() // room → the handlers of every Space on this page showing it (the vault holds one socket per room)
42
+ let seq = 0
43
+ let welcome = null
44
+ let onWelcome = null
45
+ win.addEventListener('message', (e) => {
46
+ if (e.origin !== origin || e.source !== top) return // only the vault that frames us
47
+ const d = e.data
48
+ if (!d || d.ch !== 'wbvault') return
49
+ if (d.t === 'welcome') { welcome = d; if (onWelcome) onWelcome(d); return }
50
+ if (d.t === 'res') {
51
+ const w = waiting.get(d.id); if (!w) return
52
+ waiting.delete(d.id); clearTimeout(w.timer)
53
+ if (d.error) w.rej(Object.assign(new Error(String(d.error)), { code: d.code || 'vault_refused', status: d.status, ...(d.code === 'wrong_pin' && Number.isSafeInteger(d.next) && d.next >= 0 ? { next: d.next } : {}), ...(Array.isArray(d.unavailable) ? { unavailable: d.unavailable } : {}), ...(typeof d.reason === 'string' ? { reason: d.reason } : {}), ...(d.verdict && typeof d.verdict === 'object' ? { verdict: d.verdict } : {}) })); else w.res(d.result)
54
+ return
55
+ }
56
+ if (d.t === 'ask' && typeof d.id === 'number') {
57
+ const fn = (askers.get(d.kind) || new Map()).get(d.room)
58
+ Promise.resolve().then(() => { if (!fn) throw new Error('nothing on this page takes ' + String(d.kind).slice(0, 30)); return fn(d) })
59
+ .then((result) => call('answer', d.id, { result: result === undefined ? null : result }), (err) => call('answer', d.id, { error: String((err && err.message) || err || 'refused').slice(0, 200) })).catch(() => {})
60
+ return
61
+ }
62
+ if (d.t === 'event' && d.ev === 'stream') { for (const fn of streams.get(d.room) || []) { try { fn(d) } catch { /* */ } } return }
63
+ if (d.t === 'event') { for (const fn of listeners) { try { fn(d) } catch { /* a listener's error is its own */ } } }
64
+ })
65
+ const post = (msg) => top.postMessage({ ch: 'wbvault', ...msg }, origin)
66
+ const call = (op, ...args) => new Promise((res, rej) => {
67
+ const id = ++seq
68
+ const timer = setTimeout(() => { if (waiting.delete(id)) rej(Object.assign(new Error('witbitz: the vault did not answer (' + op + ')'), { code: 'vault_timeout' })) }, PERSON_OPS.has(op) ? PERSON_MS : WAKE_OPS.has(op) ? WAKE_MS : CALL_MS)
69
+ waiting.set(id, { res, rej, timer })
70
+ try { post({ t: 'call', id, op, args }) } catch (err) { waiting.delete(id); clearTimeout(timer); rej(err) }
71
+ })
72
+ return new Promise((resolve, reject) => {
73
+ const done = (w) => {
74
+ clearTimeout(timer)
75
+ // THE KEYLESS CLIENT: the same shape workerClient gives the Spaces app — each op takes (room, mk, …rest) and drops mk.
76
+ const client = { keyless: true, vault: origin }
77
+ for (const op of [...WORKER_OPS, 'sealed', 'exportSealed']) client[op] = (room, _mk, ...rest) => call('op', op, room, ...rest) // sealed/exportSealed: the stored ciphertext, for sealedProof
78
+ client.stop = (room, key) => call('op', 'stop', room, key) // turn.abort(): stop the turn on the server — it needs no key, the vault sends it (sync sweep 10-15 #3)
79
+ // SPEECH KEYS (dictation, reading aloud): minted by the vault with ITS sign-in; the idToken argument is the page's (none)
80
+ client.stt = (_idToken, userToken) => call('speechKey', 'stt', userToken || '')
81
+ client.tts = (_idToken, userToken) => call('speechKey', 'tts', userToken || '')
82
+ // ROOM STREAMS: the socket lives in the vault's worker (it needs the key); the page gets its events. The worker
83
+ // keeps the stream in step from the polls it runs, so the page's handle has nothing to sync.
84
+ client.streamOpen = (room, onEvent, onState) => {
85
+ const fn = (d) => { if (d.event) onEvent(d.event); else if ('up' in d && onState) onState(!!d.up) }
86
+ let set = streams.get(room)
87
+ if (!set) { set = new Set(); streams.set(room, set); call('stream', room, true).catch(() => { streams.delete(room) }) } // refused or not held: the Space keeps polling
88
+ set.add(fn)
89
+ return { stop: () => { if (set.delete(fn) && !set.size && streams.get(room) === set) { streams.delete(room); call('stream', room, false).catch(() => {}) } }, setGrants: () => {}, sync: () => {} }
90
+ }
91
+ const v = {
92
+ origin, client, info: w,
93
+ create: (cfg, opts) => call('create', cfg, ...(opts ? [opts] : [])), // opts { enclave }: dropping it would make a STANDARD Space where a confidential one was asked
94
+ rooms: () => call('rooms'),
95
+ share: (room, opts) => call('share', room, opts || {}),
96
+ signIn: (opts) => call('signIn', opts || {}),
97
+ signOut: () => call('signOut'),
98
+ userToken: (t) => call('userToken', t), // per-user billing: the page's current token, handed over before an op that can spend
99
+ whoami: () => call('whoami'),
100
+ lockSettings: () => call('lockSettings'), // the vault's lock sheet (a vault started with `lock: true`): the person decides there; the page learns { available, on, protect }
101
+ notifications: () => call('notifications'), // the vault's notifications card (`push: true`): the person decides; the page learns { available, on }
102
+ forget: (room) => call('forget', room),
103
+ createLane: (shared, cfg, o) => (o ? call('createLane', shared, cfg, o) : call('createLane', shared, cfg)), // o { open }: the page asked for an admission that is not a sign-in (refused in a verified Space)
104
+ fork: (room, opts) => call('fork', room, opts),
105
+ changeMembers: (room, admission) => call('changeMembers', room, admission), // a member change in place: the vault makes and keeps the new key (sdkRekey.js)
106
+ rotateKey: (room) => call('rotateKey', room),
107
+ follow: (room, id) => call('follow', room, id),
108
+ announce: (room) => call('announce', room),
109
+ account: (ns, m, ...a) => call('account', ns, m, ...a),
110
+ roomAccount: (room, ns, m, ...a) => call('roomAccount', room, ns, m, ...a),
111
+ onAsk: (kind, room, fn) => { if (!askers.has(kind)) askers.set(kind, new Map()); askers.get(kind).set(room, fn); return () => { const m = askers.get(kind); if (m && m.get(room) === fn) m.delete(room) } },
112
+ on: (fn) => { listeners.add(fn); return () => listeners.delete(fn) },
113
+ }
114
+ resolve(v)
115
+ }
116
+ let stopped = false
117
+ const timer = setTimeout(() => { stopped = true; reject(Object.assign(new Error('witbitz: the vault at ' + origin + ' did not answer — is this page framed by it?'), { code: 'not_in_vault' })) }, helloMs)
118
+ if (welcome) return done(welcome)
119
+ onWelcome = (w) => { onWelcome = null; done(w) }
120
+ // the vault may still be starting its worker: say hello until it answers (or the wait ends)
121
+ const hello = () => { if (welcome || stopped) return; try { post({ t: 'hello', v: VAULT_PROTOCOL }) } catch { /* */ } setTimeout(hello, 250) }
122
+ hello()
123
+ })
124
+ }
package/sealShare.js ADDED
@@ -0,0 +1,18 @@
1
+ // sealShare.js — seal a bundle to an enclave's attested ECDH P-384 share key: the scheme the Sentinel's crypto.go
2
+ // `openShare` and the cloud computer's vm/crypto.go undo. One ephemeral P-384 key, ECDH → HKDF-SHA-256 (salt = the
3
+ // attest nonce, info "witbitz-cc share v1") → AES-GCM-256 with the nonce as AAD. Shared by codeCloud.js (a cloud
4
+ // computer's grant) and connections.js (a standing connection), so the wire has exactly one page-side writer.
5
+ const enc = new TextEncoder()
6
+ const b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
7
+
8
+ /** @returns {{ epk: string, iv: string, ct: string, nonce: string }} — all standard base64 */
9
+ export async function sealTo(enclaveKey, nonce, bundle) {
10
+ const eph = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-384' }, true, ['deriveBits'])
11
+ const shared = await crypto.subtle.deriveBits({ name: 'ECDH', public: enclaveKey }, eph.privateKey, 384)
12
+ const hk = await crypto.subtle.importKey('raw', shared, 'HKDF', false, ['deriveKey'])
13
+ const key = await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: nonce, info: enc.encode('witbitz-cc share v1') }, hk, { name: 'AES-GCM', length: 256 }, false, ['encrypt'])
14
+ const iv = crypto.getRandomValues(new Uint8Array(12))
15
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: nonce }, key, enc.encode(JSON.stringify(bundle))))
16
+ const epk = new Uint8Array(await crypto.subtle.exportKey('raw', eph.publicKey))
17
+ return { epk: b64(epk), iv: b64(iv), ct: b64(ct), nonce: b64(nonce) }
18
+ }