@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.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +221 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +228 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/agentDoorTools.js +28 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +165 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeAttachments.js +100 -0
- package/codeBrowse.js +224 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +650 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +389 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +59 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeProgress.js +54 -0
- package/codeRelay.js +505 -0
- package/codeSent.js +68 -0
- package/codeSentinel.js +86 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +317 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +561 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +527 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +113 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +91 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +894 -0
- package/laneAssociation.js +68 -0
- package/laneConfig.js +58 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +239 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +125 -0
- package/mirrorBatch.js +47 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opRouting.js +10 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +273 -4
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +426 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomEmbed.js +111 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +305 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +52 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +524 -0
- package/sdkAccount.js +483 -0
- package/sdkAccountDoc.js +89 -0
- package/sdkAccountSections.js +332 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +507 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +221 -0
- package/sdkComputers.js +1009 -0
- package/sdkDictation.js +232 -0
- package/sdkErase.js +288 -0
- package/sdkExports.js +71 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +96 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +340 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +71 -0
- package/sdkTemporaryRooms.js +123 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +180 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +155 -0
- package/shamir.js +85 -0
- package/sharedViews.js +52 -0
- package/sheetChrome.js +450 -0
- package/siri.js +278 -0
- package/spaceClient.js +1429 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/spaceTemplates.js +99 -0
- package/speechOut.js +102 -0
- package/splitKeyClient.js +90 -0
- package/store.js +656 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +540 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +37 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +2326 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +261 -0
- package/vaultAtRest.js +208 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +287 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +117 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1460 -0
- package/witbitz-sdk.d.ts +1197 -0
- package/witbitz-sdk.js +4258 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/witbitz-admin.js
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
// witbitz-admin.js — the BUILDER's SDK: what your server does with your tenant SECRET key (wsk_…).
|
|
2
|
+
// https://witbitz.chat/docs/sdk-roadmap.md, item 5 (2026-10-05). These ops used to live only on the page client (`wb.origins`,
|
|
3
|
+
// `wb.users`, …), so the code that takes a secret key shipped in every page bundle and nothing but a doc comment said
|
|
4
|
+
// "server only". They live here now; the page client's old names delegate here and keep working.
|
|
5
|
+
//
|
|
6
|
+
// import { WitbitzAdmin } from 'https://witbitz-spaces.pages.dev/witbitz-admin.js' // on YOUR server
|
|
7
|
+
// const admin = new WitbitzAdmin({ tenant: 'acme', tenantKey: process.env.WITBITZ_TENANT_KEY })
|
|
8
|
+
// await admin.verifyTenantKey() // → { ok: true, tenant }
|
|
9
|
+
// await admin.origins.declare(['https://app.acme.com'])
|
|
10
|
+
// const c = await admin.customers.create({ userRef: 'acct_42' }) // a customer YOU bill — not a Witbitz account
|
|
11
|
+
//
|
|
12
|
+
// `customers` is the new name of `wb.users`: your app's billed users, each with its own capped provider key.
|
|
13
|
+
import { attestStandingSentinel, STANDING_SENTINEL_PCR0 } from './connections.js'
|
|
14
|
+
import { sealTo as sealToEnclave } from './sealShare.js'
|
|
15
|
+
import { hide, redacted, REDACTED } from './sdkRedact.js'
|
|
16
|
+
// Every error a builder can switch on carries a `code`, as the SDK's do (sync sweep, 10-13): no_tenant_key, invalid_argument,
|
|
17
|
+
// the server's own refusal (refused when it names none), plus the HTTP ones above (unauthorized, bad_response, …).
|
|
18
|
+
const adminError = (code, message) => Object.assign(new Error(message), { code: String(code || 'refused') })
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
export const DEFAULT_ENDPOINT = 'https://api.witbitz.chat/v1/space'
|
|
22
|
+
|
|
23
|
+
// RETIRED in 4.0.0 — YOUR APP'S OWNER KEY, rooms only your app may use (B8). The rule it signed required a page SERVED as your app: a
|
|
24
|
+
// web page vouching for itself, which anyone can copy (the owner, 2026-11-22: "We dont need any emulation rooms"). Every call says so
|
|
25
|
+
// by name; no app ever registered a key (checked 2026-11-22), so no room depended on it.
|
|
26
|
+
const ownerRetired = () => adminError('owner_rule_retired', 'witbitz: the owner rule (rooms only your app may use) is retired — a web page cannot prove which app it is (sdk-changes.md, 4.0.0)')
|
|
27
|
+
class TenantOwner {
|
|
28
|
+
constructor (admin) { this._a = admin }
|
|
29
|
+
async register () { throw ownerRetired() }
|
|
30
|
+
async rotate () { throw ownerRetired() }
|
|
31
|
+
async room () { throw ownerRetired() }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class WitbitzAdmin {
|
|
35
|
+
/** RETIRED in 4.0.0 (the owner rule, above). */
|
|
36
|
+
static async generateOwnerKey () { throw ownerRetired() }
|
|
37
|
+
/** @param {object} opts { tenant, tenantKey, signingKey?, endpoint?, tenantEndpoint?, fetchImpl?, sentinel? } — `signingKey`: your
|
|
38
|
+
* tenant's Ed25519 PRIVATE key (a JWK, or its JSON string; WitbitzAdmin.generateSigningKey()), kept on your server. */
|
|
39
|
+
constructor({ tenant = '', tenantKey = '', signingKey = null, endpoint = DEFAULT_ENDPOINT, tenantEndpoint, fetchImpl, sentinel } = {}) {
|
|
40
|
+
this._endpoint = endpoint
|
|
41
|
+
this._tenant = tenant || ''
|
|
42
|
+
this._tenantKey = tenantKey || ''
|
|
43
|
+
this._signingKey = signingKey ? (typeof signingKey === 'string' ? JSON.parse(signingKey) : signingKey) : null
|
|
44
|
+
this._tenantEndpointOverride = tenantEndpoint ? String(tenantEndpoint) : ''
|
|
45
|
+
this._fetch = typeof fetchImpl === 'function' ? fetchImpl : ((...a) => fetch(...a))
|
|
46
|
+
this.owner = new TenantOwner(this) // RETIRED in 4.0.0: each call answers owner_rule_retired
|
|
47
|
+
// A NEW WITBITZ SENTINEL BUILD IS FOLLOWED, as in the SDK (witbitz-sdk.js; sync sweep 10-19 #5): `follow` 'published' (the
|
|
48
|
+
// default) takes a build Witbitz publishes at /sentinel-claim.json, 'off' keeps the pins. Your own `pins` are never followed.
|
|
49
|
+
const ownPins = !!(sentinel && Array.isArray(sentinel.pins)), off = !!(sentinel && sentinel.follow === 'off')
|
|
50
|
+
this._sentinel = { pins: ownPins ? sentinel.pins : STANDING_SENTINEL_PCR0, ...(sentinel && typeof sentinel.verify === 'function' ? { verify: sentinel.verify } : {}),
|
|
51
|
+
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) } }
|
|
52
|
+
/** The page origins that act for this tenant. */
|
|
53
|
+
this.origins = new TenantOrigins(this)
|
|
54
|
+
/** Your app's name — what a sign-in mail from your pages says ("Your Keepwarden code"). */
|
|
55
|
+
this.app = new TenantApp(this)
|
|
56
|
+
/** The hosts your users may attach a key for. */
|
|
57
|
+
this.hosts = new DeclaredHosts(this)
|
|
58
|
+
/** Your own OAuth apps. */
|
|
59
|
+
this.providers = new Providers(this)
|
|
60
|
+
/** Delete / restore your rooms. */
|
|
61
|
+
this.rooms = new TenantRooms(this)
|
|
62
|
+
/** Your tenant's signing key: register its public half once; from then on every tenant request is signed by it. */
|
|
63
|
+
this.signing = new TenantSigning(this)
|
|
64
|
+
/** Your app's billed customers (per-user billing) — not Witbitz accounts. */
|
|
65
|
+
this.customers = new TenantCustomers(this)
|
|
66
|
+
/** What you are billed. */
|
|
67
|
+
this.billing = new TenantBilling(this)
|
|
68
|
+
/** Your API keys — including RESTRICTED keys that carry only the capabilities you choose. */
|
|
69
|
+
this.keys = new TenantKeys(this)
|
|
70
|
+
hide(this, ['_tenantKey', '_signingKey', '_fetch'])
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The BUILDER's transport: the same endpoint with a tenant SECRET key, which the /v1 authorizer resolves to a
|
|
74
|
+
* tenant before this reaches any handler. Server-side only. */
|
|
75
|
+
/**
|
|
76
|
+
* ⛔ A BUILDER CALL MUST NOT GO TO THE SPACE ENDPOINT (2026-09-27, found by a builder whose key was fine all along).
|
|
77
|
+
* `/v1/space` is deliberately KEYLESS — a Space authenticates by its own key-commitment — so no authorizer runs there
|
|
78
|
+
* and an `authorization: Bearer wsk_…` header is never examined. Every builder op therefore answered 403
|
|
79
|
+
* `tenant_required`, identically for a real key and a forged one, and the whole builder half was unreachable in
|
|
80
|
+
* production while the refusal read like a bad secret. Builder ops belong on the AUTHENTICATED twin, where the
|
|
81
|
+
* gateway checks the key and hands the handler a tenant it cannot have been told.
|
|
82
|
+
*/
|
|
83
|
+
_tenantEndpoint() {
|
|
84
|
+
if (this._tenantEndpointOverride) return this._tenantEndpointOverride
|
|
85
|
+
// Derive rather than hardcode: a staging or self-hosted deployment answers the Space at its own path, and its
|
|
86
|
+
// tenant twin sits beside it. Only the last segment moves, so a query or a port is untouched.
|
|
87
|
+
return this._endpoint.replace(/\/space(?=$|[?#])/, '/tenant-space')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A /v1/tenant REST route beside the tenant twin (`/v1/tenant-space` → `/v1/tenant` + path), called with the tenant
|
|
91
|
+
* key. Unlike the twin these answer the /v1 envelope — `{ data }` or `{ error: { code, message } }` — and a refusal
|
|
92
|
+
* is thrown with the server's own words, since they name exactly what was wrong. */
|
|
93
|
+
async _tenantRest(method, path, body, { envelope = true, root = '/tenant', text = false } = {}) {
|
|
94
|
+
const key = this._tenantKey
|
|
95
|
+
if (!key) throw adminError('no_tenant_key', 'witbitz: this needs a tenant secret key (wsk_), or a restricted key (wrk_) with the capability — new WitbitzAdmin({ tenant, tenantKey }) ON YOUR SERVER, never in a page')
|
|
96
|
+
const url = this._tenantEndpoint().replace(/\/tenant-space(?=$|[?#])/, root + path)
|
|
97
|
+
const r = await this._fetch(url, { method, headers: { ...(body ? { 'content-type': 'application/json' } : {}), authorization: `Bearer ${key}` }, ...(body ? { body: JSON.stringify(body) } : {}) })
|
|
98
|
+
if (text && r && r.ok !== false) return r.text()
|
|
99
|
+
let j = null; try { j = await r.json() } catch { j = null }
|
|
100
|
+
if (r && r.ok === false) {
|
|
101
|
+
// The /v1 envelope says { error: { code, message } }; the room-purge route says { error, message } — read both.
|
|
102
|
+
const err = j && j.error ? (typeof j.error === 'object' ? j.error : { code: String(j.error), message: j.message || String(j.error) }) : null
|
|
103
|
+
const auth = !err && (r.status === 401 || r.status === 403)
|
|
104
|
+
const e = new Error(auth
|
|
105
|
+
? `witbitz: the tenant key was not accepted at ${url} (HTTP ${r.status}) — check the key with verifyTenantKey()`
|
|
106
|
+
: `witbitz: ${url} refused: ${(err && err.message) || 'HTTP ' + r.status}`)
|
|
107
|
+
e.code = auth ? 'tenant_key_rejected' : ((err && err.code) || 'http_' + r.status)
|
|
108
|
+
e.status = r.status
|
|
109
|
+
throw e
|
|
110
|
+
}
|
|
111
|
+
if (!j || typeof j !== 'object' || (envelope && !j.data)) { const e = new Error(`witbitz: ${url} did not answer with data`); e.code = 'bad_response'; throw e }
|
|
112
|
+
return envelope ? j.data : j
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
_tenantPost() {
|
|
116
|
+
const key = this._tenantKey
|
|
117
|
+
if (!key) throw adminError('no_tenant_key', 'witbitz: this needs a tenant secret key — new WitbitzAdmin({ tenant, tenantKey }) ON YOUR SERVER, never in a page')
|
|
118
|
+
const url = this._tenantEndpoint()
|
|
119
|
+
return async (body) => {
|
|
120
|
+
// SIGNED (docs/standing-sentinel.md § Step 1e): with a signing key, a Sentinel request carries its own signature, which
|
|
121
|
+
// the Sentinel checks itself — so no one between your server and the enclave (the Witbitz Lambda included) can act as
|
|
122
|
+
// your tenant. `whoami` is answered by the door, not the Sentinel, and is never signed.
|
|
123
|
+
if (this._signingKey && body && body.op === 'sentinel' && body.sentinel && body.sentinel.mode !== 'whoami') body = await this._signed(body)
|
|
124
|
+
const r = await this._fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` }, body: JSON.stringify(body) })
|
|
125
|
+
// ⛔ CHECK THE STATUS BEFORE THE BODY (2026-09-27). The /v1 gateway refuses an unknown key with a 403 whose body
|
|
126
|
+
// is {"message":"Forbidden"} — which PARSES, so returning it verbatim handed callers an object with neither
|
|
127
|
+
// `error` nor the field they wanted. `attestStandingSentinel` then said "the Sentinel could not be reached (no
|
|
128
|
+
// attestation)", and a builder went hunting for a fault in our enclave that did not exist. The enclave was never
|
|
129
|
+
// asked; their key was refused one hop earlier, and the status code said so all along.
|
|
130
|
+
// It THROWS rather than returning an error object, deliberately: every caller wraps a returned error in its own
|
|
131
|
+
// sentence ("could not list hosts…", "the Sentinel could not be reached…"), and those sentences all blame the
|
|
132
|
+
// wrong thing when the truth is that the gateway refused the key one hop before any of them. A throw carries the
|
|
133
|
+
// real cause past all of that. `verifyTenantKey` is the one caller that WANTS a no rather than an exception, and
|
|
134
|
+
// it catches.
|
|
135
|
+
if (r && r.ok === false) {
|
|
136
|
+
const auth = r.status === 401 || r.status === 403
|
|
137
|
+
// The server's own reason, when it gave one (2026-10-10: a builder's erase saw "HTTP 503" and nothing else). A 503
|
|
138
|
+
// with no Witbitz body is API Gateway's 30 s cap: the work may still have finished — say so.
|
|
139
|
+
let reason = null
|
|
140
|
+
if (!auth) { try { const b = await r.json(); reason = b && (b.error || b.message) ? b : null } catch { reason = null } }
|
|
141
|
+
const said = reason && reason.error ? `: ${reason.error}${reason.reason ? ' — ' + reason.reason : ''}` : ''
|
|
142
|
+
const timedOut = (r.status === 503 || r.status === 504) && !(reason && reason.error)
|
|
143
|
+
const e = new Error(auth
|
|
144
|
+
? `witbitz: the tenant key was not accepted at ${url} (HTTP ${r.status}). The enclave was never reached — check the key with verifyTenantKey()`
|
|
145
|
+
: timedOut
|
|
146
|
+
? `witbitz: ${url} answered HTTP ${r.status} — the request ran past the gateway's 30 s limit; it may still have finished. Call again: the operation is safe to repeat`
|
|
147
|
+
: `witbitz: ${url} answered HTTP ${r.status}${said}`)
|
|
148
|
+
e.code = auth ? 'tenant_key_rejected' : timedOut ? 'gateway_timeout' : (reason && reason.error) || 'http_' + r.status
|
|
149
|
+
e.status = r.status
|
|
150
|
+
if (reason) e.body = reason
|
|
151
|
+
throw e
|
|
152
|
+
}
|
|
153
|
+
try { return await r.json() } catch { const e = new Error(`witbitz: ${url} did not answer with JSON`); e.code = 'bad_response'; throw e }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Is this tenant key good, and whose is it? → `{ ok: true, tenant }` or `{ ok: false, reason }`.
|
|
158
|
+
*
|
|
159
|
+
* 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
|
|
160
|
+
* right one, but currently I can't even check that"*). Reaching the answer at all is the proof: the gateway refuses a
|
|
161
|
+
* key it does not recognise before this ever runs. Costs nothing — no enclave round trip, and it works on a
|
|
162
|
+
* deployment with no standing Sentinel, which is exactly when someone is setting one up. */
|
|
163
|
+
/** 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
|
|
164
|
+
* <tenant> is the name the gateway knows this tenant key by (asked once, `whoami`) and <req> the exact JSON sent. */
|
|
165
|
+
async _signed(body) {
|
|
166
|
+
if (!this._signedTenant) { const v = await this.verifyTenantKey(); if (!v.ok) throw adminError('tenant_key_rejected', 'witbitz: could not sign — ' + v.reason); this._signedTenant = v.tenant }
|
|
167
|
+
const req = JSON.stringify(body.sentinel), ts = String(Date.now())
|
|
168
|
+
const nonce = b64u(globalThis.crypto.getRandomValues(new Uint8Array(16)))
|
|
169
|
+
const h = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(req)))
|
|
170
|
+
const msg = `witbitz-tenant-op v1\n${this._signedTenant}\n${ts}\n${nonce}\n${Array.from(h, (b) => b.toString(16).padStart(2, '0')).join('')}`
|
|
171
|
+
const key = await globalThis.crypto.subtle.importKey('jwk', { kty: 'OKP', crv: 'Ed25519', d: this._signingKey.d, x: this._signingKey.x }, { name: 'Ed25519' }, false, ['sign'])
|
|
172
|
+
const sig = new Uint8Array(await globalThis.crypto.subtle.sign({ name: 'Ed25519' }, key, new TextEncoder().encode(msg)))
|
|
173
|
+
return { ...body, sentinel: JSON.parse(req), tsig: { ts, nonce, sig: b64u(sig), req } }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** A new tenant signing key: `{ privateKey }` (a JWK — keep it on your server, as you keep the tenant key) and `{ publicKey }`
|
|
177
|
+
* (raw Ed25519, base64url — what `admin.signing.register()` files). */
|
|
178
|
+
static async generateSigningKey() {
|
|
179
|
+
const k = await globalThis.crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])
|
|
180
|
+
const jwk = await globalThis.crypto.subtle.exportKey('jwk', k.privateKey)
|
|
181
|
+
return { privateKey: { kty: 'OKP', crv: 'Ed25519', d: jwk.d, x: jwk.x }, publicKey: jwk.x }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async verifyTenantKey() {
|
|
185
|
+
// ★ Two different things, and only one of them is an answer. NO KEY CONFIGURED is a programming error — the caller
|
|
186
|
+
// forgot `new Witbitz({ tenantKey })` — so building the poster stays OUTSIDE the catch and still throws. A key the
|
|
187
|
+
// gateway REFUSES is exactly the question this method exists to ask, so that one comes back as a plain no.
|
|
188
|
+
const post = this._tenantPost()
|
|
189
|
+
let r
|
|
190
|
+
try { r = await post({ op: 'sentinel', sentinel: { mode: 'whoami' } }) }
|
|
191
|
+
catch (e) { return { ok: false, reason: String((e && e.message) || e), code: (e && e.code) || '' } }
|
|
192
|
+
if (r && r.ok && r.tenant) return { ok: true, tenant: String(r.tenant) }
|
|
193
|
+
const reason = (r && (r.reason || r.message || r.error)) || 'no answer'
|
|
194
|
+
return { ok: false, reason: String(reason) }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
redacted(WitbitzAdmin.prototype, (a) => ({ tenant: a._tenant || null, tenantKey: a._tenantKey ? REDACTED : null, ...(a._signingKey ? { signingKey: REDACTED } : {}) }))
|
|
200
|
+
|
|
201
|
+
const b64u = (u8) => btoa(String.fromCharCode(...u8)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
202
|
+
|
|
203
|
+
/** `admin.signing` — your tenant's signing key (docs/standing-sentinel.md § Step 1e). The FIRST key is registered on your tenant
|
|
204
|
+
* key alone; once one is registered, every request of this tenant must be signed by it, and a new key is registered only by a
|
|
205
|
+
* request signed with the current one (so a stolen tenant key alone can neither act nor swap the signing key). */
|
|
206
|
+
class TenantSigning {
|
|
207
|
+
constructor(admin) { this._a = admin; hide(this, ['_a']) }
|
|
208
|
+
/** Which signing key the Sentinel holds for this tenant: `{ registered, key }`. Watch it — removing the record from the store is
|
|
209
|
+
* the one change someone with access to the Sentinel's storage could make (it cannot be forged, only deleted). */
|
|
210
|
+
async status() {
|
|
211
|
+
const r = await this._a._tenantPost()({ op: 'sentinel', sentinel: { mode: 'tenantkeyget' } })
|
|
212
|
+
if (!r || r.error) throw adminError('refused', 'witbitz: the signing key could not be read' + (r && r.error ? ': ' + r.error : ''))
|
|
213
|
+
return { registered: !!r.key, key: r.key || null, origins: Array.isArray(r.origins) ? r.origins : null }
|
|
214
|
+
}
|
|
215
|
+
/** File your SIGNED list of origins with the Sentinel (default: the list you declared — origins.list()). Once filed, a page
|
|
216
|
+
* 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.
|
|
217
|
+
* Needs a registered signing key. Replaces the list held. */
|
|
218
|
+
async publishOrigins(origins) {
|
|
219
|
+
const list = Array.isArray(origins) ? origins.map(String) : await this._a.origins.list()
|
|
220
|
+
if (!this._a._signingKey) throw adminError('no_signing_key', 'witbitz: publishOrigins signs the list — new WitbitzAdmin({ …, signingKey })')
|
|
221
|
+
const r = await this._a._tenantPost()({ op: 'sentinel', sentinel: { mode: 'tenantorigins', origins: list } })
|
|
222
|
+
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 : ''))
|
|
223
|
+
return { ok: true, origins: r.origins || list }
|
|
224
|
+
}
|
|
225
|
+
/** File the public half of `publicKey` (default: this client's own signing key). Signed by this client's key when it has one. */
|
|
226
|
+
async register(publicKey) {
|
|
227
|
+
const key = String(publicKey || (this._a._signingKey && this._a._signingKey.x) || '')
|
|
228
|
+
if (!/^[A-Za-z0-9_-]{43}$/.test(key)) throw adminError('invalid_argument', 'witbitz: signing.register needs a raw Ed25519 public key (base64url) — or a client made with { signingKey }')
|
|
229
|
+
const r = await this._a._tenantPost()({ op: 'sentinel', sentinel: { mode: 'tenantkey', key } })
|
|
230
|
+
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 : ''))
|
|
231
|
+
return { ok: true, key }
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** `wb.providers` — a BUILDER's own OAuth apps (https://witbitz.chat/docs/connections.md). Their users consent to THEM, so this
|
|
236
|
+
* platform never requests a sensitive or restricted scope on anyone's behalf. **Server-side only**: it needs your
|
|
237
|
+
* tenant SECRET key, and a page that holds one has given it away. */
|
|
238
|
+
class Providers {
|
|
239
|
+
constructor (wb) { this._wb = wb }
|
|
240
|
+
/** Attach your OAuth app once. The client secret is sealed to the attested enclave and is gone from your process
|
|
241
|
+
* when this returns. `kind` is one the enclave knows ('google'); the consent URL and every host come from there,
|
|
242
|
+
* not from you, so no provider can point your users at an unmeasured screen. → { id, kind } */
|
|
243
|
+
async attach ({ kind = 'google', clientId, clientSecret, redirectUri, scopes, label, tenant } = {}) {
|
|
244
|
+
const wb = this._wb
|
|
245
|
+
const t = String(tenant || wb._tenant || '')
|
|
246
|
+
if (!t) throw adminError('invalid_argument', 'witbitz: which tenant? pass new WitbitzAdmin({ tenant, tenantKey }) — the key proves it, the id names it')
|
|
247
|
+
if (!clientId || !clientSecret) throw adminError('invalid_argument', 'witbitz: a provider needs your OAuth clientId and clientSecret')
|
|
248
|
+
if (!/^https:\/\//.test(String(redirectUri || ''))) throw adminError('invalid_argument', 'witbitz: redirectUri must be the https callback you registered with the provider')
|
|
249
|
+
if (!Array.isArray(scopes) || !scopes.length) throw adminError('invalid_argument', 'witbitz: name at least one scope your users will be asked for')
|
|
250
|
+
const post = wb._tenantPost()
|
|
251
|
+
const { nonce, key } = await attestStandingSentinel({ post, auth: {}, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
|
|
252
|
+
const id = 'prov_' + randomId(12)
|
|
253
|
+
const sealed = await sealToEnclave(key, nonce, { id, tenant: t, kind, clientId, clientSecret: String(clientSecret), redirectUri, scopes: scopes.map(String), label: String(label || '') })
|
|
254
|
+
const r = await post({ op: 'sentinel', sentinel: { mode: 'provgrant', sealed } })
|
|
255
|
+
if (!r || r.error || !r.ok) throw adminError((r && r.error) || 'refused', `witbitz: the provider was refused (${(r && (r.error || r.reason)) || 'no answer'})`)
|
|
256
|
+
return { id, kind, tenant: t }
|
|
257
|
+
}
|
|
258
|
+
/** A REGISTERED MCP CLIENT: for an MCP server whose sign-in does not let apps register themselves (GitHub, Asana, Box…),
|
|
259
|
+
* the OAuth app you registered with that sign-in's `issuer` (as its metadata names it, e.g. https://github.com/login/oauth),
|
|
260
|
+
* and the exact https callback addresses you registered (your page's `/mcp-callback`). Today only the Spaces app signs
|
|
261
|
+
* in to MCP servers, with the apps filed under its own tenant; one filed under yours is kept for when the SDK does
|
|
262
|
+
* (connections.md). The secret (if the issuer gave one) is sealed to the attested enclave. `scopes`: the scopes your app was
|
|
263
|
+
* approved for (a string or an array) — a sign-in with it asks for exactly those, not the server's whole list (Google's
|
|
264
|
+
* Calendar server lists twelve). → { id, kind: 'mcp' } */
|
|
265
|
+
async attachMcp ({ issuer, clientId, clientSecret = '', redirectUris, label, tenant, webhookSecret = '', scopes = '' } = {}) {
|
|
266
|
+
const wb = this._wb
|
|
267
|
+
const t = String(tenant || wb._tenant || '')
|
|
268
|
+
if (!t) throw adminError('invalid_argument', 'witbitz: which tenant? pass new WitbitzAdmin({ tenant, tenantKey }) — the key proves it, the id names it')
|
|
269
|
+
if (!/^https:\/\//.test(String(issuer || ''))) throw adminError('invalid_argument', 'witbitz: issuer must be the https sign-in issuer, like https://github.com/login/oauth')
|
|
270
|
+
if (!clientId) throw adminError('invalid_argument', 'witbitz: a registered MCP client needs the clientId the issuer gave you')
|
|
271
|
+
if (!Array.isArray(redirectUris) || !redirectUris.length || !redirectUris.every((u) => /^https:\/\//.test(String(u)))) throw adminError('invalid_argument', 'witbitz: redirectUris — the https callback addresses you registered with the issuer')
|
|
272
|
+
const scopeList = (Array.isArray(scopes) ? scopes.map(String) : String(scopes || '').split(/\s+/)).filter(Boolean)
|
|
273
|
+
if (scopeList.length > 30 || !scopeList.every((x) => /^[\x21\x23-\x5b\x5d-\x7e]{1,200}$/.test(x))) throw adminError('invalid_argument', 'witbitz: scopes — the scope names your app was approved for')
|
|
274
|
+
if (webhookSecret && String(webhookSecret).length < 8) throw adminError('invalid_argument', 'witbitz: webhookSecret — the secret the service signs its notices with (Zoom: the app\'s Secret Token)')
|
|
275
|
+
const post = wb._tenantPost()
|
|
276
|
+
const { nonce, key } = await attestStandingSentinel({ post, auth: {}, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
|
|
277
|
+
const id = 'prov_' + randomId(12)
|
|
278
|
+
// webhookSecret: the service's "the person removed your app" notices are checked with it, inside the Sentinel (sealed like the client secret)
|
|
279
|
+
const sealed = await sealToEnclave(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(' ') } : {}) })
|
|
280
|
+
const r = await post({ op: 'sentinel', sentinel: { mode: 'provgrant', sealed } })
|
|
281
|
+
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'})`)
|
|
282
|
+
return { id, kind: 'mcp', tenant: t }
|
|
283
|
+
}
|
|
284
|
+
/** Your tenant's providers — never a client secret. */
|
|
285
|
+
async list () {
|
|
286
|
+
const r = await this._wb._tenantPost()({ op: 'sentinel', sentinel: { mode: 'provlist' } })
|
|
287
|
+
if (!r || r.error) throw adminError((r && r.error) || 'refused', `witbitz: could not list providers (${(r && r.error) || 'no answer'})`)
|
|
288
|
+
return Array.isArray(r.providers) ? r.providers : []
|
|
289
|
+
}
|
|
290
|
+
/** Remove an OAuth app. Every connection your users made under it dies at once. → { revoked, connections } */
|
|
291
|
+
async revoke (id) {
|
|
292
|
+
const r = await this._wb._tenantPost()({ op: 'sentinel', sentinel: { mode: 'provrevoke', id: String(id || '') } })
|
|
293
|
+
if (!r || r.error) throw adminError((r && r.error) || 'refused', `witbitz: could not revoke (${(r && r.error) || 'no answer'})`)
|
|
294
|
+
return { revoked: Number(r.revoked) || 0, connections: Number(r.connections) || 0 }
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const randomId = (n) => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(n)))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
299
|
+
|
|
300
|
+
/** `wb.rooms` — what a tenant does to its rooms from its server. **Server-side only**: it needs your tenant key. */
|
|
301
|
+
class TenantRooms {
|
|
302
|
+
constructor (wb) { this._wb = wb }
|
|
303
|
+
/** Delete ONE room. Afterwards it answers 410 to everyone, at once, whichever retention you choose:
|
|
304
|
+
* retain: 'none' (default) every stored version of everything is deleted now — sealed messages, files, the
|
|
305
|
+
* confidential tier's copies. Irreversible.
|
|
306
|
+
* retain: 'backups' the current copies are deleted now; old versions expire within 35 days (recoverable only by
|
|
307
|
+
* Witbitz operators, by hand, until then).
|
|
308
|
+
* retain: 'grace' nothing is deleted yet; `rooms.restore(room)` undoes it for `graceDays` (1–90, default 30),
|
|
309
|
+
* then it is purged as `after` says ('none' default, or 'backups').
|
|
310
|
+
* Only for a room no one else uses — a shared room belongs to its other members too, and the server cannot tell
|
|
311
|
+
* (membership is sealed), so that is yours to decide.
|
|
312
|
+
* → none/backups: { deleted:true, room, retain, versions, bytes, turnWasRunning, backupsUntil? }
|
|
313
|
+
* → grace: { deleted:false, held:true, room, purgeAt, after }
|
|
314
|
+
* When `turnWasRunning`, a reply being written may land a moment later: call delete again after a few minutes.
|
|
315
|
+
* Throws if anything could not be removed (code 'partial') — never a half-done delete reported as done. */
|
|
316
|
+
async delete (room, { retain, graceDays, after } = {}) {
|
|
317
|
+
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-…"')
|
|
318
|
+
const body = { confirm: room, ...(retain ? { retain } : {}), ...(graceDays !== undefined ? { graceDays } : {}), ...(after ? { after } : {}) }
|
|
319
|
+
const r = await this._wb._tenantRest('DELETE', '/rooms/' + encodeURIComponent(room), body, { envelope: false })
|
|
320
|
+
if (r.held) return { deleted: false, held: true, room: r.room, purgeAt: Number(r.purgeAt) || 0, after: r.after || 'none' }
|
|
321
|
+
if (!r.deleted) { const e = new Error(`witbitz: room ${room} was only partly deleted — call delete again`); e.code = 'partial'; e.result = r; throw e }
|
|
322
|
+
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) } : {}) }
|
|
323
|
+
}
|
|
324
|
+
/** Your rooms, a page at a time: `{ rooms: [{ room, createdAt, lastUsedAt, kind, split, gated, held }], next }`.
|
|
325
|
+
* `createdAt` / `lastUsedAt` are ISO times or null (`lastUsedAt` is when a member last opened, wrote or prompted in it;
|
|
326
|
+
* recorded since 2026-10-07). `held` is `{ purgeAt }` for a room pending deletion. Pass `next` back as `cursor`. */
|
|
327
|
+
async list ({ cursor, limit } = {}) {
|
|
328
|
+
const q = new URLSearchParams({ list: '1', ...(cursor ? { cursor } : {}), ...(limit ? { limit: String(limit) } : {}) })
|
|
329
|
+
const r = await this._wb._tenantRest('GET', '?' + q.toString(), null, { envelope: false, root: '/tenant/rooms' })
|
|
330
|
+
return { rooms: Array.isArray(r.rooms) ? r.rooms : [], next: r.next || null }
|
|
331
|
+
}
|
|
332
|
+
/** THE IDLE RULE: rooms no member used for `days` (30–3650) are held for 30 days — gone at once, restorable with
|
|
333
|
+
* `rooms.restore(room)` — then deleted, by a daily run. `null` turns it off. A room with no recorded use counts from
|
|
334
|
+
* 2026-10-07. At most 100 of your rooms are held per day. → { idleRoomDays } */
|
|
335
|
+
async idleDeletion (days) {
|
|
336
|
+
if (days !== null && !(Number.isInteger(days) && days >= 30 && days <= 3650)) throw adminError('invalid_argument', 'witbitz: rooms.idleDeletion(days) — a whole number of days from 30 to 3650, or null to turn it off')
|
|
337
|
+
const d = await this._wb._tenantRest('PUT', '/webhooks', { idleRoomDays: days })
|
|
338
|
+
return { idleRoomDays: d && d.tenant ? d.tenant.idle_room_days ?? null : days }
|
|
339
|
+
}
|
|
340
|
+
/** Undo a `retain: 'grace'` delete before its window ends. → { restored:true, room }. A room deleted with 'none' or
|
|
341
|
+
* 'backups', or whose window has ended, cannot come back (code 'purged' / 'grace_ended'). */
|
|
342
|
+
async restore (room) {
|
|
343
|
+
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-…"')
|
|
344
|
+
const r = await this._wb._tenantRest('POST', '/rooms/' + encodeURIComponent(room) + '/restore', {}, { envelope: false })
|
|
345
|
+
return { restored: !!r.restored, room: r.room }
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const USER_ID = /^u_[a-z0-9]{24}$/
|
|
350
|
+
const userIdOf = (id, what) => { if (typeof id !== 'string' || !USER_ID.test(id)) throw adminError('invalid_argument', `witbitz: ${what} takes a user id, e.g. "u_…" (from users.create)`); return id }
|
|
351
|
+
|
|
352
|
+
/** `wb.users` — PER-USER BILLING (https://witbitz.chat/docs/sdk-builder.md#user-billing). Each user you create gets its OWN provider key with a
|
|
353
|
+
* strict monthly cap, so what a user costs is what the provider reports for that key. Your server mints a short-lived
|
|
354
|
+
* token for the signed-in user and hands it to their page (`wb.useUserToken`). **Server-side only**: needs your tenant key. */
|
|
355
|
+
/** `admin.keys` — mint, list and revoke your tenant API keys (with your SECRET key; no other key can). A RESTRICTED key
|
|
356
|
+
* (wrk_) carries only the capabilities you choose, an optional expiry and an optional ceiling on the customer caps it may
|
|
357
|
+
* set — give your account server `customers:write` + `customers:tokens` instead of the key that can delete everything.
|
|
358
|
+
* Capabilities: customers:read · customers:write · customers:tokens · customers:erase · rooms:read · rooms:write ·
|
|
359
|
+
* rooms:delete · settings:read · settings:write · origins:write · integrations:write · billing:read · wallets:grant ·
|
|
360
|
+
* apps:release (the builder release API's release routes).
|
|
361
|
+
* Never grantable: managing keys, deleting the tenant, deleting every room. */
|
|
362
|
+
class TenantKeys {
|
|
363
|
+
constructor (wb) { this._wb = wb }
|
|
364
|
+
/** → [{ keyId, type, label, createdAt, revoked, display, scopes?, expiresAt?, maxCustomerCapUsd? }] — never a key */
|
|
365
|
+
async list () { return await this._wb._tenantRest('GET', '/keys') }
|
|
366
|
+
/** → { key, keyId, type, scopes?, maxCustomerCapUsd?, expiresAt? } — `key` is shown ONCE: store it now.
|
|
367
|
+
* @param {object} opts { type: 'restricted' | 'secret' | 'publishable', label?, scopes?, expiresAt?, maxCustomerCapUsd? } */
|
|
368
|
+
async create ({ type = 'restricted', label, scopes, expiresAt, maxCustomerCapUsd } = {}) {
|
|
369
|
+
const d = await this._wb._tenantRest('POST', '/keys', { type, ...(label ? { label } : {}), ...(scopes ? { scopes } : {}), ...(expiresAt != null ? { expiresAt } : {}), ...(maxCustomerCapUsd != null ? { maxCustomerCapUsd } : {}) })
|
|
370
|
+
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 } : {}) }
|
|
371
|
+
}
|
|
372
|
+
/** Revoke a key — refused from then on. → { revoked: true, keyId } */
|
|
373
|
+
async revoke (keyId) {
|
|
374
|
+
if (!/^k_[0-9A-Za-z]{1,40}$/.test(String(keyId || ''))) throw adminError('invalid_argument', 'witbitz: keys.revoke(keyId) — the keyId from keys.list()')
|
|
375
|
+
await this._wb._tenantRest('DELETE', '/keys/' + encodeURIComponent(keyId), null, { envelope: false, text: true })
|
|
376
|
+
return { revoked: true, keyId }
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
class TenantCustomers {
|
|
381
|
+
constructor (wb) { this._wb = wb }
|
|
382
|
+
/** `userRef` — YOUR label for the user (1–120 chars; shown to you in billing, never to the provider). `capMonthlyUsd`
|
|
383
|
+
* — a hard monthly stop (default 25). → { userId, userRef, capMonthlyUsd, createdAt, revoked } */
|
|
384
|
+
async create ({ userRef, capMonthlyUsd } = {}) {
|
|
385
|
+
const d = await this._wb._tenantRest('POST', '/users', { userRef, ...(capMonthlyUsd !== undefined ? { capMonthlyUsd } : {}) })
|
|
386
|
+
return d.user
|
|
387
|
+
}
|
|
388
|
+
/** Every user you created, oldest first — nothing secret. */
|
|
389
|
+
async list () { return await this._wb._tenantRest('GET', '/users') }
|
|
390
|
+
/** Change a user's monthly cap — a plan upgrade or a cancellation. The provider's limit moves first; the user, their key
|
|
391
|
+
* and their history stay the same. A revoked user cannot be changed. → the user, as `create` returns it. */
|
|
392
|
+
async update (userId, { capMonthlyUsd } = {}) {
|
|
393
|
+
const d = await this._wb._tenantRest('PATCH', '/users/' + userIdOf(userId, 'users.update'), { capMonthlyUsd })
|
|
394
|
+
return d.user
|
|
395
|
+
}
|
|
396
|
+
/** Revoke: the user's provider key is deleted and their tokens stop working. Spend up to now is still billed. */
|
|
397
|
+
async revoke (userId) { await this._wb._tenantRest('DELETE', '/users/' + userIdOf(userId, 'users.revoke'), null, { envelope: false, text: true }); return { revoked: true, userId } }
|
|
398
|
+
/** 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
|
|
399
|
+
* deleted — every message, file and stored version. Shared Spaces stay (what they wrote is part of the others'
|
|
400
|
+
* conversation); Spaces they only joined are not theirs to delete. Works from the list the person's own devices filed,
|
|
401
|
+
* sealed, with Witbitz's attested enclave for your app; you never see it. Run it again after a partial result
|
|
402
|
+
* (`failed` > 0 or `incomplete`) — nothing is lost. Pair it with `revoke(userId)` for their billing.
|
|
403
|
+
* → { filed, rooms, deleted, shared, notTheirs, failed, cleared } */
|
|
404
|
+
async erase ({ email } = {}) {
|
|
405
|
+
if (typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) throw adminError('invalid_argument', 'witbitz: users.erase takes { email } — the address the person signed in to your app with')
|
|
406
|
+
const r = await this._wb._tenantPost()({ op: 'sentinel', sentinel: { mode: 'eraseuser', email: email.trim() } })
|
|
407
|
+
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'})`)
|
|
408
|
+
return r
|
|
409
|
+
}
|
|
410
|
+
/** A token for this user's page, valid `ttlSec` (60–3600, default 900). → { token, expiresAt } (unix seconds).
|
|
411
|
+
* Mint it when the user signs in and again before `expiresAt`; never store it server-side longer than that. */
|
|
412
|
+
async token (userId, { ttlSec } = {}) { return await this._wb._tenantRest('POST', '/users/' + userIdOf(userId, 'users.token') + '/token', ttlSec !== undefined ? { ttlSec } : {}) }
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** `wb.billing` — what you are billed, in the provider's numbers: this month (your key live + your users' keys through
|
|
416
|
+
* yesterday), would-have-cost (markup), charged (discount), storage, by day, and per user. The same data as the tenant
|
|
417
|
+
* portal. **Server-side only**: needs your tenant key. */
|
|
418
|
+
class TenantBilling {
|
|
419
|
+
constructor (wb) { this._wb = wb }
|
|
420
|
+
/** → { tenant, rate, month, storage, days, users, userDays, at } — amounts in microdollars (1e-6 USD). */
|
|
421
|
+
async get () { return await this._wb._tenantRest('GET', '', null, { root: '/billing', envelope: false }) }
|
|
422
|
+
/** REQUIRE A USER TOKEN on every op that spends (a turn, a title, an approval, an import) in your rooms. With it on, such
|
|
423
|
+
* an op that arrives WITHOUT a user token is refused (`user_token_required`) instead of billed to you — so your
|
|
424
|
+
* per-user caps cannot be bypassed by a page that simply sends none. Reads never need one. Takes effect within about a
|
|
425
|
+
* minute. → { requireUserToken } as stored. */
|
|
426
|
+
async requireUserToken (on = true) {
|
|
427
|
+
if (typeof on !== 'boolean') throw adminError('invalid_argument', 'witbitz: billing.requireUserToken takes true or false')
|
|
428
|
+
const d = await this._wb._tenantRest('PUT', '/webhooks', { requireUserToken: on })
|
|
429
|
+
return { requireUserToken: !!(d && d.tenant && d.tenant.require_user_token) }
|
|
430
|
+
}
|
|
431
|
+
/** LIMIT VISITORS (docs/visitor-limits.md): how many questions a day (UTC) people who are NOT signed in — no user token —
|
|
432
|
+
* may ask in your rooms: at most `perNetwork` from one network, at most `total` from all of them. Over either, the
|
|
433
|
+
* question is refused before anything is spent (`429 visitor_limit`, with `scope` and a sentence to show). `null` turns
|
|
434
|
+
* it off (every question bills to you, as without it). A question with a user token is its user's, under their own cap.
|
|
435
|
+
* Takes effect within about a minute. → { visitorLimit } as stored. */
|
|
436
|
+
async visitorLimit (limit) {
|
|
437
|
+
const ok = limit === null || (limit && typeof limit === 'object' && !Array.isArray(limit) && Object.keys(limit).every((k) => k === 'perNetwork' || k === 'total') &&
|
|
438
|
+
Number.isInteger(limit.perNetwork) && Number.isInteger(limit.total) && limit.perNetwork >= 1 && limit.perNetwork <= limit.total && limit.total <= 10_000_000)
|
|
439
|
+
if (!ok) throw adminError('invalid_argument', 'witbitz: billing.visitorLimit takes { perNetwork, total } — whole numbers of questions a day, 1 ≤ perNetwork ≤ total ≤ 10000000 — or null to turn it off')
|
|
440
|
+
const d = await this._wb._tenantRest('PUT', '/webhooks', { visitorLimit: limit === null ? null : { perNetwork: limit.perNetwork, total: limit.total } })
|
|
441
|
+
const vl = d && d.tenant ? d.tenant.visitor_limit : null
|
|
442
|
+
return { visitorLimit: vl && typeof vl === 'object' ? { perNetwork: vl.perNetwork, total: vl.total } : null }
|
|
443
|
+
}
|
|
444
|
+
/** The same as CSV text: one line per day, or with `{ byUser: true }` one line per user per day. */
|
|
445
|
+
async csv ({ byUser = false } = {}) { return await this._wb._tenantRest('GET', '?format=csv' + (byUser ? '&by=user' : ''), null, { root: '/billing', text: true }) }
|
|
446
|
+
/** YOUR PREPAID BALANCE (docs/tenant-prepaid.md), or null when your app is not on prepaid billing.
|
|
447
|
+
* → { balanceMicros, paused: null | 'out_of_credit', lowWarned, earlyAccess, canBuy, packs: [{ pack, dollars, credit }], history: [{ at, kind, micros, orderId? }] }
|
|
448
|
+
* (`canBuy`: buying credit is open to your app now — while it is in testing, only to the apps in the test).
|
|
449
|
+
* While `paused`, every op that spends in your rooms is refused (`402 tenant_out_of_credit`) until you add credit. */
|
|
450
|
+
async balance () { const v = await this.get(); return (v && v.prepaid) || null }
|
|
451
|
+
/** ADD CREDIT: a payment page for one pack — 'pack25' | 'pack100' | 'pack500' — bound to your app. Open its `url` in a browser
|
|
452
|
+
* (Lemon Squeezy takes the payment and the tax); the credit lands within a minute of paying, and lifts a pause at once.
|
|
453
|
+
* `redirectUrl` (https): where the payer returns. Needs your SECRET key. → { url, pack, dollars, testMode }
|
|
454
|
+
* Refused with `payments_not_open` (buying is not open yet), `not_prepaid` (your app is not on prepaid billing), `not_a_tester`
|
|
455
|
+
* (buying is in testing, not open to your app), `checkout_unavailable` (the payment page could not be made — try again). */
|
|
456
|
+
async topUp (pack, { redirectUrl } = {}) {
|
|
457
|
+
if (!['pack25', 'pack100', 'pack500'].includes(pack)) throw adminError('invalid_argument', "witbitz: billing.topUp takes 'pack25', 'pack100' or 'pack500'")
|
|
458
|
+
if (redirectUrl != null && !/^https:\/\/\S{1,300}$/.test(String(redirectUrl))) throw adminError('invalid_argument', 'witbitz: billing.topUp redirectUrl must be an https address')
|
|
459
|
+
return await this._wb._tenantRest('POST', '/billing/checkout', { pack, ...(redirectUrl ? { redirectUrl } : {}) })
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** `admin.app` — YOUR APP'S NAME, as your users see it: a sign-in code mailed from one of your declared AND PROVEN origins comes
|
|
464
|
+
* from "<name> via Witbitz" with the subject "Your <name> code". 1–40 characters (letters, digits, spaces and
|
|
465
|
+
* . & ' + -), never "Witbitz". A rename reaches the mail within about 15 minutes. **Server-side only.** */
|
|
466
|
+
class TenantApp {
|
|
467
|
+
constructor (wb) { this._wb = wb }
|
|
468
|
+
/** → { name } as stored. Refused with the reason when the name breaks the rule. */
|
|
469
|
+
async rename (name) {
|
|
470
|
+
if (typeof name !== 'string' || !name.trim()) throw adminError('invalid_argument', "witbitz: app.rename takes your app's name, e.g. 'Keepwarden'")
|
|
471
|
+
const d = await this._wb._tenantRest('PUT', '/webhooks', { name })
|
|
472
|
+
return { name: (d && d.tenant && d.tenant.name) || '' }
|
|
473
|
+
}
|
|
474
|
+
/** The name your app is registered with now. */
|
|
475
|
+
async name () {
|
|
476
|
+
const d = await this._wb._tenantRest('GET', '')
|
|
477
|
+
return (d && typeof d.name === 'string') ? d.name : ''
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** `wb.origins` — the PAGE origins that act for this tenant: a room created from one of them belongs to the tenant, and
|
|
482
|
+
* the tenant's rooms may be read and embedded from them. Compared by exact string against the browser's Origin header,
|
|
483
|
+
* so the server stores the exact form ("https://host" or "https://host:port") and refuses anything else by name.
|
|
484
|
+
* Takes effect within about a minute. **Server-side only**: it needs your tenant key. */
|
|
485
|
+
class TenantOrigins {
|
|
486
|
+
constructor (wb) { this._wb = wb }
|
|
487
|
+
/** Declare the whole list. Declaring REPLACES what you had — keep the origins you still use.
|
|
488
|
+
* → { origins, unproven } — origins as stored (lower-cased, trailing slash removed, de-duplicated); unproven = the ones
|
|
489
|
+
* whose host does not yet say it is yours, each with how to prove it ({ origin, how }). An unproven origin works; only
|
|
490
|
+
* a proven one puts your app's name in a sign-in mail. Declare again once the file or record is in place. */
|
|
491
|
+
async declare (origins) {
|
|
492
|
+
if (!Array.isArray(origins)) throw adminError('invalid_argument', 'witbitz: origins.declare takes an array, e.g. ["https://app.example.com"]')
|
|
493
|
+
const d = await this._wb._tenantRest('PUT', '/webhooks', { origins: origins.map(String) })
|
|
494
|
+
const out = { origins: Array.isArray(d.tenant && d.tenant.origins) ? d.tenant.origins : [], unproven: Array.isArray(d.origins_unproven) ? d.origins_unproven : [] }
|
|
495
|
+
// With a signing key, the Sentinel gets the same list SIGNED (signing.publishOrigins): from then on only these pages may
|
|
496
|
+
// name your tenant there — connect through your OAuth apps, file a user's erase list for you.
|
|
497
|
+
if (this._wb._signingKey) out.signed = (await this._wb.signing.publishOrigins(out.origins)).origins
|
|
498
|
+
return out
|
|
499
|
+
}
|
|
500
|
+
/** The origins this tenant declares now. */
|
|
501
|
+
async list () {
|
|
502
|
+
const d = await this._wb._tenantRest('GET', '')
|
|
503
|
+
return Array.isArray(d.origins) ? d.origins : []
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** `wb.hosts` — the hosts THIS tenant's users may attach a key for (https://witbitz.chat/docs/connections.md). A host nobody vouches
|
|
508
|
+
* for is refused when a member attaches it, not an hour later on the first call, and the enclave's firewall opens a
|
|
509
|
+
* host only while a live connection under this tenant needs it. **Server-side only**: it needs your tenant key. */
|
|
510
|
+
class DeclaredHosts {
|
|
511
|
+
constructor (wb) { this._wb = wb }
|
|
512
|
+
/** Declare the whole list. Declaring REPLACES what you had, so removing a host is declaring without it.
|
|
513
|
+
* → { hosts } as the enclave normalised them (lower-cased, scheme and path stripped, de-duplicated). */
|
|
514
|
+
async declare (hosts) {
|
|
515
|
+
if (!Array.isArray(hosts)) throw adminError('invalid_argument', 'witbitz: declare takes an array of bare domains, e.g. ["api.todoist.com"]')
|
|
516
|
+
const r = await this._wb._tenantPost()({ op: 'sentinel', sentinel: { mode: 'hostdeclare', hosts: hosts.map(String) } })
|
|
517
|
+
if (!r || r.error || !r.ok) throw adminError((r && r.error) || 'refused', `witbitz: the hosts were refused (${(r && (r.error || r.reason)) || 'no answer'})`)
|
|
518
|
+
return { hosts: Array.isArray(r.hosts) ? r.hosts : [] }
|
|
519
|
+
}
|
|
520
|
+
/** What this tenant currently vouches for. */
|
|
521
|
+
async list () {
|
|
522
|
+
const r = await this._wb._tenantPost()({ op: 'sentinel', sentinel: { mode: 'hostlist' } })
|
|
523
|
+
if (!r || r.error) throw adminError((r && r.error) || 'refused', `witbitz: could not list hosts (${(r && r.error) || 'no answer'})`)
|
|
524
|
+
return Array.isArray(r.hosts) ? r.hosts : []
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** Back-compat for the page client: `wb.users` keeps its old class name in stack traces. */
|
|
529
|
+
export { TenantCustomers as TenantUsers }
|