@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/connections.js ADDED
@@ -0,0 +1,562 @@
1
+ // connections.js — the page's half of the STANDING Sentinel (docs/standing-sentinel.md §3): attach an API key to your
2
+ // account so a Space can use it without ever holding it.
3
+ //
4
+ // attach: attest the Sentinel (through op:'sentinel', a pipe) → seal { account, id, host, secret, callKey… } to its
5
+ // share key over the attest nonce → credgrant → put { account, id, callKey, label, host } into this room's
6
+ // sealed config (setConfig; `connections` is one of the fields that may change in place). The SECRET goes
7
+ // only into the seal. The callKey goes into the seal AND the room: it is what lets THIS room spend it.
8
+ // list: what the Sentinel holds for the signed-in account — never a secret, never a callKey.
9
+ // detach: credrevoke (the Sentinel deletes the record and stops every room at once) + drop it from this room.
10
+ // use/unuse: add or drop an existing connection in THIS room (record only; the Sentinel is not involved).
11
+ //
12
+ // The page never talks to the Sentinel's front directly (self-signed, off the CSP): the Lambda forwards, and learns
13
+ // nothing from a sealed grant. The account is the VERIFIED sign-in's email — the Lambda sets it from the token, and
14
+ // the Sentinel refuses a sealed grant whose account is not that one — so `account` here must be the signed-in email.
15
+ import { CATALOG } from './connCatalog.js'
16
+ import { verifyAttestation } from './nitroVerify.js'
17
+ import { sentinelPcrOfRelease } from './sentinelRelease.js' // a Sentinel build not pinned here, checked by its build-enclave release record
18
+ import { sealTo } from './sealShare.js'
19
+ import { adoptPendingKeys } from './connPending.js' // a key whose grant answer was lost (N#7): the rule both keepers use
20
+ import { sealDisp, withDisplay } from './connDisp.js' // step 2: a connection's name sealed to the person's devices (docs/standing-sentinel.md)
21
+
22
+ /** The standing Sentinel's image, a rollover set of PCR0s (docs/standing-sentinel.md; infra/enclave/sentinel-host/README.md
23
+ * for the repin). Empty would mean attach REFUSES: the page will not seal an API key to an enclave it cannot name.
24
+ * Pin it here and in the Lambda's SENTINEL_HOP_PCRS together. */
25
+ export const STANDING_SENTINEL_PCR0 = ['1903ce28fc5a75efe2e57a451d667f1ce8b4b6e11872fb2b81d9e62d8cd994ed80fcfa99807f289af5f281aa4e4cc010', '267a82525bbdc8f17ed32792f887dad9b06629350da41c0357ad0a6d67a3b2a8aba0a93e1d3ee9ae56bdd07948eeff98'] // st56 and st55 during the rollout
26
+
27
+ const b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
28
+ const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0))
29
+ const b64u = (u8) => b64(u8).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
30
+ export const CONNECTION_HOST = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.[a-z]{2,63}$/
31
+
32
+ export class ConnectionError extends Error { constructor(m, code = '') { super(m); this.code = code } }
33
+
34
+ /**
35
+ * Attest the standing Sentinel: a fresh nonce, its `attest` op through the Lambda, the Nitro document verified against
36
+ * the pinned root + STANDING_SENTINEL_PCR0 + the nonce, the role in user_data, and its P-384 share key imported.
37
+ * @param {{ post: (body:object)=>Promise<object>, auth: object, pins?: string[], verify?: Function }} o
38
+ * @returns {{ nonce: Uint8Array, key: CryptoKey }}
39
+ */
40
+ // A NEW PUBLISHED SENTINEL BUILD IS FOLLOWED, NOT REFUSED (the owner, 2026-10-15: an app open across a Sentinel repin said
41
+ // "PCR0 mismatch" — "we have a flag for that. It should follow the published releases" → "and if that flag is not set ask
42
+ // the user"). The pins above are this build's; Witbitz publishes the current set at /sentinel-claim.json (held equal to them
43
+ // by test, network-only in both workers, like /enclave-claim.json). On a mismatch the app reads it: a build named there is
44
+ // accepted at once when "Accept new Witbitz builds automatically" is on, and the person is ASKED when it is off. The shell
45
+ // wires the flag and the question (setSentinelFollow); with none wired (the SDK, a test) nothing changes.
46
+ const ACCEPTED_KEY = 'space:sentinelAccepted'
47
+ let _follow = null
48
+ export const setSentinelFollow = (f) => { _follow = f && typeof f.auto === 'function' && typeof f.ask === 'function' ? f : null }
49
+ const acceptedPcrs = () => { try { const a = JSON.parse(localStorage.getItem(ACCEPTED_KEY) || '[]'); return Array.isArray(a) ? a.filter((x) => /^[0-9a-f]{96}$/.test(x)) : [] } catch { return [] } }
50
+ const rememberPcr = (p) => { try { const a = acceptedPcrs(); if (!a.includes(p)) localStorage.setItem(ACCEPTED_KEY, JSON.stringify([...a, p].slice(-4))) } catch { /* */ } }
51
+ /** The standing Sentinel builds this device trusts now, newest first, at most two: a build it accepted by its published claim or its
52
+ * verified release record (rememberPcr), then this app's pins. A cloud computer's grant names these (codeCloud.js `standing`). */
53
+ export const trustedSentinelPins = () => [...new Set([...acceptedPcrs().reverse(), ...STANDING_SENTINEL_PCR0])].slice(0, 2)
54
+ export async function publishedSentinelPins(fetchImpl = (u, o) => fetch(u, o), url = '/sentinel-claim.json') {
55
+ try { const r = await fetchImpl(url, { cache: 'no-store' }); if (!r.ok) return []; const c = await r.json(); return Array.isArray(c && c.pcr0) ? c.pcr0.filter((x) => /^[0-9a-f]{96}$/.test(x)) : [] } catch { return [] }
56
+ }
57
+ /** Verify against this build's pins (and builds the person already accepted); on a mismatch, a PUBLISHED newer build by the flag or the person's yes. */
58
+ // `follow` per call (the SDK: each instance its own, and the claim read from Witbitz's site, not the builder's — sync sweep
59
+ // 10-16 #4: no SDK release could follow a Sentinel repin, so each lost connections when its pins were narrowed away).
60
+ async function verifyFollowing(verify, docBytes, { nonce, pins, follow, release = null, links = null }) {
61
+ const f = follow || _follow
62
+ const following = f && pins === STANDING_SENTINEL_PCR0
63
+ // ★ THE PINS, THEN EACH ACCEPTED BUILD ON ITS OWN (the owner, 2026-10-21, Claude Code's card: "PCR0 pins 3 values; at most
64
+ // 2"): adding the builds this device once accepted to the pins made a set of 3 under a rollover, which the verifier
65
+ // refuses before it compares — every device that ever followed a Sentinel build lost its connections.
66
+ const tryPins = (set) => verify(docBytes, { nonce, maxAgeMs: 120_000, expectedPCRs: { 0: set } })
67
+ const known = following ? [...new Set([...pins, ...acceptedPcrs()])] : pins
68
+ try { return await tryPins(pins) } catch (first) {
69
+ if (!following || !/PCR0/i.test(String((first && first.message) || first))) throw first
70
+ for (const p of known.filter((x) => !pins.includes(x))) { try { return await tryPins([p]) } catch { /* not this one */ } }
71
+ // ITS RELEASE RECORD (docs/standing-sentinel.md § Following verified releases): the build enclave's signed verdict for the running
72
+ // build came with the attestation — a build that verifies there is followed like a published one (the flag, or the person's yes)
73
+ if (release) {
74
+ let p = null; try { p = await sentinelPcrOfRelease(release, { links }) } catch { p = null } // + the build-enclave links beside it (docs/trust-root.md)
75
+ if (p && !known.includes(p)) {
76
+ let doc = null; try { doc = await tryPins([p]) } catch { doc = null }
77
+ if (doc) {
78
+ if (f.auto() || await f.ask(p)) { rememberPcr(p); return doc }
79
+ throw new ConnectionError('you did not accept the new Witbitz Sentinel build, so nothing was sent to it', 'declined')
80
+ }
81
+ }
82
+ }
83
+ for (const p of (await publishedSentinelPins(f.fetch || undefined, f.claimUrl || undefined)).filter((x) => !known.includes(x))) {
84
+ let doc = null; try { doc = await verify(docBytes, { nonce, maxAgeMs: 120_000, expectedPCRs: { 0: [p] } }) } catch { continue }
85
+ if (f.auto() || await f.ask(p)) { rememberPcr(p); return doc }
86
+ throw new ConnectionError('you did not accept the new Witbitz Sentinel build, so nothing was sent to it', 'declined')
87
+ }
88
+ throw first
89
+ }
90
+ }
91
+ export async function attestStandingSentinel({ post, auth = {}, pins = STANDING_SENTINEL_PCR0, verify = verifyAttestation, follow = null }) {
92
+ if (!Array.isArray(pins) || !pins.length) throw new ConnectionError('the standing Sentinel is not pinned in this build — nothing can be attached yet', 'unpinned')
93
+ const nonce = crypto.getRandomValues(new Uint8Array(32))
94
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'attest', nonce: b64(nonce) }, ...auth })
95
+ if (!r || r.error || typeof r.doc !== 'string') throw new ConnectionError(`the Sentinel could not be reached (${(r && r.error) || 'no attestation'})`, (r && r.error) || 'unreachable')
96
+ let doc
97
+ try { doc = await verifyFollowing(verify, unb64(r.doc), { nonce, pins, follow, release: r.release && typeof r.release === 'object' ? r.release : null, links: Array.isArray(r.links) ? r.links : null }) }
98
+ catch (e) { if (e instanceof ConnectionError) throw e; throw new ConnectionError(`the Sentinel is not running the published Witbitz image, so nothing was sent to it (${String((e && e.message) || e).split('\n')[0]})`, 'attestation') }
99
+ let said = null
100
+ try { said = JSON.parse(new TextDecoder().decode(doc.userData || new Uint8Array(0))) } catch { /* below */ }
101
+ if (!said || said.role !== 'sentinel') throw new ConnectionError('the attestation does not name a Sentinel, so nothing was sent to it', 'attestation')
102
+ const key = await crypto.subtle.importKey('spki', doc.publicKey, { name: 'ECDH', namedCurve: 'P-384' }, false, [])
103
+ return { nonce, key, spki: new Uint8Array(doc.publicKey) } // spki: the same key's bytes, for a minter that seals elsewhere (the hosted app's vault)
104
+ }
105
+
106
+ /** The entry a ROOM keeps (its sealed config): enough to name and spend the connection, never the secret. */
107
+ export const roomEntry = (c) => ({ account: c.account, id: c.id, callKey: c.callKey, label: c.label || '', host: c.host, ...(c.mcp ? { mcp: c.mcp } : {}), ...(c.webhook ? { webhook: c.webhook } : {}), ...(c.webhook && c.job ? { job: c.job } : {}), ...(c.reads === 'auto' && !c.mcp ? { reads: 'auto' } : {}) }) // reads: a GET through it runs without asking (connectionEntry.js keeps it; agent/connectionTools.mjs readsRunAlone)
108
+
109
+ /**
110
+ * Attach: seal to the Sentinel, grant, then record in this room through `record(patch, by)` — the shell passes
111
+ * `(patch, by) => l1.setConfig(room, patch, by)`; the patch is DECLARATIVE ({ add: entry }) because it crosses the L1
112
+ * façade by structured clone, and spaceClient.setConfig applies it to the room's current list under its own key.
113
+ * @returns {{ id: string, label: string, host: string, callKey: string }}
114
+ */
115
+ export async function attachConnection({ post, auth = {}, record, by, account, label, host, secret, rules, limits, pins, verify, follow, tenant, bearerWebhook, dispKey } = {}) { // dispKey: connDisp.js — the name also goes sealed to the person's devices (step 2)
116
+ const acct = String(account || '').trim().toLowerCase()
117
+ if (!/^[^\s@]{1,200}@[^\s@]{1,63}$/.test(acct)) throw new ConnectionError('sign in with your email first — a connection belongs to an account', 'account')
118
+ const s = String(secret || '')
119
+ if (!s.trim() || s.length > 4000 || /[\r\n]/.test(s)) throw new ConnectionError('paste the API key or token, on one line', 'secret')
120
+ // A SIGNED WEBHOOK (docs/signed-webhooks.md): a whsec_ secret means the receiver wants each request SIGNED, not the
121
+ // secret in a header (Grok Bot's routines). The member pastes the webhook's whole address; it becomes the host and the
122
+ // ONE path this connection may call, and the Sentinel signs every approved request.
123
+ // A BEARER WEBHOOK (Grok Bot's desktop routines): the same one-path, POST-only shape, the key sent as a Bearer header.
124
+ const signed = /^whsec_/.test(s.trim()) || bearerWebhook === true
125
+ let path = ''
126
+ if (signed) {
127
+ let u = null; try { u = new URL(/^https?:\/\//i.test(String(host || '').trim()) ? String(host).trim() : 'https://' + String(host || '').trim()) } catch { u = null }
128
+ if (!u || u.protocol !== 'https:' || !u.pathname || u.pathname === '/' || u.search || u.port) throw new ConnectionError('for a webhook, paste its whole https address (with its path) as the host', 'host')
129
+ path = u.pathname
130
+ }
131
+ const h = String(host || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/[/?#].*$/, '')
132
+ if (!CONNECTION_HOST.test(h)) throw new ConnectionError('the host must be a bare domain name, like api.example.com', 'host')
133
+ const lbl = String(label || '').trim().slice(0, 80) || h
134
+ const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
135
+ const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
136
+ // The TENANT this was attached under, when there is one: its declaration is what vouches for the host, and the
137
+ // Sentinel refuses an attach for a host it has not declared (docs/oauth-providers.md). Absent → the pre-tenant
138
+ // behaviour, unchanged.
139
+ const disp = dispKey ? await sealDisp(dispKey, id, { label: lbl }).catch(() => '') : '' // opaque to the Sentinel; '' → as before
140
+ const grant = signed
141
+ ? { id, account: acct, provider: 'bearer', host: h, secret: s.trim(), label: lbl, ...(disp ? { disp } : {}), sign: /^whsec_/.test(s.trim()) ? 'standard-webhooks' : 'bearer', rules: { paths: [path] }, own: true, ...(limits ? { limits } : {}) } // a SIGNED WEBHOOK is the member's own, never under a tenant: the tenant vouches for API hosts, and a webhook's host is wherever the member's routine lives (the app's rule, now here for every caller — the SDK filed it under its tenant and the Sentinel refused the host; sync sweep, 2026-10-10)
142
+ : { id, account: acct, provider: 'bearer', host: h, secret: s.trim(), label: lbl, ...(disp ? { disp } : {}), ...(tenant ? { tenant: String(tenant) } : {}), ...(rules ? { rules } : {}), ...(limits ? { limits } : {}) }
143
+ const sk = await sealWithCallKey(att, grant, id, { label: lbl, host: h, account: acct })
144
+ const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host: h, account: acct, at: Date.now() }, sk)
145
+ if (!g || g.error || !g.ok) throw new ConnectionError(`the Sentinel refused the connection (${(g && g.error) || 'no answer'})`, (g && g.error) || 'refused')
146
+ // ⛔ THE CONNECTION IS RETURNED EVEN WHEN THE SPACE COULD NOT RECORD IT (2026-11-08, docs/state-machines.md I16 / C#11): this threw
147
+ // after the Sentinel had taken the grant — the callKey was dropped with the error, the Sentinel kept a connection no device
148
+ // could use, and "attach it again" made a second one. Now the caller keeps it (the account has it) and says the Space did not
149
+ // take it: it is added to the Space from the account's connections, the same connection.
150
+ let roomError = ''
151
+ if (typeof record === 'function') {
152
+ let r = null; try { r = await record({ connections: { add: roomEntry({ ...grant, callKey: sk.callKey, ...(signed ? { webhook: path } : {}) }) } }, by) } catch { r = null } // held: no callKey here — the vault fills it by id
153
+ if (!r || r.status !== 200) roomError = String((r && r.error) || (r && r.status) || 'no answer')
154
+ }
155
+ return { id, label: lbl, host: h, callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}), ...(signed ? { webhook: path } : {}), ...(roomError ? { roomError } : {}) } // the callKey is the page's own material: the caller keeps it for other Spaces (held: the vault's — the caller keeps a stub)
156
+ }
157
+
158
+ // ⛔ A KEY WHOSE ANSWER WAS LOST (state machines pass 9, N#7). The callKey is made here and sealed into the grant / the sign-in's
159
+ // finish; the Sentinel files the connection and this device keeps the key only when the ANSWER arrives. An answer lost on
160
+ // the way left a connection the account lists that no device holds a key for — unusable, and the one-per-service rule then
161
+ // stopped a second sign-in. The key is kept as PENDING before the request leaves (the page's store — connectionsSheet.js),
162
+ // dropped on a definite answer (the caller keeps a granted one), and adopted when the account's list shows it.
163
+ let _pendingStore = { keep () {}, drop () {} }
164
+ export const setPendingKeyStore = (s) => { _pendingStore = { keep () {}, drop () {}, ...(s || {}) } }
165
+ export async function postWithPendingKey (post, body, id, rec) {
166
+ const store = _pendingStore
167
+ try { await store.keep(id, rec) } catch (e) { if (store.durable) throw e }
168
+ const r = await post(body) // a throw (no answer) leaves it pending
169
+ if (r && (r.error || (r.ok && !store.durable))) { try { await store.drop(id) } catch { /* */ } }
170
+ return r
171
+ }
172
+ export { adoptPendingKeys } // connPending.js — the rule, shared with the hosted app's vault (vaultConnKeys.js)
173
+
174
+ // ── WHO MINTS THE CALLKEY. Here, by default. In the HOSTED app the VAULT does (the owner, 2026-11-14: "Close the gaps" — §7.5 of
175
+ // docs/vault-core-convergence-review.md left the attach minting it in the frame): the page attests the Sentinel as always and
176
+ // hands the vault the attested key's bytes, the nonce and the grant WITHOUT a callKey; the vault mints one, keeps it PENDING
177
+ // (its own `space:connPending`), puts it in, seals the whole to that key and answers only the sealed bundle. The page posts it;
178
+ // on a definite answer it SETTLES (filed → the vault holds the key with the account's others; refused → the vault drops it),
179
+ // and keeps a stub. So the callKey is never in this page — not in memory, not in storage. A minter that does not answer, or
180
+ // refuses (an older vault, a protected device still locked): minted here, as before. Never worse.
181
+ let _minter = null
182
+ export const setCallKeyMinter = (m) => { _minter = m && typeof m.seal === 'function' ? m : null }
183
+ /** `payload` + a fresh callKey, sealed to the attested Sentinel → { sealed, callKey ('' when the vault holds it), held, settle } */
184
+ async function sealWithCallKey (att, payload, id, rec) {
185
+ if (_minter && att.spki) {
186
+ let v = null; try { v = await _minter.seal({ spki: att.spki, nonce: att.nonce, payload, id, rec }) } catch { v = null }
187
+ if (v && v.sealed) return { sealed: v.sealed, callKey: '', held: true, settle: v.settle }
188
+ }
189
+ const callKey = b64(crypto.getRandomValues(new Uint8Array(32)))
190
+ return { sealed: await sealTo(att.key, att.nonce, { ...payload, callKey }), callKey, held: false, settle: null }
191
+ }
192
+ /** Post a grant; while its answer is out the key is PENDING — in this page's store (rec = null: none), or the vault's, which a
193
+ * definite answer settles: `filed` = it was filed (r.ok), `final(r)` = what the Sentinel filed it as ({ id, label, account }). */
194
+ async function postGrant (post, body, id, rec, sk, filed = (r) => !!(r && r.ok && !r.error), final = () => ({})) {
195
+ if (!sk.held) return rec ? postWithPendingKey(post, body, id, { ...rec, callKey: sk.callKey }) : post(body)
196
+ const r = await post(body) // a throw (no answer): the vault keeps it pending, adopted when the account lists it
197
+ if (r && (r.ok || r.error)) { let ok = false; try { ok = !!(await sk.settle(filed(r), filed(r) ? final(r) : {})) } catch { ok = false } if (filed(r) && !ok) throw new ConnectionError('the connection was made, but your vault did not keep its key — open Connections again to finish', 'vault') }
198
+ return r
199
+ }
200
+
201
+ /** The signed-in account's connections, as the Sentinel lists them (no secret, no callKey). */
202
+ export async function listConnections({ post, auth = {}, dispKey }) { // dispKey: each sealed name is opened (connDisp.withDisplay)
203
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'credlist' }, ...auth })
204
+ if (!r || r.error) throw new ConnectionError(`could not list connections (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
205
+ return withDisplay(Array.isArray(r.connections) ? r.connections : [], dispKey || null)
206
+ }
207
+
208
+ /** Detach everywhere (the Sentinel forgets it; every room's callKey for it is dead), and drop it from this room. */
209
+ export async function detachConnection({ post, auth = {}, record, by, id }) {
210
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'credrevoke', id }, ...auth })
211
+ if (!r || r.error) throw new ConnectionError(`could not detach (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
212
+ if (typeof record === 'function') await record({ connections: { remove: id } }, by)
213
+ return { revoked: Number(r.revoked) || 0 }
214
+ }
215
+ /** Drop a connection from THIS room only (it stays attached to the account and usable elsewhere). */
216
+ export const unuseConnection = ({ record, by, id }) => record({ connections: { remove: id } }, by)
217
+
218
+ // ── MCP SERVERS AS CONNECTIONS (docs/mcp-connections.md) ─────────────────────────────────────────────────────────────
219
+ // A remote MCP server is attached like a key, at one endpoint (https://host/path). Either a token the member pastes, or
220
+ // the server's OWN sign-in: the Sentinel discovers it, registers Witbitz as an app there and hands back a consent URL;
221
+ // the member's browser consents; /mcp-callback hands the code back here; the code and the room's callKey ride SEALED to
222
+ // the Sentinel, which exchanges it inside. The page never holds the server's token.
223
+ //
224
+ // Servers Witbitz lists (the owner's (c), 2026-10-10): a quick pick, and their cards read as the service. Any other
225
+ // server is the member's OWN — allowed, and said so on every card.
226
+ // The catalog Connections offers (connCatalog.js — each address passed the Sentinel's sign-in steps). Labels/urls only here.
227
+ export const MCP_CURATED = CATALOG.filter((c) => c.url).map((c) => ({ label: c.name, url: c.url })) // sign-in services only: an agent's webhook (kind 'webhook') has its own form
228
+ /** "https://mcp.linear.app/mcp" (or a bare host) → { host, path }, or throws a ConnectionError. */
229
+ export function parseMcpUrl(raw) {
230
+ let s = String(raw || '').trim()
231
+ if (!s) throw new ConnectionError('paste the MCP server’s address, like https://mcp.example.com/mcp', 'url')
232
+ if (!/^https?:\/\//i.test(s)) s = 'https://' + s
233
+ let u
234
+ try { u = new URL(s) } catch { throw new ConnectionError('that is not an address, like https://mcp.example.com/mcp', 'url') }
235
+ if (u.protocol !== 'https:' || u.port || u.username || u.password || u.search || u.hash) throw new ConnectionError('the address must be https, with no port or query', 'url')
236
+ const host = u.hostname.toLowerCase()
237
+ if (!CONNECTION_HOST.test(host)) throw new ConnectionError('the address must be on a domain name, like mcp.example.com', 'url')
238
+ // THE ROOT IS A PATH TOO (2026-11-16: Vercel attached with "the MCP server refused to start a session (404)"): Vercel, Stripe,
239
+ // Calendly, Gusto and HTML/CSS to Image serve MCP at "/" and answer /mcp with 404. A root address keeps "/" when the catalog lists
240
+ // it so, or when it is typed with its trailing slash; only a BARE host ("mcp.example.com") guesses the common /mcp.
241
+ let path = u.pathname || '/'
242
+ if (path === '/') {
243
+ const cur = CATALOG.find((c) => { try { return c.url && new URL(c.url).hostname === host } catch { return false } })
244
+ const typedRoot = /^https:\/\/[^/]+\/$/i.test(s)
245
+ path = cur ? new URL(cur.url).pathname : typedRoot ? '/' : '/mcp'
246
+ }
247
+ return { host, path }
248
+ }
249
+ export const isCurated = (host) => MCP_CURATED.some((c) => { try { return new URL(c.url).hostname === host } catch { return false } })
250
+ /** What to CALL a connection on screen: the label a member gave it — unless it is empty or just the host (a phone that
251
+ * finished the sign-in without the name stored the host as the label: "api.githubcopilot.com · api.githubcopilot.com"),
252
+ * then the server's known name (GitHub), then the host. Never changes the stored label or the tools' names. */
253
+ export function connectionName (c) {
254
+ const host = String((c && c.host) || '').toLowerCase(), label = String((c && c.label) || '').trim()
255
+ if (label && label.toLowerCase() !== host) return label
256
+ const known = MCP_CURATED.find((k) => { try { return new URL(k.url).hostname === host } catch { return false } })
257
+ return known ? known.label : (host || String((c && c.id) || ''))
258
+ }
259
+
260
+ /** Attach an MCP server with a token (or none, for an open server). Same seal as attachConnection.
261
+ * ALWAYS THE MEMBER'S OWN (`own: true`), NEVER UNDER A TENANT — for every caller, as a signed webhook is (attachConnection) and as
262
+ * the Sentinel files every MCP sign-in (custody.mjs mcpOauthFinish): the owner's (c), docs/mcp-connections.md — its host is
263
+ * reachable while this connection lives, and a tenant's declared hosts vouch only for plain keys. (The SDK passed its tenant
264
+ * here, and the Sentinel refused every MCP host the builder had not declared — DeepWiki included; docs sync, 2026-11-22.)
265
+ * "Your own server" on a room's card is another mark: a server not in the catalog (connectionEntry.js, isCurated). */
266
+ export async function attachMcp({ post, auth = {}, account, label, url, token = '', pins, verify, follow, dispKey, sealGrant = sealWithCallKey } = {}) {
267
+ const acct = String(account || '').trim().toLowerCase()
268
+ if (!/^[^\s@]{1,200}@[^\s@]{1,63}$/.test(acct)) throw new ConnectionError('sign in with your email first — a connection belongs to an account', 'account')
269
+ const { host, path } = parseMcpUrl(url)
270
+ const t = String(token || '').trim()
271
+ if (t.length > 4000 || /[\r\n]/.test(t)) throw new ConnectionError('paste the token on one line', 'secret')
272
+ const lbl = String(label || '').trim().slice(0, 80) || connectionName({ host }) // empty → the server's known name (GitHub), else the host
273
+ const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
274
+ const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
275
+ const disp = dispKey ? await sealDisp(dispKey, id, { label: lbl }).catch(() => '') : ''
276
+ const grant = { id, account: acct, provider: 'bearer', host, secret: t, label: lbl, ...(disp ? { disp } : {}), mcp: { path }, own: true }
277
+ const sk = await sealGrant(att, grant, id, { label: lbl, host, account: acct })
278
+ const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, account: acct, at: Date.now() }, sk)
279
+ if (!g || g.error || !g.ok) throw new ConnectionError(`the Sentinel refused the connection (${(g && g.error) || 'no answer'})`, (g && g.error) || 'refused')
280
+ return { id, label: lbl, host, callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}) }
281
+ }
282
+
283
+ /** Does this server want a sign-in? → { needsAuth:false } or { needsAuth:true, state, authUrl }. Opens nothing. */
284
+ export async function startMcpSignIn({ post, auth = {}, url, label, redirectUri = location.origin + '/mcp-callback' }) {
285
+ const { host, path } = parseMcpUrl(url)
286
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'mcpoauthstart', host, path, redirectUri, label: String(label || '').slice(0, 80) }, ...auth })
287
+ if (!r || r.error || !r.ok) throw new ConnectionError(`${host}: ${(r && r.error) || 'no answer from the Sentinel'}`, 'signin')
288
+ return r.needsAuth ? { needsAuth: true, state: r.state, authUrl: r.authUrl, host } : { needsAuth: false, host }
289
+ }
290
+
291
+ // THE WAY BACK FROM A WINDOW THAT SHARES NOTHING WITH THIS PAGE (the owner, 2026-11-18, the hosted app on an iPhone: Todoist signed
292
+ // in, the app waited for ever). An installed app on iOS opens the sign-in in an in-app browser: no storage, no BroadcastChannel in
293
+ // common, so /mcp-callback's two hand-backs never arrive. The window is opened on /mcp-callback FIRST, with the server's sign-in,
294
+ // a one-time key and an id in the fragment (never sent anywhere); it keeps the key in its own sessionStorage, goes on to the
295
+ // server, and on its way back seals { state, code } under that key and leaves it at the auth broker under the id
296
+ // (auth-broker/functions/api/handoff/drop.js — a ciphertext it cannot open, read once, to this origin only). `null` = an
297
+ // address the callback would refuse (not https, or it does not come back to this page's /mcp-callback) — open it as before.
298
+ // The broker: the app passes its own (connectionsSheet.js, stamped at deploy); no placeholder here — the SDK ships this file.
299
+ export const AUTH_BROKER_DEFAULT = 'https://auth.witbitz.chat'
300
+ export function nativeMcpOpener(url, bridge = globalThis.WitbitzAttest) {
301
+ if (!bridge) return null
302
+ try {
303
+ const { host } = parseMcpUrl(url)
304
+ // ⚑ 11·K#6: these two hand the sign-in back through the BROKER's drop (the browser deposits it, then wakes the app), so a page the OS
305
+ // recreated meanwhile can still collect it — `byBroker` lets the sheet keep the recoverable record for them (androidConsent.js)
306
+ if (host === 'mcp.linear.app' && bridge.openLinearConsent) return Object.assign(handoff => bridge.openLinearConsent(handoff + '&returnApp=android'), { byBroker: true })
307
+ if (BROKER_CALLBACK_HOSTS.test(host)) return bridge.openCalendarConsent ? Object.assign(handoff => bridge.openCalendarConsent(handoff + '&returnApp=android'), { byBroker: true }) : null
308
+ if ((bridge.openRecoverableConnector || bridge.openConnectorConsent) && bridge.takeConnectorResult) return Object.assign(handoff => {
309
+ const handle = bridge.openRecoverableConnector ? bridge.openRecoverableConnector(handoff) : bridge.openConnectorConsent(handoff)
310
+ if (!handle || handle === 'browser') return !!handle
311
+ return () => {
312
+ const result = bridge.takeConnectorResult(handle)
313
+ return result ? JSON.parse(result) : null
314
+ }
315
+ }, { recoverable: !!bridge.openRecoverableConnector })
316
+ } catch { /* the connection form reports an invalid URL */ }
317
+ return null
318
+ }
319
+ function returnTrip (u, page, origin, forApp = '') {
320
+ const key = crypto.getRandomValues(new Uint8Array(32)), sid = b64u(crypto.getRandomValues(new Uint8Array(24)))
321
+ return { openUrl: origin + page + '#' + new URLSearchParams({ go: u.toString(), k: b64u(key), d: sid, ...(forApp ? { o: forApp } : {}) }), drop: { sid, key } }
322
+ }
323
+ // GOOGLE'S MCP SERVERS SIGN IN THROUGH THE BROKER'S CALLBACK (2026-11-23, Google Calendar): Google verifies an app only with redirect
324
+ // addresses on domains its developer owns, and the regular app lives on pages.dev — so Witbitz's Google client registers
325
+ // <broker>/mcp-callback, the page served there leaves the sealed result FOR this app (auth-broker handoff/drop.js `for`), and the app
326
+ // takes it as before. Every other server comes back to the app's own /mcp-callback.
327
+ export const BROKER_CALLBACK_HOSTS = /\.googleapis\.com$/
328
+ export function mcpRedirectFor (host, { origin = location.origin, broker = AUTH_BROKER_DEFAULT, bridge = globalThis.WitbitzAttest } = {}) {
329
+ const server = String(host || '').toLowerCase()
330
+ const useBroker = BROKER_CALLBACK_HOSTS.test(server) || (server === 'mcp.linear.app' && bridge?.openLinearConsent)
331
+ return (useBroker ? String(broker).replace(/\/$/, '') : origin) + '/mcp-callback'
332
+ }
333
+ export function mcpReturnTrip (authUrl, { origin = location.origin, broker = AUTH_BROKER_DEFAULT } = {}) {
334
+ let u; try { u = new URL(String(authUrl)) } catch { return null }
335
+ if (u.protocol !== 'https:' || !/^[A-Za-z0-9_-]{16,64}$/.test(u.searchParams.get('state') || '')) return null
336
+ const back = u.searchParams.get('redirect_uri'), b = String(broker).replace(/\/$/, '')
337
+ if (back === origin + '/mcp-callback') return returnTrip(u, '/mcp-callback', origin)
338
+ if (back === b + '/mcp-callback' && b !== origin) return returnTrip(u, '/mcp-callback', b, origin) // the broker's page, for this app
339
+ return null
340
+ }
341
+ /** The same way back for the GitHub App's install (github-callback.html): GitHub's own install page only, with a state. */
342
+ export function gitHubReturnTrip (installUrl, { origin = location.origin } = {}) {
343
+ let u; try { u = new URL(String(installUrl)) } catch { return null }
344
+ if (u.origin !== 'https://github.com' || !/^\/apps\/[^/]+\/installations\/new$/.test(u.pathname) || !/^[A-Za-z0-9_-]{8,80}$/.test(u.searchParams.get('state') || '')) return null
345
+ return returnTrip(u, '/github-callback', origin)
346
+ }
347
+ const unb64u = (s) => unb64(String(s).replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (String(s).length % 4)) % 4))
348
+ async function takeDrop (drop, { broker = AUTH_BROKER_DEFAULT, fetchImpl = fetch } = {}) {
349
+ const r = await fetchImpl(broker + '/api/handoff/drop', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sid: drop.sid, take: true }) }).then((x) => x.json()).catch(() => null)
350
+ // a broker that will never hand this app anything (not admitted there): say so now, not after the ten-minute wait
351
+ if (r && r.ok === false && r.reason === 'origin_not_allowed') throw new ConnectionError('this app cannot collect sign-ins from the auth broker (its address is not admitted there)', 'signin')
352
+ if (!r || !r.ok || typeof r.blob !== 'string') return null
353
+ return openDrop(drop, r.blob)
354
+ }
355
+ async function openDrop (drop, blob) {
356
+ const box = unb64u(blob)
357
+ const k = await crypto.subtle.importKey('raw', drop.key, 'AES-GCM', false, ['decrypt'])
358
+ return JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: box.subarray(0, 12), additionalData: new TextEncoder().encode(drop.sid) }, k, box.subarray(12))))
359
+ }
360
+
361
+ /** The code /mcp-callback hands back for `state`: a BroadcastChannel message, the localStorage note it leaves, or — with `drop`
362
+ * (mcpReturnTrip) — what it sealed at the auth broker. */
363
+ // signal: an AbortSignal — the wait ends at once with a ConnectionError of kind 'cancel' (the owner, 2026-11-19: a service that
364
+ // shows its OWN error page never comes back, and the Connect button stayed grey for the whole ten minutes)
365
+ const DISMISS_GRACE_MS = 12_000 // 11·K#2: how long a dismissed Auth Tab's grant is looked for at the broker
366
+ export function awaitMcpCallback(state, { timeoutMs = 10 * 60_000, drop = null, broker, fetchImpl, dropEveryMs = 1500, readNative = null, checkDropOnDismiss = false, signal = null } = {}) {
367
+ return new Promise((resolve, reject) => {
368
+ let done = false, bc = null, iv = 0, to = 0, dv = 0, asking = null
369
+ const onAbort = () => { if (!done) { done = true; stop(); reject(new ConnectionError('the sign-in was started again', 'cancel')) } }
370
+ const stop = () => { clearInterval(iv); clearInterval(dv); clearTimeout(to); try { bc && bc.close() } catch { /* */ }; try { typeof document !== 'undefined' && document.removeEventListener('visibilitychange', onVis) } catch { /* */ }; try { signal && signal.removeEventListener('abort', onAbort) } catch { /* */ } }
371
+ if (signal) { if (signal.aborted) { onAbort(); return } signal.addEventListener('abort', onAbort) }
372
+ const finish = (m) => {
373
+ if (done || !m || m.state !== state) return
374
+ done = true; stop()
375
+ try { localStorage.removeItem('space:mcpcb:' + state) } catch { /* */ }
376
+ if (m.error) reject(new ConnectionError(`the sign-in did not finish (${String(m.error).slice(0, 80)})`, 'signin')); else resolve(String(m.code || ''))
377
+ }
378
+ const askDrop = () => {
379
+ if (done || !drop) return
380
+ if (!asking) asking = takeDrop(drop, { broker, fetchImpl }).then(finish).catch(e => {
381
+ if (e instanceof ConnectionError && !done) { done = true; stop(); reject(e) }
382
+ }).finally(() => { asking = null })
383
+ return asking
384
+ }
385
+ const readTab = () => {
386
+ if (!readNative || done) return
387
+ const reply = readNative()
388
+ // Some browsers dismiss the tab when its verified link foregrounds the app.
389
+ // The callback deposited its grant before navigating to that link.
390
+ // ⚑ 11·K#2: the drop is asked for a few seconds, not once — one miss (a dropped fetch, the deposit not visible yet) reported a
391
+ // consent that had succeeded as cancelled, and the recovery record went with it
392
+ if (reply?.error && checkDropOnDismiss && drop) void (async () => {
393
+ const until = Date.now() + DISMISS_GRACE_MS
394
+ for (;;) {
395
+ if (asking) await asking
396
+ if (!done) await askDrop()
397
+ if (done || Date.now() >= until) break
398
+ await new Promise((r) => setTimeout(r, Math.min(dropEveryMs, 1500)))
399
+ }
400
+ finish(reply)
401
+ })()
402
+ else finish(reply)
403
+ }
404
+ const onVis = () => { if (typeof document !== 'undefined' && document.visibilityState === 'visible') { readTab(); askDrop() } } // back from the sign-in: ask at once
405
+ try { bc = new BroadcastChannel('wb-mcp-signin'); bc.onmessage = (e) => finish(e.data) } catch { bc = null }
406
+ iv = setInterval(() => { readTab(); try { const v = localStorage.getItem('space:mcpcb:' + state); if (v) finish(JSON.parse(v)) } catch { /* */ } }, 700)
407
+ if (drop) dv = setInterval(askDrop, dropEveryMs)
408
+ if (drop || readNative) { try { typeof document !== 'undefined' && document.addEventListener('visibilitychange', onVis) } catch { /* */ } }
409
+ to = setTimeout(() => { if (!done) { done = true; stop(); reject(new ConnectionError('the sign-in took too long — start again', 'signin')) } }, timeoutMs)
410
+ readTab()
411
+ })
412
+ }
413
+
414
+ // The iPhone sheet stays open until the broker hands back the code, or the person dismisses it.
415
+ // A second attempt owns its own sheet: finishing the first must never dismiss the replacement.
416
+ let activeConsent = null
417
+ export async function connectorConsent (state, { trip, authUrl, win, broker, signal, nativeOAuth, manualLink, sheet = globalThis.WitbitzSignIn }, waitForCode = awaitMcpCallback) {
418
+ if (signal?.aborted) throw new ConnectionError('the sign-in was started again', 'cancel')
419
+ const url = trip ? trip.openUrl : authUrl
420
+ const options = { drop: trip?.drop, broker, signal }
421
+ if (!trip && sheet?.open) throw new ConnectionError('The sign-in return address could not be prepared. Tap Connect to try again.', 'signin')
422
+ if (!trip || !sheet?.open || !sheet?.close) {
423
+ if (nativeOAuth) {
424
+ if (!trip) throw new ConnectionError('The sign-in could not be prepared. Tap Connect to try again.', 'signin')
425
+ let launched = false
426
+ try {
427
+ const result = nativeOAuth(url)
428
+ launched = result !== false
429
+ if (typeof result === 'function') { options.readNative = result; options.checkDropOnDismiss = !!nativeOAuth.recoverable }
430
+ } catch { /* the displayed link can still open the same trip */ }
431
+ if (!launched && !manualLink?.isConnected) throw new ConnectionError('The sign-in browser could not open. Tap Connect to try again.', 'signin')
432
+ }
433
+ else if (win) win.location.href = url
434
+ else if (!window.open(url, '_blank')) throw new ConnectionError('the sign-in window was blocked — allow pop-ups for this app and try again', 'signin')
435
+ return waitForCode(state, options)
436
+ }
437
+ activeConsent?.abort()
438
+ const controller = new AbortController()
439
+ activeConsent = controller
440
+ const abort = () => controller.abort()
441
+ signal?.addEventListener('abort', abort)
442
+ try {
443
+ const nativeDrop = typeof sheet.openConnector === 'function'
444
+ const result = Promise.resolve(nativeDrop ? sheet.openConnector(url) : sheet.open(url)).then(async reply => {
445
+ if (controller.signal.aborted) throw new ConnectionError('the sign-in was started again', 'cancel')
446
+ if (nativeDrop && reply?.blob) {
447
+ const message = await openDrop(trip.drop, reply.blob)
448
+ if (message.state !== state || (!message.code && !message.error)) throw new ConnectionError('Unexpected sign-in response. Tap Connect to try again.', 'signin')
449
+ if (message.error) throw new ConnectionError('The provider declined the sign-in.', 'signin')
450
+ return String(message.code)
451
+ }
452
+ throw new ConnectionError('Sign-in was cancelled. Tap Connect to try again.', 'dismissed')
453
+ })
454
+ // Only one reader may take the sealed envelope. The web listener still handles abort and timeout.
455
+ return await Promise.race([result, waitForCode(state, { ...options, drop: nativeDrop ? null : options.drop, signal: controller.signal })])
456
+ } finally {
457
+ signal?.removeEventListener('abort', abort)
458
+ controller.abort()
459
+ if (activeConsent === controller) {
460
+ activeConsent = null
461
+ try { await sheet.close() } catch { /* the sheet may already have closed */ }
462
+ }
463
+ }
464
+ }
465
+
466
+ /** Finish: seal { state, code, callKey, id, label } to the Sentinel, which exchanges the code and files the connection. */
467
+ export async function finishMcpSignIn({ post, auth = {}, state, code, label, host, pins, verify, follow, dispKey }) {
468
+ const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
469
+ const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
470
+ const lbl = String(label || '').trim().slice(0, 80) || connectionName({ host }) // empty → the server's known name (GitHub), else the host
471
+ // `disp` rides the sealed finish too: the Sentinel that files it from here (st28 does not yet — its mcpOauthFinish takes the
472
+ // clear label only) keeps it as it does a grant's; until then this record shows the Sentinel's label
473
+ const disp = dispKey ? await sealDisp(dispKey, id, { label: lbl }).catch(() => '') : ''
474
+ const sk = await sealWithCallKey(att, { state, code, id, label: lbl, ...(disp ? { disp } : {}) }, id, { label: lbl, host })
475
+ const r = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'mcpoauthfinish', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, at: Date.now() }, sk)
476
+ if (!r || r.error || !r.ok) throw new ConnectionError(`${host}: ${(r && r.error) || 'the sign-in did not finish'}`, 'signin')
477
+ return { id, label: lbl, host, callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}) }
478
+ }
479
+
480
+ // ── A SERVICE'S OWN API THROUGH WITBITZ'S OAUTH APP (2026-11-23, Google Calendar: Google's regular Calendar API, not its preview MCP
481
+ // server). The Sentinel's provider sign-in (custody.mjs oauthStart / oauthFinish): it mints the PKCE verifier, asks Google for offline
482
+ // access, exchanges the code and keeps the refresh token — so the connection renews itself; nothing about it lives in this page.
483
+ // `tenant`/`provider`: the Witbitz app filed with the Sentinel (connCatalog.js). The consent comes back through the same pages as an
484
+ // MCP sign-in (mcpReturnTrip: the broker's /mcp-callback for Google, which Witbitz's Google client registers).
485
+ export async function startOauthSignIn({ post, auth = {}, tenant, provider }) {
486
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'oauthstart', tenant: String(tenant || ''), providerId: String(provider || '') }, ...auth })
487
+ if (!r || r.error || !r.ok || !r.authUrl) throw new ConnectionError(`the sign-in could not start (${(r && (r.error || r.reason)) || 'no answer from the Sentinel'})`, 'signin')
488
+ return { state: r.state, authUrl: r.authUrl }
489
+ }
490
+ /** Finish: the code and a fresh callKey ride sealed to the Sentinel, which exchanges the code (its secret, its verifier) and files it. */
491
+ export async function finishOauthSignIn({ post, auth = {}, state, code, label, host, pins, verify, follow, dispKey }) {
492
+ const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
493
+ const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
494
+ const lbl = String(label || '').trim().slice(0, 80) || String(host || '')
495
+ const disp = dispKey ? await sealDisp(dispKey, id, { label: lbl }).catch(() => '') : ''
496
+ const sk = await sealWithCallKey(att, { state, code, id, label: lbl, host: String(host || ''), ...(disp ? { disp } : {}) }, id, { label: lbl, host })
497
+ const r = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'oauthfinish', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, at: Date.now() }, sk)
498
+ if (!r || r.error || !r.ok) throw new ConnectionError(`${lbl}: ${(r && r.error) || 'the sign-in did not finish'}`, 'signin')
499
+ return { id: r.id || id, label: lbl, host: r.host || host, callKey: sk.callKey, provider: 'oauth2', ...(sk.held ? { held: 1 } : {}) }
500
+ }
501
+
502
+ // ── THE WITBITZ GITHUB APP (docs/cloud-computer-connections.md, Part B) ────────────────────────────────────────────────
503
+ // GitHub's own install page: the person picks which repositories, GitHub sends them back to /github-callback with the
504
+ // install id AND a sign-in code (the app asks for that during install). The code is what proves the install is theirs —
505
+ // sealed to the Sentinel with a fresh callKey, exchanged and checked there; an install id alone proves nothing.
506
+ /** The app's slug (for the install page) → { slug, owner } or throws. */
507
+ export async function gitHubAppInfo({ post, auth = {} }) {
508
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'ghappinfo' }, ...auth })
509
+ if (!r || r.error || !r.ok || !r.slug) throw new ConnectionError(r && r.status === 404 ? 'the Witbitz GitHub app is not set up yet' : `could not reach the Witbitz GitHub app (${(r && r.error) || 'no answer'})`, 'ghapp')
510
+ return { slug: String(r.slug), owner: String(r.owner || '') }
511
+ }
512
+ export const gitHubInstallUrl = (slug, state) => `https://github.com/apps/${encodeURIComponent(slug)}/installations/new?state=${encodeURIComponent(state)}`
513
+ /** What /github-callback hands back for `state`: { installationId, code }, a BroadcastChannel message or its localStorage note. */
514
+ export function awaitGitHubInstall(state, { timeoutMs = 15 * 60_000, drop = null, broker, fetchImpl, dropEveryMs = 1500 } = {}) {
515
+ return new Promise((resolve, reject) => {
516
+ let done = false, bc = null, iv = 0, to = 0, dv = 0, asking = false
517
+ const stop = () => { clearInterval(iv); clearInterval(dv); clearTimeout(to); try { bc && bc.close() } catch { /* */ }; try { typeof document !== 'undefined' && document.removeEventListener('visibilitychange', onVis) } catch { /* */ } }
518
+ const finish = (m) => {
519
+ if (done || !m || (m.state && m.state !== state)) return
520
+ done = true; stop()
521
+ try { localStorage.removeItem('space:ghcb:' + state); localStorage.removeItem('space:ghcb:last') } catch { /* */ }
522
+ if (m.error || !m.installationId) reject(new ConnectionError(`GitHub did not finish the install (${String(m.error || 'no installation').slice(0, 80)})`, 'ghapp'))
523
+ else resolve({ installationId: Number(m.installationId), code: String(m.code || '') })
524
+ }
525
+ // the hosted app's frame shares nothing with GitHub's window (as an MCP sign-in, mcpReturnTrip): what it sealed at the broker
526
+ const askDrop = async () => { if (done || asking || !drop) return; asking = true; try { finish(await takeDrop(drop, { ...(broker ? { broker } : {}), ...(fetchImpl ? { fetchImpl } : {}) })) } catch { /* not there yet */ } finally { asking = false } }
527
+ const onVis = () => { if (typeof document !== 'undefined' && document.visibilityState === 'visible') askDrop() }
528
+ try { bc = new BroadcastChannel('wb-github-install'); bc.onmessage = (e) => finish(e.data) } catch { bc = null }
529
+ // GitHub carries `state` back only on some paths; with one install in flight, the note without a state is this one's.
530
+ iv = setInterval(() => { try { const v = localStorage.getItem('space:ghcb:' + state) || localStorage.getItem('space:ghcb:last'); if (v) finish(JSON.parse(v)) } catch { /* */ } }, 700)
531
+ if (drop) dv = setInterval(askDrop, dropEveryMs)
532
+ if (drop) { try { typeof document !== 'undefined' && document.addEventListener('visibilitychange', onVis) } catch { /* */ } }
533
+ to = setTimeout(() => { if (!done) { done = true; stop(); reject(new ConnectionError('the GitHub install took too long — start again', 'ghapp')) } }, timeoutMs)
534
+ })
535
+ }
536
+ /** Finish: seal { code, installationId, callKey, id } to the Sentinel, which checks the install is this person's and files it. */
537
+ export async function finishGitHubInstall({ post, auth = {}, code, installationId, pins, verify, follow }) {
538
+ const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
539
+ const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
540
+ const sk = await sealWithCallKey(att, { code: String(code || ''), installationId: Number(installationId), id }, id, { label: 'GitHub', host: 'api.github.com' })
541
+ // no pending key in the page here (as before: the Sentinel may file it under its own id); a vault's is settled under the filed one
542
+ const body = { op: 'sentinel', sentinel: { mode: 'ghappfinish', sealed: sk.sealed }, ...auth }
543
+ const r = sk.held ? await postGrant(post, body, id, null, sk, undefined, (x) => ({ id: String(x.id || id), label: `GitHub · ${x.login || 'app'}`, account: String(x.account || '') })) : await post(body)
544
+ if (!r || r.error || !r.ok) throw new ConnectionError(`GitHub: ${(r && r.error) || 'the install could not be connected'}`, 'ghapp')
545
+ return { id: String(r.id || id), callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}), account: String(r.account || ''), login: String(r.login || ''), installationId: Number(r.installationId || installationId), label: `GitHub · ${r.login || 'app'}` }
546
+ }
547
+
548
+ /** The server's tools, as the Sentinel lists them for the account that owns the connection. */
549
+ export async function listMcpTools({ post, auth = {}, id }) {
550
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'mcplist', id }, ...auth })
551
+ if (!r || r.error || !r.ok) throw new ConnectionError(`could not read the server’s tools (${(r && r.error) || 'no answer'})`, 'list')
552
+ return { tools: Array.isArray(r.tools) ? r.tools : [], server: r.server || null, truncated: !!r.truncated }
553
+ }
554
+
555
+ /** What changed between the tools a room chose and what the server lists now — shown before anything is adopted. */
556
+ export function mcpToolDiff(kept, now) {
557
+ const k = new Map((kept || []).map((t) => [t.name, t])), n = new Map((now || []).map((t) => [t.name, t]))
558
+ const added = [...n.keys()].filter((x) => !k.has(x))
559
+ const removed = [...k.keys()].filter((x) => !n.has(x))
560
+ const changed = [...k.keys()].filter((x) => n.has(x) && (k.get(x).description !== n.get(x).description || JSON.stringify(k.get(x).inputSchema) !== JSON.stringify(n.get(x).inputSchema)))
561
+ return { added, removed, changed, same: !added.length && !removed.length && !changed.length }
562
+ }
package/credits.js ADDED
@@ -0,0 +1,30 @@
1
+ // credits.js — WHAT A PERSON SEES IS CREDITS (the owner, 2026-10-24: "move all customer facing usage to credit terminology
2
+ // instead of dollar" → "100 credits = $1"). One unit for replies, cloud computers and whatever charges next; the price behind
3
+ // it (markup, discount, a cheaper host) can move without the number moving. Ledgers, keys, caps and a builder's billing stay
4
+ // in the providers' dollars — this converts for display only, so there is one source of truth and no rounding drift.
5
+
6
+ export const CREDITS_PER_USD = 100
7
+ export const RATE_LINE = '100 credits = $1'
8
+
9
+ /** Dollars → credits (a number, not rounded). */
10
+ export const creditsOf = (usd) => (Number(usd) || 0) * CREDITS_PER_USD
11
+ /** Micro-dollars → credits. */
12
+ export const creditsOfMicros = (micros) => (Number(micros) || 0) / 1e6 * CREDITS_PER_USD
13
+ /** Credits → dollars (what an amount typed in credits means to the API). */
14
+ export const usdOfCredits = (credits) => (Number(credits) || 0) / CREDITS_PER_USD
15
+
16
+ /** A number of credits a person can read: whole from 10 up (with separators), one decimal from 1, two below — and never a
17
+ * "0" for something that cost something (the smallest shown is 0.01). */
18
+ export function creditsNumber (c) {
19
+ const v = Number(c) || 0
20
+ if (v <= 0) return '0'
21
+ if (v >= 10) return Math.round(v).toLocaleString('en-US')
22
+ if (v >= 1) return String(Math.round(v * 10) / 10)
23
+ return String(Math.max(Math.round(v * 100) / 100, 0.01))
24
+ }
25
+ /** "4 credits", "1 credit", "0.12 credits". */
26
+ export const creditsText = (c) => { const n = creditsNumber(c); return n + (n === '1' ? ' credit' : ' credits') }
27
+ /** Micro-dollars → "3.8 credits". */
28
+ export const creditsFromMicros = (micros) => creditsText(creditsOfMicros(micros))
29
+ /** Dollars → "5,000 credits". */
30
+ export const creditsFromUsd = (usd) => creditsText(creditsOf(usd))