@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
package/roomState.js ADDED
@@ -0,0 +1,58 @@
1
+ import { isAttestedRoom } from './attestedRooms.js'
2
+ // roomState.js — the per-room key/persistence custody layer (Verified-Client Phase 1, L1).
3
+ // Pure, self-contained localStorage helpers keyed by room id: the room key (mk) read, the per-member
4
+ // signing identity, the email-gate flag, and the key model. Extracted from space.js as the first TCB
5
+ // module. NOTE: rememberMk stays in space.js for now — it also mirrors mk into IndexedDB for the SW
6
+ // and enqueues a recovery backup, so it moves when those layers modularize. Everything here is dep-free.
7
+
8
+ export const mkKey = (r) => 'space:mk:' + r
9
+ export const recallMk = (r) => { try { return localStorage.getItem(mkKey(r)) } catch { return null } }
10
+ // The CURRENT room's key from state (worker-held mk lives there, not in localStorage); any other room's from the store.
11
+ export const curMk = (r = state.room) => (r === state.room ? (state.mk || recallMk(r)) : recallMk(r))
12
+ // TENANT SPLIT-KEY (docs/tenant-split-key-dualstore.md): a split room stores the user's MEMBERSHIP half (userShare) +
13
+ // the room's commit instead of `mk`. Never both — a room is normal (space:mk:) XOR split (space:us:+space:spc:).
14
+ export const usKey = (r) => 'space:us:' + r
15
+ export const spcKey = (r) => 'space:spc:' + r
16
+ export const recallUserShare = (r) => { try { return localStorage.getItem(usKey(r)) } catch { return null } }
17
+ // Room TYPE (is it split?) reads the NON-SECRET commit marker (space:spc:), not the secret userShare (space:us:). The
18
+ // commit is a public hash of mk, written alongside the userShare at every split site; keying room-type off it means the
19
+ // main thread never needs the secret to know a room is split — a prerequisite for confining the userShare to the kernel.
20
+ // (Kept `|| usKey` for the rare split entry that predates a commit; either marker means split.)
21
+ export const isSplitRoom = (r) => { try { return !!localStorage.getItem(spcKey(r)) || !!localStorage.getItem(usKey(r)) } catch { return false } }
22
+ export const modelKey = (r) => 'space:model:' + r
23
+ export const setModel = (r, m) => { try { localStorage.setItem(modelKey(r), m) } catch { /* private mode */ } }
24
+ export const getModel = (r) => { try { return localStorage.getItem(modelKey(r)) } catch { return null } }
25
+ export const idKey = (r) => 'space:id:' + r
26
+ export const rememberId = (r, id) => { try { localStorage.setItem(idKey(r), JSON.stringify(id)) } catch { /* private mode */ } }
27
+ export const recallId = (r) => { try { const s = localStorage.getItem(idKey(r)); return s ? JSON.parse(s) : null } catch { return null } }
28
+ export const gateKey = (r) => 'space:gate:' + r
29
+ export const setGate = (r, g) => { try { localStorage.setItem(gateKey(r), g) } catch { /* private mode */ } }
30
+ export const gateOf = (r) => { try { return localStorage.getItem(gateKey(r)) || '' } catch { return '' } }
31
+ // Verified-client marker (docs/verified-client-design.md): this room requires the Verified Client — its share link is a
32
+ // `?vc=` capability and it opens only in the extension. Local hint (mirrors setGate) so the share UI picks the right link.
33
+ export const vcKey = (r) => 'space:vc:' + r
34
+ export const setVerifiedClient = (r) => { try { localStorage.setItem(vcKey(r), '1') } catch { /* private mode */ } }
35
+ export const isVerifiedClient = (r) => { try { return localStorage.getItem(vcKey(r)) === '1' } catch { return false } }
36
+ export const signKey = (r) => 'space:sign:' + r
37
+ // EVERYTHING THIS DEVICE KEEPS UNDER A ROOM'S NAME (2026-10-26, the owner: "Check that there are no problems when we delete a
38
+ // space"). A delete removed the key, the model and the split shares, and left the rest — the room's private signing identity
39
+ // and keypair among them — for good, through every relaunch. space.js forgetSpace removes each of these; roomKeysOnDelete.test
40
+ // fails when a new `'space:<x>:' + room` key appears in the app without being here (or named as kept on purpose).
41
+ export const ROOM_KEY_PREFIXES = ['space:mk:', 'space:model:', 'space:us:', 'space:spc:', 'space:id:', 'space:sign:', 'space:gate:', 'space:vc:',
42
+ 'space:ak:', 'space:lanes:', 'space:nolane:', 'space:lanechk:', 'space:lanechk2:', 'space:laneup:', 'space:crossed:', 'space:epoch:', 'space:mykey:', 'space:notif:',
43
+ 'space:moved-unsent:', 'space:away-unsent:', 'space:safemedia:', 'space:inviteowed:', 'space:removed:']
44
+ export const recallSign = (r) => { try { const s = localStorage.getItem(signKey(r)); return s ? JSON.parse(s) : null } catch { return null } }
45
+ export const rememberSign = (r, kp) => { try { localStorage.setItem(signKey(r), JSON.stringify(kp)) } catch { /* private mode */ } }
46
+
47
+ // The LIVE session singleton — a mutable object so extracted TCB modules can READ and WRITE the same
48
+ // session state across module boundaries (ES imports are read-only bindings, but an object's properties
49
+ // are not). `client` is assigned at runtime in space.js (its init needs the page's auth/enclave glue).
50
+ export const state = { room: null, mk: null, etag: null, count: 0, client: null, myName: '', enclaveKey: null, enclaveClaim: null, enclaveAttested: null, apiEndpoint: '', enclaveAsleep: false, wakingEnclave: false, sessionRelease: null, lastBackupRead: null }
51
+
52
+ // A TEMPORARY room (docs: spaces-temporary-rooms) is named by its id — `tmp-` — and lives in the shreddable temp index,
53
+ // never in durable recents/backups. One definition, read by the shell and the modules alike.
54
+ export const isTempRoom = (r) => String(r || '').startsWith('tmp-')
55
+ // NOTHING OF THIS ROOM IS KEPT ON THE DEVICE: a temporary room (session-only) and an ATTESTED room of any kind (docs/emulated-
56
+ // attested-rooms.md; the owner, 2026-10-18: "attested rooms cannot be watched offline") — its key only in memory, released
57
+ // after a fresh attestation; no chat, state or image cache at rest. One rule for every cache.
58
+ export const noDeviceCopy = (r) => isTempRoom(r) || isAttestedRoom(r)
@@ -0,0 +1,115 @@
1
+ // roomStreamClient.js — the READING end of a room stream (docs/change-inbox.md § Room streams; the writer is
2
+ // agent/roomStream.mjs). While a room is on screen, the realm that holds its key keeps a socket on the room's channel on
3
+ // the relay and turns sealed frames into events: the reply as it grows (so the bubble is fed directly instead of by a
4
+ // poll every 350 ms), "poll now" when the ledger grew, and "the turn ended". It runs wherever the key is — the l1 worker
5
+ // by default (mk never leaves it), the page itself on the direct path — so it takes mk and never hands it on.
6
+ //
7
+ // The channel and the frame key derive from the room key (and, in a gated room, from the current epoch's GRANT, handed
8
+ // out only by a poll that passed the room's gate) — identical to agent/roomStream.mjs, held equal by
9
+ // spaces/test/roomStreamClient.test.mjs. Nothing here is the record: any doubt (a gap, a rewrite, a frame too big to
10
+ // send) becomes one "poll now", and a socket that cannot open leaves the page polling exactly as before.
11
+ import { open } from './e2ee.js'
12
+ import { RELAY_URL, RELAY_PING, RELAY_PONG, HEARTBEAT_MS, PONG_WAIT_MS } from './changePush.js'
13
+
14
+ export const STREAM_EPOCH_MS = 10 * 60 * 1000 // == agent/roomStream.mjs
15
+ const te = new TextEncoder()
16
+ const b64u = (u) => { let s = ''; for (const b of u) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
17
+ const sha = async (s) => new Uint8Array(await crypto.subtle.digest('SHA-256', te.encode(s)))
18
+ export const streamChannel = async (mk, grant = '') => b64u(await sha('witbitz-room-stream|' + mk + (grant ? '|' + grant : '')))
19
+ export const streamKey = async (mk, grant = '') => (grant ? b64u(await sha('witbitz-room-stream-key|' + mk + '|' + grant)) : mk)
20
+ /** The grant for the epoch `now` falls in, from a poll's grants; null when none is current (poll again for fresh ones). */
21
+ export function currentGrant (grants, now = Date.now()) {
22
+ const e = Math.floor(now / STREAM_EPOCH_MS)
23
+ const g = (Array.isArray(grants) ? grants : []).find((x) => x && x.e === e && typeof x.g === 'string')
24
+ return g ? g.g : null
25
+ }
26
+
27
+ /** Pure reassembly: frames in → events out. {k:'partial', text, pseq, step} · {k:'poll', why} · {k:'end'}.
28
+ * sync(text): the page just POLLED and holds `text` as the reply so far — later deltas continue from it. */
29
+ export function frameReader () {
30
+ let text = '', valid = true, lastSeq = 0, owedPoll = false, turn = null
31
+ const poll = (why) => { if (owedPoll) return null; owedPoll = true; return { k: 'poll', why } } // one poll per doubt, not one per frame
32
+ return {
33
+ // A poll's text REPAIRS a reader that lost its place; it never overrides one that has not. The writer stores each
34
+ // step and THEN posts its frame, so a poll can be ahead of the frames or behind them — the frames are the authority
35
+ // while they are whole (the page's renderPartial orders the two by sequence number).
36
+ sync (t) { if (valid) return; text = String(t || ''); valid = true; owedPoll = false },
37
+ apply (f) {
38
+ if (!f || typeof f !== 'object') return null
39
+ // A write announced OUTSIDE any turn (agent/spaceService.mjs announceWrite): poll now, and leave the turn's sequence
40
+ // and the reply in progress exactly as they are — it carries no seq on purpose.
41
+ // An ARTIFACT changed (spaceService noteViewWrite): the page reads the room's one version list — not the ledger.
42
+ // A frame may CARRY the newest entry, sealed with the room key (agent/asyncTurn.mjs frameTail; 2026-10-20): { count, box }
43
+ // rides the poll event as `tail` — the key worker answers that poll from it (l1-worker.js frameTails), no network.
44
+ const tail = Number.isInteger(f.count) && f.count > 0 && typeof f.box === 'string' ? { tail: { count: f.count, box: f.box } } : {}
45
+ if (f.oob) return f.k === 'entries' ? { k: 'poll', why: 'changed', ...tail, ...(typeof f.doc === 'string' && /^[A-Za-z0-9]{1,24}$/.test(f.doc) ? { doc: f.doc } : {}) } : f.k === 'views' ? { k: 'views' } : null
46
+ if (f.seq === 1) { lastSeq = 0; text = ''; valid = true; owedPoll = false; turn = typeof f.tid === 'string' ? f.tid : null } // a new turn
47
+ // ANOTHER TURN'S FRAME (state machines pass 7, L#12): two turns on one channel each count from 1, so the other's next
48
+ // seq could look like ours and its text was spliced onto this reply. A frame naming another publisher is a doubt.
49
+ else if (turn && typeof f.tid === 'string' && f.tid !== turn) { valid = false; return poll('other turn') }
50
+ const gap = lastSeq && f.seq !== lastSeq + 1
51
+ lastSeq = Number(f.seq) || lastSeq
52
+ if (gap) { valid = false; return poll('gap') }
53
+ if (f.k === 'entries') { if (tail.tail) { owedPoll = true; return { k: 'poll', why: 'entries', ...tail } } return poll('entries') } // a carried entry is never deduped away
54
+ if (f.k === 'resync') { valid = false; return poll('resync') }
55
+ if (f.k === 'end') { owedPoll = false; return { k: 'end' } }
56
+ if (f.k !== 'partial') return null
57
+ const add = typeof f.add === 'string' ? f.add : ''
58
+ // A reply only grows, so a frame that starts INSIDE what we hold continues it from there; one that starts beyond it
59
+ // means frames were lost.
60
+ if (f.from === 0) { text = add; valid = true; owedPoll = false } else if (valid && f.from <= text.length) text = text.slice(0, f.from) + add
61
+ else { valid = false; return poll('gap') }
62
+ return { k: 'partial', text, pseq: f.pseq, step: f.step || null }
63
+ },
64
+ }
65
+ }
66
+
67
+ /** Hold the room's stream. onEvent(ev) per event above; onState(up). → { up(), sync(text), setGrants(grants), stop() }.
68
+ * `grants` null → an open room (the key alone); an array → a gated room (no current grant → no socket until fresh ones). */
69
+ export function openRoomStream ({ mk, grants = null, tag = '', onEvent = () => {}, onState = () => {}, relay = RELAY_URL, path = 'c', WebSocketImpl = globalThis.WebSocket, now = () => Date.now(), heartbeatMs = HEARTBEAT_MS, pongWaitMs = PONG_WAIT_MS } = {}) {
70
+ if (!mk || typeof WebSocketImpl !== 'function') return { up: () => false, sync () {}, setGrants () {}, stop () {} }
71
+ const reader = frameReader()
72
+ let ws = null, up = false, stopped = false, backoff = 1000, retry = null, beat = null, pongTimer = null, epochTimer = null, key = null, gs = grants
73
+ const setUp = (v) => { if (v !== up) { up = v; try { onState(v) } catch { /* */ } } }
74
+ const drop = () => { clearInterval(beat); clearTimeout(pongTimer); clearTimeout(epochTimer); beat = pongTimer = epochTimer = null; setUp(false); if (ws) { try { ws.onclose = ws.onerror = ws.onmessage = null; ws.close() } catch { /* */ } } ws = null }
75
+ const schedule = () => { if (stopped || retry) return; retry = setTimeout(() => { retry = null; connect() }, backoff); backoff = Math.min(backoff * 2, 30_000) }
76
+ async function connect () {
77
+ if (stopped || ws) return
78
+ const grant = gs ? currentGrant(gs, now()) : ''
79
+ if (gs && !grant) return // a gated room with no current grant: wait for the next poll's
80
+ key = await streamKey(mk, grant)
81
+ let s
82
+ // path 's': a page on ANY origin (the SDK) — the relay's /s/ namespace (relay/relay.mjs); the app keeps 'c'
83
+ try { s = new WebSocketImpl(String(relay).replace(/\/+$/, '') + '/' + path + '/' + await streamChannel(mk, grant) + (tag ? '?v=' + encodeURIComponent(tag) : '')) } catch { schedule(); return } // tag: THIS device is viewing (spaceClient viewingTag)
84
+ if (stopped) { try { s.close() } catch { /* */ } return }
85
+ ws = s
86
+ s.onopen = () => {
87
+ backoff = 1000; setUp(true)
88
+ beat = setInterval(() => { if (!ws || pongTimer) return; try { ws.send(RELAY_PING) } catch { drop(); schedule(); return } pongTimer = setTimeout(() => { pongTimer = null; drop(); schedule() }, pongWaitMs) }, heartbeatMs)
89
+ if (gs) { const t = now(); epochTimer = setTimeout(() => { drop(); connect() }, (Math.floor(t / STREAM_EPOCH_MS) + 1) * STREAM_EPOCH_MS - t + 50) } // a gated room moves to the next epoch's channel
90
+ }
91
+ s.onmessage = async (ev) => {
92
+ const text = typeof ev.data === 'string' ? ev.data : ''
93
+ if (text === RELAY_PONG) { clearTimeout(pongTimer); pongTimer = null; return }
94
+ if (!text || text.startsWith('{"t":')) return
95
+ let f = null
96
+ try { f = JSON.parse((await open(JSON.parse(text), { mk: key })) || 'null') } catch { f = null }
97
+ const e = f && reader.apply(f)
98
+ if (e) { try { onEvent(e) } catch { /* */ } }
99
+ }
100
+ s.onclose = s.onerror = () => { if (ws === s) { drop(); schedule() } }
101
+ }
102
+ connect()
103
+ return {
104
+ up: () => up,
105
+ sync: (t) => reader.sync(t),
106
+ /** Fresh grants from a poll (a gated room): reconnect only if the current epoch's grant changed (a rotation). */
107
+ setGrants (next) {
108
+ if (!Array.isArray(next)) return
109
+ const changed = currentGrant(next, now()) !== currentGrant(gs, now())
110
+ gs = next
111
+ if (changed || !ws) { drop(); clearTimeout(retry); retry = null; connect() }
112
+ },
113
+ stop () { stopped = true; clearTimeout(retry); drop() },
114
+ }
115
+ }
package/rosterCount.js ADDED
@@ -0,0 +1,49 @@
1
+ // rosterCount.js — how many people an email-gated room admits, counted from its sealed config: the PAGE's copy of the
2
+ // server's rule (agent/rosterCount.mjs rosterParticipants), held equal by spaces/test/fundingCounts.test.mjs.
3
+ // ⋯ → Fund this room uses it (sync sweep, 2026-10-10): the member count sets the grant's ceiling, and the sheet summed
4
+ // every list as is — a person listed both plain and hashed counted twice, a domain
5
+ // room given a number nobody can know.
6
+ // null = "this room's shape cannot know" (not email-gated, a domain wildcard, nothing enumerable); 0 is an answer.
7
+ import { memberHash } from './rosterHash.js'
8
+
9
+ const norm = (s) => String(s == null ? '' : s).toLowerCase().trim()
10
+ const list = (v) => (Array.isArray(v) ? v.map(norm).filter(Boolean) : [])
11
+
12
+ /** Exactly one admitted identity, and it is the signed-in person; no usernames or domains. */
13
+ export async function isSoloVerified(cfg, room, me, { hash = memberHash } = {}) {
14
+ const email = norm(me), allow = cfg?.allow
15
+ if (!email || cfg?.admission !== 'email' || !allow || allow.users?.length || allow.domains?.length) return false
16
+ const shown = Array.isArray(allow.emails) ? allow.emails.map(norm) : []
17
+ const hidden = Array.isArray(allow.mh) ? allow.mh : []
18
+ if (shown.length + hidden.length !== 1) return false
19
+ return shown.length ? shown[0] === email : hidden[0] === await hash(email, room)
20
+ }
21
+
22
+ export async function rosterParticipants (space, roomSalt, { seen = null } = {}) {
23
+ if (!space || space.admission !== 'email') return null
24
+ const allow = space.allow && typeof space.allow === 'object' ? space.allow : {}
25
+ if (list(allow.domains).length) return null
26
+ const emails = new Set(list(allow.emails))
27
+ const mh = new Set(Array.isArray(allow.mh) ? allow.mh.filter((h) => typeof h === 'string' && h) : [])
28
+ const users = new Set((Array.isArray(allow.users) ? allow.users : []).map((u) => u && typeof u === 'object' ? norm(u.handle) : '').filter(Boolean))
29
+ if (!emails.size && !mh.size && !users.size) return null
30
+ const plainOnly = new Set()
31
+ for (const e of emails) if (!(mh.size && mh.has(await memberHash(e, roomSalt)))) plainOnly.add(e)
32
+ return mh.size + plainOnly.size + users.size - await samePeople(seen, { mh, plainOnly, users })
33
+ }
34
+ // ONE PERSON, ONE COUNT (the owner, 2026-10-23: added by email AND by @username is "One person"). The list cannot tell —
35
+ // an @username's tag is unlinkable to an email by design — but the server can when that person signs in: roster_seen keeps,
36
+ // per signed-in member, the list entries their verified email matched (spaceOidc allowEntriesFor). Entries one person
37
+ // matched count once. → how many entries to take off.
38
+ export async function samePeople(seen, { mh, plainOnly, users }) {
39
+ if (!seen || typeof seen !== 'object') return 0
40
+ const counted = new Set([...[...mh].map((h) => 'mh:' + h), ...[...plainOnly].map((e) => 'e:' + e), ...[...users].map((u) => 'u:' + u)])
41
+ const parent = new Map(), find = (k) => { while (parent.get(k) !== k) k = parent.get(k); return k }
42
+ let merged = 0
43
+ for (const p of Object.values(seen)) {
44
+ const ks = (p && Array.isArray(p.entries) ? p.entries : []).filter((k) => counted.has(k))
45
+ for (const k of ks) if (!parent.has(k)) parent.set(k, k)
46
+ for (let i = 1; i < ks.length; i++) { const a = find(ks[0]), b = find(ks[i]); if (a !== b) { parent.set(b, a); merged++ } }
47
+ }
48
+ return merged
49
+ }
package/rosterHash.js ADDED
@@ -0,0 +1,13 @@
1
+ // Client twin of agent/rosterHash.mjs — a room-bound salted hash of a roster identity (an email), ported from
2
+ // kibitz/src/core/rosterHash.ts. Used at CREATE time to hash the email allow-list before it's sealed into the config,
3
+ // so co-members can't read each other's addresses; the server-side gate hashes the verified email the same way and
4
+ // checks membership. Output MUST be byte-identical to the server twin (same NFKC→trim→lowercase, SHA-256, base64url).
5
+ const enc = new TextEncoder()
6
+ const b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
7
+ const norm = (s) => String(s == null ? '' : s).normalize('NFKC').trim().toLowerCase()
8
+
9
+ /** base64url(SHA-256(`norm(identity)|roomSalt`)); roomSalt (the room id) appended raw — matches kibitz + the server. */
10
+ export async function memberHash(identity, roomSalt) {
11
+ const digest = await crypto.subtle.digest('SHA-256', enc.encode(`${norm(identity)}|${roomSalt}`))
12
+ return b64url(digest)
13
+ }
package/rowSchema.js ADDED
@@ -0,0 +1,113 @@
1
+ // rowSchema.js — a store collection's ROW SCHEMA: a small, deterministic JSON Schema subset (portal/docs/sdk-store.md#schemas).
2
+ //
3
+ // One module, two callers, one verdict: the server (agent/dataTools.mjs — a member's write is refused, the assistant's
4
+ // data_put is not proposed) and the SDK (checkDataSchema refuses a schema the server could not enforce). No dependency:
5
+ // it is in the confidential tier's measured code, and every keyword below is a few lines anyone can read.
6
+ //
7
+ // Supported: type (object|string|number|integer|boolean|array|null, or a list of them), properties, required,
8
+ // additionalProperties (true|false), enum, const, minLength, maxLength, minimum, maximum, exclusiveMinimum,
9
+ // exclusiveMaximum, items, minItems, maxItems, format (date | date-time | email | uri), and the annotations description,
10
+ // title, default, examples (kept for the assistant, never checked).
11
+ // Refused: anything else, including `pattern` — a regular expression from a room's config run against every row on our
12
+ // servers is a denial-of-service waiting to happen. A keyword we cannot check is REFUSED at declaration, never ignored:
13
+ // a schema that silently skips a rule reads exactly like one that holds it.
14
+
15
+ export const MAX_SCHEMA_BYTES = 8_000
16
+ export const MAX_SCHEMA_DEPTH = 6
17
+ const TYPES = new Set(['object', 'string', 'number', 'integer', 'boolean', 'array', 'null'])
18
+ const CHECKED = new Set(['type', 'properties', 'required', 'additionalProperties', 'enum', 'const', 'minLength', 'maxLength', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'items', 'minItems', 'maxItems', 'format'])
19
+ const ANNOTATIONS = new Set(['description', 'title', 'default', 'examples', '$comment'])
20
+ const FORMATS = new Set(['date', 'date-time', 'email', 'uri'])
21
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
22
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v)
23
+ const isCount = (v) => Number.isInteger(v) && v >= 0
24
+
25
+ /** Why this schema cannot be enforced, or null when it can. The top level must describe an object (a row). */
26
+ export function schemaProblem(schema) {
27
+ let bytes
28
+ try { bytes = new TextEncoder().encode(JSON.stringify(schema)).length } catch { return 'it is not JSON' }
29
+ if (bytes > MAX_SCHEMA_BYTES) return `it is ${bytes} bytes; the limit is ${MAX_SCHEMA_BYTES}`
30
+ if (!isObj(schema)) return 'it must be an object'
31
+ if (schema.type !== undefined && schema.type !== 'object') return 'a row schema describes an object: type must be "object"'
32
+ return walk(schema, '', 0)
33
+ }
34
+
35
+ function walk(s, at, depth) {
36
+ const where = at || 'the row'
37
+ if (!isObj(s)) return `${where}: a schema must be an object`
38
+ if (depth > MAX_SCHEMA_DEPTH) return `${where}: nested deeper than ${MAX_SCHEMA_DEPTH}`
39
+ for (const k of Object.keys(s)) if (!CHECKED.has(k) && !ANNOTATIONS.has(k)) return `${where}: "${k}" is not supported${k === 'pattern' ? ' (regular expressions are not run on the server)' : ''}`
40
+ if (s.type !== undefined) { const ts = Array.isArray(s.type) ? s.type : [s.type]; if (!ts.length || ts.some((t) => !TYPES.has(t))) return `${where}: type must be one of ${[...TYPES].join(', ')}` }
41
+ if (s.properties !== undefined) {
42
+ if (!isObj(s.properties)) return `${where}: properties must be an object`
43
+ for (const [k, v] of Object.entries(s.properties)) { const p = walk(v, `${at ? at + '.' : ''}${k}`, depth + 1); if (p) return p }
44
+ }
45
+ if (s.required !== undefined && !(Array.isArray(s.required) && s.required.every((x) => typeof x === 'string'))) return `${where}: required must be a list of field names`
46
+ if (s.additionalProperties !== undefined && typeof s.additionalProperties !== 'boolean') return `${where}: additionalProperties must be true or false`
47
+ if (s.enum !== undefined && !(Array.isArray(s.enum) && s.enum.length)) return `${where}: enum must be a non-empty list`
48
+ for (const k of ['minLength', 'maxLength', 'minItems', 'maxItems']) if (s[k] !== undefined && !isCount(s[k])) return `${where}: ${k} must be a whole number`
49
+ for (const k of ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum']) if (s[k] !== undefined && !isNum(s[k])) return `${where}: ${k} must be a number`
50
+ if (s.format !== undefined && !FORMATS.has(s.format)) return `${where}: format must be one of ${[...FORMATS].join(', ')}`
51
+ if (s.items !== undefined) { const p = walk(s.items, `${at || 'row'}[]`, depth + 1); if (p) return p }
52
+ return null
53
+ }
54
+
55
+ const typeOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v === 'number' ? 'number' : typeof v)
56
+ const matchesType = (v, t) => { const k = typeOf(v); return k === t || (t === 'number' && k === 'integer') }
57
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
58
+ const okFormat = {
59
+ date: (v) => /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(v + 'T00:00:00Z')),
60
+ 'date-time': (v) => /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/.test(v) && !Number.isNaN(Date.parse(v)),
61
+ email: (v) => /^[^\s@]{1,200}@[^\s@]{1,253}\.[^\s@]{2,63}$/.test(v),
62
+ uri: (v) => { try { return !!new URL(v).protocol } catch { return false } },
63
+ }
64
+
65
+ /** The FIRST way `row` breaks `schema` — `{ path, message }` — or null when it fits. Deterministic: properties are checked
66
+ * in the schema's own order, so the same row always gets the same answer. Assumes schemaProblem(schema) === null. */
67
+ export function rowProblem(schema, row) { return check(schema, row, '') }
68
+
69
+ function check(s, v, at) {
70
+ const where = at || 'the row'
71
+ const fail = (message) => ({ path: at || '', message: `${where} ${message}` })
72
+ if (s.type !== undefined) { const ts = Array.isArray(s.type) ? s.type : [s.type]; if (!ts.some((t) => matchesType(v, t))) return fail(`must be ${ts.join(' or ')}, not ${typeOf(v)}`) }
73
+ if (s.const !== undefined && !same(v, s.const)) return fail(`must be ${JSON.stringify(s.const)}`)
74
+ if (s.enum !== undefined && !s.enum.some((e) => same(e, v))) return fail(`must be one of ${s.enum.map((e) => JSON.stringify(e)).join(', ')}`)
75
+ if (typeof v === 'string') {
76
+ if (s.minLength !== undefined && [...v].length < s.minLength) return fail(`must be at least ${s.minLength} characters`)
77
+ if (s.maxLength !== undefined && [...v].length > s.maxLength) return fail(`must be at most ${s.maxLength} characters`)
78
+ if (s.format !== undefined && !okFormat[s.format](v)) return fail(`must be a valid ${s.format}`)
79
+ }
80
+ if (typeof v === 'number') {
81
+ if (s.minimum !== undefined && v < s.minimum) return fail(`must be ≥ ${s.minimum}`)
82
+ if (s.maximum !== undefined && v > s.maximum) return fail(`must be ≤ ${s.maximum}`)
83
+ if (s.exclusiveMinimum !== undefined && v <= s.exclusiveMinimum) return fail(`must be > ${s.exclusiveMinimum}`)
84
+ if (s.exclusiveMaximum !== undefined && v >= s.exclusiveMaximum) return fail(`must be < ${s.exclusiveMaximum}`)
85
+ }
86
+ if (Array.isArray(v)) {
87
+ if (s.minItems !== undefined && v.length < s.minItems) return fail(`must have at least ${s.minItems} items`)
88
+ if (s.maxItems !== undefined && v.length > s.maxItems) return fail(`must have at most ${s.maxItems} items`)
89
+ if (s.items !== undefined) for (let i = 0; i < v.length; i++) { const p = check(s.items, v[i], `${at || 'row'}[${i}]`); if (p) return p }
90
+ }
91
+ if (isObj(v)) {
92
+ for (const k of (s.required || [])) if (v[k] === undefined) return { path: at ? `${at}.${k}` : k, message: `${at ? at + '.' : ''}${k} is required` }
93
+ const props = s.properties || {}
94
+ for (const [k, sub] of Object.entries(props)) if (v[k] !== undefined) { const p = check(sub, v[k], at ? `${at}.${k}` : k); if (p) return p }
95
+ if (s.additionalProperties === false) { const extra = Object.keys(v).find((k) => !(k in props)); if (extra !== undefined) return { path: at ? `${at}.${extra}` : extra, message: `${at ? at + '.' : ''}${extra} is not a field of this collection` } }
96
+ }
97
+ return null
98
+ }
99
+
100
+ /** A short, readable line per field for the assistant's tool description: "title (string, required)". */
101
+ export function describeFields(schema) {
102
+ const props = isObj(schema && schema.properties) ? schema.properties : {}
103
+ const req = new Set(Array.isArray(schema && schema.required) ? schema.required : [])
104
+ return Object.entries(props).map(([k, s]) => {
105
+ const bits = []
106
+ if (s && s.type) bits.push(Array.isArray(s.type) ? s.type.join('|') : s.type)
107
+ if (s && Array.isArray(s.enum)) bits.push('one of ' + s.enum.map((e) => JSON.stringify(e)).join('/'))
108
+ if (s && s.format) bits.push(s.format)
109
+ if (req.has(k)) bits.push('required')
110
+ if (s && typeof s.description === 'string') bits.push(s.description.slice(0, 120))
111
+ return `${k}${bits.length ? ' (' + bits.join(', ') + ')' : ''}`
112
+ }).join(', ')
113
+ }
package/safeMedia.js ADDED
@@ -0,0 +1,116 @@
1
+ // safeMedia.js — SAFE MEDIA on the device (docs/safe-media.md; the owner, 2026-10-26: "do it"). A photo or a PDF is made safe
2
+ // ONCE, when it is posted: the posting device sends it — sealed to the tools enclave's ATTESTED key — through the Space
3
+ // server (op:'safemedia', which sees ciphertext only), and gets back, sealed to its one-time key, the safe versions (JPEGs our
4
+ // enclave encoded from pixels a keyless one-shot parser produced) with an attestation whose nonce is sha256(statement). Every
5
+ // other device checks that attestation BEFORE it decodes anything: a version is drawn only if the hardware vouches that this
6
+ // enclave image (PCR0) and the safe-media tool (its register) made exactly these bytes.
7
+ //
8
+ // makeSafe({ bytes, kind, mime }, { client, idToken }) → { statement, att, versions: [{ w, h, bytes }], text } (posting)
9
+ // verifySafe({ statement, att }, versionBytes) → { ok, why, st } (reading)
10
+ import { sealTo, openBox, genRecipientKey } from './e2ee.js'
11
+ import { verifyAttestation, b64ToBytes } from './nitroVerify.js'
12
+ import { SAFE_MEDIA_PINS } from './safeMediaPins.js'
13
+ import { checkToolPaired } from './followImage.js' // a tools-enclave image released since, by its release log (docs/release-trust-design.md § 6)
14
+
15
+ export const SAFE_USER_DATA = 'witbitz-safe-media-v1' // app/sealed.go safeUserData
16
+ export const SAFE_REGISTER = 20 // infra/tools-enclave/build-blobs.sh PCR_safe_media
17
+ export const SAFE_MAX_INPUT = 3 * 1024 * 1024 // what op:'safemedia' carries after two base64 layers (agent/safeMediaRelay.mjs MAX_BOX)
18
+
19
+ const enc = new TextEncoder()
20
+ const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')
21
+ const sha256 = async (bytes) => new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))
22
+ const stdB64 = (bytes) => { let s = ''; const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000)); return btoa(s) }
23
+ const fromStdB64 = (s) => Uint8Array.from(atob(String(s || '')), (c) => c.charCodeAt(0))
24
+
25
+ /** The accepted builds: { pcr0: [hex96…], register: [hex96…] } — empty until a release names them (safeMediaPins.js). */
26
+ function pinsOf (pins) {
27
+ const p = pins || SAFE_MEDIA_PINS || {}
28
+ return { pcr0: Array.isArray(p.pcr0) ? p.pcr0 : [], register: Array.isArray(p.register) ? p.register : [] }
29
+ }
30
+
31
+ /** Is there an accepted safe-media build at all? — until a release names one, the room setting is not offered. */
32
+ export const safeMediaReady = (pins) => { const p = pinsOf(pins); return p.pcr0.length > 0 && p.register.length > 0 }
33
+
34
+ /** A statement + its attestation → { ok, why, st }. `versionBytes[i]` (when given) must hash to the statement's versions[i];
35
+ * checked as of the document's OWN time (a stored statement outlives the ~3-hour Nitro leaf, as turn certificates do). */
36
+ export async function verifySafe ({ statement, att } = {}, versionBytes = [], { pins, root, follow } = {}) {
37
+ const p = pinsOf(pins)
38
+ if (!p.pcr0.length || !p.register.length) return { ok: false, why: 'no accepted safe-media build yet' }
39
+ if (typeof statement !== 'string' || typeof att !== 'string') return { ok: false, why: 'no statement' }
40
+ let st
41
+ try { st = JSON.parse(statement) } catch { return { ok: false, why: 'the statement is not readable' } }
42
+ if (!st || st.v !== 1 || st.tool !== 'safe_media' || !Array.isArray(st.versions)) return { ok: false, why: 'not a safe-media statement' }
43
+ try {
44
+ const nonce = await sha256(enc.encode(statement))
45
+ const doc = await checkToolPaired((p0, reg) => verifyAttestation(fromStdB64(att), { root, nonce, expectedPCRs: { 0: p0, [SAFE_REGISTER]: reg }, atDocTime: true }), p, SAFE_REGISTER, follow === undefined ? {} : { follow })
46
+ if (!doc.userData || new TextDecoder().decode(doc.userData) !== SAFE_USER_DATA) return { ok: false, why: 'not a safe-media attestation' }
47
+ } catch (e) { return { ok: false, why: String((e && e.message) || e).split('\n')[0] } }
48
+ for (let i = 0; i < versionBytes.length; i++) {
49
+ if (!versionBytes[i]) continue
50
+ const want = st.versions[i] && st.versions[i].sha256
51
+ if (!want || hex(await sha256(versionBytes[i])) !== want) return { ok: false, why: 'a safe version is not the one the enclave made' }
52
+ }
53
+ return { ok: true, why: '', st }
54
+ }
55
+
56
+ /** Does `orig` hash to what the statement says was made safe? — checked before "Open original" opens it. */
57
+ export async function isTheOriginal (st, orig) { return !!(st && orig && hex(await sha256(orig)) === st.orig) }
58
+ /** THE ONE CHECK the app (safeMediaRoom.js) and the SDK (sdkSafeMedia.js) run over a photo's safe copies (sync sweep 2026-11-09,
59
+ * still open P3 — it was written twice): the first candidate whose fetched versions VERIFY and whose statement was made from
60
+ * THIS original (sync sweep 2026-10-29 #1). `fetch(cand, versions)` → { bytes, ...extra } (bytes as verifySafe takes them; a
61
+ * throw = could not be fetched); `verify(safe, bytes)` → { ok, st, why }; `original()` → the original's bytes (read once, only
62
+ * when a copy verifies). → { ok: true, cand, st, ...extra, bytes } | { ok: false, why } */
63
+ export async function firstVerifiedCopy (cands, { fetch, verify, original }) {
64
+ let why = '', orig
65
+ for (const cand of cands) {
66
+ const vs = cand && cand.c && cand.c.safe && Array.isArray(cand.c.safe.versions) ? cand.c.safe.versions : []
67
+ if (!vs.length) continue
68
+ let got = null
69
+ try { got = await fetch(cand, vs) } catch { got = null }
70
+ if (!got || !got.bytes) { why = 'a safe copy could not be fetched'; continue }
71
+ const v = await verify(cand.c.safe, got.bytes)
72
+ if (!v || !v.ok) { why = (v && v.why) || 'the safe copy does not verify'; continue }
73
+ if (orig === undefined) { try { orig = (await original()) || null } catch { orig = null } }
74
+ if (!orig || !(await isTheOriginal(v.st, orig))) { why = orig ? 'the copy was made from another file' : 'the original could not be read to check the copy against it'; continue }
75
+ return { ok: true, cand, st: v.st, ...got }
76
+ }
77
+ return { ok: false, why: why || 'no safe copy verifies' }
78
+ }
79
+
80
+ /** The enclave's front key, from a FRESH attestation for our nonce (PCR0 + the safe-media register) → its public JWK. */
81
+ async function frontKey (client, idToken, pins, root, now) {
82
+ const p = pinsOf(pins)
83
+ if (!p.pcr0.length || !p.register.length) throw new Error('safe media is not available in this build yet')
84
+ const nonce = crypto.getRandomValues(new Uint8Array(32))
85
+ const r = await client.safeMedia(idToken, { step: 'attest', nonce: hex(nonce) })
86
+ if (!r || r.status !== 200 || typeof r.cose !== 'string') throw new Error((r && (r.reason || r.error)) || 'the safe-media enclave did not answer')
87
+ const doc = await checkToolPaired((p0, reg) => verifyAttestation(fromStdB64(r.cose), { root, nonce, expectedPCRs: { 0: p0, [SAFE_REGISTER]: reg }, maxAgeMs: 5 * 60_000, ...(now ? { now } : {}) }), p, SAFE_REGISTER)
88
+ if (!doc.publicKey) throw new Error('the enclave named no key')
89
+ const key = await crypto.subtle.importKey('spki', doc.publicKey, { name: 'ECDH', namedCurve: 'P-256' }, true, [])
90
+ const jwk = await crypto.subtle.exportKey('jwk', key)
91
+ return { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y }
92
+ }
93
+
94
+ /** Make a file safe (the POSTING device): → { statement, att, versions: [{ w, h, bytes }], text } — verified here too, so a
95
+ * device never stores a result it would itself refuse. Throws with a reason a person can read. */
96
+ export async function makeSafe ({ bytes, kind, mime = '' }, { client, idToken, pins, root, now } = {}) {
97
+ if (kind !== 'image' && kind !== 'pdf') throw new Error('only photos and PDFs are made safe')
98
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
99
+ if (!b.length || b.length > SAFE_MAX_INPUT) throw new Error('this file is too large to make safe')
100
+ const to = await frontKey(client, idToken, pins, root, now)
101
+ const reply = await genRecipientKey()
102
+ const box = await sealTo(JSON.stringify({ v: 1, reply: { x: reply.publicJwk.x, y: reply.publicJwk.y }, job: { kind, mime: String(mime).slice(0, 80), data: stdB64(b) } }), to)
103
+ const r = await client.safeMedia(idToken, { step: 'make', box })
104
+ if (!r || r.status !== 200 || !r.box) throw new Error((r && (r.reason || r.error)) || 'the safe-media enclave did not answer')
105
+ const plain = await openBox(r.box, reply.privateJwk)
106
+ if (plain == null) throw new Error('the answer was not sealed to this device')
107
+ const rep = JSON.parse(plain)
108
+ if (rep.error) throw new Error(rep.error)
109
+ const versions = (rep.versions || []).map((v) => ({ w: v.w, h: v.h, bytes: fromStdB64(v.jpeg) }))
110
+ const v = await verifySafe({ statement: rep.statement, att: rep.att }, versions.map((x) => x.bytes), { pins, root })
111
+ if (!v.ok) throw new Error('the safe versions did not verify: ' + v.why)
112
+ if (!(await isTheOriginal(v.st, b))) throw new Error('the enclave made safe another file')
113
+ return { statement: rep.statement, att: rep.att, versions, text: rep.text || '' }
114
+ }
115
+
116
+ export { b64ToBytes }
@@ -0,0 +1,17 @@
1
+ // safeMediaPins.js — WHICH tools-enclave builds may make a file safe (docs/safe-media.md § 4.3). A device draws a safe version
2
+ // only if its attestation names one of these images (PCR0) AND one of these safe-media tool blobs (register 20).
3
+ //
4
+ // EMPTY until the first tools-enclave release that carries safe_media: until then nothing verifies, and every photo or PDF
5
+ // in a Safe media room is the held card — never drawn on trust. A release adds its values here (infra/tools-enclave:
6
+ // make the image → PCR0; build-blobs.sh → registers.json safe_media.register), and keeps the old ones for as long as stored
7
+ // safe versions made by them should still be drawn (a statement is checked as of its own time, forever).
8
+ export const SAFE_MEDIA_PINS = Object.freeze({
9
+ // tools enclave sm1 (2026-10-26, d7237d35) and rd1 (2026-11-07, 7fc8308c — read_doc; build enclave PASS, Rekor 3729370493):
10
+ // each kernel built on the x86 build host, the safe_media blob by build-blobs.sh. sm1's copies stay drawable after rd1 serves.
11
+ // rd2 (2026-11-13, 627fc06c — the base image with pass 9's E#3 supervisor; registers unchanged, safe_media still cafa891b).
12
+ // ga1 (2026-11-17, 7e18e8e0f): the tools enclave on Graviton — the kernel built for arm64 (PCR0 d2ec214b), safe_media's canvas
13
+ // arm64 (register 22a099e7). The x86 builds stay: their copies stay drawable.
14
+ // trixie (2026-11-20, 2d93f0006): the tools enclave's base on Debian 13 — PCR0 fb52764f, safe_media's register unchanged
15
+ pcr0: Object.freeze(['fb52764f784e50899285686bb3d9a4c90cf62681e6a61f8c81385843a85ed7add3b8e0782e6ce62b7de69b4a817ad7c2', 'd2ec214b4ef46d139e1c399629934579460284958e03a01abccde534a46c39b796a27e5725ae96c373c826f391f37e26', '761cd9c173630ebabc0ed1b311f7842f77aff950697d3e8c2d4b0a6d339fdae7cc2d9c1a9654c1cb7232a196d82212e7', '05dd1d2ef314348e32395a7d01fe72917e115c8e2cc7944e109a83dcfccbf6318baff9840d853080c5fc4abad2c6b326', 'f27fdc2247f0805df125e3fcdde0a9760434d4a02c6191a9b1b939e37036ce602d58f6d989617929dd101a5fabd98878']),
16
+ register: Object.freeze(['22a099e721774a1ed89b6bf9f1980ffbbd62041179d002ea3f0a91e1a2737f4c1fb365aae52700b061b27b6dff354ad3', 'b34003b176af07e3021551d339285bc4f55bfc8aa631d00077496ded105edd582960552ec3ad4b3c9a636d38ee844950', 'cafa891b126afa78340d601d203252b67fc7bb756804feca7a882a59539c616950cebced5a326778828c2dee363c3f03']),
17
+ })
@@ -0,0 +1,78 @@
1
+ // schedulesDoc.js — A SPACE'S SCHEDULES, kept IN the Space (docs/cloud-device.md § 12): a sealed room document `schedules`,
2
+ // one list that the ⋯ → Always on card edits, the assistant reads (its summary line rides every turn, as every widget's
3
+ // does), and a cloud device holding this Space runs. Pure — the app, the cloud device (Node) and the agent import it.
4
+ // doc state: { jobs: [{ id, when: { every } | { at, tz }, text, by, at }] }
5
+ export const SCHEDULES_DOC = 'schedules'
6
+ export const MIN_EVERY_MIN = 5
7
+ export const MAX_JOBS = 10
8
+ export const MAX_TEXT = 2000
9
+ export const PAUSE_AFTER_FAILS = 3 // owner, 2026-11-16: no limits, only this — a schedule that fails 3 runs in a row pauses until resumed
10
+ // ALWAYS ON (owner, 2026-11-16: "If it has no cloud device it should refuse"): a cloud device that holds this Space says so IN the
11
+ // Space — a sealed doc `alwayson` { on, seen } it writes when it takes the Space, refreshes while it runs, and clears when the
12
+ // Space is taken off or the device signed out. The assistant's schedule_task refuses unless it is on and recent: the server cannot
13
+ // know which devices hold a room, the room can.
14
+ export const ALWAYSON_DOC = 'alwayson'
15
+ export const ALWAYSON_REFRESH_MS = 6 * 3600_000
16
+ export const ALWAYSON_FRESH_MS = 3 * 24 * 3600_000
17
+ export const alwaysOnNow = (doc, now = Date.now()) => !!(doc && doc.state && doc.state.on === true && now - (Number(doc.state.seen) || 0) < ALWAYSON_FRESH_MS)
18
+ const HHMM = /^([01]\d|2[0-3]):([0-5]\d)$/
19
+ const ID = /^j[0-9a-f]{6,12}$/
20
+
21
+ /** A schedule's `when`, checked → { every } | { at, tz }. Throws on anything else. */
22
+ export function checkWhen (w) {
23
+ if (w && Number.isInteger(w.every)) {
24
+ if (w.every < MIN_EVERY_MIN) throw Object.assign(new Error(`every: at least ${MIN_EVERY_MIN} minutes`), { code: 'invalid' })
25
+ if (w.every > 7 * 24 * 60) throw Object.assign(new Error('every: at most a week'), { code: 'invalid' })
26
+ return { every: w.every }
27
+ }
28
+ if (w && typeof w.at === 'string' && HHMM.test(w.at)) {
29
+ const tz = typeof w.tz === 'string' && w.tz ? w.tz : 'UTC'
30
+ try { new Intl.DateTimeFormat('en-US', { timeZone: tz }) } catch { throw Object.assign(new Error('unknown time zone: ' + tz), { code: 'invalid' }) }
31
+ return { at: w.at, tz }
32
+ }
33
+ throw Object.assign(new Error('a schedule is { every: minutes } or { at: "HH:MM", tz }'), { code: 'invalid' })
34
+ }
35
+
36
+ /** The jobs a doc holds — anything malformed is left out, never thrown (a member's device may have written it). */
37
+ export function jobsOf (doc) {
38
+ const raw = doc && doc.state && Array.isArray(doc.state.jobs) ? doc.state.jobs : []
39
+ const out = []
40
+ for (const j of raw) {
41
+ if (!j || !ID.test(String(j.id)) || typeof j.text !== 'string' || !j.text.trim()) continue
42
+ let when; try { when = checkWhen(j.when) } catch { continue }
43
+ out.push({ id: j.id, when, text: j.text.slice(0, MAX_TEXT), by: typeof j.by === 'string' ? j.by.slice(0, 80) : '', at: Number(j.at) || 0, ...(j.paused === true ? { paused: true, pausedAt: Number(j.pausedAt) || 0 } : {}) })
44
+ if (out.length >= MAX_JOBS) break
45
+ }
46
+ return out
47
+ }
48
+
49
+ export const whenText = (w) => (w.every ? (w.every % 60 === 0 ? `every ${w.every / 60 === 1 ? 'hour' : w.every / 60 + ' hours'}` : `every ${w.every} min`) : `every day at ${w.at} (${w.tz})`)
50
+
51
+ /** The short line the assistant reads on its turns (the widget summary). */
52
+ export const summaryOf = (jobs) => (jobs.length ? 'Scheduled in this Space: ' + jobs.map((j) => `${whenText(j.when)} — "${j.text.slice(0, 80)}"${j.paused ? ' (paused — the person resumes it in ⋯ → Always on)' : ''}`).join('; ') : 'No schedules in this Space.')
53
+
54
+ const newId = () => 'j' + [...globalThis.crypto.getRandomValues(new Uint8Array(4))].map((b) => b.toString(16).padStart(2, '0')).join('')
55
+
56
+ /** jobs + one more → the new list (a new array). */
57
+ export function withJob (jobs, { when, text, by = '' }, now = Date.now()) {
58
+ const t = String(text || '').trim().slice(0, MAX_TEXT)
59
+ if (!t) throw Object.assign(new Error('a schedule needs text'), { code: 'invalid' })
60
+ if (jobs.length >= MAX_JOBS) throw Object.assign(new Error(`at most ${MAX_JOBS} schedules in a Space`), { code: 'limit' })
61
+ return [...jobs, { id: newId(), when: checkWhen(when), text: t, by: String(by || '').slice(0, 80), at: now }]
62
+ }
63
+ export const withoutJob = (jobs, id) => jobs.filter((j) => j.id !== id)
64
+ /** One job paused (after failed runs) or resumed → the new list. */
65
+ export const withPaused = (jobs, id, paused, now = Date.now()) => jobs.map((j) => { if (j.id !== id) return j; const { paused: _p, pausedAt: _a, ...rest } = j; return paused ? { ...rest, paused: true, pausedAt: now } : rest })
66
+
67
+ /** When is a job due? `last` = the last run (ms, 0 = never). */
68
+ function localParts (ms, tz) {
69
+ const p = Object.fromEntries(new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
70
+ .formatToParts(new Date(ms)).map((x) => [x.type, x.value]))
71
+ return { day: `${p.year}-${p.month}-${p.day}`, hm: `${p.hour}:${p.minute}` }
72
+ }
73
+ export function isDue (when, last, now) {
74
+ if (when.every) return !last || now - last >= when.every * 60_000
75
+ const n = localParts(now, when.tz)
76
+ if (n.hm < when.at) return false
77
+ return !last || localParts(last, when.tz).day !== n.day
78
+ }