@witbitz/sdk 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/blocks.js ADDED
@@ -0,0 +1,115 @@
1
+ // blocks.js — BLOCK A PERSON (App Store rule 1.2; docs/report-and-block.md §4; the owner, 2026-11-07: blocked messages are
2
+ // collapsed with "Show", never gone). Everything happens on your own devices: their messages collapse here, nothing changes for
3
+ // anyone else in the room (an admin can still remove them — Change members).
4
+ //
5
+ // WHO can be blocked is decided by what proves who wrote a message, never by the typed name — every proof the device has, kept
6
+ // together, a message matching ANY of them (the owner, 2026-11-08: "Yes" to keying Block on the verified identity):
7
+ // { email } the verified email the room recorded for the key that signed it (roster_seen, senderNames.attestedIdentity) —
8
+ // the same person on every device, in every Space, whatever they rename themselves to
9
+ // { user } the @username the SERVER stamped on a verified room's message — every room, until they rename
10
+ // { room, sid } the key that signed it, in that room only (a person with no verified identity; any signed message)
11
+ // A message with none offers no Block. One entry per person: keyed on the email, else the username, else the key. Kept in localStorage `space:blocks` (durable; in the hosted app it goes to the vault
12
+ // like every key) and synced to your other devices as the account document `blocks` (roomSync.js syncBlocks). An unblock is
13
+ // kept as a tombstone (`gone`) so a device that still lists the person does not bring them back: the newer `at` wins.
14
+ export const BLOCKS_KEY = 'space:blocks'
15
+ export const BLOCKS_DOC = 'blocks'
16
+ const MAX = 500
17
+
18
+ const EMAIL = /^[^@\s]{1,64}@[^@\s]{1,190}\.[^@\s]{1,60}$/
19
+ const keyOf = (b) => (b.email ? 'e:' + String(b.email).toLowerCase() : b.user ? 'u:' + String(b.user).toLowerCase() : b.room && b.sid ? 's:' + b.room + '|' + b.sid : '')
20
+ /** Does this list entry name the writer `who` ({ email?, user?, room?, sid? })? Any proof the two share. */
21
+ const names = (b, who) => !!who && ((b.email && who.email && b.email === String(who.email).toLowerCase()) ||
22
+ (b.user && who.user && b.user === String(who.user).toLowerCase()) ||
23
+ (b.room && b.sid && who.room === b.room && who.sid === b.sid))
24
+
25
+ /** A clean list: known fields only, one entry per person (the newest), at most MAX. */
26
+ export function cleanBlocks(list) {
27
+ const by = new Map()
28
+ for (const b of Array.isArray(list) ? list : []) {
29
+ if (!b || typeof b !== 'object') continue
30
+ const e = {
31
+ ...(typeof b.email === 'string' && EMAIL.test(b.email) ? { email: b.email.toLowerCase() } : {}),
32
+ ...(typeof b.user === 'string' && /^[a-z0-9_.-]{1,40}$/i.test(b.user) ? { user: b.user.toLowerCase() } : {}),
33
+ ...(typeof b.room === 'string' && b.room.length <= 80 && typeof b.sid === 'string' && b.sid.length <= 200 ? { room: b.room, sid: b.sid } : {}),
34
+ name: typeof b.name === 'string' ? b.name.slice(0, 80) : '',
35
+ at: Number.isFinite(+b.at) ? +b.at : 0,
36
+ ...(b.gone === true ? { gone: true } : {}),
37
+ }
38
+ const k = keyOf(e); if (!k) continue
39
+ const was = by.get(k); if (!was || e.at >= was.at) by.set(k, e)
40
+ }
41
+ // ⛔ AN UNBLOCK NAMES THE PERSON, NOT ONE KEY (2026-11-09, docs/state-machines.md C#18): a tombstone keyed on the email left an
42
+ // older live entry of the same person kept under another proof (a key-only block from another device) — it still named them,
43
+ // and the merge blocked them again everywhere. A newer unblock retires every older block it shares a proof with.
44
+ const gone = [...by.values()].filter((g) => g.gone)
45
+ for (const [k, b] of by) if (!b.gone) { const g = gone.find((t) => t.at >= b.at && names(t, b)); if (g) by.set(k, { ...b, name: '', at: g.at, gone: true }) }
46
+ return [...by.values()].sort((a, b) => b.at - a.at).slice(0, MAX)
47
+ }
48
+
49
+ /** Two devices' lists → one: per person the newer entry (a block or an unblock) wins. */
50
+ export const mergeBlocks = (a, b) => cleanBlocks([...(a || []), ...(b || [])])
51
+
52
+ let syncHook = null
53
+ export function setBlocksSync(fn) { syncHook = typeof fn === 'function' ? fn : null }
54
+ export function readBlocks() { try { return cleanBlocks(JSON.parse(localStorage.getItem(BLOCKS_KEY) || '[]')) } catch { return [] } }
55
+ function writeBlocks(list, { sync = true } = {}) {
56
+ const clean = cleanBlocks(list)
57
+ try { localStorage.setItem(BLOCKS_KEY, JSON.stringify(clean)) } catch { /* storage full: the list holds for this session */ }
58
+ try { window.dispatchEvent(new CustomEvent('wb-blocks')) } catch { /* not in a page */ }
59
+ if (sync && syncHook) { try { syncHook() } catch { /* */ } }
60
+ return clean
61
+ }
62
+ /** Another device's list arrived: merged in, no echo back. */
63
+ export function adoptBlocks(list) { return writeBlocks(mergeBlocks(readBlocks(), list), { sync: false }) }
64
+
65
+ /** Who wrote this entry, as Block knows a person → { email?, user?, room?, sid? } | null. `id`: what the room verified about
66
+ * its writer (senderNames.attestedIdentity → { email, user }), read by the caller. */
67
+ export function blockIdentity(room, e, { attested = false, sid = '', id = null } = {}) {
68
+ if (!e) return null
69
+ const out = {}
70
+ if (attested && e.verified === true) {
71
+ const email = id && typeof id.email === 'string' && EMAIL.test(id.email) ? id.email.toLowerCase() : ''
72
+ const user = (id && id.user) || (typeof e.user === 'string' ? e.user : '')
73
+ if (email) out.email = email
74
+ if (user && /^[a-z0-9_.-]{1,40}$/i.test(String(user).replace(/^@/, ''))) out.user = String(user).replace(/^@/, '').toLowerCase()
75
+ }
76
+ if (room && sid) { out.room = room; out.sid = sid }
77
+ return Object.keys(out).length ? out : null
78
+ }
79
+
80
+ export function isBlocked(who, list = readBlocks()) {
81
+ if (!who || !keyOf(who)) return false
82
+ // the newest word per person wins (cleanBlocks); a person is blocked when a live entry names them by any proof
83
+ return list.some((b) => !b.gone && names(b, who))
84
+ }
85
+
86
+ /** §4 "their invites are dropped" (sync sweep 2026-11-13 P5): an invite box is an anonymous drop, so only a DIRECT CHAT's invite
87
+ * says who sent it (`direct`: the sender's address, space.js). True when that address is blocked; a typed `from` is never matched.
88
+ * A forged address only drops the forger's own invite; a blocked person's messages collapse inside any room they reach anyway. */
89
+ export function blockedInvite(inv, list = readBlocks()) {
90
+ const a = inv && typeof inv.direct === 'string' ? inv.direct.trim() : ''
91
+ if (!a) return false
92
+ const who = a.startsWith('@') ? { user: a.slice(1).toLowerCase() } : (EMAIL.test(a) ? { email: a.toLowerCase() } : null)
93
+ return !!who && isBlocked(who, list)
94
+ }
95
+
96
+ export function block(who, name = '') { if (!keyOf(who || {})) return readBlocks(); return writeBlocks([...readBlocks(), { ...who, name, at: Date.now() }]) }
97
+ /** Every live entry that names this writer goes — one made from another of their proofs (an older key-only block) too. */
98
+ export function unblock(who) {
99
+ if (!keyOf(who || {})) return readBlocks()
100
+ const at = Date.now(), list = readBlocks()
101
+ const gone = list.filter((b) => !b.gone && names(b, who)).map((b) => ({ ...b, name: '', at, gone: true }))
102
+ return writeBlocks([...list, ...(gone.length ? gone : [{ ...who, name: '', at, gone: true }])])
103
+ }
104
+ export const blockedPeople = () => readBlocks().filter((b) => !b.gone)
105
+
106
+ /** The account document: read it, merge ours in, write it back when it differs (a pull when no `write`); never over an unknown state. */
107
+ export async function syncBlocksDocument({ read, write }) {
108
+ const r = await read()
109
+ if (!r || (r.status !== 200 && r.status !== 404)) return false
110
+ const theirs = r.status === 200 && r.state && Array.isArray(r.state.list) ? r.state.list : []
111
+ const merged = mergeBlocks(readBlocks(), theirs)
112
+ writeBlocks(merged, { sync: false })
113
+ if (write && JSON.stringify(cleanBlocks(theirs)) !== JSON.stringify(merged)) await write({ v: 1, list: merged }) // no `write`: a pull only
114
+ return true
115
+ }
package/blocksPush.js ADDED
@@ -0,0 +1,64 @@
1
+ // blocksPush.js — NO NOTIFICATION FROM A PERSON YOU BLOCKED (docs/report-and-block.md §4 (b); the owner, 2026-11-16: "Do b+c").
2
+ // The service worker shows a push without the app running and holds no list of yours, so the page leaves it one: `blocks:sw` in
3
+ // the 'spaces' idb the worker reads (in the hosted app, the VAULT's — its worker shows the notification), an array of HASHES of the
4
+ // blocked proofs a push can carry (agent/notif.mjs seals the writer's key `k` and, in a verified room, their `u` in the preview):
5
+ // 'u:' + @username a person blocked by their username
6
+ // 's:' + room + '|' + sid the key that signed in that room — a key-only block, or a key this device has SEEN carry a blocked
7
+ // email (a message never carries the email — the room's record maps key → email, blockView.js)
8
+ // A hash, not the names: a stolen disk reads no list of whom you blocked. The worker hashes what the push carried the same way
9
+ // (sw-notif-core wbxBlockedSender) and, on a match, shows the notification silently and closes it at once (iOS requires one).
10
+ // A push it cannot open (no preview key — "Show message preview" off on a protected device) is shown as before.
11
+ import { readBlocks } from './blocks.js'
12
+
13
+ export const BLOCKS_SW_KEY = 'blocks:sw'
14
+ const LEARNED_KEY = 'space:blocks:keys' // { email: ['room|sid', …] } — keys seen writing for a BLOCKED email (blockView noteBlockedKey)
15
+ const PER_EMAIL = 20, MAX_EMAILS = 200
16
+
17
+ const enc = new TextEncoder()
18
+ /** The worker's hash of one proof — sw-notif-core.js wbxBlockToken MUST stay byte-identical (a test asserts it). */
19
+ export async function blockToken (s) {
20
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(String(s))))
21
+ let b = ''; for (let i = 0; i < 16; i++) b += d[i].toString(16).padStart(2, '0')
22
+ return b
23
+ }
24
+
25
+ const readLearned = () => { try { const o = JSON.parse(localStorage.getItem(LEARNED_KEY) || '{}'); return o && typeof o === 'object' && !Array.isArray(o) ? o : {} } catch { return {} } }
26
+
27
+ /** A message of a BLOCKED email was drawn with the key that signed it: that key, in that room, is theirs (for the worker). */
28
+ export function noteBlockedKey (email, room, sid) {
29
+ if (!email || !room || !sid) return false
30
+ const l = readLearned(), e = String(email).toLowerCase(), k = room + '|' + sid
31
+ const was = Array.isArray(l[e]) ? l[e] : []
32
+ if (was.includes(k)) return false
33
+ const next = { ...l, [e]: [k, ...was].slice(0, PER_EMAIL) }
34
+ const keys = Object.keys(next); if (keys.length > MAX_EMAILS) for (const x of keys.slice(0, keys.length - MAX_EMAILS)) if (x !== e) delete next[x]
35
+ try { localStorage.setItem(LEARNED_KEY, JSON.stringify(next)) } catch { return false }
36
+ return true
37
+ }
38
+
39
+ /** The proofs a push can be matched on, for the live blocks → sorted, unique token list. */
40
+ export async function blockTokens (list = readBlocks(), learned = readLearned()) {
41
+ const raw = new Set()
42
+ for (const b of list) {
43
+ if (!b || b.gone) continue
44
+ if (b.user) raw.add('u:' + b.user)
45
+ if (b.room && b.sid) raw.add('s:' + b.room + '|' + b.sid)
46
+ if (b.email && Array.isArray(learned[b.email])) for (const k of learned[b.email]) raw.add('s:' + k)
47
+ }
48
+ return [...new Set(await Promise.all([...raw].map(blockToken)))].sort()
49
+ }
50
+
51
+ /** `store(tokens|null)` writes where this device's worker reads (null = remove it); `keep()` false = a locked device that keeps
52
+ * nothing clear for its worker (protection on, previews off — its pushes cannot be opened anyway). */
53
+ export function makeBlocksMirror ({ store, keep = () => true }) {
54
+ let last = '', chain = Promise.resolve()
55
+ const run = async () => {
56
+ let on = true; try { on = !!keep() } catch { on = true }
57
+ const tokens = on ? await blockTokens() : null
58
+ const sig = JSON.stringify(tokens)
59
+ if (sig === last) return
60
+ await store(tokens && tokens.length ? tokens : null)
61
+ last = sig
62
+ }
63
+ return () => (chain = chain.then(run, run).catch(() => {}))
64
+ }
package/browseSeal.js ADDED
@@ -0,0 +1,103 @@
1
+ // browseSeal.js — the envelope the agent's browser and the owner's phone share, and the only thing the relay ever
2
+ // carries (docs/cloud-computer.md § 12). ONE file, imported by both ends: the publisher inside the enclave
3
+ // (infra/cloud-computer/vm/browse-publisher.mjs, bundled) and the viewer page. A second implementation of a wire
4
+ // format is a second set of bugs, and this one has to agree byte for byte or nothing decodes.
5
+ //
6
+ // Why not e2ee.js's envelope: that one seals a STRING into a JSON object with a wrapped content key per recipient —
7
+ // right for a ledger entry, wrong for 249 binary frames a second, where base64 alone would add a third to the
8
+ // measured 267 KB/s. This is the same primitive (AES-256-GCM) with a fixed single recipient and no JSON at all:
9
+ //
10
+ // [ 1 byte kind ][ 12 byte iv ][ ciphertext+tag ]
11
+ //
12
+ // The kind byte is INSIDE the ciphertext's associated data, so a frame cannot be replayed as a control message.
13
+ const enc = new TextEncoder()
14
+ const dec = new TextDecoder()
15
+
16
+ export const KIND_RFB = 1 // raw bytes of KasmVNC's own protocol, in either direction
17
+ export const KIND_CTL = 2 // JSON: the viewer taking the controls, and the publisher's answer
18
+ // The browser's SOUND, publisher → phone only: 20 ms of PCM, signed 16-bit little-endian, mono, 24 kHz (960 bytes).
19
+ // KasmVNC carries no audio (its server has no audio path; the Kasm desktops get theirs from a separate helper), so
20
+ // this is a second stream beside the screen. PCM rather than a codec on purpose for the first cut: nothing to decode
21
+ // on the phone but a ring buffer, and the publisher sends NOTHING while the browser is silent, so an idle screen
22
+ // costs no audio at all. ~384 kbit/s while sound plays; a codec (Opus) is the follow-up once that is measured.
23
+ export const KIND_AUDIO = 3
24
+ export const AUDIO_RATE = 24000
25
+ export const AUDIO_FRAME_MS = 20
26
+ // ONE FRAME of the screencast, publisher → viewer (docs/agent-browser-views.md, stage 1): a JPEG of the shown tab and a
27
+ // small JSON header saying what it is (its CSS size, its url). Packed as [2-byte header length][header][jpeg].
28
+ // A viewer from before stage 1 does not know this kind and ignores it (open() returns null) — which is what lets the
29
+ // publisher stream frames on a channel where an older viewer is still watching by KasmVNC.
30
+ export const KIND_FRAME = 4
31
+
32
+ export function packFrame (header, jpeg) {
33
+ const h = enc.encode(JSON.stringify(header))
34
+ if (h.length > 65535) throw new Error('frame header too large')
35
+ const out = new Uint8Array(2 + h.length + jpeg.length)
36
+ out[0] = h.length >> 8; out[1] = h.length & 255
37
+ out.set(h, 2)
38
+ out.set(jpeg, 2 + h.length)
39
+ return out
40
+ }
41
+
42
+ /** → {header, jpeg} or null. */
43
+ export function unpackFrame (bytes) {
44
+ if (!bytes || bytes.length < 2) return null
45
+ const n = (bytes[0] << 8) | bytes[1]
46
+ if (bytes.length < 2 + n) return null
47
+ try { return { header: JSON.parse(dec.decode(bytes.subarray(2, 2 + n))), jpeg: bytes.subarray(2 + n) } } catch { return null }
48
+ }
49
+
50
+ /** The key as the bundle carries it (base64 of 32 bytes) → an AES-GCM key usable by both ends. */
51
+ export async function browseKey (b64) {
52
+ const raw = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))
53
+ if (raw.length !== 32) throw new Error('browse key must be 32 bytes, got ' + raw.length)
54
+ return crypto.subtle.importKey('raw', raw, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
55
+ }
56
+
57
+ /** The relay channel, derived from the key so the relay is told a hash and never the key. Same shape the browse
58
+ * room used in August (43 chars of base64url), because the relay's path regex already accepts exactly that. */
59
+ export async function channelFor (b64) {
60
+ const h = new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(b64 + ':witbitz-browse-relay-v1')))
61
+ let s = ''
62
+ for (const b of h) s += String.fromCharCode(b)
63
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '').slice(0, 43)
64
+ }
65
+
66
+ /** The relay channel of one FRAME STREAM — a mirror at one shape (docs/agent-browser-views.md, stage 2). Each stream
67
+ * has its own channel because the relay sends everything on a channel to everyone on it: a phone must not download
68
+ * the desktop stream to throw it away. Derived from the key like the main channel; the relay sees only a hash. */
69
+ export async function streamChannelFor (b64, stream) {
70
+ if (!/^[a-z]{1,8}$/.test(stream)) throw new Error('bad stream name')
71
+ const h = new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(b64 + ':witbitz-browse-stream-v1:' + stream)))
72
+ let s = ''
73
+ for (const b of h) s += String.fromCharCode(b)
74
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '').slice(0, 43)
75
+ }
76
+
77
+ export async function seal (key, kind, bytes) {
78
+ const iv = crypto.getRandomValues(new Uint8Array(12))
79
+ const ct = new Uint8Array(await crypto.subtle.encrypt(
80
+ { name: 'AES-GCM', iv, additionalData: new Uint8Array([kind]) }, key, bytes))
81
+ const out = new Uint8Array(1 + 12 + ct.length)
82
+ out[0] = kind
83
+ out.set(iv, 1)
84
+ out.set(ct, 13)
85
+ return out
86
+ }
87
+
88
+ /** → {kind, bytes} or null. Fail-closed and silent: anything that does not open under this key is not ours, which
89
+ * on a shared relay channel is an ordinary thing to receive, not an error to report. */
90
+ export async function open (key, buf) {
91
+ try {
92
+ const b = buf instanceof Uint8Array ? buf : new Uint8Array(buf)
93
+ if (b.length < 14) return null
94
+ const kind = b[0]
95
+ if (kind !== KIND_RFB && kind !== KIND_CTL && kind !== KIND_AUDIO && kind !== KIND_FRAME) return null
96
+ const pt = new Uint8Array(await crypto.subtle.decrypt(
97
+ { name: 'AES-GCM', iv: b.subarray(1, 13), additionalData: new Uint8Array([kind]) }, key, b.subarray(13)))
98
+ return { kind, bytes: pt }
99
+ } catch { return null }
100
+ }
101
+
102
+ export const sealCtl = async (key, obj) => seal(key, KIND_CTL, enc.encode(JSON.stringify(obj)))
103
+ export const readCtl = (bytes) => { try { return JSON.parse(dec.decode(bytes)) } catch { return null } }
package/cbor.js ADDED
@@ -0,0 +1,225 @@
1
+ // spaces/public/cbor.js — the small CBOR subset a Nitro attestation document needs.
2
+ //
3
+ // WHY NOT A LIBRARY. This runs in the browser as part of a *trust* claim: the user is verifying that the code which
4
+ // handled their plaintext was measured hardware. Every byte of that path they have to take on faith weakens the claim,
5
+ // and a general CBOR library is thousands of lines of generality we don't want auditors reading. The subset an
6
+ // attestation document actually uses is small enough to read in one sitting, so it is written out here.
7
+ //
8
+ // DELIBERATELY MISSING: bignums, half-floats, and every tag but transparent unwrapping. A document using them is
9
+ // rejected rather than guessed at — a parser that accepts more than the producer emits is a place for two
10
+ // implementations to disagree, and disagreement in a verifier means a forged document that "verifies".
11
+ //
12
+ // ★ INDEFINITE LENGTHS ARE SUPPORTED, AND THAT WAS NOT OPTIONAL. This decoder originally rejected them on exactly the
13
+ // reasoning above — and then a document captured from live Nitro hardware (2026-07-29) turned out to open with 0xbf,
14
+ // an indefinite-length map. Current NSM firmware STREAMS the attestation payload. Both public fixtures we had (2022
15
+ // and 2025) use definite-length maps, so nothing in the suite could catch it: the verifier would have rejected every
16
+ // document from current hardware. The lesson is the inverse of the one above — being stricter than the producer is
17
+ // not caution, it is a bug, and only real output shows you which you have.
18
+ //
19
+ // Re-encoding is never involved (COSE is verified over the RAW payload bytes), so accepting the streamed form
20
+ // introduces no canonicalisation ambiguity.
21
+
22
+ const MAX_LEN = 1 << 22 // 4MB — an attestation document is ~5KB; anything near this is an attack, not a document.
23
+
24
+ /** Decode one CBOR item. Maps come back as `Map` (attestation PCRs are keyed by INTEGER, so an object would lie).
25
+ * Throws on anything malformed or outside the supported subset. */
26
+ export function decode(bytes) {
27
+ const b = toBytes(bytes)
28
+ const [value, off] = readItem(b, 0)
29
+ if (value === BREAK) throw new Error('cbor: stray break byte')
30
+ if (off !== b.length) throw new Error(`cbor: ${b.length - off} trailing bytes`)
31
+ return value
32
+ }
33
+
34
+ function toBytes(x) {
35
+ if (x instanceof Uint8Array) return x
36
+ if (x instanceof ArrayBuffer) return new Uint8Array(x)
37
+ if (ArrayBuffer.isView(x)) return new Uint8Array(x.buffer, x.byteOffset, x.byteLength)
38
+ throw new Error('cbor: expected bytes')
39
+ }
40
+
41
+ function need(b, off, n) {
42
+ if (n < 0 || off + n > b.length) throw new Error('cbor: truncated')
43
+ return off + n
44
+ }
45
+
46
+ /** Read the initial byte + argument. → [major, value, nextOffset] */
47
+ function readHead(b, off) {
48
+ need(b, off, 1)
49
+ const ib = b[off]
50
+ const major = ib >> 5
51
+ const ai = ib & 31
52
+ if (ai < 24) return [major, ai, off + 1]
53
+ if (ai === 24) { need(b, off + 1, 1); return [major, b[off + 1], off + 2] }
54
+ if (ai === 25) { need(b, off + 1, 2); return [major, (b[off + 1] << 8) | b[off + 2], off + 3] }
55
+ if (ai === 26) {
56
+ need(b, off + 1, 4)
57
+ // >>> 0 because a 4-byte length with the high bit set is positive in CBOR but negative under JS's signed `<<`.
58
+ const v = ((b[off + 1] << 24) | (b[off + 2] << 16) | (b[off + 3] << 8) | b[off + 4]) >>> 0
59
+ return [major, v, off + 5]
60
+ }
61
+ if (ai === 27) {
62
+ need(b, off + 1, 8)
63
+ let v = 0
64
+ for (let i = 1; i <= 8; i++) v = v * 256 + b[off + i]
65
+ if (!Number.isSafeInteger(v)) throw new Error('cbor: 64-bit value exceeds safe integer range')
66
+ return [major, v, off + 9]
67
+ }
68
+ if (ai === 31) throw new Error('cbor: indefinite length handled by the caller')
69
+ throw new Error(`cbor: reserved additional information ${ai}`)
70
+ }
71
+
72
+ /** Returned for the 0xff "break" byte. Only the indefinite-length readers may consume it; anywhere else it is an
73
+ * error, which is what stops a stray break from silently truncating a structure. */
74
+ const BREAK = Symbol('cbor-break')
75
+
76
+ /** An indefinite-length string is a run of DEFINITE-length chunks of the same major type, ended by a break. */
77
+ function readChunked(b, off, major, depth) {
78
+ const parts = []
79
+ let total = 0
80
+ let p = off
81
+ for (;;) {
82
+ need(b, p, 1)
83
+ const head = b[p]
84
+ if (head === 0xff) { p += 1; break }
85
+ // RFC 8949: each chunk must be a DEFINITE-length string of the SAME major type. Checking the decoded value
86
+ // instead of the head byte would silently accept a nested indefinite chunk, which is malformed.
87
+ if ((head >> 5) !== major || (head & 31) === 31) {
88
+ throw new Error('cbor: indefinite-length string contains a chunk of the wrong kind')
89
+ }
90
+ const [chunk, next] = readItem(b, p, depth + 1)
91
+ p = next
92
+ const bytes = major === 2 ? chunk : new TextEncoder().encode(chunk)
93
+ total += bytes.length
94
+ if (total > MAX_LEN) throw new Error('cbor: indefinite-length string too large')
95
+ parts.push(bytes)
96
+ }
97
+ const out = concat(...parts)
98
+ return [major === 2 ? out : new TextDecoder('utf-8', { fatal: true }).decode(out), p]
99
+ }
100
+
101
+ function readItem(b, off, depth = 0) {
102
+ if (depth > 16) throw new Error('cbor: nesting too deep')
103
+ need(b, off, 1)
104
+ const ib = b[off]
105
+ const major0 = ib >> 5
106
+
107
+ if ((ib & 31) === 31) {
108
+ if (major0 === 7) return [BREAK, off + 1]
109
+ if (major0 === 2 || major0 === 3) return readChunked(b, off + 1, major0, depth)
110
+ if (major0 === 4 || major0 === 5) {
111
+ // Streamed array/map: read items until the break. Nitro's NSM emits the attestation payload this way.
112
+ const isMap = major0 === 5
113
+ const arr = []
114
+ const map = new Map()
115
+ let p = off + 1
116
+ let n = 0
117
+ for (;;) {
118
+ const [k, n1] = readItem(b, p, depth + 1)
119
+ p = n1
120
+ if (k === BREAK) break
121
+ if (++n > MAX_LEN) throw new Error('cbor: indefinite-length collection too large')
122
+ if (!isMap) { arr.push(k); continue }
123
+ const [v, n2] = readItem(b, p, depth + 1)
124
+ p = n2
125
+ if (v === BREAK) throw new Error('cbor: indefinite-length map ended between a key and its value')
126
+ if (map.has(k)) throw new Error('cbor: duplicate map key')
127
+ map.set(k, v)
128
+ }
129
+ return [isMap ? map : arr, p]
130
+ }
131
+ throw new Error(`cbor: indefinite length is not valid for major type ${major0}`)
132
+ }
133
+
134
+ const [major, value, p] = readHead(b, off)
135
+ switch (major) {
136
+ case 0: return [value, p]
137
+ case 1: return [-1 - value, p]
138
+ case 2: { // byte string
139
+ if (value > MAX_LEN) throw new Error('cbor: byte string too large')
140
+ const end = need(b, p, value)
141
+ return [b.slice(p, end), end]
142
+ }
143
+ case 3: { // text string
144
+ if (value > MAX_LEN) throw new Error('cbor: text string too large')
145
+ const end = need(b, p, value)
146
+ return [new TextDecoder('utf-8', { fatal: true }).decode(b.subarray(p, end)), end]
147
+ }
148
+ case 4: { // array
149
+ if (value > MAX_LEN) throw new Error('cbor: array too long')
150
+ const out = []
151
+ let q = p
152
+ for (let i = 0; i < value; i++) {
153
+ const [v, n] = readItem(b, q, depth + 1)
154
+ if (v === BREAK) throw new Error('cbor: break inside a definite-length array')
155
+ out.push(v); q = n
156
+ }
157
+ return [out, q]
158
+ }
159
+ case 5: { // map
160
+ if (value > MAX_LEN) throw new Error('cbor: map too large')
161
+ const out = new Map()
162
+ let q = p
163
+ for (let i = 0; i < value; i++) {
164
+ const [k, n1] = readItem(b, q, depth + 1)
165
+ const [v, n2] = readItem(b, n1, depth + 1)
166
+ if (k === BREAK || v === BREAK) throw new Error('cbor: break inside a definite-length map')
167
+ // A duplicate key lets a producer show one value to us and another to a different parser. Reject.
168
+ if (out.has(k)) throw new Error('cbor: duplicate map key')
169
+ out.set(k, v)
170
+ q = n2
171
+ }
172
+ return [out, q]
173
+ }
174
+ case 6: { // tag — unwrapped transparently (COSE_Sign1 is emitted both tagged and bare in the wild)
175
+ const [v, n] = readItem(b, p, depth + 1)
176
+ return [v, n]
177
+ }
178
+ case 7:
179
+ if (value === 20) return [false, p]
180
+ if (value === 21) return [true, p]
181
+ if (value === 22) return [null, p]
182
+ if (value === 23) return [undefined, p]
183
+ throw new Error(`cbor: unsupported simple/float value ${value}`)
184
+ default:
185
+ throw new Error('cbor: unreachable')
186
+ }
187
+ }
188
+
189
+ // ---- encoding -------------------------------------------------------------------------------------------------
190
+ // Only what building a COSE Sig_structure needs: definite-length arrays, text strings, byte strings. The encoder
191
+ // exists so we can RE-CREATE the exact bytes that were signed; it is not a general serialiser.
192
+
193
+ function head(major, value) {
194
+ if (value < 24) return Uint8Array.of((major << 5) | value)
195
+ if (value < 0x100) return Uint8Array.of((major << 5) | 24, value)
196
+ if (value < 0x10000) return Uint8Array.of((major << 5) | 25, value >> 8, value & 0xff)
197
+ if (value < 0x100000000) {
198
+ return Uint8Array.of((major << 5) | 26, (value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff)
199
+ }
200
+ throw new Error('cbor: length too large to encode')
201
+ }
202
+
203
+ export function encodeBytes(u8) {
204
+ const b = toBytes(u8)
205
+ return concat(head(2, b.length), b)
206
+ }
207
+
208
+ export function encodeText(s) {
209
+ const b = new TextEncoder().encode(String(s))
210
+ return concat(head(3, b.length), b)
211
+ }
212
+
213
+ /** Encode a definite-length array of already-encoded items. */
214
+ export function encodeArray(items) {
215
+ return concat(head(4, items.length), ...items)
216
+ }
217
+
218
+ export function concat(...parts) {
219
+ let n = 0
220
+ for (const p of parts) n += p.length
221
+ const out = new Uint8Array(n)
222
+ let o = 0
223
+ for (const p of parts) { out.set(p, o); o += p.length }
224
+ return out
225
+ }
package/changePush.js ADDED
@@ -0,0 +1,75 @@
1
+ // changePush.js — PUSH for the change inbox (docs/change-inbox.md § Push). While the app is open this device keeps ONE
2
+ // socket on the relay (relay/relay.mjs, wss://code-relay.witbitz.chat — the Code section's relay, already in the CSP).
3
+ // When one of its rooms changes, the Space Lambda posts a sealed HINT to this device's channel and the relay pushes it
4
+ // down the socket: the page polls that room at once instead of asking "what changed?" every two seconds.
5
+ //
6
+ // The relay learns neither the device's inbox nor the room: the CHANNEL and the hint's AES-GCM KEY both derive from the
7
+ // inbox id, which only this device and the Lambda hold (agent/changeFeed.mjs hintChannel / sealHint — same derivations,
8
+ // held equal by spaces/test/changePush.test.mjs).
9
+ //
10
+ // A hint is a nudge, never the record: a lost one costs latency (the slow "what changed?" and the sweep remain), never a
11
+ // message. A socket that cannot open (another origin, a network that blocks it) simply leaves the page on the 2 s checks.
12
+
13
+ // Same relay, same heartbeat as codeRelay.js (not imported: that module brings the Code section with it).
14
+ export const RELAY_URL = 'wss://code-relay.witbitz.chat'
15
+ export const RELAY_PING = '{"t":"relay-ping"}'
16
+ export const RELAY_PONG = '{"t":"relay-pong"}'
17
+ export const HEARTBEAT_MS = 25_000
18
+ export const PONG_WAIT_MS = 10_000
19
+ const MIN_BACKOFF = 1000, MAX_BACKOFF = 30_000
20
+
21
+ const te = new TextEncoder()
22
+ const b64u = (u) => { let s = ''; for (const b of u) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
23
+ const ub64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))
24
+ const sha = async (s) => new Uint8Array(await crypto.subtle.digest('SHA-256', te.encode(s)))
25
+
26
+ /** This inbox's relay channel — 43 characters, as the relay requires. == agent/changeFeed.mjs hintChannel. */
27
+ export const hintChannel = async (inbox) => b64u(await sha('witbitz-change-channel|' + inbox))
28
+ /** Open a sealed hint → { room, live, v, t? }, or null (not a hint, or not ours). */
29
+ export async function openHint (inbox, text) {
30
+ try {
31
+ const { iv, ct } = JSON.parse(text)
32
+ const key = await crypto.subtle.importKey('raw', await sha('witbitz-change-hint|' + inbox), 'AES-GCM', false, ['decrypt'])
33
+ const h = JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ub64u(iv) }, key, ub64u(ct))))
34
+ return h && typeof h.room === 'string' ? h : null
35
+ } catch { return null }
36
+ }
37
+
38
+ /** Keep the socket up; call onHint(hint) for each hint; onState(up) on every change. → { up(), wake(), stop() } */
39
+ export function startChangePush ({ inbox, onHint = () => {}, onState = () => {}, relay = RELAY_URL, path = 'c', WebSocketImpl = globalThis.WebSocket, heartbeatMs = HEARTBEAT_MS, pongWaitMs = PONG_WAIT_MS } = {}) {
40
+ if (!inbox || typeof WebSocketImpl !== 'function') return { up: () => false, wake () {}, stop () {} }
41
+ let ws = null, up = false, stopped = false, backoff = MIN_BACKOFF, retry = null, beat = null, pongTimer = null
42
+ const setUp = (v) => { if (v !== up) { up = v; try { onState(v) } catch { /* */ } } }
43
+ const clearTimers = () => { clearInterval(beat); clearTimeout(pongTimer); beat = pongTimer = null }
44
+ const drop = () => { clearTimers(); setUp(false); if (ws) { try { ws.onclose = ws.onerror = ws.onmessage = null; ws.close() } catch { /* */ } } ws = null }
45
+ const schedule = () => { if (stopped || retry) return; retry = setTimeout(() => { retry = null; connect() }, backoff); backoff = Math.min(backoff * 2, MAX_BACKOFF) }
46
+ // A dead path can leave a socket "open" for minutes (codeRelay.js measured it): ask the relay, which answers itself.
47
+ const probe = (waitMs = pongWaitMs) => {
48
+ if (!ws || pongTimer) return
49
+ try { ws.send(RELAY_PING) } catch { drop(); schedule(); return }
50
+ pongTimer = setTimeout(() => { pongTimer = null; drop(); schedule() }, waitMs)
51
+ }
52
+ async function connect () {
53
+ if (stopped || ws) return
54
+ let s
55
+ try { s = new WebSocketImpl(String(relay).replace(/\/+$/, '') + '/' + path + '/' + await hintChannel(inbox)) } catch { schedule(); return }
56
+ if (stopped) { try { s.close() } catch { /* */ } return }
57
+ ws = s
58
+ s.onopen = () => { backoff = MIN_BACKOFF; setUp(true); beat = setInterval(() => probe(), heartbeatMs) }
59
+ s.onmessage = async (ev) => {
60
+ const text = typeof ev.data === 'string' ? ev.data : ''
61
+ if (text === RELAY_PONG) { clearTimeout(pongTimer); pongTimer = null; return }
62
+ if (!text || text.startsWith('{"t":')) return // the relay's own peer count
63
+ const h = await openHint(inbox, text)
64
+ if (h) { try { onHint(h) } catch { /* */ } }
65
+ }
66
+ s.onclose = s.onerror = () => { if (ws === s) { drop(); schedule() } }
67
+ }
68
+ connect()
69
+ return {
70
+ up: () => up,
71
+ /** The page came back to the foreground: a socket iOS froze in the background may be dead — prove it now. */
72
+ wake () { if (stopped) return; if (!ws) { clearTimeout(retry); retry = null; backoff = MIN_BACKOFF; connect() } else probe(3000) },
73
+ stop () { stopped = true; clearTimeout(retry); drop() },
74
+ }
75
+ }