@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/connDisp.js ADDED
@@ -0,0 +1,76 @@
1
+ // connDisp.js — A CONNECTION'S LABEL, SEALED TO THE PERSON'S OWN DEVICES (Sentinel step 2; docs/standing-sentinel.md § Step 2;
2
+ // the owner, 2026-11-07: "Yes"). The standing Sentinel keeps what it must act on (the secret, the host, the limits) and, until
3
+ // now, also what it only SHOWS back: the name the person gave a connection. Now every grant also carries `disp` — that name
4
+ // sealed under a key only the account's devices derive, which the Sentinel stores and hands back on credlist but cannot open.
5
+ // Once every record carries one, the Sentinel stops keeping the readable label (its own later image).
6
+ //
7
+ // THE KEY: AES-256-GCM from the account's backup master — HKDF(master, salt "witbitz-sentinel-display-v1", info
8
+ // "sentinel-display"), the same on every device of the account, as the erase key is (sdkErase.js eraseKeyOf). SYMMETRIC on
9
+ // purpose: only the person's devices seal and open these. (The design's P-256 "display box" is for step 2's other part — the
10
+ // Sentinel sealing delivered A2A history TO the person — and gets its own key when that is built; a browser cannot derive a
11
+ // P-256 pair deterministically from a secret.)
12
+ //
13
+ // THE FORMAT: "d1." + b64url(iv) + "." + b64url(ciphertext), AAD = "witbitz-disp v1\n" + the connection's id — a sealed name
14
+ // opens only on the record it was made for (the Sentinel cannot move one onto another connection). Inside: { v: 1, label }.
15
+ // Pure: no storage, no DOM — the app, the hosted vault and the SDK all use it.
16
+
17
+ const enc = new TextEncoder(), dec = new TextDecoder()
18
+ const SALT = enc.encode('witbitz-sentinel-display-v1'), INFO = enc.encode('sentinel-display')
19
+ const PREFIX = 'd1.'
20
+ export const DISP_MAX = 8192 // the Sentinel's limit (custody.mjs)
21
+
22
+ const b64u = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
23
+ const ub64 = (s) => { const t = String(s).replace(/-/g, '+').replace(/_/g, '/'); const p = t + '='.repeat((4 - (t.length % 4)) % 4); const bin = atob(p); const u = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u }
24
+ const bytesOf = (m) => (m instanceof Uint8Array ? m : (typeof m === 'string' && m ? ub64(m) : null))
25
+ const aadOf = (id) => enc.encode('witbitz-disp v1\n' + String(id || ''))
26
+
27
+ /** The 32 raw bytes of the display key, from the backup master (Uint8Array, or base64 / base64url text). null without one. */
28
+ export async function dispRawOf (master) {
29
+ const m = bytesOf(master)
30
+ if (!m || m.length < 16) return null
31
+ const km = await crypto.subtle.importKey('raw', m, 'HKDF', false, ['deriveBits'])
32
+ return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: INFO }, km, 256))
33
+ }
34
+
35
+ /** A non-extractable AES-GCM key from the raw bytes (what the hosted vault hands its frame). null for anything else. */
36
+ export async function dispKeyFromRaw (raw) {
37
+ const r = bytesOf(raw)
38
+ if (!r || r.length !== 32) return null
39
+ return crypto.subtle.importKey('raw', r, 'AES-GCM', false, ['encrypt', 'decrypt'])
40
+ }
41
+
42
+ /** The display key straight from the master. */
43
+ export async function dispKeyOf (master) { const raw = await dispRawOf(master); return raw ? dispKeyFromRaw(raw) : null }
44
+
45
+ /** Seal { label } for connection `id` → the `disp` string ('' when it cannot be made or would not fit). */
46
+ export async function sealDisp (key, id, { label = '' } = {}) {
47
+ if (!key || !id) return ''
48
+ const iv = crypto.getRandomValues(new Uint8Array(12))
49
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aadOf(id) }, key, enc.encode(JSON.stringify({ v: 1, label: String(label || '').slice(0, 200) }))))
50
+ const out = PREFIX + b64u(iv) + '.' + b64u(ct)
51
+ return out.length <= DISP_MAX ? out : ''
52
+ }
53
+
54
+ /** Open a `disp` made for connection `id` → { label } or null (another account's key, another connection, tampered, unknown form). */
55
+ export async function openDisp (key, id, disp) {
56
+ if (!key || !id || typeof disp !== 'string' || !disp.startsWith(PREFIX)) return null
57
+ const parts = disp.slice(PREFIX.length).split('.')
58
+ if (parts.length !== 2) return null
59
+ try {
60
+ const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ub64(parts[0]), additionalData: aadOf(id) }, key, ub64(parts[1]))
61
+ const o = JSON.parse(dec.decode(pt))
62
+ return o && o.v === 1 && typeof o.label === 'string' ? { label: o.label } : null
63
+ } catch { return null }
64
+ }
65
+
66
+ /** A credlist answer with each sealed name opened: `label` = the person's own name when its `disp` opens, else what the
67
+ * Sentinel holds (a record made before step 2, or by a sign-in the Sentinel finished). `disp` is left out of the result. */
68
+ export async function withDisplay (list, key) {
69
+ if (!Array.isArray(list)) return []
70
+ return Promise.all(list.map(async (c) => {
71
+ if (!c || typeof c !== 'object') return c
72
+ const { disp, ...rest } = c
73
+ const o = key && disp ? await openDisp(key, c.id, disp) : null
74
+ return o && o.label ? { ...rest, label: o.label, labelSealed: true } : rest
75
+ }))
76
+ }
@@ -0,0 +1,74 @@
1
+ import { parseMcpUrl } from './connections.js'
2
+
3
+ // connOtherWays.js — the Connections card's "other ways to connect" (an MCP server by its address, a service's own API key): WHERE they
4
+ // show and what a typed address means. Pure — the card (connectionsSheet.js renderConnList) draws what these decide.
5
+ // The owner, 2026-11-26: "placed in almost unreachable place" — the section was the last, under the whole catalog, and a search that did
6
+ // not match its own name hid it (a server not in the catalog — Zoom before its approval — had no way in).
7
+
8
+ /** An MCP server's address typed or pasted in the search box → its https URL, else ''. A bare host (mcp.zoom.us/…) gets https://;
9
+ * anything but https on a dotted host is not an address here (the MCP form refuses it anyway). */
10
+ export function typedMcpUrl (raw) {
11
+ try {
12
+ const { host, path } = parseMcpUrl(raw)
13
+ return 'https://' + host + path
14
+ } catch { return '' }
15
+ }
16
+
17
+ /** Which of the other ways to show, and under what heading → { title, rows } (rows: a subset of `all`, in order).
18
+ * Not searching: all, as "Other ways to connect" (placed right after the person's own connections). Searching: the ones whose name
19
+ * or line matches; when NOTHING on the card matched, all of them, as "Not listed? Connect it another way" — never a dead end. */
20
+ export function otherWaysRows ({ all, matches, searching, anythingElse }) {
21
+ if (!searching) return { title: 'Other ways to connect', rows: all }
22
+ const hit = all.filter(matches)
23
+ if (hit.length) return { title: 'Other ways to connect', rows: hit }
24
+ return anythingElse ? { title: '', rows: [] } : { title: 'Not listed? Connect it another way', rows: all }
25
+ }
26
+
27
+ /** Read connection IDs only. An unreadable private assistant makes a negative result inconclusive. */
28
+ export async function readConnectionUse(room, assistants, read, { verifiedOnly = false } = {}) {
29
+ const ids = new Set(), locations = new Map()
30
+ let incomplete = false
31
+ for (const id of new Set([room, ...assistants])) {
32
+ let cfg
33
+ try { cfg = await read(id) } catch { cfg = null }
34
+ if (!cfg || typeof cfg !== 'object' || cfg.error || cfg.gated || (cfg.status && cfg.status !== 200)) {
35
+ incomplete = true
36
+ continue
37
+ }
38
+ if (id === room && verifiedOnly && cfg.admission !== 'email') return { ids, locations, incomplete, eligible: false }
39
+ for (const c of Array.isArray(cfg.connections) ? cfg.connections : []) if (typeof c?.id === 'string') {
40
+ ids.add(c.id)
41
+ if (!locations.has(c.id)) locations.set(c.id, [])
42
+ locations.get(c.id).push(id)
43
+ }
44
+ }
45
+ return { ids, locations, incomplete, eligible: true }
46
+ }
47
+
48
+ export async function spacesUsingConnection(id, rooms, read) {
49
+ if (typeof id !== 'string' || !id.trim()) throw Object.assign(new Error('a connection ID is required'), { code: 'invalid_argument' })
50
+ const uses = [], unreadable = []
51
+ const lanes = new Map()
52
+ for (const row of rooms) if (row.shared) {
53
+ if (!lanes.has(row.shared)) lanes.set(row.shared, [])
54
+ lanes.get(row.shared).push(row.room)
55
+ }
56
+ const rows = rooms.filter(r => r.room && !r.shared && r.kind !== 'lane' && !r.room.startsWith('tmp-'))
57
+ for (let i = 0; i < rows.length; i += 6) {
58
+ const batch = rows.slice(i, i + 6)
59
+ const results = await Promise.all(batch.map(r => readConnectionUse(r.room, lanes.get(r.room) || [], read, { verifiedOnly: true })))
60
+ results.forEach(({ ids, incomplete }, index) => {
61
+ const { room } = batch[index]
62
+ if (ids.has(id)) uses.push(room)
63
+ if (incomplete) unreadable.push(room)
64
+ })
65
+ }
66
+ return { rooms: uses, unreadable, incomplete: unreadable.length > 0 }
67
+ }
68
+
69
+ export function grantStatus(grant, account, known) {
70
+ if (known?.has(grant.id)) return 'connected'
71
+ if (!grant.account || !account) return 'unknown'
72
+ if (grant.account !== account) return 'other_member'
73
+ return known ? 'detached' : 'unknown'
74
+ }
package/connPending.js ADDED
@@ -0,0 +1,16 @@
1
+ // connPending.js — A CALL KEY WHOSE GRANT ANSWER WAS LOST (state machines pass 9, N#7), the rule both keepers use: the regular app's
2
+ // page (connections.js postWithPendingKey, connectionsSheet.js) and, in the hosted app, the VAULT, which mints and keeps the key
3
+ // itself (vaultConnKeys.js mint). A leaf: no DOM, no storage.
4
+
5
+ export const PENDING_MS = 86_400_000 // a day: older, the grant is taken as never filed
6
+
7
+ /** The pending keys the account's list now shows (and this keeper holds no key for) → adopt; older than a day → dropped. Pure. */
8
+ export function adoptPendingKeys (pending, listedIds, haveKeys, now = Date.now()) {
9
+ const listed = new Set(listedIds || []), adopt = [], left = {}
10
+ for (const [id, rec] of Object.entries(pending || {})) {
11
+ if (!rec || typeof rec.callKey !== 'string' || !(now - (Number(rec.at) || 0) < PENDING_MS)) continue
12
+ if (listed.has(id)) { if (!(haveKeys && haveKeys[id])) { const { at: _a, ...k } = rec; adopt.push([id, k]) } continue }
13
+ left[id] = rec
14
+ }
15
+ return { adopt, pending: left }
16
+ }
package/connWrap.js ADDED
@@ -0,0 +1,53 @@
1
+ // connWrap.js — MOVE 3 of the Sentinel's per-account keys (docs/standing-sentinel.md § The two open pieces; owner, 2026-11-18:
2
+ // "Do it"). A connection the Sentinel still holds in the OLD form keeps its callKey beside its secret, so the Sentinel's data key
3
+ // opens it with no caller present. It is locked under the callKey the first time a caller brings that key — and a connection no
4
+ // room ever spends never meets one. So a device that holds the key presents it: the same proof and the same sealed key a call
5
+ // makes (agent/sentinelRelay.mjs credCall), over the wrap's own request, and the Sentinel locks it without calling the service.
6
+ // The callKey lives where it lives: the regular app's page, the hosted app's VAULT (it answers `proofOf` itself — vaultConnKeys.js
7
+ // connWrapProof — so the key never enters the frame), the SDK's store. Pure: WebCrypto only.
8
+ import { sealTo } from './sealShare.js'
9
+
10
+ /** The request a wrap's proof is over (custody.mjs WRAP_REQUEST): never one a call could make. */
11
+ export const WRAP_REQUEST = '{"wrap":1}'
12
+ const enc = new TextEncoder()
13
+ const b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
14
+ const unb64 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0))
15
+
16
+ /** The proof (HMAC(callKey, nonce ‖ "\n" ‖ sha256(request))) and the callKey sealed to the attested share key, for THIS wrap. */
17
+ export async function wrapProof({ callKey, nonce, key }) {
18
+ const reqHash = new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(WRAP_REQUEST)))
19
+ const hk = await crypto.subtle.importKey('raw', unb64(callKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
20
+ const msg = new Uint8Array([...enc.encode(String(nonce) + '\n'), ...reqHash])
21
+ const [mac, keySealed] = await Promise.all([ // one hop each on WebKit, run together (webkit-webcrypto-await-per-call)
22
+ crypto.subtle.sign('HMAC', hk, msg).then(b64),
23
+ sealTo(key, crypto.getRandomValues(new Uint8Array(16)), { v: 1, callKey, nonce, reqHash: b64(reqHash) }),
24
+ ])
25
+ return { mac, keySealed }
26
+ }
27
+
28
+ /**
29
+ * Lock every listed connection the Sentinel marks `locked: false` whose key can be reached here.
30
+ * @param {object} o
31
+ * @param {(body) => Promise<object>} o.post — the Space client's sentinel post ({ op:'sentinel', sentinel, ...auth })
32
+ * @param {Array<{ id, locked? }>} o.list — credlist's connections (an older Sentinel marks none: nothing is asked)
33
+ * @param {() => Promise<{ key: CryptoKey, spki?: Uint8Array }>} o.attest — the standing Sentinel, attested (connections.js)
34
+ * @param {(id, nonce, key, spki) => Promise<{ mac, keySealed } | null>} o.proofOf — null: this device does not hold its key
35
+ * → { locked, failed, skipped } — never throws for one connection.
36
+ */
37
+ export async function lockConnections({ post, auth = {}, list, attest, proofOf }) {
38
+ const out = { locked: 0, failed: 0, skipped: 0 }
39
+ const todo = (Array.isArray(list) ? list : []).filter((c) => c && typeof c.id === 'string' && c.locked === false)
40
+ if (!todo.length) return out
41
+ const att = await attest()
42
+ for (const c of todo) {
43
+ try {
44
+ const n = await post({ op: 'sentinel', sentinel: { mode: 'crednonce' }, ...auth })
45
+ if (!n || typeof n.nonce !== 'string') { out.failed++; continue }
46
+ const p = await proofOf(c.id, n.nonce, att.key, att.spki)
47
+ if (!p) { out.skipped++; continue }
48
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'credwrap', connection: c.id, nonce: n.nonce, mac: p.mac, request: WRAP_REQUEST, keySealed: p.keySealed }, ...auth })
49
+ if (r && r.ok && r.locked) out.locked++; else out.failed++
50
+ } catch { out.failed++ }
51
+ }
52
+ return out
53
+ }
@@ -0,0 +1,89 @@
1
+ // connectionEntry.js — what a ROOM keeps about a connection (its sealed config), bounded: never a secret; for an MCP
2
+ // server, the tools the members chose and which of them run without asking (docs/mcp-connections.md § 5).
3
+ // Shared by spaceClient.setConfig (the write) and the Connections sheet (what it shows), so the two cannot disagree.
4
+
5
+ export const MCP_TOOLS_PER_SERVER = 40 // = agent/connectionTools.mjs MCP_TOOLS_PER_SERVER (the server drops the rest)
6
+ const TOOL_NAME = /^[A-Za-z0-9_.-]{1,64}$/
7
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v)
8
+
9
+ /** One tool as the room keeps it: name, title, description, input schema (≤ 8 KB), the server's read-only claim. */
10
+ export function roomTool(t) {
11
+ if (!isObj(t) || !TOOL_NAME.test(String(t.name || ''))) return null
12
+ const schema = isObj(t.inputSchema) && JSON.stringify(t.inputSchema).length <= 8192 ? t.inputSchema : { type: 'object', properties: {} }
13
+ return { name: String(t.name), title: String(t.title || '').slice(0, 120), description: String(t.description || '').slice(0, 1000), inputSchema: schema, readOnly: t.readOnly === true }
14
+ }
15
+
16
+ // AN AGENT THAT TAKES JOBS (jobAgents.js, docs/job-agents.md): where a job goes in the request and the fixed headers every
17
+ // call carries. Kept only on a webhook connection. The credential headers can never be named here — the Sentinel drops them
18
+ // anyway (custody.mjs CALLER_HEADER_DROP). ≡ agent/connectionTools.mjs jobOf (a test holds them equal).
19
+ const JOB_FIELD = /^[A-Za-z_][A-Za-z0-9_]{0,23}$/, JOB_HEADER = /^[a-z0-9][a-z0-9-]{0,39}$/
20
+ export const JOB_HEADER_DROP = new Set(['authorization', 'cookie', 'host', 'connection', 'content-length', 'transfer-encoding', 'x-api-key', 'webhook-id', 'webhook-timestamp', 'webhook-signature'])
21
+ export function roomJob(j) {
22
+ if (!isObj(j)) return null
23
+ const headers = {}
24
+ for (const [k, v] of Object.entries(isObj(j.headers) ? j.headers : {}).slice(0, 6)) {
25
+ const lk = String(k).toLowerCase()
26
+ if (JOB_HEADER.test(lk) && !JOB_HEADER_DROP.has(lk) && !lk.startsWith('x-witbitz-') && typeof v === 'string' && v.length <= 200 && !/[\r\n]/.test(v)) headers[lk] = v
27
+ }
28
+ return { field: JOB_FIELD.test(String(j.field || '')) ? String(j.field) : 'text', headers }
29
+ }
30
+
31
+ /** A connection entry → its bounded form, or null. `mcp` is kept only with at least one tool. */
32
+ export function roomConnection(x) {
33
+ if (!isObj(x) || !x.id || !x.account || !x.callKey) return null
34
+ const out = { account: String(x.account), id: String(x.id), callKey: String(x.callKey), label: String(x.label || '').slice(0, 80), host: String(x.host || '') }
35
+ if (typeof x.webhook === 'string' && /^\/[^\s?#]{1,199}$/.test(x.webhook)) out.webhook = x.webhook // a signed webhook's one path, so the assistant can name it (docs/signed-webhooks.md)
36
+ if (out.webhook && isObj(x.job)) out.job = roomJob(x.job) // an agent that takes jobs (jobAgents.js)
37
+ if (isObj(x.mcp) && Array.isArray(x.mcp.tools)) {
38
+ const tools = x.mcp.tools.map(roomTool).filter(Boolean).slice(0, MCP_TOOLS_PER_SERVER)
39
+ const names = new Set(tools.map((t) => t.name))
40
+ if (tools.length) {
41
+ out.mcp = {
42
+ tools,
43
+ auto: (Array.isArray(x.mcp.auto) ? x.mcp.auto.map(String) : []).filter((n) => names.has(n)),
44
+ ...(x.mcp.own === true ? { own: true } : {}),
45
+ ...(Number.isFinite(x.mcp.listedAt) ? { listedAt: x.mcp.listedAt } : {}),
46
+ // THE TOOL BOOK (agent/toolBook.mjs): the tools' descriptions and schemas, stored once in the room — the entry keeps names
47
+ ...(isObj(x.mcp.book) && /^i_[A-Za-z0-9_-]{8,64}$/.test(String(x.mcp.book.ref || '')) && /^[0-9a-f]{64}$/.test(String(x.mcp.book.sha256 || '')) ? { book: { ref: x.mcp.book.ref, sha256: x.mcp.book.sha256 } } : {}),
48
+ }
49
+ }
50
+ }
51
+ // reads run without asking (agent/connectionTools.mjs readsRunAlone): a GET through it runs in the turn; every other call is a card
52
+ if (x.reads === 'auto' && !out.mcp) out.reads = 'auto'
53
+ return out
54
+ }
55
+
56
+ /** The room's current list + a DECLARATIVE patch ({ add } | { remove } | { update: { id, mcp } } | a whole list). */
57
+ export function applyConnectionsPatch(cur, c) {
58
+ const list = Array.isArray(cur) ? cur : []
59
+ const v = c == null ? null
60
+ : Array.isArray(c) ? c
61
+ : c.add ? [...list.filter((x) => x && x.id !== c.add.id), c.add]
62
+ : c.remove ? list.filter((x) => x && x.id !== c.remove)
63
+ : c.update && c.update.id ? list.map((x) => (x && x.id === c.update.id ? { ...x, ...('mcp' in c.update ? { mcp: c.update.mcp } : {}), ...('reads' in c.update ? { reads: c.update.reads } : {}) } : x))
64
+ : list
65
+ return v == null ? undefined : v.map(roomConnection).filter(Boolean).slice(0, 32)
66
+ }
67
+
68
+ // The name the model calls an MCP tool by — `<label>__<tool>`. ≡ agent/connectionTools.mjs mcpToolName (a test holds them
69
+ // equal), so a card and the typing line can say which server and tool a proposed call is for.
70
+ const slug = (s, n) => String(s || '').toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, n)
71
+ export function mcpToolName(conn, tool) {
72
+ const left = slug(conn.label || conn.host || conn.id, 24) || 'server'
73
+ return `${left}__${slug(tool, 64 - left.length - 2) || 'tool'}`
74
+ }
75
+ /** A proposed action's type → { conn, tool } for the room's MCP connections, or null. */
76
+ export function mcpToolFor(connections, type) {
77
+ if (typeof type !== 'string' || !type.includes('__')) return null
78
+ for (const c of Array.isArray(connections) ? connections : []) {
79
+ if (!c || !c.mcp || !Array.isArray(c.mcp.tools)) continue
80
+ const t = c.mcp.tools.find((x) => x && mcpToolName(c, x.name) === type)
81
+ if (t) return { conn: c, tool: t }
82
+ }
83
+ return null
84
+ }
85
+ /** A call's arguments as short lines a person can read: "title: Fix the login bug". */
86
+ export function argLines(args, { max = 8, len = 160 } = {}) {
87
+ if (!args || typeof args !== 'object') return []
88
+ return Object.entries(args).slice(0, max).map(([k, v]) => { const s = typeof v === 'string' ? v : JSON.stringify(v); return `${k}: ${s.length > len ? s.slice(0, len) + '…' : s}` })
89
+ }