@witbitz/sdk 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
@@ -0,0 +1,1460 @@
1
+ // Witbitz admin client — one file for your SERVER (https://witbitz.chat/docs/sdk#builder-calls). Never ship it in a page.
2
+
3
+ // spaces/public/sdk/4.4.0/connCatalog.js
4
+ var GCAL_PROVIDER = "prov_XE5FdiPdAx881HKs";
5
+ var CATALOG = [
6
+ // AN AGENT YOU SEND JOBS TO, not a service you sign in to (the owner, 2026-10-15: "Doesn't grokbot have a connector like
7
+ // other connectors?" → "Yes"). Grok Bot takes MCP servers but offers none; what starts a run from outside is a routine's
8
+ // trigger "When this webhook receives a request": an Endpoint https://grok.com/webhook/automation/<id> and a Signing
9
+ // secret whsec_… — a SIGNED webhook (docs/signed-webhooks.md). Attached through grokRoutine.js; each call is approved.
10
+ { name: "Grok Bot", kind: "webhook", host: "grok.com", desc: "Send a job to one of your Grok Bot routines \u2014 you approve each one.", cat: "Agents", png: "/icons/services/grok-bot.png" },
11
+ // CLAUDE CODE (the owner, 2026-10-21: "Let's do Claude code"): the same kind as Grok Bot — a scheduled task's API trigger
12
+ // (a bearer webhook on api.anthropic.com) takes the job, the run reports back through this Space's MCP address. The card and
13
+ // what the room keeps come from jobAgents.js (docs/job-agents.md).
14
+ { name: "Claude Code", kind: "webhook", host: "api.anthropic.com", desc: "Send a job to a Claude Code task in Anthropic's cloud \u2014 you approve each one.", cat: "Agents", png: "/icons/services/claude-code.png" },
15
+ // AN AGENT THAT COMES TO YOU (the owner, 2026-10-15: "add a muse ai connector like we did for grokbot"). Meta's Muse takes
16
+ // custom MCP connectors (streamable HTTP, a bearer key) but nothing can start a Muse task from outside — no webhook, no
17
+ // public API (docs/outside-agents.md). So it is ONE way: Muse reaches a Space's private assistant through the Sentinel's
18
+ // MCP door (message_member / get_reply), and a recurring Muse task asks that assistant for work. Set up by connectionsSheet.js openMuse.
19
+ { name: "Muse", kind: "agent", host: "meta.ai", desc: "Let Meta's Muse work with this Space's assistant \u2014 it asks for jobs and sends back the results.", cat: "Agents", png: "/icons/services/muse.png" },
20
+ // OpenAI's Dots (the owner, 2026-10-15: "OpenAI new dots bot" → "Do a"): a ChatGPT custom MCP server (name + URL, the key in
21
+ // it). One way for now, as Muse; ChatGPT's MCP Events could push it jobs later (a Sentinel cycle).
22
+ { name: "Dots", kind: "agent", host: "chatgpt.com", desc: "Let your OpenAI dot work with this Space's assistant \u2014 it asks for jobs and sends back the results.", cat: "Agents", png: "/icons/services/dots.png" },
23
+ { name: "Context7", url: "https://mcp.context7.com/mcp", desc: "Up-to-date docs for code libraries.", cat: "Engineering", png: "/icons/services/context7.png" },
24
+ { name: "GitHub", url: "https://api.githubcopilot.com/mcp/", desc: "Repositories, issues and pull requests.", cat: "Engineering", registered: true },
25
+ { name: "Hugging Face", url: "https://huggingface.co/mcp", desc: "Models, datasets and Spaces.", cat: "Engineering" },
26
+ { name: "Jam", url: "https://mcp.jam.dev/mcp", desc: "Bug reports with console and network logs.", cat: "Engineering", png: "/icons/services/jam.png" },
27
+ { name: "Linear", url: "https://mcp.linear.app/mcp", desc: "Issues, projects and cycles.", cat: "Engineering" },
28
+ { name: "Neon", url: "https://mcp.neon.tech/mcp", desc: "Postgres databases and branches.", cat: "Engineering", png: "/icons/services/neon.png" },
29
+ { name: "Sentry", url: "https://mcp.sentry.dev/mcp", desc: "Errors, issues and releases.", cat: "Engineering" },
30
+ { name: "Statsig", url: "https://api.statsig.com/v3/mcp", desc: "Inspect and manage feature gates, experiments, dynamic configs, and metrics.", cat: "Engineering", png: "/icons/services/statsig.png", src: "cursor" },
31
+ { name: "Supabase", url: "https://mcp.supabase.com/mcp", desc: "Databases, tables and edge functions.", cat: "Engineering" },
32
+ { name: "Airtable", url: "https://mcp.airtable.com/mcp", desc: "Bases, tables and records.", cat: "Productivity" },
33
+ { name: "Atlassian", url: "https://mcp.atlassian.com/v1/mcp", desc: "Jira issues and Confluence pages.", cat: "Productivity" },
34
+ { name: "Basecamp", url: "https://mcp.basecamp.com/mcp", desc: "Projects, to-dos and messages.", cat: "Productivity" },
35
+ { name: "ClickUp", url: "https://mcp.clickup.com/mcp", desc: "Tasks, docs and spaces.", cat: "Productivity" },
36
+ { name: "Jotform", url: "https://mcp.jotform.com", desc: "Create and edit forms, then read submissions.", cat: "Productivity", png: "/icons/services/jotform.png", src: "cursor" },
37
+ { name: "monday.com", url: "https://mcp.monday.com/mcp", desc: "Boards, items and updates.", cat: "Productivity", png: "/icons/services/monday.png" },
38
+ { name: "Todoist", url: "https://ai.todoist.net/mcp", desc: "Create, find, and complete tasks and projects.", cat: "Productivity", png: "/icons/services/todoist.png", src: "cursor" },
39
+ { name: "Trello", url: "https://mcp.trello.com/v1", desc: "Boards, lists and cards: create, move and complete, with checklists and due dates.", cat: "Productivity", png: "/icons/services/trello.png", src: "cursor" },
40
+ { name: "Zapier", url: "https://mcp.zapier.com/api/mcp/mcp", desc: "Actions across thousands of apps.", cat: "Productivity" },
41
+ { name: "Coda", url: "https://docs.superhuman.com/apis/mcp", desc: "Search docs, read pages, and update tables.", cat: "Documents", png: "/icons/services/coda.png", src: "cursor" },
42
+ { name: "Craft", url: "https://mcp.craft.do/my/mcp", desc: "Search, create, and update documents and daily notes.", cat: "Documents", png: "/icons/services/craft.png", src: "cursor" },
43
+ { name: "Guru", url: "https://mcp.api.getguru.com/mcp", desc: "Search company knowledge and draft verified answers.", cat: "Documents", png: "/icons/services/guru.png", src: "cursor" },
44
+ { name: "Mem", url: "https://mcp.mem.ai/mcp", desc: "Capture, search, and organize notes and collections.", cat: "Documents", png: "/icons/services/mem.png", src: "cursor" },
45
+ { name: "Notion", url: "https://mcp.notion.com/mcp", desc: "Search, read and write pages.", cat: "Documents" },
46
+ { name: "Readwise", url: "https://mcp2.readwise.io/mcp", desc: "Search highlights and Reader documents, save articles.", cat: "Documents", png: "/icons/services/readwise.png", src: "cursor" },
47
+ { name: "Canva", url: "https://mcp.canva.com/mcp", desc: "Designs, templates and exports.", cat: "Design" },
48
+ { name: "Excalidraw", url: "https://mcp.excalidraw.com/mcp", desc: "Hand-drawn diagrams and sketches.", cat: "Design" },
49
+ { name: "Miro", url: "https://mcp.miro.com/", desc: "Boards, diagrams and sticky notes.", cat: "Design" },
50
+ { name: "Webflow", url: "https://mcp.webflow.com/sse", desc: "Sites, pages and CMS items.", cat: "Design" },
51
+ { name: "Wix", url: "https://mcp.wix.com/mcp", desc: "Sites, stores and bookings.", cat: "Design" },
52
+ { name: "Circleback", url: "https://circleback.ai/api/mcp", desc: "Search meetings, transcripts, action items, and emails.", cat: "Meetings", png: "/icons/services/circleback.png", src: "cursor" },
53
+ { name: "Fathom", url: "https://api.fathom.ai/mcp", desc: "Search meetings and pull transcripts and summaries.", cat: "Meetings", png: "/icons/services/fathom.png", src: "cursor" },
54
+ { name: "Fireflies", url: "https://api.fireflies.ai/mcp", desc: "Search meeting transcripts, summaries, and action items.", cat: "Meetings", png: "/icons/services/fireflies.png", src: "cursor" },
55
+ { name: "Granola", url: "https://mcp.granola.ai/mcp", desc: "Your meeting notes and transcripts.", cat: "Meetings", png: "/icons/services/granola.png" },
56
+ { name: "Otter.ai", url: "https://mcp.otter.ai/mcp", desc: "Search meeting history and pull full transcripts.", cat: "Meetings", png: "/icons/services/otter.png", src: "cursor" },
57
+ { name: "Plaud", url: "https://mcp.plaud.ai/mcp", desc: "Your Plaud recordings: transcripts with speakers, summaries and action items.", cat: "Meetings", png: "/icons/services/plaud.png", src: "cursor" },
58
+ { name: "Read AI", url: "https://api.read.ai/mcp", desc: "Meeting summaries and transcripts.", cat: "Meetings", png: "/icons/services/readai.png" },
59
+ { name: "Calendly", url: "https://mcp.calendly.com/", desc: "Check availability and book, cancel, or reschedule.", cat: "Scheduling", png: "/icons/services/calendly.png", src: "cursor" },
60
+ { name: "Amplemarket", url: "https://mcp.amplemarket.com/mcp", desc: "Search people and companies, enrich leads, run sequences.", cat: "Sales", png: "/icons/services/amplemarket.png", src: "cursor" },
61
+ { name: "Attio", url: "https://mcp.attio.com/mcp", desc: "Search and update CRM records, lists, notes, and tasks.", cat: "Sales", png: "/icons/services/attio.png", src: "cursor" },
62
+ { name: "Clay", url: "https://api.clay.com/v3/mcp", desc: "Enrich people and companies, run AI research agents.", cat: "Sales", png: "/icons/services/clay.png", src: "cursor" },
63
+ { name: "Gong", url: "https://mcp.gong.io/mcp", desc: "Pull account summaries, deal insights, and call briefs.", cat: "Sales", png: "/icons/services/gong.png", src: "cursor" },
64
+ { name: "HubSpot", url: "https://mcp.hubspot.com/", desc: "Contacts, companies, deals and tickets in your CRM.", cat: "Sales", registered: true },
65
+ { name: "Hunter", url: "https://mcp.hunter.io/mcp", desc: "Find and verify emails, discover companies, and save leads.", cat: "Sales", png: "/icons/services/hunter.png", src: "cursor" },
66
+ { name: "Juicebox", url: "https://mcp.juicebox.ai/v1", desc: "Query recruiting analytics, shortlists, and sourcing agents.", cat: "Sales", png: "/icons/services/juicebox.png", src: "cursor" },
67
+ { name: "Outreach", url: "https://api.outreach.io/mcp", desc: "Search sequences, prospects, and Kaia meetings.", cat: "Sales", png: "/icons/services/outreach.png", src: "cursor" },
68
+ { name: "beehiiv", url: "https://mcp.beehiiv.com/mcp", desc: "Your newsletter: posts, subscribers, segments and performance.", cat: "Marketing", png: "/icons/services/beehiiv.png", src: "cursor" },
69
+ { name: "Customer.io", url: "https://mcp.customer.io/mcp", desc: "Build campaigns, manage segments, and query people.", cat: "Marketing", png: "/icons/services/customer-io.png", src: "cursor" },
70
+ { name: "Klaviyo", url: "https://mcp.klaviyo.com/mcp", desc: "Manage profiles, segments, campaigns, and flows.", cat: "Marketing", png: "/icons/services/klaviyo.png", src: "cursor" },
71
+ { name: "MailerLite", url: "https://mcp.mailerlite.com/mcp", desc: "Manage subscribers, groups, campaigns, and automations.", cat: "Marketing", png: "/icons/services/mailerlite.png", src: "cursor" },
72
+ { name: "Meltwater", url: "https://api.meltwater.com/v2/mcp", desc: "Search media and social mentions and pull analytics.", cat: "Marketing", png: "/icons/services/meltwater.png", src: "cursor" },
73
+ { name: "Profound", url: "https://mcp.tryprofound.com/mcp", desc: "Track AI visibility, sentiment, and citations.", cat: "Marketing", png: "/icons/services/profound.png", src: "cursor" },
74
+ { name: "Plain", url: "https://mcp.plain.com/mcp", desc: "Support threads, customers and help articles.", cat: "Customer support", png: "/icons/services/plain.png" },
75
+ { name: "Amplitude", url: "https://mcp.amplitude.com/mcp", desc: "Product analytics and charts.", cat: "Data analytics", png: "/icons/services/amplitude.png" },
76
+ { name: "PostHog", url: "https://mcp.posthog.com/mcp", desc: "Product analytics and SQL, feature flags, experiments, errors and replays.", cat: "Data analytics", png: "/icons/services/posthog-mcp.png", src: "cursor" },
77
+ { name: "Similarweb", url: "https://mcp.similarweb.com", desc: "Analyze website traffic, audiences, and competitors.", cat: "Data analytics", png: "/icons/services/similarweb.png", src: "cursor" },
78
+ { name: "Ashby", url: "https://mcp.ashbyhq.com/mcp/v1", desc: "Search candidates, prep interviews, and manage pipeline tasks.", cat: "Hiring", png: "/icons/services/ashby.png", src: "cursor" },
79
+ { name: "Greenhouse", url: "https://mcp.us.greenhouse.io/mcp", desc: "Search candidates, jobs, and applications, and review scorecards in Greenhouse Recruiting.", cat: "Hiring", png: "/icons/services/greenhouse.png", src: "cursor" },
80
+ { name: "Workable", url: "https://mcp.workable.com/mcp", desc: "Search candidates, move pipelines, and manage HR records.", cat: "Hiring", png: "/icons/services/workable.png", src: "cursor" },
81
+ { name: "Brex", url: "https://api.brex.com/mcp", desc: "Query expenses, receipts, bills, cards, and travel.", cat: "Finance", png: "/icons/services/brex.png", src: "cursor" },
82
+ { name: "Daloopa", url: "https://mcp.daloopa.com/server/mcp", desc: "Pull source-linked fundamentals, KPIs, filings, and prices.", cat: "Finance", png: "/icons/services/daloopa.png", src: "cursor" },
83
+ { name: "Interactive Brokers", url: "https://api.ibkr.com/v1/api/mcp-public", desc: "Review positions, balances, P&L, and draft trade instructions.", cat: "Finance", png: "/icons/services/interactive-brokers.png", src: "cursor" },
84
+ { name: "PayPal", url: "https://mcp.paypal.com/mcp", desc: "Orders, invoices and payments.", cat: "Finance" },
85
+ { name: "Robinhood", url: "https://agent.robinhood.com/mcp/trading", desc: "View portfolios, positions, orders, watchlists, and market data, and trade in a Robinhood Agentic account.", cat: "Finance", png: "/icons/services/robinhood.png", src: "cursor" },
86
+ { name: "S&P Global", url: "https://kfinance.kensho.com/integrations/mcp", desc: "Query S&P Capital IQ financials, prices, and transcripts.", cat: "Finance", png: "/icons/services/sp-global.png", src: "cursor" },
87
+ { name: "Stripe", url: "https://mcp.stripe.com/", desc: "Payments, customers and invoices.", cat: "Finance" },
88
+ { name: "Webull", url: "https://api.webull.com/mcp", desc: "View accounts, positions, orders, watchlists, and market data.", cat: "Finance", png: "/icons/services/webull.png", src: "cursor" },
89
+ { name: "Ahrefs", url: "https://api.ahrefs.com/mcp/mcp", desc: "Research keywords, backlinks, rankings, and site health.", cat: "Research", png: "/icons/services/ahrefs.png", src: "cursor" },
90
+ { name: "Cloudflare Docs", url: "https://docs.mcp.cloudflare.com/mcp", desc: "Cloudflare\u2019s developer documentation.", cat: "Research" },
91
+ { name: "Exa", url: "https://mcp.exa.ai/mcp", desc: "Web search and page contents.", cat: "Research", png: "/icons/services/exa.png" },
92
+ { name: "TinyFish", url: "https://agent.tinyfish.ai/mcp", desc: "Web automations, search and clean page content in remote browsers.", cat: "Research", png: "/icons/services/tinyfish.png", src: "cursor" },
93
+ // FROM GROK BOT'S PLUGIN MARKETPLACE (github.com/xai-org/plugin-marketplace, read 2026-11-16; the owner: "look at grokbot opensource
94
+ // connections - update our connections and add missing ones"): each address passed tools/conn-catalog/probe.mjs's sign-in steps
95
+ // that day (GoDaddy answers without one — domain suggestions and availability only). Descriptions are ours; no logos copied.
96
+ // Left out: the 13 that register no outside app (HubSpot, Zoom, Google's, X, DocuSign, Shopify…), the 22 that refuse Witbitz's
97
+ // registration (Figma, Vercel, Netlify, Railway, Intercom, Square…), Stable (its tools need the person's own API key), TikTok Ads
98
+ // (no sign-in method), and every address behind Cursor's or Grok's own gateway. Navan was removed: it now refuses registration.
99
+ { name: "Axiom", url: "https://mcp.axiom.co/mcp", desc: "Logs and metrics: queries, dashboards and monitors.", cat: "Engineering", png: "/icons/services/axiom.png" },
100
+ { name: "Clerk", url: "https://mcp.clerk.com/mcp", desc: "Your app's users, organizations and sign-in.", cat: "Engineering" },
101
+ { name: "Cloudflare", url: "https://mcp.cloudflare.com/mcp", desc: "Workers, DNS and your Cloudflare account.", cat: "Engineering" },
102
+ { name: "Expo", url: "https://mcp.expo.dev/mcp", desc: "Build, test and ship iOS and Android apps.", cat: "Engineering" },
103
+ { name: "GoDaddy", url: "https://api.godaddy.com/v1/domains/mcp", desc: "Domain name ideas and whether a name is free.", cat: "Engineering" },
104
+ { name: "Pi Security", url: "https://mcp.pi.security/mcp", desc: "Security findings, posture and how to fix them.", cat: "Engineering", png: "/icons/services/pi-security.png" },
105
+ { name: "RingCentral Team Messaging", url: "https://mcp.labs.ringcentral.com/ringex/v1.1.0/team-chat", desc: "Team chats and messages in RingCentral.", cat: "Productivity", png: "/icons/services/ringcentral-team-messaging.png" },
106
+ { name: "Framer", url: "https://mcp.framer.com/mcp", desc: "Pages and content of a Framer website.", cat: "Design" },
107
+ { name: "HTML/CSS to Image", url: "https://mcp.hcti.io", desc: "Turn HTML or a web page into an image or a PDF.", cat: "Design", png: "/icons/services/html-css-to-image.png" },
108
+ { name: "VideoGen", url: "https://mcp.videogen.io/mcp", desc: "Make a video from text, images or a script.", cat: "Design", png: "/icons/services/videogen.png" },
109
+ { name: "Cal.com", url: "https://mcp.cal.com/mcp", desc: "Availability, bookings and event types.", cat: "Scheduling" },
110
+ // GOOGLE CALENDAR (2026-11-23, docs/google-calendar-verification.md): Google's own Calendar MCP server takes no self-registered
111
+ // app — Witbitz files its own client (project witbitz-spaces-calendar, scope calendar.events alone) with the Sentinel, and the
112
+ // sign-in comes back through the broker's callback (connections.js mcpRedirectFor). Until Google verifies the client, only its
113
+ // test users can sign in.
114
+ // ⛔ OUT OF THE CATALOG until Google makes the Calendar MCP server generally available (2026-11-23): it answers only projects in
115
+ // the Workspace Developer Preview Program, which takes only Workspace-domain accounts, and its terms keep preview features out of
116
+ // public apps. Everything else is in place (the filed client, st51, the broker's callback) — put this line back then:
117
+ // { name: "Google Calendar", url: "https://calendarmcp.googleapis.com/mcp/v1", desc: "Read your events and, when you approve, add or change them.", cat: "Scheduling", registered: true },
118
+ // GOOGLE CALENDAR ON GOOGLE'S REGULAR CALENDAR API (2026-11-23; owner: "it did not sync automatically" → this): kind 'oauth' = the
119
+ // Sentinel's own Google sign-in (custody.mjs oauthStart: offline access, a refresh token it renews itself) with Witbitz's app filed
120
+ // under `tenant` as `provider`; the connection reaches `host`. Reads run without asking, a change is a card (connSpaces readsAutoFor).
121
+ { name: "Google Calendar", kind: "oauth", tenant: "t_815e94f68944437592310c0b80861cd9", provider: GCAL_PROVIDER, host: "www.googleapis.com", reads: "auto", desc: "Read your events and, when you approve, add or change them.", cat: "Scheduling" },
122
+ { name: "Helena", url: "https://agent.enrichlabs.ai/api/mcp", desc: "An AI marketer for SEO, ads, social and email campaigns.", cat: "Marketing", png: "/icons/services/helena.png" },
123
+ { name: "Omneky", url: "https://mcp.omneky.com/mcp", desc: "Ad campaigns, their results and new creatives.", cat: "Marketing", png: "/icons/services/omneky.png" },
124
+ { name: "Quo", url: "https://mcp.quo.com/mcp", desc: "Business texts, calls and contacts.", cat: "Customer support", png: "/icons/services/quo.png" },
125
+ { name: "RingCentral Phone", url: "https://mcp.labs.ringcentral.com/ringex/phone", desc: "Calls, voicemail and texts in RingCentral.", cat: "Customer support", png: "/icons/services/ringcentral-phone.png" },
126
+ { name: "Finary", url: "https://public-api.finary.com/mcp", desc: "Your investments, accounts and net worth.", cat: "Finance", png: "/icons/services/finary.png" },
127
+ { name: "Gusto", url: "https://mcp.api.gusto.com/", desc: "Payroll, employees and benefits.", cat: "Finance" },
128
+ { name: "Firecrawl", url: "https://mcp.firecrawl.dev/v2/mcp-oauth", desc: "Scrape, crawl and search websites as clean text.", cat: "Research", png: "/icons/services/firecrawl.png" },
129
+ { name: "Octen", url: "https://mcp.octen.ai/mcp", desc: "Web and news search, and page extraction.", cat: "Research", png: "/icons/services/octen.png" },
130
+ { name: "Tavily", url: "https://mcp.tavily.com/mcp", desc: "Web search, page extraction and research.", cat: "Research", png: "/icons/services/tavily.png" },
131
+ // SINCE STANDING SENTINEL st33 (2026-11-16): Netlify (its client id is a 447-character token — the Sentinel took 400 at most) and
132
+ // the services that refuse a web app's self-registration but take the app as its OWN client (client ID metadata documents —
133
+ // /mcp-client.json). Vercel signed in end to end on the owner's phone; Railway, Typeform and Upwork showed their consent page.
134
+ { name: "Netlify", url: "https://mcp.netlify.com/mcp", desc: "Sites, deploys and build logs.", cat: "Engineering" },
135
+ { name: "Railway", url: "https://mcp.railway.com", desc: "Services, deployments and logs.", cat: "Engineering" },
136
+ { name: "Vercel", url: "https://mcp.vercel.com", desc: "Deployments, build logs and domains.", cat: "Engineering" },
137
+ { name: "Typeform", url: "https://api.typeform.com/mcp", desc: "Forms and their responses.", cat: "Productivity" },
138
+ { name: "Upwork", url: "https://mcp.upwork.com/mcp", desc: "Jobs, proposals and contracts.", cat: "Hiring" },
139
+ // FROM THE MONTHLY CHECK (2026-11-16, owner: "yes"): eight that newly pass the sign-in steps, from Cursor's plugins and Grok Bot's
140
+ // marketplace; their marks found by the same check (tools/conn-catalog/icons.mjs). Descriptions are ours.
141
+ { name: "Mixpanel", url: "https://mcp.mixpanel.com/mcp", desc: "Events, funnels, retention and dashboards.", cat: "Data analytics" },
142
+ { name: "Metricool", url: "https://ai.metricool.com/mcp", desc: "Plan and publish social posts, and their results.", cat: "Marketing", png: "/icons/services/metricool.png" },
143
+ { name: "Squarespace", url: "https://mcp.squarespace.com/mcp", desc: "Business name ideas and domains: availability and price.", cat: "Design" },
144
+ { name: "Runta", url: "https://mcp.runta.com/mcp", desc: "Run lasting agent runtimes: ports, checkpoints and images.", cat: "Engineering", png: "/icons/services/runta.png" },
145
+ { name: "OnePay", url: "https://mcp.onepay.com", desc: "Balances and spending across your OnePay accounts.", cat: "Finance", png: "/icons/services/onepay.png" },
146
+ { name: "Questrade", url: "https://mcp.questrade.com/v1/brokerage/mcp", desc: "Your portfolio and live market data.", cat: "Finance", png: "/icons/services/questrade.png" },
147
+ { name: "Engine", url: "https://mcp.engine.com/mcp", desc: "Find and book hotels, change or cancel stays.", cat: "Travel", png: "/icons/services/engine.png" },
148
+ { name: "Eight Sleep", url: "https://public-api.8slp.net/mcp", desc: "Your sleep scores and your Pod's temperature.", cat: "Health" },
149
+ { name: "AgentMail", url: "https://mcp.agentmail.to/mcp", desc: "Email inboxes for your assistant.", cat: "Email", png: "/icons/services/agentmail.png" },
150
+ // GMAIL BY FORWARDING (the owner, 2026-11-21: Nylas's verified Google app — the only way to read Gmail without Google's yearly
151
+ // assessment — was "too expensive" → "lets do this forward connector to gmail"). Not a sign-in: Gmail forwards what the person
152
+ // chooses to the Space's own address (Witbitz Mail, mailShare.js — received and sealed in the Sentinel). kind 'mail': no MCP address;
153
+ // connectionsSheet.js opens the Space's Mail card with Gmail's steps. (Reading through Nylas is built and kept: nylas.mjs.)
154
+ { name: "Gmail", kind: "mail", host: "mail.google.com", desc: "Forward the mail you choose into a Space of your own \u2014 the assistant reads it when you ask.", cat: "Email" }
155
+ ];
156
+
157
+ // spaces/public/sdk/4.4.0/cbor.js
158
+ var MAX_LEN = 1 << 22;
159
+ function decode(bytes) {
160
+ const b = toBytes(bytes);
161
+ const [value, off] = readItem(b, 0);
162
+ if (value === BREAK) throw new Error("cbor: stray break byte");
163
+ if (off !== b.length) throw new Error(`cbor: ${b.length - off} trailing bytes`);
164
+ return value;
165
+ }
166
+ function toBytes(x) {
167
+ if (x instanceof Uint8Array) return x;
168
+ if (x instanceof ArrayBuffer) return new Uint8Array(x);
169
+ if (ArrayBuffer.isView(x)) return new Uint8Array(x.buffer, x.byteOffset, x.byteLength);
170
+ throw new Error("cbor: expected bytes");
171
+ }
172
+ function need(b, off, n) {
173
+ if (n < 0 || off + n > b.length) throw new Error("cbor: truncated");
174
+ return off + n;
175
+ }
176
+ function readHead(b, off) {
177
+ need(b, off, 1);
178
+ const ib = b[off];
179
+ const major = ib >> 5;
180
+ const ai = ib & 31;
181
+ if (ai < 24) return [major, ai, off + 1];
182
+ if (ai === 24) {
183
+ need(b, off + 1, 1);
184
+ return [major, b[off + 1], off + 2];
185
+ }
186
+ if (ai === 25) {
187
+ need(b, off + 1, 2);
188
+ return [major, b[off + 1] << 8 | b[off + 2], off + 3];
189
+ }
190
+ if (ai === 26) {
191
+ need(b, off + 1, 4);
192
+ const v = (b[off + 1] << 24 | b[off + 2] << 16 | b[off + 3] << 8 | b[off + 4]) >>> 0;
193
+ return [major, v, off + 5];
194
+ }
195
+ if (ai === 27) {
196
+ need(b, off + 1, 8);
197
+ let v = 0;
198
+ for (let i = 1; i <= 8; i++) v = v * 256 + b[off + i];
199
+ if (!Number.isSafeInteger(v)) throw new Error("cbor: 64-bit value exceeds safe integer range");
200
+ return [major, v, off + 9];
201
+ }
202
+ if (ai === 31) throw new Error("cbor: indefinite length handled by the caller");
203
+ throw new Error(`cbor: reserved additional information ${ai}`);
204
+ }
205
+ var BREAK = /* @__PURE__ */ Symbol("cbor-break");
206
+ function readChunked(b, off, major, depth) {
207
+ const parts = [];
208
+ let total = 0;
209
+ let p = off;
210
+ for (; ; ) {
211
+ need(b, p, 1);
212
+ const head2 = b[p];
213
+ if (head2 === 255) {
214
+ p += 1;
215
+ break;
216
+ }
217
+ if (head2 >> 5 !== major || (head2 & 31) === 31) {
218
+ throw new Error("cbor: indefinite-length string contains a chunk of the wrong kind");
219
+ }
220
+ const [chunk, next] = readItem(b, p, depth + 1);
221
+ p = next;
222
+ const bytes = major === 2 ? chunk : new TextEncoder().encode(chunk);
223
+ total += bytes.length;
224
+ if (total > MAX_LEN) throw new Error("cbor: indefinite-length string too large");
225
+ parts.push(bytes);
226
+ }
227
+ const out = concat(...parts);
228
+ return [major === 2 ? out : new TextDecoder("utf-8", { fatal: true }).decode(out), p];
229
+ }
230
+ function readItem(b, off, depth = 0) {
231
+ if (depth > 16) throw new Error("cbor: nesting too deep");
232
+ need(b, off, 1);
233
+ const ib = b[off];
234
+ const major0 = ib >> 5;
235
+ if ((ib & 31) === 31) {
236
+ if (major0 === 7) return [BREAK, off + 1];
237
+ if (major0 === 2 || major0 === 3) return readChunked(b, off + 1, major0, depth);
238
+ if (major0 === 4 || major0 === 5) {
239
+ const isMap = major0 === 5;
240
+ const arr = [];
241
+ const map = /* @__PURE__ */ new Map();
242
+ let p2 = off + 1;
243
+ let n = 0;
244
+ for (; ; ) {
245
+ const [k, n1] = readItem(b, p2, depth + 1);
246
+ p2 = n1;
247
+ if (k === BREAK) break;
248
+ if (++n > MAX_LEN) throw new Error("cbor: indefinite-length collection too large");
249
+ if (!isMap) {
250
+ arr.push(k);
251
+ continue;
252
+ }
253
+ const [v, n2] = readItem(b, p2, depth + 1);
254
+ p2 = n2;
255
+ if (v === BREAK) throw new Error("cbor: indefinite-length map ended between a key and its value");
256
+ if (map.has(k)) throw new Error("cbor: duplicate map key");
257
+ map.set(k, v);
258
+ }
259
+ return [isMap ? map : arr, p2];
260
+ }
261
+ throw new Error(`cbor: indefinite length is not valid for major type ${major0}`);
262
+ }
263
+ const [major, value, p] = readHead(b, off);
264
+ switch (major) {
265
+ case 0:
266
+ return [value, p];
267
+ case 1:
268
+ return [-1 - value, p];
269
+ case 2: {
270
+ if (value > MAX_LEN) throw new Error("cbor: byte string too large");
271
+ const end = need(b, p, value);
272
+ return [b.slice(p, end), end];
273
+ }
274
+ case 3: {
275
+ if (value > MAX_LEN) throw new Error("cbor: text string too large");
276
+ const end = need(b, p, value);
277
+ return [new TextDecoder("utf-8", { fatal: true }).decode(b.subarray(p, end)), end];
278
+ }
279
+ case 4: {
280
+ if (value > MAX_LEN) throw new Error("cbor: array too long");
281
+ const out = [];
282
+ let q = p;
283
+ for (let i = 0; i < value; i++) {
284
+ const [v, n] = readItem(b, q, depth + 1);
285
+ if (v === BREAK) throw new Error("cbor: break inside a definite-length array");
286
+ out.push(v);
287
+ q = n;
288
+ }
289
+ return [out, q];
290
+ }
291
+ case 5: {
292
+ if (value > MAX_LEN) throw new Error("cbor: map too large");
293
+ const out = /* @__PURE__ */ new Map();
294
+ let q = p;
295
+ for (let i = 0; i < value; i++) {
296
+ const [k, n1] = readItem(b, q, depth + 1);
297
+ const [v, n2] = readItem(b, n1, depth + 1);
298
+ if (k === BREAK || v === BREAK) throw new Error("cbor: break inside a definite-length map");
299
+ if (out.has(k)) throw new Error("cbor: duplicate map key");
300
+ out.set(k, v);
301
+ q = n2;
302
+ }
303
+ return [out, q];
304
+ }
305
+ case 6: {
306
+ const [v, n] = readItem(b, p, depth + 1);
307
+ return [v, n];
308
+ }
309
+ case 7:
310
+ if (value === 20) return [false, p];
311
+ if (value === 21) return [true, p];
312
+ if (value === 22) return [null, p];
313
+ if (value === 23) return [void 0, p];
314
+ throw new Error(`cbor: unsupported simple/float value ${value}`);
315
+ default:
316
+ throw new Error("cbor: unreachable");
317
+ }
318
+ }
319
+ function head(major, value) {
320
+ if (value < 24) return Uint8Array.of(major << 5 | value);
321
+ if (value < 256) return Uint8Array.of(major << 5 | 24, value);
322
+ if (value < 65536) return Uint8Array.of(major << 5 | 25, value >> 8, value & 255);
323
+ if (value < 4294967296) {
324
+ return Uint8Array.of(major << 5 | 26, value >>> 24 & 255, value >>> 16 & 255, value >>> 8 & 255, value & 255);
325
+ }
326
+ throw new Error("cbor: length too large to encode");
327
+ }
328
+ function encodeBytes(u8) {
329
+ const b = toBytes(u8);
330
+ return concat(head(2, b.length), b);
331
+ }
332
+ function encodeText(s) {
333
+ const b = new TextEncoder().encode(String(s));
334
+ return concat(head(3, b.length), b);
335
+ }
336
+ function encodeArray(items) {
337
+ return concat(head(4, items.length), ...items);
338
+ }
339
+ function concat(...parts) {
340
+ let n = 0;
341
+ for (const p of parts) n += p.length;
342
+ const out = new Uint8Array(n);
343
+ let o = 0;
344
+ for (const p of parts) {
345
+ out.set(p, o);
346
+ o += p.length;
347
+ }
348
+ return out;
349
+ }
350
+
351
+ // spaces/public/sdk/4.4.0/x509.js
352
+ var TAG = { INT: 2, BITSTRING: 3, OID: 6, SEQ: 48, UTCTIME: 23, GENTIME: 24 };
353
+ var SIG_OIDS = /* @__PURE__ */ new Map([
354
+ ["1.2.840.10045.4.3.2", { hash: "SHA-256" }],
355
+ ["1.2.840.10045.4.3.3", { hash: "SHA-384" }],
356
+ ["1.2.840.10045.4.3.4", { hash: "SHA-512" }]
357
+ ]);
358
+ var CURVE_OIDS = /* @__PURE__ */ new Map([
359
+ ["1.2.840.10045.3.1.7", { curve: "P-256", size: 32 }],
360
+ ["1.3.132.0.34", { curve: "P-384", size: 48 }],
361
+ ["1.3.132.0.35", { curve: "P-521", size: 66 }]
362
+ ]);
363
+ function readTLV(b, off) {
364
+ if (off + 2 > b.length) throw new Error("der: truncated tag");
365
+ const tag = b[off];
366
+ if ((tag & 31) === 31) throw new Error("der: multi-byte tags not supported");
367
+ let p = off + 1;
368
+ let len = b[p++];
369
+ if (len & 128) {
370
+ const n = len & 127;
371
+ if (n === 0) throw new Error("der: indefinite length is not valid DER");
372
+ if (n > 4) throw new Error("der: length too large");
373
+ if (p + n > b.length) throw new Error("der: truncated length");
374
+ len = 0;
375
+ for (let i = 0; i < n; i++) len = len * 256 + b[p++];
376
+ }
377
+ const contentEnd = p + len;
378
+ if (contentEnd > b.length) throw new Error("der: truncated content");
379
+ return { tag, start: off, contentStart: p, contentEnd };
380
+ }
381
+ function expect(b, off, tag, what) {
382
+ const t = readTLV(b, off);
383
+ if (t.tag !== tag) throw new Error(`der: expected ${what} (tag 0x${tag.toString(16)}), got 0x${t.tag.toString(16)}`);
384
+ return t;
385
+ }
386
+ function children(b, t) {
387
+ const out = [];
388
+ let p = t.contentStart;
389
+ while (p < t.contentEnd) {
390
+ const c = readTLV(b, p);
391
+ out.push(c);
392
+ p = c.contentEnd;
393
+ }
394
+ return out;
395
+ }
396
+ function oidString(b, t) {
397
+ const c = b.subarray(t.contentStart, t.contentEnd);
398
+ if (!c.length) throw new Error("der: empty OID");
399
+ const parts = [Math.floor(c[0] / 40), c[0] % 40];
400
+ let v = 0;
401
+ for (let i = 1; i < c.length; i++) {
402
+ v = v * 128 + (c[i] & 127);
403
+ if (!(c[i] & 128)) {
404
+ parts.push(v);
405
+ v = 0;
406
+ }
407
+ }
408
+ return parts.join(".");
409
+ }
410
+ function parseTime(b, t) {
411
+ const s = String.fromCharCode(...b.subarray(t.contentStart, t.contentEnd));
412
+ let m;
413
+ if (t.tag === TAG.UTCTIME) {
414
+ m = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s);
415
+ if (!m) throw new Error("der: bad UTCTime");
416
+ const yy = Number(m[1]);
417
+ return Date.UTC(yy >= 50 ? 1900 + yy : 2e3 + yy, Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));
418
+ }
419
+ if (t.tag === TAG.GENTIME) {
420
+ m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s);
421
+ if (!m) throw new Error("der: bad GeneralizedTime");
422
+ return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));
423
+ }
424
+ throw new Error("der: unsupported time tag");
425
+ }
426
+ function derSigToRaw(der, size) {
427
+ const b = der instanceof Uint8Array ? der : new Uint8Array(der);
428
+ const seq = expect(b, 0, TAG.SEQ, "signature SEQUENCE");
429
+ const [rT, sT] = children(b, seq);
430
+ if (!rT || !sT || rT.tag !== TAG.INT || sT.tag !== TAG.INT) throw new Error("der: bad ECDSA signature");
431
+ const out = new Uint8Array(size * 2);
432
+ for (const [i, t] of [[0, rT], [1, sT]]) {
433
+ let v = b.subarray(t.contentStart, t.contentEnd);
434
+ while (v.length > 1 && v[0] === 0) v = v.subarray(1);
435
+ if (v.length > size) throw new Error("der: ECDSA integer too large for curve");
436
+ out.set(v, i * size + (size - v.length));
437
+ }
438
+ return out;
439
+ }
440
+ function parseCertificate(der) {
441
+ const b = der instanceof Uint8Array ? der : new Uint8Array(der);
442
+ const cert = expect(b, 0, TAG.SEQ, "Certificate");
443
+ const [tbsT, algT, sigT] = children(b, cert);
444
+ if (!tbsT || !algT || !sigT) throw new Error("der: Certificate needs 3 fields");
445
+ if (sigT.tag !== TAG.BITSTRING) throw new Error("der: signatureValue must be a BIT STRING");
446
+ const sigAlgOid = oidString(b, expect(b, algT.contentStart, TAG.OID, "signature algorithm"));
447
+ const sigAlg = SIG_OIDS.get(sigAlgOid);
448
+ if (!sigAlg) throw new Error(`der: unsupported signature algorithm ${sigAlgOid}`);
449
+ if (b[sigT.contentStart] !== 0) throw new Error("der: signature BIT STRING has unused bits");
450
+ const sigDer = b.subarray(sigT.contentStart + 1, sigT.contentEnd);
451
+ const kids = children(b, tbsT);
452
+ const base = kids[0] && kids[0].tag === 160 ? 1 : 0;
453
+ const [serialT, innerAlgT, issuerT, validityT, subjectT, spkiT] = kids.slice(base, base + 6);
454
+ if (!serialT || !innerAlgT || !issuerT || !validityT || !subjectT || !spkiT) throw new Error("der: malformed tbsCertificate");
455
+ const innerOid = oidString(b, expect(b, innerAlgT.contentStart, TAG.OID, "inner signature algorithm"));
456
+ if (innerOid !== sigAlgOid) throw new Error("der: signature algorithm mismatch between tbs and certificate");
457
+ const [nbT, naT] = children(b, validityT);
458
+ if (!nbT || !naT) throw new Error("der: malformed validity");
459
+ const [spkiAlgT] = children(b, spkiT);
460
+ const spkiAlgKids = children(b, spkiAlgT);
461
+ if (spkiAlgKids.length < 2) throw new Error("der: SPKI algorithm needs a curve parameter");
462
+ const keyOid = oidString(b, spkiAlgKids[0]);
463
+ if (keyOid !== "1.2.840.10045.2.1") throw new Error(`der: not an EC public key (${keyOid})`);
464
+ const curveOid = oidString(b, spkiAlgKids[1]);
465
+ const curve = CURVE_OIDS.get(curveOid);
466
+ if (!curve) throw new Error(`der: unsupported curve ${curveOid}`);
467
+ let isCA = false;
468
+ for (const k of kids.slice(base + 6)) {
469
+ if (k.tag !== 163) continue;
470
+ for (const ext of children(b, children(b, k)[0] || k)) {
471
+ const extKids = children(b, ext);
472
+ if (!extKids.length || oidString(b, extKids[0]) !== "2.5.29.19") continue;
473
+ const octet = extKids[extKids.length - 1];
474
+ const bcSeq = readTLV(b, octet.contentStart);
475
+ const bcKids = children(b, bcSeq);
476
+ isCA = !!(bcKids[0] && bcKids[0].tag === 1 && b[bcKids[0].contentStart] !== 0);
477
+ }
478
+ }
479
+ return {
480
+ tbs: b.subarray(tbsT.start, tbsT.contentEnd),
481
+ sig: derSigToRaw(sigDer, curve.size),
482
+ sigHash: sigAlg.hash,
483
+ spki: b.slice(spkiT.start, spkiT.contentEnd),
484
+ // copy: this is handed to WebCrypto, which wants its own buffer
485
+ curve: curve.curve,
486
+ size: curve.size,
487
+ issuer: b.subarray(issuerT.start, issuerT.contentEnd),
488
+ subject: b.subarray(subjectT.start, subjectT.contentEnd),
489
+ notBefore: parseTime(b, nbT),
490
+ notAfter: parseTime(b, naT),
491
+ isCA
492
+ };
493
+ }
494
+ function bytesEqual(a, b) {
495
+ if (!a || !b || a.length !== b.length) return false;
496
+ let d = 0;
497
+ for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];
498
+ return d === 0;
499
+ }
500
+ async function importSpki(cert) {
501
+ return crypto.subtle.importKey("spki", cert.spki, { name: "ECDSA", namedCurve: cert.curve }, false, ["verify"]);
502
+ }
503
+ async function verifyChain(chainDer, { now = Date.now() } = {}) {
504
+ if (!Array.isArray(chainDer) || chainDer.length < 2) throw new Error("chain: need an anchor and at least one certificate");
505
+ const certs = chainDer.map((d, i) => {
506
+ try {
507
+ return parseCertificate(d);
508
+ } catch (e) {
509
+ throw new Error(`chain: certificate ${i} unparseable: ${e.message}`);
510
+ }
511
+ });
512
+ for (let i = 1; i < certs.length; i++) {
513
+ const child = certs[i];
514
+ const parent = certs[i - 1];
515
+ if (!bytesEqual(child.issuer, parent.subject)) throw new Error(`chain: certificate ${i} was not issued by certificate ${i - 1}`);
516
+ if (i > 1 && !parent.isCA) throw new Error(`chain: certificate ${i - 1} signs but is not a CA`);
517
+ if (now < child.notBefore) throw new Error(`chain: certificate ${i} is not yet valid`);
518
+ if (now > child.notAfter) throw new Error(`chain: certificate ${i} has expired`);
519
+ const ok = await crypto.subtle.verify({ name: "ECDSA", hash: child.sigHash }, await importSpki(parent), child.sig, child.tbs);
520
+ if (!ok) throw new Error(`chain: certificate ${i} has a bad signature`);
521
+ }
522
+ return certs[certs.length - 1];
523
+ }
524
+
525
+ // spaces/public/sdk/4.4.0/nitroVerify.js
526
+ var NITRO_ROOT_G1_B64 = "MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTELMAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYDVQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4MTQyODA1WjBJMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEGBSuBBAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSksfbb48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ3BABIeTPYwEoCWZEh8l5YoQwTcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkFR+eWw5b6cp3PmanfS5YwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPWrfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6NIwLz3/Y=";
527
+ var COSE_ALG_ES384 = -35;
528
+ var MAX_DOC = 1 << 20;
529
+ var MAX_FIELD = 1024;
530
+ var MAX_CABUNDLE = 8;
531
+ function b64ToBytes(b643) {
532
+ const s = String(b643).replace(/-/g, "+").replace(/_/g, "/").replace(/\s+/g, "");
533
+ const bin = atob(s);
534
+ const out = new Uint8Array(bin.length);
535
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
536
+ return out;
537
+ }
538
+ var toHex = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, "0")).join("");
539
+ var isBytes = (x) => x instanceof Uint8Array;
540
+ var optBytes = (m, k) => {
541
+ const v = m.get(k);
542
+ if (v === null || v === void 0) return null;
543
+ if (!isBytes(v) || v.length > MAX_FIELD) throw new Error(`attestation: bad ${k}`);
544
+ return v.length ? v : null;
545
+ };
546
+ function sigStructure(protectedBytes, payloadBytes) {
547
+ return encodeArray([
548
+ encodeText("Signature1"),
549
+ encodeBytes(protectedBytes),
550
+ encodeBytes(new Uint8Array(0)),
551
+ // external_aad — always empty for Nitro
552
+ encodeBytes(payloadBytes)
553
+ ]);
554
+ }
555
+ function parseDocument(payloadBytes) {
556
+ const m = decode(payloadBytes);
557
+ if (!(m instanceof Map)) throw new Error("attestation: payload is not a map");
558
+ const moduleId = m.get("module_id");
559
+ if (typeof moduleId !== "string" || !moduleId || moduleId.length > MAX_FIELD) throw new Error("attestation: bad module_id");
560
+ const digest = m.get("digest");
561
+ if (digest !== "SHA384") throw new Error(`attestation: unexpected digest ${digest}`);
562
+ const timestamp = m.get("timestamp");
563
+ if (typeof timestamp !== "number" || !(timestamp > 0)) throw new Error("attestation: bad timestamp");
564
+ const pcrsMap = m.get("pcrs");
565
+ if (!(pcrsMap instanceof Map) || pcrsMap.size < 1 || pcrsMap.size > 32) throw new Error("attestation: bad pcrs");
566
+ const pcrs = {};
567
+ for (const [k, v] of pcrsMap) {
568
+ if (!Number.isInteger(k) || k < 0 || k > 31) throw new Error("attestation: bad PCR index");
569
+ if (!isBytes(v) || v.length !== 32 && v.length !== 48 && v.length !== 64) throw new Error(`attestation: bad PCR${k}`);
570
+ pcrs[k] = toHex(v);
571
+ }
572
+ const certificate = m.get("certificate");
573
+ if (!isBytes(certificate) || !certificate.length) throw new Error("attestation: missing certificate");
574
+ const cabundle = m.get("cabundle");
575
+ if (!Array.isArray(cabundle) || !cabundle.length || cabundle.length > MAX_CABUNDLE) throw new Error("attestation: bad cabundle");
576
+ for (const c of cabundle) if (!isBytes(c) || !c.length) throw new Error("attestation: bad cabundle entry");
577
+ return {
578
+ moduleId,
579
+ timestamp,
580
+ digest,
581
+ pcrs,
582
+ certificate,
583
+ cabundle,
584
+ publicKey: optBytes(m, "public_key"),
585
+ userData: optBytes(m, "user_data"),
586
+ nonce: optBytes(m, "nonce")
587
+ };
588
+ }
589
+ var MAX_PIN_SET = 2;
590
+ function acceptedSet(pin, label = "pin") {
591
+ const list = (Array.isArray(pin) ? pin : [pin]).map((h) => String(h).toLowerCase());
592
+ if (!list.length) throw new Error(`attestation: ${label} pins an empty set \u2014 that is not a check`);
593
+ if (list.length > MAX_PIN_SET) throw new Error(`attestation: ${label} pins ${list.length} values; at most ${MAX_PIN_SET} (a rollover is {outgoing, incoming})`);
594
+ return list;
595
+ }
596
+ async function verifyAttestation(cose, { root, now = Date.now(), maxAgeMs = 0, expectedPCRs = null, nonce = null, atDocTime = false, clockBoundMs = 0 } = {}) {
597
+ const raw = cose instanceof Uint8Array ? cose : new Uint8Array(cose);
598
+ if (!raw.length || raw.length > MAX_DOC) throw new Error("attestation: implausible document size");
599
+ const cs = decode(raw);
600
+ if (!Array.isArray(cs) || cs.length !== 4) throw new Error("attestation: not a COSE_Sign1 structure");
601
+ const [protectedBytes, unprotected, payloadBytes, signature] = cs;
602
+ if (!isBytes(protectedBytes) || !isBytes(payloadBytes) || !isBytes(signature)) throw new Error("attestation: malformed COSE_Sign1");
603
+ if (!(unprotected instanceof Map)) throw new Error("attestation: malformed COSE header");
604
+ const ph = protectedBytes.length ? decode(protectedBytes) : /* @__PURE__ */ new Map();
605
+ if (!(ph instanceof Map) || ph.get(1) !== COSE_ALG_ES384) throw new Error("attestation: protected header must specify ES384");
606
+ if (signature.length !== 96) throw new Error("attestation: ES384 signature must be 96 bytes");
607
+ const doc = parseDocument(payloadBytes);
608
+ const anchor = root ? root instanceof Uint8Array ? root : new Uint8Array(root) : b64ToBytes(NITRO_ROOT_G1_B64);
609
+ const leaf = await verifyChain([anchor, ...doc.cabundle.slice(1), doc.certificate], { now: atDocTime && Number.isFinite(doc.timestamp) ? doc.timestamp : now });
610
+ const ok = await crypto.subtle.verify(
611
+ { name: "ECDSA", hash: "SHA-384" },
612
+ await importSpki(leaf),
613
+ signature,
614
+ sigStructure(protectedBytes, payloadBytes)
615
+ );
616
+ if (!ok) throw new Error("attestation: COSE signature does not verify under the leaf certificate");
617
+ if (atDocTime && clockBoundMs > 0 && Number.isFinite(doc.timestamp) && Math.abs(now - doc.timestamp) > clockBoundMs) {
618
+ const h = Math.round(Math.abs(now - doc.timestamp) / 36e5);
619
+ const e = new Error(`attestation: this device's clock is about ${h} hour${h === 1 ? "" : "s"} off the enclave's \u2014 check the date and time settings`);
620
+ e.code = "clock_off";
621
+ throw e;
622
+ }
623
+ if (maxAgeMs > 0 && now - doc.timestamp > maxAgeMs) {
624
+ throw new Error(`attestation: document is ${Math.round((now - doc.timestamp) / 1e3)}s old`);
625
+ }
626
+ if (nonce) {
627
+ const want = typeof nonce === "string" ? new TextEncoder().encode(nonce) : new Uint8Array(nonce);
628
+ if (!doc.nonce || !bytesEqual(doc.nonce, want)) throw new Error("attestation: nonce does not match the challenge");
629
+ }
630
+ if (expectedPCRs) {
631
+ const wanted = Object.entries(expectedPCRs);
632
+ if (!wanted.length) throw new Error("attestation: expectedPCRs was empty \u2014 that is not a check");
633
+ for (const [idx, pin] of wanted) {
634
+ const n = Number(idx);
635
+ if (!Number.isInteger(n) || n < 0 || n > 31) {
636
+ throw new Error(`attestation: expectedPCRs key ${JSON.stringify(idx)} is not a PCR index (0-31)`);
637
+ }
638
+ const accepted = acceptedSet(pin, `PCR${idx}`);
639
+ const got = doc.pcrs[n];
640
+ if (!got) throw new Error(`attestation: PCR${idx} is absent from the document`);
641
+ if (!accepted.includes(got)) throw new Error(`attestation: PCR${idx} mismatch
642
+ expected ${accepted.join(" or ")}
643
+ got ${got}`);
644
+ }
645
+ }
646
+ return { ok: true, ...doc, leaf };
647
+ }
648
+
649
+ // spaces/public/sdk/4.4.0/sentinelRelease.js
650
+ var BUILD_ENCLAVE_PCR0 = Object.freeze([
651
+ "c6a8cbd0c05d8e003e75b266f1dde2a6426b7cd61f845e4b128e59063e40968b44f30d934bbe1925582fe33bbdd0b1d7",
652
+ "f490096d57e4287146e8b8d7bf4c75f423984ca52199efab0ee8684fbee6cfe6ab82c72d54f05a38f24a0d4ad6e2f557",
653
+ "41ec7e0e54beac5759fba7efa06c48081dbd96c7299c29c92a9c619036ce057cec357ad4ad71a165d7f881df120b043b",
654
+ "9f0801335a952bdbac70b6793150738d7ce30bc3a0d520fec6f573de22a822aa5ef762f78648bc8608ca0b2eeccda556",
655
+ "a145e8524bbe8764d4db6b81b4e18d72eae42e8b9e1c834e62e22aba18cce318f9eaa84942671c688c3eeb89ec30b0e8",
656
+ "5d29c3691cd38f6c6ce0da2b2f9d1da82712d9da12a89c99d38a03cae6369ebe6ba7a1ab1060cfa9daf6a19228c7a2dc",
657
+ "6c962286faed81c395bcf3d319011f91893cfec723c2dc7069ad8805980d77e99f75c94671881cc793794521fe5d2ff0",
658
+ "578945d0342d346d72e50b36ffe74a3631e53e111bc010394108457e362d10830ebadcc7ec5ffa4445d5b10b9c522d28",
659
+ "7e9f760db923c6f31fd18db06f6b60a53902beb6b0d80b91b5355d33c461e43bcddc31c08e2380ff9dc75c10909e6acb",
660
+ "5b6bffe6953eef271a69e453072b6e202ae024cd3983fff3a637b7421a60ad92ab3fd19f8ae809e19182a3feebbe94c2",
661
+ "551006e397efd43a619b370ef336a6a594d8a8338cd49860e54845330354c73afd3ba673360d50f78e5f1d702e19946b",
662
+ "eecf817c561e633b30632ca434a28ad56ed46395d765172fedcc0742d8d5c9982845d6ce32b6451b943f4b6f0a55ea36",
663
+ "3df18dce5385b467208bfa325d2f812bd622ef6def87ef97e63116310a896427db9f2c69d7c2631bccc9c65549b3d512",
664
+ "a51fcaeafa6d188b46d11710442f981169304aa4feecc4b40263943966c3dd8ff9b986d30989b4152fa1540c85a76b5e",
665
+ "f977e0490f5abfc77c311b426399bddd6909848bb8175db4142885c839e9cc23c3ca0047317b039883dce4b1a2efe096",
666
+ "d5f13dff5647f5f4ee351dd9e1ba9348ecd39da88acd6ffd9c324897b0ca7563da974b08c2e84504a76dc98b48700b74",
667
+ "2babe4262b2a00949eeef5b04a81327eb606dc347caaf507527d04f8847730a31dd26d6d7be3e0a672c537b51c914133",
668
+ "25a0967ec1366bc0ec43e45e2f89c435adb1a3e54d8702d89599acb442337afcb36f8f64d51a6608cefb3bb1e4f6b8ed",
669
+ "8665867cbb86ea3178f4179cf040fdec9e6df22bdd4f1e3d8df6b2d9096db5aecd8420b42203969bbe9446b585c78870",
670
+ "ef738ca713ddc39dc29505d857c2aac22a0598a714163ae01e2879085e1c262cc5bde3c239b7ce76385d10c5910ed487",
671
+ "41de07c0c12f388f9dc7d87cfa835edce2c58be42f6893f227002329d263285bf78bb209cd69c384dd7566097f2a3d47",
672
+ "a77141c4ac00099cbdd9053e0190b70234aa2eccdb22cb358e9b8b0fef5bef6b7ad6d9b5eb73137244a3790f98869505",
673
+ "70dde35fed128d1cb007f8c6edfa3de70e991955e1748aa500ad4685d1c752b1775565fb9a6d11c483969d5596e3b159",
674
+ "f0ea83ee58b3a4a9ebe7c8c74f102eba17118711573b6ce773b6f31ed223564cbf215992b5a7a30462b70281ae624453",
675
+ "f7adfbec8cf3a014f9585c7decc21bb03a50484339811ea3b44947d23fc16aff8eedb56346915b816e83fc5faad55e7a",
676
+ "917f7d95eabd64eabd1145cc0898c08ff414037775fd416162002c4783b4f95dcb550c3c5493baadaf41eaceb0e7da0d",
677
+ "74b1cbd4398f319a636de05d36eaa40953df4dc0bb86769f7ac4e0fe2c576f55b3c4a15a5583048ded80b0b4d303f55e",
678
+ "420088665bd62edcba51dfbcc55cbc85611529985fde54b655a3476198a8f9421e02d1898db28180b153550ceeb66798"
679
+ ]);
680
+ var enc = new TextEncoder();
681
+ var unb64 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0));
682
+ var hex = (u8) => [...new Uint8Array(u8)].map((b) => b.toString(16).padStart(2, "0")).join("");
683
+ var same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
684
+ var PROOFS = ["attestation", "signature", "rekor"];
685
+ async function sentinelPcrOfRelease(r, { builders = BUILD_ENCLAVE_PCR0, links = null, verify = verifyAttestation, site = chainFromSite } = {}) {
686
+ const trusted = Array.isArray(links) && links.length ? await trustedBuilders(links, { anchors: builders, verify }) : builders;
687
+ try {
688
+ return await recordPcr(r, "standing-sentinel", trusted, verify);
689
+ } catch (e) {
690
+ if (!site || !/not made by a build enclave this app trusts/.test(String(e && e.message || e))) throw e;
691
+ const all = [...Array.isArray(links) ? links : [], ...await site()];
692
+ if (!all.length) throw e;
693
+ return recordPcr(r, "standing-sentinel", await trustedBuilders(all, { anchors: builders, verify, max: Infinity }), verify);
694
+ }
695
+ }
696
+ var _siteChain = null;
697
+ var CHAIN_URLS = Object.freeze(["https://api.witbitz.chat/v1/trust/build-enclave.jsonl", "/audit/releases/build-enclave.jsonl"]);
698
+ function chainFromSite({ fetchFn = typeof fetch === "function" ? fetch : null, urls = CHAIN_URLS } = {}) {
699
+ if (!fetchFn) return Promise.resolve([]);
700
+ const own = fetchFn === globalThis.fetch && urls === CHAIN_URLS;
701
+ if (own && typeof process !== "undefined" && process.env && process.env.NODE_TEST_CONTEXT) return Promise.resolve([]);
702
+ if (!own) return readChain(fetchFn, urls);
703
+ return _siteChain || (_siteChain = readChain(fetchFn, urls).then((l) => {
704
+ if (!l.length) _siteChain = null;
705
+ return l;
706
+ }));
707
+ }
708
+ function readChain(fetchFn, urls) {
709
+ return (async () => {
710
+ for (const u of urls) {
711
+ try {
712
+ const res = await fetchFn(u, { cache: "no-store" });
713
+ if (!res || res.status !== 200 || /text\/html/.test(res.headers && res.headers.get && res.headers.get("content-type") || "")) continue;
714
+ const l = linksOfLogText(await res.text());
715
+ if (l.length) return l;
716
+ } catch {
717
+ }
718
+ }
719
+ return [];
720
+ })();
721
+ }
722
+ function linksOfLogText(text) {
723
+ const out = [];
724
+ for (const l of String(text || "").split("\n")) {
725
+ try {
726
+ const r = JSON.parse(l);
727
+ if (r && r.subject === "build-enclave" && r.verdict === "pass") out.push(r);
728
+ } catch {
729
+ }
730
+ }
731
+ return out.reverse();
732
+ }
733
+ var BUILD_ENCLAVE_DENY = Object.freeze([]);
734
+ var LINKS_MAX = 4;
735
+ var verified = /* @__PURE__ */ new Map();
736
+ async function trustedBuilders(links = [], { anchors = BUILD_ENCLAVE_PCR0, deny = BUILD_ENCLAVE_DENY, verify = verifyAttestation, max = LINKS_MAX } = {}) {
737
+ const denied = new Set((deny || []).map((x) => String(x).toLowerCase()));
738
+ const trusted = new Set((anchors || []).map((x) => String(x).toLowerCase()).filter((x) => !denied.has(x)));
739
+ const cache = verify === verifyAttestation;
740
+ let pending = Array.isArray(links) ? links.slice(0, max) : [];
741
+ for (let grew = true; grew && pending.length; ) {
742
+ grew = false;
743
+ const left = [];
744
+ for (const l of pending) {
745
+ try {
746
+ const sig = l && l.signature && typeof l.signature.sig === "string" ? l.signature.sig : "";
747
+ const known = sig && cache ? verified.get(sig) : null;
748
+ let p;
749
+ if (known && trusted.has(known.builder) && String(l.measurement && l.measurement.pcr0 || "").toLowerCase() === known.pcr0) p = known.pcr0;
750
+ else {
751
+ const got = await recordPcrBy(l, "build-enclave", [...trusted], verify);
752
+ p = got.pcr0;
753
+ if (sig && cache) {
754
+ if (verified.size >= 4096) verified.delete(verified.keys().next().value);
755
+ verified.set(sig, got);
756
+ }
757
+ }
758
+ if (!denied.has(p) && !trusted.has(p)) {
759
+ trusted.add(p);
760
+ grew = true;
761
+ }
762
+ } catch (e) {
763
+ if (/not made by a build enclave this app trusts/.test(String(e && e.message || e))) left.push(l);
764
+ }
765
+ }
766
+ pending = left;
767
+ }
768
+ return [...trusted];
769
+ }
770
+ async function recordPcr(r, subject, builders, verify) {
771
+ return (await recordPcrBy(r, subject, builders, verify)).pcr0;
772
+ }
773
+ async function recordPcrBy(r, subject, builders, verify = verifyAttestation) {
774
+ if (!r || typeof r !== "object") throw new Error("no release record came with the attestation");
775
+ if (r.subject !== subject || r.verdict !== "pass") throw new Error(`the record is not a passing ${subject} release`);
776
+ const repro = Array.isArray(r.checks) && r.checks.find((c) => c && c.name === "reproducible-build");
777
+ if (!repro || repro.ok !== true) throw new Error("the record does not say the image was rebuilt from its source");
778
+ const pcr0 = String(r.measurement && r.measurement.pcr0 || "").toLowerCase();
779
+ if (!/^[0-9a-f]{96}$/.test(pcr0) || r.claim && String(r.claim.pcr0 || "").toLowerCase() !== pcr0) throw new Error("the record names no single PCR0");
780
+ if (!r.attestation || !r.attestation.doc || !r.signature || !r.signature.key || !r.signature.sig) throw new Error("the record carries no proof");
781
+ const rest = {};
782
+ for (const [k, v] of Object.entries(r)) if (!PROOFS.includes(k)) rest[k] = v;
783
+ const art = enc.encode(JSON.stringify(rest));
784
+ const doc = await verify(unb64(r.attestation.doc), { atDocTime: true });
785
+ const builder = String(doc.pcrs && doc.pcrs[0] || "").toLowerCase();
786
+ if (!builders.includes(builder)) throw new Error("the record was not made by a build enclave this app trusts");
787
+ const want = enc.encode(JSON.stringify({ role: "build-enclave", verdict: hex(await crypto.subtle.digest("SHA-256", art)) }));
788
+ if (!doc.userData || !same(new Uint8Array(doc.userData), want)) throw new Error("the build enclave's attestation is not for this record");
789
+ const spki = unb64(r.signature.key);
790
+ if (!doc.publicKey || !same(new Uint8Array(doc.publicKey), spki)) throw new Error("the record is not signed by the key the build enclave attested");
791
+ const key = await crypto.subtle.importKey("spki", spki, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
792
+ const ok = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, derSigToRaw(unb64(r.signature.sig), 32), art);
793
+ if (!ok) throw new Error("the record's signature does not verify");
794
+ return { pcr0, builder };
795
+ }
796
+
797
+ // spaces/public/sdk/4.4.0/sealShare.js
798
+ var enc2 = new TextEncoder();
799
+ var b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)));
800
+ async function sealTo(enclaveKey, nonce, bundle) {
801
+ const eph = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-384" }, true, ["deriveBits"]);
802
+ const shared = await crypto.subtle.deriveBits({ name: "ECDH", public: enclaveKey }, eph.privateKey, 384);
803
+ const hk = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
804
+ const key = await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: nonce, info: enc2.encode("witbitz-cc share v1") }, hk, { name: "AES-GCM", length: 256 }, false, ["encrypt"]);
805
+ const iv = crypto.getRandomValues(new Uint8Array(12));
806
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: nonce }, key, enc2.encode(JSON.stringify(bundle))));
807
+ const epk = new Uint8Array(await crypto.subtle.exportKey("raw", eph.publicKey));
808
+ return { epk: b64(epk), iv: b64(iv), ct: b64(ct), nonce: b64(nonce) };
809
+ }
810
+
811
+ // spaces/public/sdk/4.4.0/connDisp.js
812
+ var enc3 = new TextEncoder();
813
+ var dec = new TextDecoder();
814
+ var SALT = enc3.encode("witbitz-sentinel-display-v1");
815
+ var INFO = enc3.encode("sentinel-display");
816
+
817
+ // spaces/public/sdk/4.4.0/connections.js
818
+ var STANDING_SENTINEL_PCR0 = ["1903ce28fc5a75efe2e57a451d667f1ce8b4b6e11872fb2b81d9e62d8cd994ed80fcfa99807f289af5f281aa4e4cc010"];
819
+ var b642 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)));
820
+ var unb642 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
821
+ var ConnectionError = class extends Error {
822
+ constructor(m, code = "") {
823
+ super(m);
824
+ this.code = code;
825
+ }
826
+ };
827
+ var ACCEPTED_KEY = "space:sentinelAccepted";
828
+ var _follow = null;
829
+ var acceptedPcrs = () => {
830
+ try {
831
+ const a = JSON.parse(localStorage.getItem(ACCEPTED_KEY) || "[]");
832
+ return Array.isArray(a) ? a.filter((x) => /^[0-9a-f]{96}$/.test(x)) : [];
833
+ } catch {
834
+ return [];
835
+ }
836
+ };
837
+ var rememberPcr = (p) => {
838
+ try {
839
+ const a = acceptedPcrs();
840
+ if (!a.includes(p)) localStorage.setItem(ACCEPTED_KEY, JSON.stringify([...a, p].slice(-4)));
841
+ } catch {
842
+ }
843
+ };
844
+ async function publishedSentinelPins(fetchImpl = (u, o) => fetch(u, o), url = "/sentinel-claim.json") {
845
+ try {
846
+ const r = await fetchImpl(url, { cache: "no-store" });
847
+ if (!r.ok) return [];
848
+ const c = await r.json();
849
+ return Array.isArray(c && c.pcr0) ? c.pcr0.filter((x) => /^[0-9a-f]{96}$/.test(x)) : [];
850
+ } catch {
851
+ return [];
852
+ }
853
+ }
854
+ async function verifyFollowing(verify, docBytes, { nonce, pins, follow, release = null, links = null }) {
855
+ const f = follow || _follow;
856
+ const following = f && pins === STANDING_SENTINEL_PCR0;
857
+ const tryPins = (set) => verify(docBytes, { nonce, maxAgeMs: 12e4, expectedPCRs: { 0: set } });
858
+ const known = following ? [.../* @__PURE__ */ new Set([...pins, ...acceptedPcrs()])] : pins;
859
+ try {
860
+ return await tryPins(pins);
861
+ } catch (first) {
862
+ if (!following || !/PCR0/i.test(String(first && first.message || first))) throw first;
863
+ for (const p of known.filter((x) => !pins.includes(x))) {
864
+ try {
865
+ return await tryPins([p]);
866
+ } catch {
867
+ }
868
+ }
869
+ if (release) {
870
+ let p = null;
871
+ try {
872
+ p = await sentinelPcrOfRelease(release, { links });
873
+ } catch {
874
+ p = null;
875
+ }
876
+ if (p && !known.includes(p)) {
877
+ let doc = null;
878
+ try {
879
+ doc = await tryPins([p]);
880
+ } catch {
881
+ doc = null;
882
+ }
883
+ if (doc) {
884
+ if (f.auto() || await f.ask(p)) {
885
+ rememberPcr(p);
886
+ return doc;
887
+ }
888
+ throw new ConnectionError("you did not accept the new Witbitz Sentinel build, so nothing was sent to it", "declined");
889
+ }
890
+ }
891
+ }
892
+ for (const p of (await publishedSentinelPins(f.fetch || void 0, f.claimUrl || void 0)).filter((x) => !known.includes(x))) {
893
+ let doc = null;
894
+ try {
895
+ doc = await verify(docBytes, { nonce, maxAgeMs: 12e4, expectedPCRs: { 0: [p] } });
896
+ } catch {
897
+ continue;
898
+ }
899
+ if (f.auto() || await f.ask(p)) {
900
+ rememberPcr(p);
901
+ return doc;
902
+ }
903
+ throw new ConnectionError("you did not accept the new Witbitz Sentinel build, so nothing was sent to it", "declined");
904
+ }
905
+ throw first;
906
+ }
907
+ }
908
+ async function attestStandingSentinel({ post, auth = {}, pins = STANDING_SENTINEL_PCR0, verify = verifyAttestation, follow = null }) {
909
+ if (!Array.isArray(pins) || !pins.length) throw new ConnectionError("the standing Sentinel is not pinned in this build \u2014 nothing can be attached yet", "unpinned");
910
+ const nonce = crypto.getRandomValues(new Uint8Array(32));
911
+ const r = await post({ op: "sentinel", sentinel: { mode: "attest", nonce: b642(nonce) }, ...auth });
912
+ 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");
913
+ let doc;
914
+ try {
915
+ doc = await verifyFollowing(verify, unb642(r.doc), { nonce, pins, follow, release: r.release && typeof r.release === "object" ? r.release : null, links: Array.isArray(r.links) ? r.links : null });
916
+ } catch (e) {
917
+ if (e instanceof ConnectionError) throw e;
918
+ 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");
919
+ }
920
+ let said = null;
921
+ try {
922
+ said = JSON.parse(new TextDecoder().decode(doc.userData || new Uint8Array(0)));
923
+ } catch {
924
+ }
925
+ if (!said || said.role !== "sentinel") throw new ConnectionError("the attestation does not name a Sentinel, so nothing was sent to it", "attestation");
926
+ const key = await crypto.subtle.importKey("spki", doc.publicKey, { name: "ECDH", namedCurve: "P-384" }, false, []);
927
+ return { nonce, key, spki: new Uint8Array(doc.publicKey) };
928
+ }
929
+ var MCP_CURATED = CATALOG.filter((c) => c.url).map((c) => ({ label: c.name, url: c.url }));
930
+
931
+ // spaces/public/sdk/4.4.0/sdkRedact.js
932
+ var REDACTED = "[REDACTED]";
933
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
934
+ function hide(obj, names) {
935
+ for (const n of names) {
936
+ const d = Object.getOwnPropertyDescriptor(obj, n);
937
+ Object.defineProperty(obj, n, { value: d ? d.value : void 0, writable: true, configurable: true, enumerable: false });
938
+ }
939
+ return obj;
940
+ }
941
+ function redacted(proto, summary) {
942
+ Object.defineProperty(proto, "toJSON", { value: function toJSON() {
943
+ return summary(this);
944
+ }, writable: true, configurable: true });
945
+ Object.defineProperty(proto, INSPECT, {
946
+ value: function inspect(depth, options, nodeInspect) {
947
+ const s = summary(this);
948
+ const name = this && this.constructor && this.constructor.name || "Object";
949
+ return typeof nodeInspect === "function" ? `${name} ${nodeInspect(s, options)}` : { [name]: s };
950
+ },
951
+ writable: true,
952
+ configurable: true
953
+ });
954
+ }
955
+
956
+ // spaces/public/sdk/4.4.0/witbitz-admin.js
957
+ var adminError = (code, message) => Object.assign(new Error(message), { code: String(code || "refused") });
958
+ var DEFAULT_ENDPOINT = "https://api.witbitz.chat/v1/space";
959
+ var ownerRetired = () => adminError("owner_rule_retired", "witbitz: the owner rule (rooms only your app may use) is retired \u2014 a web page cannot prove which app it is (sdk-changes.md, 4.0.0)");
960
+ var TenantOwner = class {
961
+ constructor(admin) {
962
+ this._a = admin;
963
+ }
964
+ async register() {
965
+ throw ownerRetired();
966
+ }
967
+ async rotate() {
968
+ throw ownerRetired();
969
+ }
970
+ async room() {
971
+ throw ownerRetired();
972
+ }
973
+ };
974
+ var WitbitzAdmin = class {
975
+ /** RETIRED in 4.0.0 (the owner rule, above). */
976
+ static async generateOwnerKey() {
977
+ throw ownerRetired();
978
+ }
979
+ /** @param {object} opts { tenant, tenantKey, signingKey?, endpoint?, tenantEndpoint?, fetchImpl?, sentinel? } — `signingKey`: your
980
+ * tenant's Ed25519 PRIVATE key (a JWK, or its JSON string; WitbitzAdmin.generateSigningKey()), kept on your server. */
981
+ constructor({ tenant = "", tenantKey = "", signingKey = null, endpoint = DEFAULT_ENDPOINT, tenantEndpoint, fetchImpl, sentinel } = {}) {
982
+ this._endpoint = endpoint;
983
+ this._tenant = tenant || "";
984
+ this._tenantKey = tenantKey || "";
985
+ this._signingKey = signingKey ? typeof signingKey === "string" ? JSON.parse(signingKey) : signingKey : null;
986
+ this._tenantEndpointOverride = tenantEndpoint ? String(tenantEndpoint) : "";
987
+ this._fetch = typeof fetchImpl === "function" ? fetchImpl : ((...a) => fetch(...a));
988
+ this.owner = new TenantOwner(this);
989
+ const ownPins = !!(sentinel && Array.isArray(sentinel.pins)), off = !!(sentinel && sentinel.follow === "off");
990
+ this._sentinel = {
991
+ pins: ownPins ? sentinel.pins : STANDING_SENTINEL_PCR0,
992
+ ...sentinel && typeof sentinel.verify === "function" ? { verify: sentinel.verify } : {},
993
+ follow: ownPins || off ? null : { auto: () => true, ask: async () => false, claimUrl: String(sentinel && sentinel.claimUrl || "https://witbitz-spaces.pages.dev/sentinel-claim.json"), fetch: (u, o) => this._fetch(u, o) }
994
+ };
995
+ this.origins = new TenantOrigins(this);
996
+ this.app = new TenantApp(this);
997
+ this.hosts = new DeclaredHosts(this);
998
+ this.providers = new Providers(this);
999
+ this.rooms = new TenantRooms(this);
1000
+ this.signing = new TenantSigning(this);
1001
+ this.customers = new TenantCustomers(this);
1002
+ this.billing = new TenantBilling(this);
1003
+ this.keys = new TenantKeys(this);
1004
+ hide(this, ["_tenantKey", "_signingKey", "_fetch"]);
1005
+ }
1006
+ /** The BUILDER's transport: the same endpoint with a tenant SECRET key, which the /v1 authorizer resolves to a
1007
+ * tenant before this reaches any handler. Server-side only. */
1008
+ /**
1009
+ * ⛔ A BUILDER CALL MUST NOT GO TO THE SPACE ENDPOINT (2026-09-27, found by a builder whose key was fine all along).
1010
+ * `/v1/space` is deliberately KEYLESS — a Space authenticates by its own key-commitment — so no authorizer runs there
1011
+ * and an `authorization: Bearer wsk_…` header is never examined. Every builder op therefore answered 403
1012
+ * `tenant_required`, identically for a real key and a forged one, and the whole builder half was unreachable in
1013
+ * production while the refusal read like a bad secret. Builder ops belong on the AUTHENTICATED twin, where the
1014
+ * gateway checks the key and hands the handler a tenant it cannot have been told.
1015
+ */
1016
+ _tenantEndpoint() {
1017
+ if (this._tenantEndpointOverride) return this._tenantEndpointOverride;
1018
+ return this._endpoint.replace(/\/space(?=$|[?#])/, "/tenant-space");
1019
+ }
1020
+ /** A /v1/tenant REST route beside the tenant twin (`/v1/tenant-space` → `/v1/tenant` + path), called with the tenant
1021
+ * key. Unlike the twin these answer the /v1 envelope — `{ data }` or `{ error: { code, message } }` — and a refusal
1022
+ * is thrown with the server's own words, since they name exactly what was wrong. */
1023
+ async _tenantRest(method, path, body, { envelope = true, root = "/tenant", text = false } = {}) {
1024
+ const key = this._tenantKey;
1025
+ if (!key) throw adminError("no_tenant_key", "witbitz: this needs a tenant secret key (wsk_), or a restricted key (wrk_) with the capability \u2014 new WitbitzAdmin({ tenant, tenantKey }) ON YOUR SERVER, never in a page");
1026
+ const url = this._tenantEndpoint().replace(/\/tenant-space(?=$|[?#])/, root + path);
1027
+ const r = await this._fetch(url, { method, headers: { ...body ? { "content-type": "application/json" } : {}, authorization: `Bearer ${key}` }, ...body ? { body: JSON.stringify(body) } : {} });
1028
+ if (text && r && r.ok !== false) return r.text();
1029
+ let j = null;
1030
+ try {
1031
+ j = await r.json();
1032
+ } catch {
1033
+ j = null;
1034
+ }
1035
+ if (r && r.ok === false) {
1036
+ const err = j && j.error ? typeof j.error === "object" ? j.error : { code: String(j.error), message: j.message || String(j.error) } : null;
1037
+ const auth = !err && (r.status === 401 || r.status === 403);
1038
+ const e = new Error(auth ? `witbitz: the tenant key was not accepted at ${url} (HTTP ${r.status}) \u2014 check the key with verifyTenantKey()` : `witbitz: ${url} refused: ${err && err.message || "HTTP " + r.status}`);
1039
+ e.code = auth ? "tenant_key_rejected" : err && err.code || "http_" + r.status;
1040
+ e.status = r.status;
1041
+ throw e;
1042
+ }
1043
+ if (!j || typeof j !== "object" || envelope && !j.data) {
1044
+ const e = new Error(`witbitz: ${url} did not answer with data`);
1045
+ e.code = "bad_response";
1046
+ throw e;
1047
+ }
1048
+ return envelope ? j.data : j;
1049
+ }
1050
+ _tenantPost() {
1051
+ const key = this._tenantKey;
1052
+ if (!key) throw adminError("no_tenant_key", "witbitz: this needs a tenant secret key \u2014 new WitbitzAdmin({ tenant, tenantKey }) ON YOUR SERVER, never in a page");
1053
+ const url = this._tenantEndpoint();
1054
+ return async (body) => {
1055
+ if (this._signingKey && body && body.op === "sentinel" && body.sentinel && body.sentinel.mode !== "whoami") body = await this._signed(body);
1056
+ const r = await this._fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${key}` }, body: JSON.stringify(body) });
1057
+ if (r && r.ok === false) {
1058
+ const auth = r.status === 401 || r.status === 403;
1059
+ let reason = null;
1060
+ if (!auth) {
1061
+ try {
1062
+ const b = await r.json();
1063
+ reason = b && (b.error || b.message) ? b : null;
1064
+ } catch {
1065
+ reason = null;
1066
+ }
1067
+ }
1068
+ const said = reason && reason.error ? `: ${reason.error}${reason.reason ? " \u2014 " + reason.reason : ""}` : "";
1069
+ const timedOut = (r.status === 503 || r.status === 504) && !(reason && reason.error);
1070
+ const e = new Error(auth ? `witbitz: the tenant key was not accepted at ${url} (HTTP ${r.status}). The enclave was never reached \u2014 check the key with verifyTenantKey()` : timedOut ? `witbitz: ${url} answered HTTP ${r.status} \u2014 the request ran past the gateway's 30 s limit; it may still have finished. Call again: the operation is safe to repeat` : `witbitz: ${url} answered HTTP ${r.status}${said}`);
1071
+ e.code = auth ? "tenant_key_rejected" : timedOut ? "gateway_timeout" : reason && reason.error || "http_" + r.status;
1072
+ e.status = r.status;
1073
+ if (reason) e.body = reason;
1074
+ throw e;
1075
+ }
1076
+ try {
1077
+ return await r.json();
1078
+ } catch {
1079
+ const e = new Error(`witbitz: ${url} did not answer with JSON`);
1080
+ e.code = "bad_response";
1081
+ throw e;
1082
+ }
1083
+ };
1084
+ }
1085
+ /** Is this tenant key good, and whose is it? → `{ ok: true, tenant }` or `{ ok: false, reason }`.
1086
+ *
1087
+ * It exists because there was no way to ask (a builder, 2026-09-27: *"I am not 100% sure the secret I saved was the
1088
+ * right one, but currently I can't even check that"*). Reaching the answer at all is the proof: the gateway refuses a
1089
+ * key it does not recognise before this ever runs. Costs nothing — no enclave round trip, and it works on a
1090
+ * deployment with no standing Sentinel, which is exactly when someone is setting one up. */
1091
+ /** The tenant's own signature over one request: Ed25519 over "witbitz-tenant-op v1\n<tenant>\n<ts>\n<nonce>\n<hex sha256(req)>", where
1092
+ * <tenant> is the name the gateway knows this tenant key by (asked once, `whoami`) and <req> the exact JSON sent. */
1093
+ async _signed(body) {
1094
+ if (!this._signedTenant) {
1095
+ const v = await this.verifyTenantKey();
1096
+ if (!v.ok) throw adminError("tenant_key_rejected", "witbitz: could not sign \u2014 " + v.reason);
1097
+ this._signedTenant = v.tenant;
1098
+ }
1099
+ const req = JSON.stringify(body.sentinel), ts = String(Date.now());
1100
+ const nonce = b64u(globalThis.crypto.getRandomValues(new Uint8Array(16)));
1101
+ const h = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(req)));
1102
+ const msg = `witbitz-tenant-op v1
1103
+ ${this._signedTenant}
1104
+ ${ts}
1105
+ ${nonce}
1106
+ ${Array.from(h, (b) => b.toString(16).padStart(2, "0")).join("")}`;
1107
+ const key = await globalThis.crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", d: this._signingKey.d, x: this._signingKey.x }, { name: "Ed25519" }, false, ["sign"]);
1108
+ const sig = new Uint8Array(await globalThis.crypto.subtle.sign({ name: "Ed25519" }, key, new TextEncoder().encode(msg)));
1109
+ return { ...body, sentinel: JSON.parse(req), tsig: { ts, nonce, sig: b64u(sig), req } };
1110
+ }
1111
+ /** A new tenant signing key: `{ privateKey }` (a JWK — keep it on your server, as you keep the tenant key) and `{ publicKey }`
1112
+ * (raw Ed25519, base64url — what `admin.signing.register()` files). */
1113
+ static async generateSigningKey() {
1114
+ const k = await globalThis.crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]);
1115
+ const jwk = await globalThis.crypto.subtle.exportKey("jwk", k.privateKey);
1116
+ return { privateKey: { kty: "OKP", crv: "Ed25519", d: jwk.d, x: jwk.x }, publicKey: jwk.x };
1117
+ }
1118
+ async verifyTenantKey() {
1119
+ const post = this._tenantPost();
1120
+ let r;
1121
+ try {
1122
+ r = await post({ op: "sentinel", sentinel: { mode: "whoami" } });
1123
+ } catch (e) {
1124
+ return { ok: false, reason: String(e && e.message || e), code: e && e.code || "" };
1125
+ }
1126
+ if (r && r.ok && r.tenant) return { ok: true, tenant: String(r.tenant) };
1127
+ const reason = r && (r.reason || r.message || r.error) || "no answer";
1128
+ return { ok: false, reason: String(reason) };
1129
+ }
1130
+ };
1131
+ redacted(WitbitzAdmin.prototype, (a) => ({ tenant: a._tenant || null, tenantKey: a._tenantKey ? REDACTED : null, ...a._signingKey ? { signingKey: REDACTED } : {} }));
1132
+ var b64u = (u8) => btoa(String.fromCharCode(...u8)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1133
+ var TenantSigning = class {
1134
+ constructor(admin) {
1135
+ this._a = admin;
1136
+ hide(this, ["_a"]);
1137
+ }
1138
+ /** Which signing key the Sentinel holds for this tenant: `{ registered, key }`. Watch it — removing the record from the store is
1139
+ * the one change someone with access to the Sentinel's storage could make (it cannot be forged, only deleted). */
1140
+ async status() {
1141
+ const r = await this._a._tenantPost()({ op: "sentinel", sentinel: { mode: "tenantkeyget" } });
1142
+ if (!r || r.error) throw adminError("refused", "witbitz: the signing key could not be read" + (r && r.error ? ": " + r.error : ""));
1143
+ return { registered: !!r.key, key: r.key || null, origins: Array.isArray(r.origins) ? r.origins : null };
1144
+ }
1145
+ /** File your SIGNED list of origins with the Sentinel (default: the list you declared — origins.list()). Once filed, a page
1146
+ * that names your tenant there must be one of these; Witbitz's own app may name you only if you list one of its origins.
1147
+ * Needs a registered signing key. Replaces the list held. */
1148
+ async publishOrigins(origins) {
1149
+ const list = Array.isArray(origins) ? origins.map(String) : await this._a.origins.list();
1150
+ if (!this._a._signingKey) throw adminError("no_signing_key", "witbitz: publishOrigins signs the list \u2014 new WitbitzAdmin({ \u2026, signingKey })");
1151
+ const r = await this._a._tenantPost()({ op: "sentinel", sentinel: { mode: "tenantorigins", origins: list } });
1152
+ if (!r || !r.ok) throw adminError(r && r.error && String(r.error).split(":")[0] || "refused", "witbitz: the origin list was not filed" + (r && r.error ? ": " + r.error : ""));
1153
+ return { ok: true, origins: r.origins || list };
1154
+ }
1155
+ /** File the public half of `publicKey` (default: this client's own signing key). Signed by this client's key when it has one. */
1156
+ async register(publicKey) {
1157
+ const key = String(publicKey || this._a._signingKey && this._a._signingKey.x || "");
1158
+ if (!/^[A-Za-z0-9_-]{43}$/.test(key)) throw adminError("invalid_argument", "witbitz: signing.register needs a raw Ed25519 public key (base64url) \u2014 or a client made with { signingKey }");
1159
+ const r = await this._a._tenantPost()({ op: "sentinel", sentinel: { mode: "tenantkey", key } });
1160
+ if (!r || !r.ok) throw adminError(r && r.error && String(r.error).split(":")[0] || "refused", "witbitz: the signing key was not registered" + (r && r.error ? ": " + r.error : ""));
1161
+ return { ok: true, key };
1162
+ }
1163
+ };
1164
+ var Providers = class {
1165
+ constructor(wb) {
1166
+ this._wb = wb;
1167
+ }
1168
+ /** Attach your OAuth app once. The client secret is sealed to the attested enclave and is gone from your process
1169
+ * when this returns. `kind` is one the enclave knows ('google'); the consent URL and every host come from there,
1170
+ * not from you, so no provider can point your users at an unmeasured screen. → { id, kind } */
1171
+ async attach({ kind = "google", clientId, clientSecret, redirectUri, scopes, label, tenant } = {}) {
1172
+ const wb = this._wb;
1173
+ const t = String(tenant || wb._tenant || "");
1174
+ if (!t) throw adminError("invalid_argument", "witbitz: which tenant? pass new WitbitzAdmin({ tenant, tenantKey }) \u2014 the key proves it, the id names it");
1175
+ if (!clientId || !clientSecret) throw adminError("invalid_argument", "witbitz: a provider needs your OAuth clientId and clientSecret");
1176
+ if (!/^https:\/\//.test(String(redirectUri || ""))) throw adminError("invalid_argument", "witbitz: redirectUri must be the https callback you registered with the provider");
1177
+ if (!Array.isArray(scopes) || !scopes.length) throw adminError("invalid_argument", "witbitz: name at least one scope your users will be asked for");
1178
+ const post = wb._tenantPost();
1179
+ const { nonce, key } = await attestStandingSentinel({ post, auth: {}, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow });
1180
+ const id = "prov_" + randomId(12);
1181
+ const sealed = await sealTo(key, nonce, { id, tenant: t, kind, clientId, clientSecret: String(clientSecret), redirectUri, scopes: scopes.map(String), label: String(label || "") });
1182
+ const r = await post({ op: "sentinel", sentinel: { mode: "provgrant", sealed } });
1183
+ if (!r || r.error || !r.ok) throw adminError(r && r.error || "refused", `witbitz: the provider was refused (${r && (r.error || r.reason) || "no answer"})`);
1184
+ return { id, kind, tenant: t };
1185
+ }
1186
+ /** A REGISTERED MCP CLIENT: for an MCP server whose sign-in does not let apps register themselves (GitHub, Asana, Box…),
1187
+ * the OAuth app you registered with that sign-in's `issuer` (as its metadata names it, e.g. https://github.com/login/oauth),
1188
+ * and the exact https callback addresses you registered (your page's `/mcp-callback`). Today only the Spaces app signs
1189
+ * in to MCP servers, with the apps filed under its own tenant; one filed under yours is kept for when the SDK does
1190
+ * (connections.md). The secret (if the issuer gave one) is sealed to the attested enclave. `scopes`: the scopes your app was
1191
+ * approved for (a string or an array) — a sign-in with it asks for exactly those, not the server's whole list (Google's
1192
+ * Calendar server lists twelve). → { id, kind: 'mcp' } */
1193
+ async attachMcp({ issuer, clientId, clientSecret = "", redirectUris, label, tenant, webhookSecret = "", scopes = "" } = {}) {
1194
+ const wb = this._wb;
1195
+ const t = String(tenant || wb._tenant || "");
1196
+ if (!t) throw adminError("invalid_argument", "witbitz: which tenant? pass new WitbitzAdmin({ tenant, tenantKey }) \u2014 the key proves it, the id names it");
1197
+ if (!/^https:\/\//.test(String(issuer || ""))) throw adminError("invalid_argument", "witbitz: issuer must be the https sign-in issuer, like https://github.com/login/oauth");
1198
+ if (!clientId) throw adminError("invalid_argument", "witbitz: a registered MCP client needs the clientId the issuer gave you");
1199
+ if (!Array.isArray(redirectUris) || !redirectUris.length || !redirectUris.every((u) => /^https:\/\//.test(String(u)))) throw adminError("invalid_argument", "witbitz: redirectUris \u2014 the https callback addresses you registered with the issuer");
1200
+ const scopeList = (Array.isArray(scopes) ? scopes.map(String) : String(scopes || "").split(/\s+/)).filter(Boolean);
1201
+ if (scopeList.length > 30 || !scopeList.every((x) => /^[\x21\x23-\x5b\x5d-\x7e]{1,200}$/.test(x))) throw adminError("invalid_argument", "witbitz: scopes \u2014 the scope names your app was approved for");
1202
+ if (webhookSecret && String(webhookSecret).length < 8) throw adminError("invalid_argument", "witbitz: webhookSecret \u2014 the secret the service signs its notices with (Zoom: the app's Secret Token)");
1203
+ const post = wb._tenantPost();
1204
+ const { nonce, key } = await attestStandingSentinel({ post, auth: {}, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow });
1205
+ const id = "prov_" + randomId(12);
1206
+ const sealed = await sealTo(key, nonce, { id, tenant: t, kind: "mcp", issuer: String(issuer), clientId: String(clientId), clientSecret: String(clientSecret || ""), redirectUris: redirectUris.map(String), label: String(label || ""), ...webhookSecret ? { webhookSecret: String(webhookSecret) } : {}, ...scopeList.length ? { scopes: scopeList.join(" ") } : {} });
1207
+ const r = await post({ op: "sentinel", sentinel: { mode: "provgrant", sealed } });
1208
+ if (!r || r.error || !r.ok) throw adminError(r && r.error || "refused", `witbitz: the MCP client was refused (${r && (r.error || r.reason) || "no answer"})`);
1209
+ return { id, kind: "mcp", tenant: t };
1210
+ }
1211
+ /** Your tenant's providers — never a client secret. */
1212
+ async list() {
1213
+ const r = await this._wb._tenantPost()({ op: "sentinel", sentinel: { mode: "provlist" } });
1214
+ if (!r || r.error) throw adminError(r && r.error || "refused", `witbitz: could not list providers (${r && r.error || "no answer"})`);
1215
+ return Array.isArray(r.providers) ? r.providers : [];
1216
+ }
1217
+ /** Remove an OAuth app. Every connection your users made under it dies at once. → { revoked, connections } */
1218
+ async revoke(id) {
1219
+ const r = await this._wb._tenantPost()({ op: "sentinel", sentinel: { mode: "provrevoke", id: String(id || "") } });
1220
+ if (!r || r.error) throw adminError(r && r.error || "refused", `witbitz: could not revoke (${r && r.error || "no answer"})`);
1221
+ return { revoked: Number(r.revoked) || 0, connections: Number(r.connections) || 0 };
1222
+ }
1223
+ };
1224
+ var randomId = (n) => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(n)))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1225
+ var TenantRooms = class {
1226
+ constructor(wb) {
1227
+ this._wb = wb;
1228
+ }
1229
+ /** Delete ONE room. Afterwards it answers 410 to everyone, at once, whichever retention you choose:
1230
+ * retain: 'none' (default) every stored version of everything is deleted now — sealed messages, files, the
1231
+ * confidential tier's copies. Irreversible.
1232
+ * retain: 'backups' the current copies are deleted now; old versions expire within 35 days (recoverable only by
1233
+ * Witbitz operators, by hand, until then).
1234
+ * retain: 'grace' nothing is deleted yet; `rooms.restore(room)` undoes it for `graceDays` (1–90, default 30),
1235
+ * then it is purged as `after` says ('none' default, or 'backups').
1236
+ * Only for a room no one else uses — a shared room belongs to its other members too, and the server cannot tell
1237
+ * (membership is sealed), so that is yours to decide.
1238
+ * → none/backups: { deleted:true, room, retain, versions, bytes, turnWasRunning, backupsUntil? }
1239
+ * → grace: { deleted:false, held:true, room, purgeAt, after }
1240
+ * When `turnWasRunning`, a reply being written may land a moment later: call delete again after a few minutes.
1241
+ * Throws if anything could not be removed (code 'partial') — never a half-done delete reported as done. */
1242
+ async delete(room, { retain, graceDays, after } = {}) {
1243
+ if (typeof room !== "string" || !/^(?:sp|tmp)-[0-9a-z-]{1,48}$/.test(room)) throw adminError("invalid_argument", 'witbitz: rooms.delete takes a room id, e.g. "sp-\u2026"');
1244
+ const body = { confirm: room, ...retain ? { retain } : {}, ...graceDays !== void 0 ? { graceDays } : {}, ...after ? { after } : {} };
1245
+ const r = await this._wb._tenantRest("DELETE", "/rooms/" + encodeURIComponent(room), body, { envelope: false });
1246
+ if (r.held) return { deleted: false, held: true, room: r.room, purgeAt: Number(r.purgeAt) || 0, after: r.after || "none" };
1247
+ if (!r.deleted) {
1248
+ const e = new Error(`witbitz: room ${room} was only partly deleted \u2014 call delete again`);
1249
+ e.code = "partial";
1250
+ e.result = r;
1251
+ throw e;
1252
+ }
1253
+ return { deleted: true, room: r.room, retain: r.retain || "none", versions: Number(r.versions) || 0, bytes: Number(r.bytes) || 0, turnWasRunning: !!r.turnWasRunning, ...r.backupsUntil ? { backupsUntil: Number(r.backupsUntil) } : {} };
1254
+ }
1255
+ /** Your rooms, a page at a time: `{ rooms: [{ room, createdAt, lastUsedAt, kind, split, gated, held }], next }`.
1256
+ * `createdAt` / `lastUsedAt` are ISO times or null (`lastUsedAt` is when a member last opened, wrote or prompted in it;
1257
+ * recorded since 2026-10-07). `held` is `{ purgeAt }` for a room pending deletion. Pass `next` back as `cursor`. */
1258
+ async list({ cursor, limit } = {}) {
1259
+ const q = new URLSearchParams({ list: "1", ...cursor ? { cursor } : {}, ...limit ? { limit: String(limit) } : {} });
1260
+ const r = await this._wb._tenantRest("GET", "?" + q.toString(), null, { envelope: false, root: "/tenant/rooms" });
1261
+ return { rooms: Array.isArray(r.rooms) ? r.rooms : [], next: r.next || null };
1262
+ }
1263
+ /** THE IDLE RULE: rooms no member used for `days` (30–3650) are held for 30 days — gone at once, restorable with
1264
+ * `rooms.restore(room)` — then deleted, by a daily run. `null` turns it off. A room with no recorded use counts from
1265
+ * 2026-10-07. At most 100 of your rooms are held per day. → { idleRoomDays } */
1266
+ async idleDeletion(days) {
1267
+ if (days !== null && !(Number.isInteger(days) && days >= 30 && days <= 3650)) throw adminError("invalid_argument", "witbitz: rooms.idleDeletion(days) \u2014 a whole number of days from 30 to 3650, or null to turn it off");
1268
+ const d = await this._wb._tenantRest("PUT", "/webhooks", { idleRoomDays: days });
1269
+ return { idleRoomDays: d && d.tenant ? d.tenant.idle_room_days ?? null : days };
1270
+ }
1271
+ /** Undo a `retain: 'grace'` delete before its window ends. → { restored:true, room }. A room deleted with 'none' or
1272
+ * 'backups', or whose window has ended, cannot come back (code 'purged' / 'grace_ended'). */
1273
+ async restore(room) {
1274
+ if (typeof room !== "string" || !/^(?:sp|tmp)-[0-9a-z-]{1,48}$/.test(room)) throw adminError("invalid_argument", 'witbitz: rooms.restore takes a room id, e.g. "sp-\u2026"');
1275
+ const r = await this._wb._tenantRest("POST", "/rooms/" + encodeURIComponent(room) + "/restore", {}, { envelope: false });
1276
+ return { restored: !!r.restored, room: r.room };
1277
+ }
1278
+ };
1279
+ var USER_ID = /^u_[a-z0-9]{24}$/;
1280
+ var userIdOf = (id, what) => {
1281
+ if (typeof id !== "string" || !USER_ID.test(id)) throw adminError("invalid_argument", `witbitz: ${what} takes a user id, e.g. "u_\u2026" (from users.create)`);
1282
+ return id;
1283
+ };
1284
+ var TenantKeys = class {
1285
+ constructor(wb) {
1286
+ this._wb = wb;
1287
+ }
1288
+ /** → [{ keyId, type, label, createdAt, revoked, display, scopes?, expiresAt?, maxCustomerCapUsd? }] — never a key */
1289
+ async list() {
1290
+ return await this._wb._tenantRest("GET", "/keys");
1291
+ }
1292
+ /** → { key, keyId, type, scopes?, maxCustomerCapUsd?, expiresAt? } — `key` is shown ONCE: store it now.
1293
+ * @param {object} opts { type: 'restricted' | 'secret' | 'publishable', label?, scopes?, expiresAt?, maxCustomerCapUsd? } */
1294
+ async create({ type = "restricted", label, scopes, expiresAt, maxCustomerCapUsd } = {}) {
1295
+ const d = await this._wb._tenantRest("POST", "/keys", { type, ...label ? { label } : {}, ...scopes ? { scopes } : {}, ...expiresAt != null ? { expiresAt } : {}, ...maxCustomerCapUsd != null ? { maxCustomerCapUsd } : {} });
1296
+ return { key: d.key, keyId: d.key_id, type: d.type, ...d.type === "restricted" ? { scopes: d.scopes || [], maxCustomerCapUsd: d.max_customer_cap_usd ?? null, expiresAt: d.expires_at ?? null } : {} };
1297
+ }
1298
+ /** Revoke a key — refused from then on. → { revoked: true, keyId } */
1299
+ async revoke(keyId) {
1300
+ if (!/^k_[0-9A-Za-z]{1,40}$/.test(String(keyId || ""))) throw adminError("invalid_argument", "witbitz: keys.revoke(keyId) \u2014 the keyId from keys.list()");
1301
+ await this._wb._tenantRest("DELETE", "/keys/" + encodeURIComponent(keyId), null, { envelope: false, text: true });
1302
+ return { revoked: true, keyId };
1303
+ }
1304
+ };
1305
+ var TenantCustomers = class {
1306
+ constructor(wb) {
1307
+ this._wb = wb;
1308
+ }
1309
+ /** `userRef` — YOUR label for the user (1–120 chars; shown to you in billing, never to the provider). `capMonthlyUsd`
1310
+ * — a hard monthly stop (default 25). → { userId, userRef, capMonthlyUsd, createdAt, revoked } */
1311
+ async create({ userRef, capMonthlyUsd } = {}) {
1312
+ const d = await this._wb._tenantRest("POST", "/users", { userRef, ...capMonthlyUsd !== void 0 ? { capMonthlyUsd } : {} });
1313
+ return d.user;
1314
+ }
1315
+ /** Every user you created, oldest first — nothing secret. */
1316
+ async list() {
1317
+ return await this._wb._tenantRest("GET", "/users");
1318
+ }
1319
+ /** Change a user's monthly cap — a plan upgrade or a cancellation. The provider's limit moves first; the user, their key
1320
+ * and their history stay the same. A revoked user cannot be changed. → the user, as `create` returns it. */
1321
+ async update(userId, { capMonthlyUsd } = {}) {
1322
+ const d = await this._wb._tenantRest("PATCH", "/users/" + userIdOf(userId, "users.update"), { capMonthlyUsd });
1323
+ return d.user;
1324
+ }
1325
+ /** Revoke: the user's provider key is deleted and their tokens stop working. Spend up to now is still billed. */
1326
+ async revoke(userId) {
1327
+ await this._wb._tenantRest("DELETE", "/users/" + userIdOf(userId, "users.revoke"), null, { envelope: false, text: true });
1328
+ return { revoked: true, userId };
1329
+ }
1330
+ /** ERASE A USER WHO IS GONE (https://witbitz.chat/docs/sdk-builder.md#user-erasure): the Spaces this person created in YOUR app that nobody else used are
1331
+ * deleted — every message, file and stored version. Shared Spaces stay (what they wrote is part of the others'
1332
+ * conversation); Spaces they only joined are not theirs to delete. Works from the list the person's own devices filed,
1333
+ * sealed, with Witbitz's attested enclave for your app; you never see it. Run it again after a partial result
1334
+ * (`failed` > 0 or `incomplete`) — nothing is lost. Pair it with `revoke(userId)` for their billing.
1335
+ * → { filed, rooms, deleted, shared, notTheirs, failed, cleared } */
1336
+ async erase({ email } = {}) {
1337
+ if (typeof email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) throw adminError("invalid_argument", "witbitz: users.erase takes { email } \u2014 the address the person signed in to your app with");
1338
+ const r = await this._wb._tenantPost()({ op: "sentinel", sentinel: { mode: "eraseuser", email: email.trim() } });
1339
+ if (!r || r.error || r.ok === false) throw adminError(r && r.error || "refused", `witbitz: the erase was refused (${r && (r.error || r.reason) || "no answer"})`);
1340
+ return r;
1341
+ }
1342
+ /** A token for this user's page, valid `ttlSec` (60–3600, default 900). → { token, expiresAt } (unix seconds).
1343
+ * Mint it when the user signs in and again before `expiresAt`; never store it server-side longer than that. */
1344
+ async token(userId, { ttlSec } = {}) {
1345
+ return await this._wb._tenantRest("POST", "/users/" + userIdOf(userId, "users.token") + "/token", ttlSec !== void 0 ? { ttlSec } : {});
1346
+ }
1347
+ };
1348
+ var TenantBilling = class {
1349
+ constructor(wb) {
1350
+ this._wb = wb;
1351
+ }
1352
+ /** → { tenant, rate, month, storage, days, users, userDays, at } — amounts in microdollars (1e-6 USD). */
1353
+ async get() {
1354
+ return await this._wb._tenantRest("GET", "", null, { root: "/billing", envelope: false });
1355
+ }
1356
+ /** REQUIRE A USER TOKEN on every op that spends (a turn, a title, an approval, an import) in your rooms. With it on, such
1357
+ * an op that arrives WITHOUT a user token is refused (`user_token_required`) instead of billed to you — so your
1358
+ * per-user caps cannot be bypassed by a page that simply sends none. Reads never need one. Takes effect within about a
1359
+ * minute. → { requireUserToken } as stored. */
1360
+ async requireUserToken(on = true) {
1361
+ if (typeof on !== "boolean") throw adminError("invalid_argument", "witbitz: billing.requireUserToken takes true or false");
1362
+ const d = await this._wb._tenantRest("PUT", "/webhooks", { requireUserToken: on });
1363
+ return { requireUserToken: !!(d && d.tenant && d.tenant.require_user_token) };
1364
+ }
1365
+ /** LIMIT VISITORS (docs/visitor-limits.md): how many questions a day (UTC) people who are NOT signed in — no user token —
1366
+ * may ask in your rooms: at most `perNetwork` from one network, at most `total` from all of them. Over either, the
1367
+ * question is refused before anything is spent (`429 visitor_limit`, with `scope` and a sentence to show). `null` turns
1368
+ * it off (every question bills to you, as without it). A question with a user token is its user's, under their own cap.
1369
+ * Takes effect within about a minute. → { visitorLimit } as stored. */
1370
+ async visitorLimit(limit) {
1371
+ const ok = limit === null || limit && typeof limit === "object" && !Array.isArray(limit) && Object.keys(limit).every((k) => k === "perNetwork" || k === "total") && Number.isInteger(limit.perNetwork) && Number.isInteger(limit.total) && limit.perNetwork >= 1 && limit.perNetwork <= limit.total && limit.total <= 1e7;
1372
+ if (!ok) throw adminError("invalid_argument", "witbitz: billing.visitorLimit takes { perNetwork, total } \u2014 whole numbers of questions a day, 1 \u2264 perNetwork \u2264 total \u2264 10000000 \u2014 or null to turn it off");
1373
+ const d = await this._wb._tenantRest("PUT", "/webhooks", { visitorLimit: limit === null ? null : { perNetwork: limit.perNetwork, total: limit.total } });
1374
+ const vl = d && d.tenant ? d.tenant.visitor_limit : null;
1375
+ return { visitorLimit: vl && typeof vl === "object" ? { perNetwork: vl.perNetwork, total: vl.total } : null };
1376
+ }
1377
+ /** The same as CSV text: one line per day, or with `{ byUser: true }` one line per user per day. */
1378
+ async csv({ byUser = false } = {}) {
1379
+ return await this._wb._tenantRest("GET", "?format=csv" + (byUser ? "&by=user" : ""), null, { root: "/billing", text: true });
1380
+ }
1381
+ /** YOUR PREPAID BALANCE (docs/tenant-prepaid.md), or null when your app is not on prepaid billing.
1382
+ * → { balanceMicros, paused: null | 'out_of_credit', lowWarned, earlyAccess, canBuy, packs: [{ pack, dollars, credit }], history: [{ at, kind, micros, orderId? }] }
1383
+ * (`canBuy`: buying credit is open to your app now — while it is in testing, only to the apps in the test).
1384
+ * While `paused`, every op that spends in your rooms is refused (`402 tenant_out_of_credit`) until you add credit. */
1385
+ async balance() {
1386
+ const v = await this.get();
1387
+ return v && v.prepaid || null;
1388
+ }
1389
+ /** ADD CREDIT: a payment page for one pack — 'pack25' | 'pack100' | 'pack500' — bound to your app. Open its `url` in a browser
1390
+ * (Lemon Squeezy takes the payment and the tax); the credit lands within a minute of paying, and lifts a pause at once.
1391
+ * `redirectUrl` (https): where the payer returns. Needs your SECRET key. → { url, pack, dollars, testMode }
1392
+ * Refused with `payments_not_open` (buying is not open yet), `not_prepaid` (your app is not on prepaid billing), `not_a_tester`
1393
+ * (buying is in testing, not open to your app), `checkout_unavailable` (the payment page could not be made — try again). */
1394
+ async topUp(pack, { redirectUrl } = {}) {
1395
+ if (!["pack25", "pack100", "pack500"].includes(pack)) throw adminError("invalid_argument", "witbitz: billing.topUp takes 'pack25', 'pack100' or 'pack500'");
1396
+ if (redirectUrl != null && !/^https:\/\/\S{1,300}$/.test(String(redirectUrl))) throw adminError("invalid_argument", "witbitz: billing.topUp redirectUrl must be an https address");
1397
+ return await this._wb._tenantRest("POST", "/billing/checkout", { pack, ...redirectUrl ? { redirectUrl } : {} });
1398
+ }
1399
+ };
1400
+ var TenantApp = class {
1401
+ constructor(wb) {
1402
+ this._wb = wb;
1403
+ }
1404
+ /** → { name } as stored. Refused with the reason when the name breaks the rule. */
1405
+ async rename(name) {
1406
+ if (typeof name !== "string" || !name.trim()) throw adminError("invalid_argument", "witbitz: app.rename takes your app's name, e.g. 'Keepwarden'");
1407
+ const d = await this._wb._tenantRest("PUT", "/webhooks", { name });
1408
+ return { name: d && d.tenant && d.tenant.name || "" };
1409
+ }
1410
+ /** The name your app is registered with now. */
1411
+ async name() {
1412
+ const d = await this._wb._tenantRest("GET", "");
1413
+ return d && typeof d.name === "string" ? d.name : "";
1414
+ }
1415
+ };
1416
+ var TenantOrigins = class {
1417
+ constructor(wb) {
1418
+ this._wb = wb;
1419
+ }
1420
+ /** Declare the whole list. Declaring REPLACES what you had — keep the origins you still use.
1421
+ * → { origins, unproven } — origins as stored (lower-cased, trailing slash removed, de-duplicated); unproven = the ones
1422
+ * whose host does not yet say it is yours, each with how to prove it ({ origin, how }). An unproven origin works; only
1423
+ * a proven one puts your app's name in a sign-in mail. Declare again once the file or record is in place. */
1424
+ async declare(origins) {
1425
+ if (!Array.isArray(origins)) throw adminError("invalid_argument", 'witbitz: origins.declare takes an array, e.g. ["https://app.example.com"]');
1426
+ const d = await this._wb._tenantRest("PUT", "/webhooks", { origins: origins.map(String) });
1427
+ const out = { origins: Array.isArray(d.tenant && d.tenant.origins) ? d.tenant.origins : [], unproven: Array.isArray(d.origins_unproven) ? d.origins_unproven : [] };
1428
+ if (this._wb._signingKey) out.signed = (await this._wb.signing.publishOrigins(out.origins)).origins;
1429
+ return out;
1430
+ }
1431
+ /** The origins this tenant declares now. */
1432
+ async list() {
1433
+ const d = await this._wb._tenantRest("GET", "");
1434
+ return Array.isArray(d.origins) ? d.origins : [];
1435
+ }
1436
+ };
1437
+ var DeclaredHosts = class {
1438
+ constructor(wb) {
1439
+ this._wb = wb;
1440
+ }
1441
+ /** Declare the whole list. Declaring REPLACES what you had, so removing a host is declaring without it.
1442
+ * → { hosts } as the enclave normalised them (lower-cased, scheme and path stripped, de-duplicated). */
1443
+ async declare(hosts) {
1444
+ if (!Array.isArray(hosts)) throw adminError("invalid_argument", 'witbitz: declare takes an array of bare domains, e.g. ["api.todoist.com"]');
1445
+ const r = await this._wb._tenantPost()({ op: "sentinel", sentinel: { mode: "hostdeclare", hosts: hosts.map(String) } });
1446
+ if (!r || r.error || !r.ok) throw adminError(r && r.error || "refused", `witbitz: the hosts were refused (${r && (r.error || r.reason) || "no answer"})`);
1447
+ return { hosts: Array.isArray(r.hosts) ? r.hosts : [] };
1448
+ }
1449
+ /** What this tenant currently vouches for. */
1450
+ async list() {
1451
+ const r = await this._wb._tenantPost()({ op: "sentinel", sentinel: { mode: "hostlist" } });
1452
+ if (!r || r.error) throw adminError(r && r.error || "refused", `witbitz: could not list hosts (${r && r.error || "no answer"})`);
1453
+ return Array.isArray(r.hosts) ? r.hosts : [];
1454
+ }
1455
+ };
1456
+ export {
1457
+ DEFAULT_ENDPOINT,
1458
+ TenantCustomers as TenantUsers,
1459
+ WitbitzAdmin
1460
+ };