@witnium/witniumchain 0.0.0-stage → 0.25.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/dist/index.mjs ADDED
@@ -0,0 +1,2058 @@
1
+ // src/errors.ts
2
+ var WitniumchainApiError = class extends Error {
3
+ status;
4
+ errorLabel;
5
+ body;
6
+ constructor(args) {
7
+ super(args.message);
8
+ this.name = "WitniumchainApiError";
9
+ this.status = args.status;
10
+ this.errorLabel = args.errorLabel;
11
+ this.body = args.body ?? null;
12
+ }
13
+ };
14
+
15
+ // src/pkce.ts
16
+ var STORAGE_PREFIX = "witniumchain.pkce.";
17
+ function defaultVerifierStorage() {
18
+ const storage = globalThis.sessionStorage;
19
+ if (!storage) {
20
+ throw new Error(
21
+ "WitniumchainClient: defaultVerifierStorage requires globalThis.sessionStorage. In a non-browser context, pass `verifierStorage` to the OAuth helpers."
22
+ );
23
+ }
24
+ return {
25
+ set(stateKey, verifier) {
26
+ storage.setItem(STORAGE_PREFIX + stateKey, verifier);
27
+ },
28
+ get(stateKey) {
29
+ return storage.getItem(STORAGE_PREFIX + stateKey);
30
+ },
31
+ remove(stateKey) {
32
+ storage.removeItem(STORAGE_PREFIX + stateKey);
33
+ }
34
+ };
35
+ }
36
+ function generateCodeVerifier() {
37
+ const bytes = new Uint8Array(64);
38
+ cryptoRef().getRandomValues(bytes);
39
+ return base64UrlEncode(bytes);
40
+ }
41
+ async function deriveCodeChallenge(verifier) {
42
+ const data = new TextEncoder().encode(verifier);
43
+ const digest = await cryptoRef().subtle.digest("SHA-256", data);
44
+ return base64UrlEncode(new Uint8Array(digest));
45
+ }
46
+ function generateState() {
47
+ const bytes = new Uint8Array(32);
48
+ cryptoRef().getRandomValues(bytes);
49
+ return base64UrlEncode(bytes);
50
+ }
51
+ function base64UrlEncode(bytes) {
52
+ let binary = "";
53
+ for (const b of bytes) binary += String.fromCharCode(b);
54
+ const b64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64");
55
+ return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
56
+ }
57
+ function cryptoRef() {
58
+ const c = globalThis.crypto;
59
+ if (!c || !c.subtle || !c.getRandomValues) {
60
+ throw new Error(
61
+ "WitniumchainClient: globalThis.crypto with subtle + getRandomValues is required for PKCE. Modern browsers and Node 18+ provide this natively."
62
+ );
63
+ }
64
+ return c;
65
+ }
66
+
67
+ // src/client.ts
68
+ var WitniumchainClient = class {
69
+ baseUrl;
70
+ chainBaseUrl;
71
+ cfg;
72
+ timeout;
73
+ fetchImpl;
74
+ // Mutable OAuth state. Constructor seeds these from the config; the OAuth
75
+ // flow helpers (begin/complete/refresh/signOut) read and rewrite them as
76
+ // the user authenticates and tokens rotate. `applyAuth` reads `accessToken`
77
+ // off this field — never directly off `cfg` — so a token rotated mid-flight
78
+ // (during a 401-retry refresh) is picked up by the very next call.
79
+ accessToken;
80
+ // Browser SPAs in production receive the refresh token as an HttpOnly cookie
81
+ // (see src/oauth/refresh-cookie.ts on the server), so this field stays
82
+ // `undefined` and the cookie rides via `credentials: 'include'` on every
83
+ // /token call. Non-browser callers (Node SSR, native apps without a cookie
84
+ // jar) get the refresh token in the response body and the SDK stashes it
85
+ // here as a fallback. Either path drives `refreshAccessToken` identically.
86
+ refreshToken;
87
+ // Sentinel: the most recent token response set an HttpOnly refresh cookie.
88
+ // The SDK can't directly observe an HttpOnly cookie, but the response body
89
+ // tells us indirectly — server strips `refresh_token` when it sets the
90
+ // cookie, so an absent body field on a successful /token response means
91
+ // the cookie path is in use. Used to gate the 401-retry: with a cookie,
92
+ // refresh might work even when the in-memory refresh token is undefined.
93
+ hasRefreshCookie = false;
94
+ oauthClientId;
95
+ verifierStorage;
96
+ // Cache of the parsed OIDC discovery document keyed by issuer URL. Saves a
97
+ // round trip on every OAuth call after the first. oidc-provider's discovery
98
+ // doc is static for the life of an issuer; cache is per-client-instance, so
99
+ // it dies with the SDK consumer's lifecycle.
100
+ discoveryCache;
101
+ // Single-flight gate for refresh. When a 401 fans out to N concurrent retries
102
+ // (or the consumer calls refreshAccessToken directly while another refresh
103
+ // is mid-flight), all callers await the same in-flight promise — refresh
104
+ // tokens rotate on use (D10), so a second concurrent refresh would race the
105
+ // first and one of them would 401.
106
+ refreshInFlight;
107
+ // True when the current `accessToken` was minted by the session→token
108
+ // exchange (`exchangeSessionForToken`) rather than the OAuth code/refresh
109
+ // flow. Drives the 401-retry: a session-exchanged token has no refresh
110
+ // credential, so on expiry the SDK re-mints from the cookie instead of
111
+ // refreshing. Reset to false whenever an OAuth /token response lands.
112
+ accessTokenFromSession = false;
113
+ // Single-flight gate for the session→token exchange. A cookie-only client's
114
+ // first BearerJWT call (and any concurrent fan-out) awaits one in-flight
115
+ // mint rather than minting N tokens.
116
+ sessionExchangeInFlight;
117
+ // Bumped whenever the cached credentials stop being valid (sign-out, the
118
+ // TOTP-confirm epoch bump). A mint or refresh that started under an older
119
+ // generation must not store its result: it could be a previous user's
120
+ // token, or one the server has already ended.
121
+ credentialGeneration = 0;
122
+ /** Subscriptions / billing helpers. See {@link Subscriptions}. */
123
+ subscriptions;
124
+ /** Delegated-key namespace including the one-call {@link DelegatedKeys.provision} flow. */
125
+ delegatedKeys;
126
+ /** Owner signing-key management (list / add / revoke). */
127
+ keys;
128
+ /** OAuth session management. Accessed as `client.oauth.sessions.*`. */
129
+ oauth;
130
+ /** Setting up a sign-in method after a signup link or recovery (`wac_enroll`). `client.enrollment.*`. */
131
+ enrollment;
132
+ /** Account recovery (`wac_recovery`). `client.recovery.*`. */
133
+ recovery;
134
+ /** The signed-in user's sign-in methods, behind step-up. `client.security.*`. */
135
+ security;
136
+ /** Session-cookie team management (org-admin only). `client.orgUsers.*`. */
137
+ orgUsers;
138
+ /** The home org's API keys (session; org admins create and revoke). `client.apiKeys.*`. */
139
+ apiKeys;
140
+ /** The signed-in member's dashboard signing key on a managed contract. `client.dashboardKey.*`. */
141
+ dashboardKey;
142
+ /** The home org's managed contract: pause, resume, activity. `client.orgContract.*`. */
143
+ orgContract;
144
+ keyRequests;
145
+ constructor(config) {
146
+ if (!config.baseUrl) {
147
+ throw new Error("WitniumchainClient: baseUrl is required");
148
+ }
149
+ this.cfg = config;
150
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
151
+ this.chainBaseUrl = config.chainBaseUrl?.replace(/\/$/, "");
152
+ this.timeout = config.timeout ?? 3e4;
153
+ const resolvedFetch = config.fetch ?? (globalThis.fetch ? globalThis.fetch.bind(globalThis) : void 0);
154
+ if (!resolvedFetch) {
155
+ throw new Error(
156
+ "WitniumchainClient: no fetch implementation available. Pass `config.fetch`."
157
+ );
158
+ }
159
+ this.fetchImpl = resolvedFetch;
160
+ this.accessToken = config.accessToken;
161
+ this.oauthClientId = config.oauthClientId;
162
+ this.verifierStorage = config.verifierStorage;
163
+ this.subscriptions = new Subscriptions(this);
164
+ this.delegatedKeys = new DelegatedKeys(this);
165
+ this.keys = new SigningKeys(this);
166
+ this.oauth = new OauthNamespace(this);
167
+ this.enrollment = new Enrollment(this);
168
+ this.recovery = new Recovery(this);
169
+ this.security = new AccountSecurity(this);
170
+ this.orgUsers = new OrgMembers(this);
171
+ this.apiKeys = new OrgApiKeys(this);
172
+ this.dashboardKey = new DashboardKey(this);
173
+ this.orgContract = new OrgContract(this);
174
+ this.keyRequests = new SigningKeyRequests(this);
175
+ }
176
+ /**
177
+ * Convenience alias for {@link getAccount} — returns the authenticated
178
+ * user's profile, the org they belong to, and their signing keys.
179
+ */
180
+ me() {
181
+ return this.getAccount();
182
+ }
183
+ // ────────────────────────────────────────────────────────────────────────
184
+ // Auth (/v1/auth/*)
185
+ // ────────────────────────────────────────────────────────────────────────
186
+ signup(body) {
187
+ return this.req("POST", "/v1/auth/signup", { auth: "Public", body });
188
+ }
189
+ /**
190
+ * Self-serve org creation (Phase RBAC Thread D). One public call that
191
+ * creates the admin user, the org, the org-admin membership, and deploys
192
+ * the contract with the caller's client-generated `ownerPublicKey` +
193
+ * `initialSigningPublicKey`. Witnium never sees the private bytes.
194
+ *
195
+ * Returns `{ orgId, userId, contractAddress, contractVersion }`. The
196
+ * email-verify link is mailed to `adminEmail` and never returned, so there
197
+ * is nothing to render. If the mail cannot be sent, nothing is created and
198
+ * the call fails with a 502; retry it.
199
+ */
200
+ createOrg(body) {
201
+ return this.req("POST", "/v1/orgs", { auth: "Public", body });
202
+ }
203
+ // ── Team management (session-cookie; org-admin only) ──────────────────────
204
+ // Backing methods for the `orgUsers` namespace. All resolve the caller's
205
+ // org + org-admin role server-side from the session — no orgId in the path.
206
+ getDashboardKey() {
207
+ return this.req("GET", "/v1/account/dashboard-key", { auth: "SessionCookie" });
208
+ }
209
+ ensureDashboardKey() {
210
+ return this.req("POST", "/v1/account/dashboard-key", { auth: "SessionCookie" });
211
+ }
212
+ /** Revoke your own added dashboard key on chain; 409 for the organization's base key. */
213
+ revokeDashboardKey() {
214
+ return this.req("DELETE", "/v1/account/dashboard-key", { auth: "SessionCookie", expectNoContent: true });
215
+ }
216
+ pauseOrgContract() {
217
+ return this.req("POST", "/v1/orgs/me/contract/pause", { auth: "SessionCookie" });
218
+ }
219
+ /**
220
+ * Add a key you hold to the org's managed contract (plan §17.7): org
221
+ * admins, after a step-up. Witnium signs the add; the key counts once
222
+ * the returned op confirms.
223
+ */
224
+ addOrgContractKey(body) {
225
+ return this.req("POST", "/v1/orgs/me/contract/keys", { auth: "SessionCookie", body });
226
+ }
227
+ /** Revoke a key added with {@link addOrgContractKey} (org admins). */
228
+ removeOrgContractKey(publicKey) {
229
+ return this.req("DELETE", `/v1/orgs/me/contract/keys/${encodeURIComponent(publicKey)}`, { auth: "SessionCookie" });
230
+ }
231
+ /** Needs a step-up within 5 minutes (`client.security.stepUp`). */
232
+ resumeOrgContract() {
233
+ return this.req("POST", "/v1/orgs/me/contract/resume", { auth: "SessionCookie" });
234
+ }
235
+ getContractActivity(limit) {
236
+ return this.req("GET", "/v1/orgs/me/owner-operations", { auth: "SessionCookie", query: { limit } });
237
+ }
238
+ /** Create an API key (org admin, after a step-up). The secret is in this response only. */
239
+ createApiKey(body) {
240
+ return this.req("POST", "/v1/orgs/me/api-keys", { auth: "SessionCookie", body });
241
+ }
242
+ listApiKeys() {
243
+ return this.req("GET", "/v1/orgs/me/api-keys", { auth: "SessionCookie" });
244
+ }
245
+ /** Revoke an API key (org admin). It stops working when this returns. */
246
+ revokeApiKey(id) {
247
+ return this.req("DELETE", `/v1/orgs/me/api-keys/${encodeURIComponent(id)}`, {
248
+ auth: "SessionCookie",
249
+ expectNoContent: true
250
+ });
251
+ }
252
+ listMembers() {
253
+ return this.req("GET", "/v1/orgs/me/members", { auth: "SessionCookie" });
254
+ }
255
+ inviteMember(body) {
256
+ return this.req("POST", "/v1/orgs/me/members/invite", {
257
+ auth: "SessionCookie",
258
+ body
259
+ });
260
+ }
261
+ suspendMember(userId) {
262
+ return this.req(
263
+ "POST",
264
+ `/v1/orgs/me/members/${encodeURIComponent(userId)}/suspend`,
265
+ { auth: "SessionCookie" }
266
+ );
267
+ }
268
+ unsuspendMember(userId) {
269
+ return this.req(
270
+ "POST",
271
+ `/v1/orgs/me/members/${encodeURIComponent(userId)}/unsuspend`,
272
+ { auth: "SessionCookie" }
273
+ );
274
+ }
275
+ setMemberRole(userId, body) {
276
+ return this.req(
277
+ "PUT",
278
+ `/v1/orgs/me/members/${encodeURIComponent(userId)}/role`,
279
+ { auth: "SessionCookie", body }
280
+ );
281
+ }
282
+ removeMember(userId) {
283
+ return this.req(
284
+ "DELETE",
285
+ `/v1/orgs/me/members/${encodeURIComponent(userId)}`,
286
+ { auth: "SessionCookie" }
287
+ );
288
+ }
289
+ resendMemberInvite(userId) {
290
+ return this.req(
291
+ "POST",
292
+ `/v1/orgs/me/members/${encodeURIComponent(userId)}/resend-invite`,
293
+ { auth: "SessionCookie" }
294
+ );
295
+ }
296
+ /**
297
+ * Open a signup link. Works only in the browser that signed up (the
298
+ * `wac_signup` cookie): `next: 'secure-account'` means an enrollment
299
+ * session is open (continue with {@link enrollment}); `next:
300
+ * 'open-in-signup-browser'` means nothing was consumed.
301
+ */
302
+ verifySignup(token) {
303
+ return this.req("POST", "/v1/auth/verify", { auth: "Public", body: { token } });
304
+ }
305
+ /**
306
+ * Accept an invitation from its emailed link, in any browser: the address
307
+ * is verified and an enrollment session opens (continue with
308
+ * {@link enrollment}). 400 when the link is used, expired or superseded;
309
+ * 409 when the account is already secured (sign in instead).
310
+ */
311
+ acceptInvite(token) {
312
+ return this.req("POST", "/v1/auth/invite/accept", { auth: "Public", body: { token } });
313
+ }
314
+ /**
315
+ * Deploy the org's self-custody contract with keys made on your side
316
+ * (plan §17.4): the owner key's public half and the first signing key.
317
+ * Safe to retry with the same keys at once; it returns the same contract.
318
+ */
319
+ deploySelfCustodyContract(body) {
320
+ return this.req("POST", "/v1/account/contract/deploy", { auth: "SessionOrBearer", body });
321
+ }
322
+ /** Every signing key on the org's contract: customer-held and any Witnium-held, with holders. */
323
+ listContractSigningKeys() {
324
+ return this.req("GET", "/v1/account/signing-keys", { auth: "SessionOrBearer" });
325
+ }
326
+ createSigningKeyRequest(body) {
327
+ return this.req("POST", "/v1/account/signing-key-requests", { auth: "SessionOrBearer", body });
328
+ }
329
+ listSigningKeyRequests() {
330
+ return this.req("GET", "/v1/account/signing-key-requests", { auth: "SessionCookie" });
331
+ }
332
+ approveSigningKeyRequest(id, body) {
333
+ return this.req("POST", `/v1/account/signing-key-requests/${encodeURIComponent(id)}/approve`, {
334
+ auth: "SessionCookie",
335
+ body
336
+ });
337
+ }
338
+ declineSigningKeyRequest(id) {
339
+ return this.req("POST", `/v1/account/signing-key-requests/${encodeURIComponent(id)}/decline`, {
340
+ auth: "SessionCookie",
341
+ expectNoContent: true
342
+ });
343
+ }
344
+ /** Options for a passkey sign-in (a discoverable credential: no email). */
345
+ passkeySignInOptions() {
346
+ return this.req("POST", "/v1/auth/passkey/options", { auth: "Public" });
347
+ }
348
+ /** Sign in with the passkey's answer (`credential.toJSON()`); sets the session cookie. */
349
+ passkeySignIn(credential) {
350
+ return this.call("POST", "/v1/auth/passkey", { auth: "Public", body: { credential } }, "session-changed");
351
+ }
352
+ /**
353
+ * First step of a password + authenticator sign-in. Never a session:
354
+ * `'mfa_required'` (a short-lived challenge cookie is set; follow with
355
+ * {@link loginMfa}), or `'enrollment_required'` (an account without an
356
+ * authenticator: a link to secure it was emailed, valid in this browser).
357
+ */
358
+ login(body) {
359
+ return this.req("POST", "/v1/auth/login", { auth: "Public", body });
360
+ }
361
+ /**
362
+ * Second step of a password sign-in, after `login()` returned `'mfa_required'`.
363
+ * Relies on the challenge cookie from that call (`credentials: 'include'`).
364
+ * 401 `mfa_code_invalid`: wrong or reused code, the user may retry.
365
+ * 401 `mfa_challenge_invalid`: expired or used up, start again at `login()`.
366
+ * 429 `mfa_rate_limited`: the body carries `retryAfterSeconds`.
367
+ */
368
+ loginMfa(body) {
369
+ return this.call("POST", "/v1/auth/login/mfa", { auth: "Public", body }, "session-changed");
370
+ }
371
+ /**
372
+ * End the first-party session. The cached bearer token is dropped even when
373
+ * the request fails, so a logged-out tab never keeps the previous user's
374
+ * token.
375
+ */
376
+ async logout() {
377
+ try {
378
+ return await this.req("POST", "/v1/auth/logout", { auth: "Public" });
379
+ } finally {
380
+ this.signOut();
381
+ }
382
+ }
383
+ forgotPassword(body) {
384
+ return this.req("POST", "/v1/auth/forgot-password", { auth: "Public", body });
385
+ }
386
+ resetPassword(body) {
387
+ return this.req("POST", "/v1/auth/reset-password", { auth: "Public", body });
388
+ }
389
+ // ────────────────────────────────────────────────────────────────────────
390
+ // Billing (/v1/billing/*)
391
+ // ────────────────────────────────────────────────────────────────────────
392
+ createCheckoutSession(body) {
393
+ return this.req("POST", "/v1/billing/checkout", {
394
+ auth: "SessionCookie",
395
+ body
396
+ });
397
+ }
398
+ createPortalSession() {
399
+ return this.req("GET", "/v1/billing/portal", { auth: "SessionCookie" });
400
+ }
401
+ // Webhook endpoint is intentionally NOT exposed: only Stripe should call it.
402
+ // ────────────────────────────────────────────────────────────────────────
403
+ // Orgs (/v1/orgs/me/*)
404
+ // ────────────────────────────────────────────────────────────────────────
405
+ /** The calling API key's own description: its contract and signing key (API key only). */
406
+ getApiKeySelf() {
407
+ return this.req("GET", "/v1/api-key", { auth: "ApiKey" });
408
+ }
409
+ // ────────────────────────────────────────────────────────────────────────
410
+ // Delegated keys (/v1/users/me/delegated-keys/*)
411
+ // ────────────────────────────────────────────────────────────────────────
412
+ listDelegatedKeys(query) {
413
+ return this.req("GET", "/v1/users/me/delegated-keys", {
414
+ auth: "BearerJWT",
415
+ query: query ?? {}
416
+ });
417
+ }
418
+ prepareDelegatedKey(body) {
419
+ return this.req("POST", "/v1/users/me/delegated-keys", {
420
+ auth: "BearerJWT",
421
+ body
422
+ });
423
+ }
424
+ submitDelegatedKey(id, body) {
425
+ return this.req(
426
+ "POST",
427
+ `/v1/users/me/delegated-keys/${encodeURIComponent(id)}/submit`,
428
+ { auth: "BearerJWT", body }
429
+ );
430
+ }
431
+ revokeDelegatedKey(id) {
432
+ return this.req(
433
+ "DELETE",
434
+ `/v1/users/me/delegated-keys/${encodeURIComponent(id)}`,
435
+ { auth: "BearerJWT" }
436
+ );
437
+ }
438
+ // ────────────────────────────────────────────────────────────────────────
439
+ // Sign (/v1/sign)
440
+ // ────────────────────────────────────────────────────────────────────────
441
+ sign(body, requestId) {
442
+ const headers = requestId ? { "x-request-id": requestId } : void 0;
443
+ return this.req("POST", "/v1/sign", {
444
+ auth: this.writeAuth(),
445
+ body,
446
+ ...headers ? { headers } : {}
447
+ });
448
+ }
449
+ // ────────────────────────────────────────────────────────────────────────
450
+ // Contracts (/v1/contracts/* + /v1/keys/*)
451
+ // ────────────────────────────────────────────────────────────────────────
452
+ /**
453
+ * @deprecated Removed with accounts step 7d (plan §17.6). Use
454
+ * {@link deploySelfCustodyContract}, which needs no provisioning token.
455
+ */
456
+ provisionContract(body) {
457
+ return this.req("POST", "/v1/contracts/provision", {
458
+ auth: "Public",
459
+ body
460
+ });
461
+ }
462
+ addSigningKey(body) {
463
+ return this.req("POST", "/v1/keys", { auth: "SessionOrBearer", body });
464
+ }
465
+ revokeSigningKey(body) {
466
+ return this.req("POST", "/v1/keys/revoke", {
467
+ auth: "SessionOrBearer",
468
+ body
469
+ });
470
+ }
471
+ pauseContract(body) {
472
+ return this.req("POST", "/v1/contracts/pause", {
473
+ auth: "SessionCookie",
474
+ body
475
+ });
476
+ }
477
+ unpauseContract(body) {
478
+ return this.req("POST", "/v1/contracts/unpause", {
479
+ auth: "SessionCookie",
480
+ body
481
+ });
482
+ }
483
+ // ────────────────────────────────────────────────────────────────────────
484
+ // Witnesses (/v1/contracts/{addr}/witnesses/*)
485
+ // ────────────────────────────────────────────────────────────────────────
486
+ async proposeWitness(contractAddress, body, idempotencyKey) {
487
+ const key = idempotencyKey ?? await deriveBodyKey("v1:propose", contractAddress, body);
488
+ return this.req(
489
+ "POST",
490
+ `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
491
+ { auth: "SignedRequest", body, headers: { "idempotency-key": key } }
492
+ );
493
+ }
494
+ signWitness(contractAddress, witnessId, body) {
495
+ return this.req(
496
+ "POST",
497
+ `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}/sign`,
498
+ { auth: "SignedRequest", body }
499
+ );
500
+ }
501
+ finalizeWitness(contractAddress, witnessId) {
502
+ return this.req(
503
+ "POST",
504
+ `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}/finalize`,
505
+ { auth: "SignedRequest" }
506
+ );
507
+ }
508
+ async revokeWitness(contractAddress, witnessId, body, idempotencyKey) {
509
+ const key = idempotencyKey ?? await deriveBodyKey("v1:revoke", contractAddress, { witnessId, body });
510
+ return this.req(
511
+ "POST",
512
+ `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}/revoke`,
513
+ { auth: "SignedRequest", body, headers: { "idempotency-key": key } }
514
+ );
515
+ }
516
+ getWitness(contractAddress, witnessId) {
517
+ return this.req(
518
+ "GET",
519
+ `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}`,
520
+ { auth: "Public" }
521
+ );
522
+ }
523
+ // ────────────────────────────────────────────────────────────────────────
524
+ // v5 Witnesses (/v5/contracts/{addr}/witnesses/*)
525
+ //
526
+ // The v5 write surface is a metered proxy in accounts: every billable
527
+ // call (propose, revoke) reserves a credit; sign/finalize forward to
528
+ // chain-api with the admin token. Auth is OAuth Bearer (the URL
529
+ // contract must match the user's bound contract), or an org API key for
530
+ // propose, sign and finalize (its org's active contract).
531
+ //
532
+ // The propose/revoke methods default Idempotency-Key to a stable hash
533
+ // of the request body so an application-level retry with the same
534
+ // arguments dedupes against the original reservation instead of
535
+ // burning a second credit. Pass an explicit `idempotencyKey` to
536
+ // override (e.g. if you genuinely want two witnesses for the same
537
+ // body).
538
+ // ────────────────────────────────────────────────────────────────────────
539
+ async proposeWitnessV5(contractAddress, body, idempotencyKey) {
540
+ const key = idempotencyKey ?? await deriveBodyKey("v5:propose", contractAddress, body);
541
+ return this.req(
542
+ "POST",
543
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
544
+ { auth: this.writeAuth(), body, headers: { "idempotency-key": key } }
545
+ );
546
+ }
547
+ /**
548
+ * What happened to an intent whose propose or finalize answer was lost
549
+ * (read-only, the caller's own contract): accounts' stored finalize
550
+ * response when it has one, otherwise chain-api's status for the intent.
551
+ */
552
+ recoverWitnessIntentV5(contractAddress, intentId) {
553
+ return this.req(
554
+ "GET",
555
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/intents/${encodeURIComponent(intentId)}`,
556
+ { auth: this.writeAuth() }
557
+ );
558
+ }
559
+ signWitnessV5(contractAddress, intentId, body) {
560
+ return this.req(
561
+ "POST",
562
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(intentId)}/sign`,
563
+ { auth: this.writeAuth(), body }
564
+ );
565
+ }
566
+ finalizeWitnessV5(contractAddress, intentId) {
567
+ return this.req(
568
+ "POST",
569
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(intentId)}/finalize`,
570
+ { auth: this.writeAuth() }
571
+ );
572
+ }
573
+ async revokeWitnessV5(contractAddress, witnessId, body, idempotencyKey) {
574
+ const key = idempotencyKey ?? await deriveBodyKey("v5:revoke", contractAddress, { witnessId, body });
575
+ return this.req(
576
+ "POST",
577
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}/revoke`,
578
+ { auth: "BearerJWT", body, headers: { "idempotency-key": key } }
579
+ );
580
+ }
581
+ // ────────────────────────────────────────────────────────────────────────
582
+ // Users / account (/v1/account/*)
583
+ // ────────────────────────────────────────────────────────────────────────
584
+ getAccount() {
585
+ return this.req("GET", "/v1/account", { auth: "SessionCookie" });
586
+ }
587
+ getLedger() {
588
+ return this.req("GET", "/v1/account/ledger", { auth: "SessionCookie" });
589
+ }
590
+ /**
591
+ * DEV-ONLY: hard-delete the authenticated user + their org + contracts +
592
+ * delegated keys so signup can be re-run from scratch. Gated behind
593
+ * WITNIUM_PRE_LAUNCH on the server (throws 403 otherwise). The on-chain
594
+ * contract is orphaned (immutable). Removed before customer onboarding —
595
+ * do not build product UI on this; it's a dev-loop convenience.
596
+ */
597
+ deleteAccount() {
598
+ return this.req("DELETE", "/v1/account", { auth: "SessionCookie" });
599
+ }
600
+ /**
601
+ * Re-mint a provisioning token for a verified-but-not-yet-provisioned
602
+ * self-custody account whose earlier token was lost. Throws 409 if the email isn't
603
+ * verified or a contract already exists; rate-limited per account.
604
+ *
605
+ * @deprecated Removed with accounts step 7d (plan §17.6). Use
606
+ * {@link deploySelfCustodyContract}, which needs no provisioning token.
607
+ */
608
+ reissueProvisioningToken() {
609
+ return this.req("POST", "/v1/account/provisioning-token/reissue", {
610
+ auth: "SessionCookie"
611
+ });
612
+ }
613
+ /**
614
+ * The state of the org's contract. Poll it after choosing managed keys
615
+ * until `status` is `ready`; Witnium deploys the contract usually within
616
+ * a minute.
617
+ */
618
+ getAccountContract() {
619
+ return this.req("GET", "/v1/account/contract", { auth: "SessionOrBearer" });
620
+ }
621
+ /**
622
+ * Choose who holds the contract's owner key, once, after the account is
623
+ * secured. `witnium`: Witnium deploys now (poll {@link getAccountContract}).
624
+ * `customer`: returns a provisioning token for `POST /v1/contracts/provision`.
625
+ */
626
+ chooseContractCustody(body) {
627
+ return this.req("POST", "/v1/account/contract", { auth: "SessionOrBearer", body });
628
+ }
629
+ // ────────────────────────────────────────────────────────────────────────
630
+ // OAuth sessions (/v1/oauth/sessions*)
631
+ // ────────────────────────────────────────────────────────────────────────
632
+ listOauthSessions() {
633
+ return this.req("GET", "/v1/oauth/sessions", { auth: "SessionCookie" });
634
+ }
635
+ revokeOauthSession(jti) {
636
+ return this.req("DELETE", `/v1/oauth/sessions/${encodeURIComponent(jti)}`, {
637
+ auth: "SessionCookie",
638
+ expectNoContent: true
639
+ });
640
+ }
641
+ revokeAllOauthSessions() {
642
+ return this.req("DELETE", "/v1/oauth/sessions", {
643
+ auth: "SessionCookie",
644
+ expectNoContent: true
645
+ });
646
+ }
647
+ // ────────────────────────────────────────────────────────────────────────
648
+ // Health (/health/*)
649
+ // ────────────────────────────────────────────────────────────────────────
650
+ healthLive() {
651
+ return this.req("GET", "/health/live", { auth: "Public" });
652
+ }
653
+ healthReady() {
654
+ return this.req("GET", "/health/ready", { auth: "Public" });
655
+ }
656
+ // ════════════════════════════════════════════════════════════════════════
657
+ // Chain-api reads (called against chainBaseUrl, e.g. api.witniumchain.com)
658
+ //
659
+ // Routing: every method here passes `service: 'chain'` to `req()`. Calls
660
+ // throw at call time if `chainBaseUrl` wasn't configured.
661
+ //
662
+ // Auth: the contract, witness, transaction and wallet reads are public on
663
+ // chain-api (anyone can check a witness), so they send no credential. The
664
+ // dashboard reads are BearerJWT: the accounts-issued token already carries
665
+ // `aud=https://api.witniumchain.com`, so the same `accessToken` works
666
+ // unchanged against both services.
667
+ //
668
+ // What's NOT here: chain-api v5 WRITES (propose/sign/finalize/revoke). Those
669
+ // are proxied by accounts (proposeWitnessV5, etc.) so credits get reserved
670
+ // and idempotency is enforced. See docs/PLAN-PHASE-SDK-UNIFIED.md for the
671
+ // routing rules; calling chain-api writes directly would burn credits
672
+ // without billing them.
673
+ // ════════════════════════════════════════════════════════════════════════
674
+ getContractInfo(contractAddress) {
675
+ return this.req(
676
+ "GET",
677
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/info`,
678
+ { auth: "Public", service: "chain" }
679
+ );
680
+ }
681
+ getContractVerification(contractAddress) {
682
+ return this.req(
683
+ "GET",
684
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/verify`,
685
+ { auth: "Public", service: "chain" }
686
+ );
687
+ }
688
+ listWitnessesV5(contractAddress, params) {
689
+ return this.req(
690
+ "GET",
691
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses`,
692
+ { auth: "Public", service: "chain", query: params }
693
+ );
694
+ }
695
+ getWitnessV5(contractAddress, witnessId) {
696
+ return this.req(
697
+ "GET",
698
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}`,
699
+ { auth: "Public", service: "chain" }
700
+ );
701
+ }
702
+ getContractTransaction(contractAddress, txHash) {
703
+ return this.req(
704
+ "GET",
705
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/transactions/${encodeURIComponent(txHash)}`,
706
+ { auth: "Public", service: "chain" }
707
+ );
708
+ }
709
+ getTransaction(txHash) {
710
+ return this.req(
711
+ "GET",
712
+ `/v5/transactions/${encodeURIComponent(txHash)}`,
713
+ { auth: "Public", service: "chain" }
714
+ );
715
+ }
716
+ getWalletBalance(address) {
717
+ return this.req(
718
+ "GET",
719
+ `/v5/wallets/${encodeURIComponent(address)}/balance`,
720
+ { auth: "Public", service: "chain" }
721
+ );
722
+ }
723
+ getDashboardContract() {
724
+ return this.req("GET", "/v5/dashboard/contract", {
725
+ auth: "BearerJWT",
726
+ service: "chain"
727
+ });
728
+ }
729
+ getDashboardWitnesses(params) {
730
+ return this.req("GET", "/v5/dashboard/witnesses", {
731
+ auth: "BearerJWT",
732
+ service: "chain",
733
+ query: params
734
+ });
735
+ }
736
+ // ════════════════════════════════════════════════════════════════════════
737
+ // OAuth 2.1 + PKCE flow helpers (Phase AUTH Thread A)
738
+ //
739
+ // Designed for browser SPAs without a backend ("Sign in with Witnium" for a
740
+ // Lovable customer). The flow:
741
+ //
742
+ // 1. App calls `beginOAuthLogin({ redirectUri })`, gets a URL, redirects.
743
+ // 2. User authenticates at auth.witniumchain.com, server redirects back
744
+ // to the app's redirectUri with `?code=…&state=…`.
745
+ // 3. App calls `completeOAuthLogin(window.location.href)`, gets back an
746
+ // access token. The SDK stashes it in memory; subsequent `BearerJWT`
747
+ // calls use it transparently.
748
+ // 4. When a `BearerJWT` call returns 401 (token expired), `req()` calls
749
+ // `refreshAccessToken` once and retries. Caller never sees the 401.
750
+ //
751
+ // Access tokens live in memory only — never localStorage. They die on tab
752
+ // close; the refresh token (held in memory today, planned to migrate to an
753
+ // HttpOnly cookie set by /token server-side) survives long enough for a
754
+ // silent refresh on the next /completeOAuthLogin or 401-retry. Refresh
755
+ // tokens rotate on every use, so a single-flight gate avoids racing two
756
+ // concurrent refreshes against the same token.
757
+ //
758
+ // Endpoint discovery: the SDK fetches /.well-known/openid-configuration
759
+ // from `baseUrl` once and reuses the parsed result. oidc-provider's paths
760
+ // (/auth, /token, /jwks, etc.) are not hard-coded — if accounts ever moves
761
+ // them, only the discovery doc has to be right.
762
+ // ════════════════════════════════════════════════════════════════════════
763
+ /**
764
+ * Build the authorization-server URL for the start of an OAuth login flow.
765
+ *
766
+ * Generates a fresh PKCE verifier + challenge, stashes the verifier in the
767
+ * configured {@link PkceVerifierStorage} under the `state` key, and returns
768
+ * the URL the caller should redirect the user to. Side-effects:
769
+ *
770
+ * - sessionStorage gets a PKCE entry under `witniumchain.pkce.<state>`.
771
+ * - The client instance remembers the `redirectUri` for this `state`
772
+ * so {@link completeOAuthLogin} can rebuild the matching token request
773
+ * without the caller threading the URI through twice.
774
+ *
775
+ * The caller is responsible for the redirect itself
776
+ * (`window.location.assign(result.authorizationUrl)`); the SDK doesn't
777
+ * touch `window` directly so SSR + non-browser callers are not broken.
778
+ */
779
+ async beginOAuthLogin(args) {
780
+ if (!this.oauthClientId) {
781
+ throw new WitniumchainApiError({
782
+ status: 0,
783
+ message: "WitniumchainClient: beginOAuthLogin requires `oauthClientId` to be set on the constructor."
784
+ });
785
+ }
786
+ const discovery = await this.fetchDiscovery();
787
+ const state = args.state ?? generateState();
788
+ const verifier = generateCodeVerifier();
789
+ const challenge = await deriveCodeChallenge(verifier);
790
+ const scope = (args.scope ?? ["openid", "profile", "email"]).join(" ");
791
+ const url = new URL(discovery.authorization_endpoint);
792
+ url.searchParams.set("response_type", "code");
793
+ url.searchParams.set("client_id", this.oauthClientId);
794
+ url.searchParams.set("redirect_uri", args.redirectUri);
795
+ url.searchParams.set("scope", scope);
796
+ url.searchParams.set("state", state);
797
+ url.searchParams.set("code_challenge", challenge);
798
+ url.searchParams.set("code_challenge_method", "S256");
799
+ if (args.prompt) url.searchParams.set("prompt", args.prompt);
800
+ const storage = this.verifierStorageOrDefault();
801
+ storage.set(state, verifier);
802
+ storage.set(redirectUriKey(state), args.redirectUri);
803
+ return { authorizationUrl: url.toString(), state };
804
+ }
805
+ /**
806
+ * Exchange an authorization-code callback for an access token.
807
+ *
808
+ * Reads `code` and `state` from the callback URL, validates the state
809
+ * against a stored verifier, exchanges the code at the token endpoint,
810
+ * and stores the access token (and refresh token) in the client's
811
+ * in-memory state. Returns the access token + its expiry for callers
812
+ * who want to display the session or schedule a proactive refresh.
813
+ *
814
+ * Throws (without consuming the verifier) when the callback URL is
815
+ * missing `code` or `state`, or when the state has no matching verifier
816
+ * — the latter happens when the user opens an old/forged callback URL,
817
+ * or when sessionStorage was cleared between authorize and callback.
818
+ *
819
+ * The caller is responsible for stripping `code` and `state` from the
820
+ * browser URL afterwards (`window.history.replaceState`) so a refresh
821
+ * doesn't re-trigger the exchange against an already-consumed code.
822
+ */
823
+ async completeOAuthLogin(callbackUrl) {
824
+ if (!this.oauthClientId) {
825
+ throw new WitniumchainApiError({
826
+ status: 0,
827
+ message: "WitniumchainClient: completeOAuthLogin requires `oauthClientId` to be set on the constructor."
828
+ });
829
+ }
830
+ const url = callbackUrl instanceof URL ? callbackUrl : new URL(callbackUrl);
831
+ const code = url.searchParams.get("code");
832
+ const state = url.searchParams.get("state");
833
+ const error = url.searchParams.get("error");
834
+ if (error) {
835
+ throw new WitniumchainApiError({
836
+ status: 0,
837
+ message: `OAuth authorize returned error: ${error}${url.searchParams.get("error_description") ? ` (${url.searchParams.get("error_description")})` : ""}`,
838
+ errorLabel: error
839
+ });
840
+ }
841
+ if (!code || !state) {
842
+ throw new WitniumchainApiError({
843
+ status: 0,
844
+ message: "WitniumchainClient: callbackUrl missing required `code` and/or `state` parameters."
845
+ });
846
+ }
847
+ const storage = this.verifierStorageOrDefault();
848
+ const verifier = storage.get(state);
849
+ if (!verifier) {
850
+ throw new WitniumchainApiError({
851
+ status: 0,
852
+ message: "WitniumchainClient: no PKCE verifier stored for this `state`. The login flow either was not started in this tab, was already completed, or the sessionStorage entry was cleared."
853
+ });
854
+ }
855
+ const redirectUri = storage.get(redirectUriKey(state));
856
+ if (!redirectUri) {
857
+ storage.remove(state);
858
+ throw new WitniumchainApiError({
859
+ status: 0,
860
+ message: "WitniumchainClient: PKCE verifier exists but the redirectUri stored with it for this `state` is missing."
861
+ });
862
+ }
863
+ const discovery = await this.fetchDiscovery();
864
+ const form = new URLSearchParams();
865
+ form.set("grant_type", "authorization_code");
866
+ form.set("code", code);
867
+ form.set("redirect_uri", redirectUri);
868
+ form.set("client_id", this.oauthClientId);
869
+ form.set("code_verifier", verifier);
870
+ const tokens = await this.postTokenEndpoint(discovery.token_endpoint, form);
871
+ storage.remove(state);
872
+ storage.remove(redirectUriKey(state));
873
+ return this.persistTokenResponse(tokens);
874
+ }
875
+ /**
876
+ * Refresh the access token. Sends `grant_type=refresh_token` to the token
877
+ * endpoint with the in-memory refresh token, and updates `accessToken`
878
+ * (and the rotated refresh token) on success.
879
+ *
880
+ * Concurrent callers — including the 401-retry interceptor inside `req()`
881
+ * fanning out N parallel calls — share a single in-flight refresh promise:
882
+ * refresh tokens rotate on use, so issuing two concurrent refreshes would
883
+ * race and one would 401 with `invalid_grant`.
884
+ *
885
+ * Throws `WitniumchainApiError` if the refresh token is missing (the SDK
886
+ * was constructed without one and `completeOAuthLogin` was never called)
887
+ * or if the AS rejects the refresh (token revoked / expired). On rejection
888
+ * the in-memory tokens are cleared so subsequent BearerJWT calls fail fast
889
+ * instead of retrying with a now-invalid token.
890
+ */
891
+ async refreshAccessToken() {
892
+ if (this.refreshInFlight) return this.refreshInFlight;
893
+ let flight = void 0;
894
+ flight = (async () => {
895
+ try {
896
+ return await this.refreshAccessTokenInternal();
897
+ } finally {
898
+ if (this.refreshInFlight === flight) this.refreshInFlight = void 0;
899
+ }
900
+ })();
901
+ this.refreshInFlight = flight;
902
+ return flight;
903
+ }
904
+ /**
905
+ * Exchange the logged-in session (the `wac_session` cookie) for a short-lived
906
+ * bearer access token and cache it as the client's `accessToken`.
907
+ *
908
+ * This is the SDK side of the session→token model (accounts'
909
+ * `POST /v1/auth/access-token`): the dashboard authenticates with the
910
+ * cookie, but the operational API (delegated keys, witness writes, chain
911
+ * reads) is bearer-only — no endpoint accepts the ambient cookie, so there's
912
+ * no CSRF surface even with `SameSite=None`. The minted token is
913
+ * byte-compatible with an OAuth user token (same signing key, `iss`, `aud`,
914
+ * scope + org/role/contracts claims), so every `BearerJWT` route accepts it.
915
+ *
916
+ * Callers rarely invoke this directly — {@link applyAuth} mints transparently
917
+ * on the first `BearerJWT` call when no token is set and re-mints on a 401.
918
+ * It's exposed so a dashboard can pre-warm the token right after login.
919
+ *
920
+ * Requires a session: either `sessionCookie` on the constructor (Node) or an
921
+ * ambient `wac_session` cookie carried by the browser (`credentials:
922
+ * 'include'`). Throws {@link WitniumchainApiError} (401) when there's no
923
+ * valid session.
924
+ */
925
+ async exchangeSessionForToken() {
926
+ if (this.sessionExchangeInFlight) return this.sessionExchangeInFlight;
927
+ const generation = this.credentialGeneration;
928
+ let flight = void 0;
929
+ flight = (async () => {
930
+ try {
931
+ const res = await this.req("POST", "/v1/auth/access-token", { auth: "SessionCookie" });
932
+ this.assertCredentialGeneration(generation);
933
+ this.accessToken = res.accessToken;
934
+ this.accessTokenFromSession = true;
935
+ this.refreshToken = void 0;
936
+ this.hasRefreshCookie = false;
937
+ return {
938
+ accessToken: res.accessToken,
939
+ expiresAt: Math.floor(new Date(res.expiresAt).getTime() / 1e3)
940
+ };
941
+ } finally {
942
+ if (this.sessionExchangeInFlight === flight) this.sessionExchangeInFlight = void 0;
943
+ }
944
+ })();
945
+ this.sessionExchangeInFlight = flight;
946
+ return flight;
947
+ }
948
+ assertCredentialGeneration(generation) {
949
+ if (generation !== this.credentialGeneration) {
950
+ throw new WitniumchainApiError({
951
+ status: 0,
952
+ message: "WitniumchainClient: the session changed (sign-out or MFA confirmation) while a token request was in flight; its token was discarded."
953
+ });
954
+ }
955
+ }
956
+ /**
957
+ * Forget every cached credential and orphan in-flight mints/refreshes, so
958
+ * none of them can store a token afterwards.
959
+ */
960
+ invalidateCredentials() {
961
+ this.credentialGeneration++;
962
+ this.accessToken = void 0;
963
+ this.accessTokenFromSession = false;
964
+ this.refreshToken = void 0;
965
+ this.hasRefreshCookie = false;
966
+ this.sessionExchangeInFlight = void 0;
967
+ this.refreshInFlight = void 0;
968
+ }
969
+ /**
970
+ * Best-effort transparent mint for the `BearerJWT` path: if no access token
971
+ * is cached, try the session exchange (single-flight). Swallows failure so
972
+ * the caller in {@link applyAuth} surfaces the actionable "no token / no
973
+ * session" guidance rather than a raw 401 from the exchange endpoint.
974
+ */
975
+ async ensureSessionAccessToken() {
976
+ if (this.accessToken) return;
977
+ try {
978
+ await this.exchangeSessionForToken();
979
+ } catch (err) {
980
+ if (!(err instanceof WitniumchainApiError && err.status === 401)) throw err;
981
+ }
982
+ }
983
+ /**
984
+ * Obtain a fresh access token for a 401-retry, picking the right mechanism:
985
+ * an OAuth refresh when a refresh credential exists, else a session re-mint
986
+ * for a session-exchanged token. Returns true when a fresh token is in hand.
987
+ */
988
+ async reauthenticateForRetry() {
989
+ if (this.refreshToken || this.hasRefreshCookie) {
990
+ try {
991
+ await this.refreshAccessToken();
992
+ return true;
993
+ } catch {
994
+ return false;
995
+ }
996
+ }
997
+ if (this.accessTokenFromSession) {
998
+ this.accessToken = void 0;
999
+ try {
1000
+ await this.exchangeSessionForToken();
1001
+ return true;
1002
+ } catch {
1003
+ return false;
1004
+ }
1005
+ }
1006
+ return false;
1007
+ }
1008
+ /**
1009
+ * End the OAuth session.
1010
+ *
1011
+ * Clears the in-memory access + refresh tokens. Best-effort revocation of
1012
+ * the server-side session would require a server endpoint that accepts a
1013
+ * Bearer-token-authenticated DELETE (today's `/v1/oauth/sessions` requires
1014
+ * the first-party `wac_session` cookie, see oauth-sessions.controller.ts).
1015
+ * That endpoint will arrive with Phase AUTH Thread E; until then,
1016
+ * `signOut` clears local state only and the access token's natural TTL
1017
+ * (currently 60 min) bounds residual risk if the refresh token is also
1018
+ * dropped — which it is, here.
1019
+ */
1020
+ signOut() {
1021
+ this.invalidateCredentials();
1022
+ }
1023
+ // ────────────────────────────────────────────────────────────────────────
1024
+ // Internal: OAuth flow helpers
1025
+ // ────────────────────────────────────────────────────────────────────────
1026
+ verifierStorageOrDefault() {
1027
+ if (this.verifierStorage) return this.verifierStorage;
1028
+ return defaultVerifierStorage();
1029
+ }
1030
+ async fetchDiscovery() {
1031
+ if (this.discoveryCache) return this.discoveryCache;
1032
+ this.discoveryCache = (async () => {
1033
+ const url = `${this.baseUrl}/.well-known/openid-configuration`;
1034
+ let res;
1035
+ try {
1036
+ res = await this.fetchImpl(url, {
1037
+ method: "GET",
1038
+ headers: { accept: "application/json" }
1039
+ });
1040
+ } catch (err) {
1041
+ this.discoveryCache = void 0;
1042
+ throw new WitniumchainApiError({
1043
+ status: 0,
1044
+ message: err instanceof Error ? `OIDC discovery fetch failed: ${err.message}` : "OIDC discovery fetch failed"
1045
+ });
1046
+ }
1047
+ if (!res.ok) {
1048
+ this.discoveryCache = void 0;
1049
+ throw new WitniumchainApiError({
1050
+ status: res.status,
1051
+ message: `OIDC discovery fetch failed: HTTP ${res.status}`
1052
+ });
1053
+ }
1054
+ const parsed = await res.json();
1055
+ if (!parsed.authorization_endpoint || !parsed.token_endpoint) {
1056
+ this.discoveryCache = void 0;
1057
+ throw new WitniumchainApiError({
1058
+ status: 0,
1059
+ message: "OIDC discovery doc is missing `authorization_endpoint` or `token_endpoint`."
1060
+ });
1061
+ }
1062
+ return {
1063
+ authorization_endpoint: parsed.authorization_endpoint,
1064
+ token_endpoint: parsed.token_endpoint,
1065
+ issuer: parsed.issuer ?? this.baseUrl
1066
+ };
1067
+ })();
1068
+ return this.discoveryCache;
1069
+ }
1070
+ async postTokenEndpoint(endpoint, form) {
1071
+ const controller = new AbortController();
1072
+ const timer = setTimeout(() => controller.abort(), this.timeout);
1073
+ let res;
1074
+ try {
1075
+ res = await this.fetchImpl(endpoint, {
1076
+ method: "POST",
1077
+ headers: {
1078
+ accept: "application/json",
1079
+ "content-type": "application/x-www-form-urlencoded"
1080
+ },
1081
+ body: form.toString(),
1082
+ signal: controller.signal,
1083
+ // Sends the HttpOnly refresh-token cookie when the server starts
1084
+ // setting it (planned server-side change); a no-op until then.
1085
+ credentials: "include"
1086
+ });
1087
+ } catch (err) {
1088
+ throw new WitniumchainApiError({
1089
+ status: 0,
1090
+ message: err instanceof Error ? `Token endpoint fetch failed: ${err.message}` : "Token endpoint fetch failed"
1091
+ });
1092
+ } finally {
1093
+ clearTimeout(timer);
1094
+ }
1095
+ const text = await res.text();
1096
+ let parsed = null;
1097
+ if (text.length > 0) {
1098
+ try {
1099
+ parsed = JSON.parse(text);
1100
+ } catch {
1101
+ }
1102
+ }
1103
+ if (!res.ok) {
1104
+ throw this.parseApiError(res.status, parsed, text);
1105
+ }
1106
+ return parsed;
1107
+ }
1108
+ persistTokenResponse(tokens) {
1109
+ if (!tokens.access_token) {
1110
+ throw new WitniumchainApiError({
1111
+ status: 0,
1112
+ message: "Token endpoint response missing `access_token`."
1113
+ });
1114
+ }
1115
+ this.accessToken = tokens.access_token;
1116
+ this.accessTokenFromSession = false;
1117
+ if (tokens.refresh_token) {
1118
+ this.refreshToken = tokens.refresh_token;
1119
+ } else {
1120
+ this.refreshToken = void 0;
1121
+ this.hasRefreshCookie = true;
1122
+ }
1123
+ const ttlSeconds = typeof tokens.expires_in === "number" ? tokens.expires_in : 3600;
1124
+ const expiresAt = Math.floor(Date.now() / 1e3) + ttlSeconds;
1125
+ return { accessToken: tokens.access_token, expiresAt };
1126
+ }
1127
+ async refreshAccessTokenInternal() {
1128
+ if (!this.oauthClientId) {
1129
+ throw new WitniumchainApiError({
1130
+ status: 0,
1131
+ message: "WitniumchainClient: refreshAccessToken requires `oauthClientId` to be set on the constructor."
1132
+ });
1133
+ }
1134
+ if (!this.refreshToken && !this.hasRefreshCookie) {
1135
+ throw new WitniumchainApiError({
1136
+ status: 0,
1137
+ message: "WitniumchainClient: no refresh credential available. Call `completeOAuthLogin` first \u2014 the server delivers the refresh token either in the response body (Node) or as an HttpOnly cookie (browser)."
1138
+ });
1139
+ }
1140
+ const generation = this.credentialGeneration;
1141
+ const discovery = await this.fetchDiscovery();
1142
+ const form = new URLSearchParams();
1143
+ form.set("grant_type", "refresh_token");
1144
+ form.set("client_id", this.oauthClientId);
1145
+ if (this.refreshToken) {
1146
+ form.set("refresh_token", this.refreshToken);
1147
+ }
1148
+ let tokens;
1149
+ try {
1150
+ tokens = await this.postTokenEndpoint(discovery.token_endpoint, form);
1151
+ } catch (err) {
1152
+ this.assertCredentialGeneration(generation);
1153
+ this.accessToken = void 0;
1154
+ this.refreshToken = void 0;
1155
+ this.hasRefreshCookie = false;
1156
+ throw err;
1157
+ }
1158
+ this.assertCredentialGeneration(generation);
1159
+ return this.persistTokenResponse(tokens);
1160
+ }
1161
+ // ────────────────────────────────────────────────────────────────────────
1162
+ // Internal: fetch wrapper that maps non-2xx → WitniumchainApiError
1163
+ // and applies the configured credential to the request.
1164
+ // ────────────────────────────────────────────────────────────────────────
1165
+ /**
1166
+ * @internal For the `enrollment`, `recovery` and `security` namespaces,
1167
+ * which group endpoints instead of mirroring each as a client method.
1168
+ * `'session-changed'`: the call ends or replaces the session, so cached
1169
+ * and in-flight bearer tokens are dropped and the next bearer call mints
1170
+ * from the new session.
1171
+ */
1172
+ async call(method, path, opts, effect) {
1173
+ const res = await this.req(method, path, opts);
1174
+ if (effect === "session-changed") this.invalidateCredentials();
1175
+ return res;
1176
+ }
1177
+ async req(method, path, opts) {
1178
+ const pathWithQuery = this.buildPathWithQuery(path, opts.query);
1179
+ const base = this.resolveBaseUrl(opts.service);
1180
+ const url = `${base}${pathWithQuery}`;
1181
+ const headers = {
1182
+ accept: "application/json",
1183
+ ...opts.headers ?? {}
1184
+ };
1185
+ if (opts.body !== void 0) {
1186
+ headers["content-type"] = "application/json";
1187
+ }
1188
+ const bodyString = opts.body !== void 0 ? JSON.stringify(opts.body) : void 0;
1189
+ await this.applyAuth(
1190
+ headers,
1191
+ opts.auth,
1192
+ method,
1193
+ pathWithQuery,
1194
+ bodyString ?? ""
1195
+ );
1196
+ const controller = new AbortController();
1197
+ const timer = setTimeout(() => controller.abort(), this.timeout);
1198
+ let res;
1199
+ try {
1200
+ res = await this.fetchImpl(url, {
1201
+ method,
1202
+ headers,
1203
+ body: bodyString,
1204
+ signal: controller.signal,
1205
+ // Send cookies cross-origin when the consumer is a browser using
1206
+ // SessionCookie auth via document.cookie.
1207
+ credentials: "include"
1208
+ });
1209
+ } catch (err) {
1210
+ throw new WitniumchainApiError({
1211
+ status: 0,
1212
+ message: err instanceof Error ? `Network error contacting ${base}: ${err.message}` : `Network error contacting ${base}`
1213
+ });
1214
+ } finally {
1215
+ clearTimeout(timer);
1216
+ }
1217
+ if (opts.expectNoContent) {
1218
+ if (!res.ok) {
1219
+ if (await this.shouldRefreshAndRetry(res, opts)) {
1220
+ return this.req(method, path, { ...opts, _isRetry: true });
1221
+ }
1222
+ throw await this.toApiError(res);
1223
+ }
1224
+ return void 0;
1225
+ }
1226
+ const text = await res.text();
1227
+ let parsed = null;
1228
+ if (text.length > 0) {
1229
+ try {
1230
+ parsed = JSON.parse(text);
1231
+ } catch {
1232
+ }
1233
+ }
1234
+ if (!res.ok) {
1235
+ if (await this.shouldRefreshAndRetryParsed(res.status, parsed, opts)) {
1236
+ return this.req(method, path, { ...opts, _isRetry: true });
1237
+ }
1238
+ throw this.parseApiError(res.status, parsed, text);
1239
+ }
1240
+ return parsed;
1241
+ }
1242
+ /**
1243
+ * Decide whether a non-2xx response on a `BearerJWT` route should trigger
1244
+ * a refresh + single retry. Returns false (no retry) when:
1245
+ *
1246
+ * - this call IS the retry — never recurse,
1247
+ * - the auth mode isn't BearerJWT — refresh only helps Bearer tokens,
1248
+ * - the status isn't 401 — refresh doesn't unstick 403/404/500/etc,
1249
+ * - we don't have a refresh token in memory — nothing to refresh with,
1250
+ * - the response body doesn't look like an expired-token signal.
1251
+ *
1252
+ * On a positive answer, the method ALSO performs the refresh in-line:
1253
+ * the caller just gets back `true` and replays the original request,
1254
+ * which picks up the freshly-rotated `accessToken` via `applyAuth`.
1255
+ * Refresh failures are swallowed here (the caller falls through to the
1256
+ * regular error path); `refreshAccessTokenInternal` already cleared the
1257
+ * in-memory tokens so the retry won't have anything to send.
1258
+ */
1259
+ async shouldRefreshAndRetry(res, opts) {
1260
+ if (opts._isRetry) return false;
1261
+ if (opts.auth !== "BearerJWT") return false;
1262
+ if (res.status !== 401) return false;
1263
+ if (!this.refreshToken && !this.hasRefreshCookie && !this.accessTokenFromSession)
1264
+ return false;
1265
+ return this.reauthenticateForRetry();
1266
+ }
1267
+ /**
1268
+ * Same decision as `shouldRefreshAndRetry` but for the JSON-parsed path,
1269
+ * where we have the body. Adds one extra gate: only retry when the parsed
1270
+ * body looks like a "token expired" signal (`error: 'token_expired'` per
1271
+ * the AUTH plan, or `error: 'invalid_token'` per RFC 6750 §3.1). A 401
1272
+ * with any other `error` label is a real authn/authz failure that refresh
1273
+ * won't fix — surface it instead of burning a refresh token.
1274
+ */
1275
+ async shouldRefreshAndRetryParsed(status, parsed, opts) {
1276
+ if (opts._isRetry) return false;
1277
+ if (opts.auth !== "BearerJWT") return false;
1278
+ if (status !== 401) return false;
1279
+ if (!this.refreshToken && !this.hasRefreshCookie && !this.accessTokenFromSession)
1280
+ return false;
1281
+ const body = parsed;
1282
+ const label = typeof body?.error === "string" ? body.error : void 0;
1283
+ if (label !== void 0 && label !== "token_expired" && label !== "invalid_token") {
1284
+ return false;
1285
+ }
1286
+ return this.reauthenticateForRetry();
1287
+ }
1288
+ /**
1289
+ * Resolve which base URL to call. Default is accounts (`baseUrl`). When a
1290
+ * method opts into 'chain', `chainBaseUrl` must be configured — throw at call
1291
+ * time with a clear message rather than fall back silently to accounts (no
1292
+ * defaults: a wrong base URL is a real bug and would mask itself as a 404).
1293
+ */
1294
+ resolveBaseUrl(service) {
1295
+ if (service === "chain") {
1296
+ if (!this.chainBaseUrl) {
1297
+ throw new WitniumchainApiError({
1298
+ status: 0,
1299
+ message: 'WitniumchainClient: chain-api method called without `chainBaseUrl` configured. Pass `chainBaseUrl: "https://api.witniumchain.com"` (or your environment\'s chain-api URL) to the client constructor.'
1300
+ });
1301
+ }
1302
+ return this.chainBaseUrl;
1303
+ }
1304
+ return this.baseUrl;
1305
+ }
1306
+ buildPathWithQuery(path, query) {
1307
+ if (!query) return path;
1308
+ const qs = new URLSearchParams();
1309
+ for (const [k, v] of Object.entries(query)) {
1310
+ if (v !== void 0) qs.set(k, String(v));
1311
+ }
1312
+ const suffix = qs.toString();
1313
+ return suffix ? `${path}?${suffix}` : path;
1314
+ }
1315
+ /** The credential for the calls an org API key may make (plan §14.5). */
1316
+ writeAuth() {
1317
+ return this.cfg.apiKey ? "ApiKey" : "BearerJWT";
1318
+ }
1319
+ async applyAuth(headers, auth, method, path, bodyString) {
1320
+ switch (auth) {
1321
+ case "Public":
1322
+ return;
1323
+ case "SessionCookie": {
1324
+ if (this.cfg.sessionCookie) {
1325
+ headers["cookie"] = `wac_session=${this.cfg.sessionCookie}`;
1326
+ }
1327
+ return;
1328
+ }
1329
+ case "SessionOrBearer": {
1330
+ if (this.accessToken) headers["authorization"] = `Bearer ${this.accessToken}`;
1331
+ else if (this.cfg.sessionCookie) headers["cookie"] = `wac_session=${this.cfg.sessionCookie}`;
1332
+ return;
1333
+ }
1334
+ case "BearerJWT": {
1335
+ if (!this.accessToken) {
1336
+ await this.ensureSessionAccessToken();
1337
+ }
1338
+ if (!this.accessToken) {
1339
+ throw new Error(
1340
+ `WitniumchainClient: ${method} ${path} requires an OAuth access token. Pass \`accessToken\` to the constructor, call \`beginOAuthLogin\`/\`completeOAuthLogin\`, or \u2014 for a logged-in dashboard \u2014 provide \`sessionCookie\` (Node) or rely on the browser \`wac_session\` cookie so the SDK can mint one.`
1341
+ );
1342
+ }
1343
+ headers["authorization"] = `Bearer ${this.accessToken}`;
1344
+ return;
1345
+ }
1346
+ case "ApiKey": {
1347
+ if (!this.cfg.apiKey) {
1348
+ throw new Error(
1349
+ `WitniumchainClient: ${method} ${path} requires an org API key. Pass \`apiKey\` to the constructor.`
1350
+ );
1351
+ }
1352
+ headers["authorization"] = `Bearer ${this.cfg.apiKey}`;
1353
+ return;
1354
+ }
1355
+ case "SignedRequest": {
1356
+ if (!this.cfg.signedRequest) {
1357
+ throw new Error(
1358
+ `WitniumchainClient: ${method} ${path} requires a signed-request signer. Pass \`signedRequest\` to the constructor.`
1359
+ );
1360
+ }
1361
+ const timestamp = Math.floor(Date.now() / 1e3).toString();
1362
+ const bodyHash = await sha256Hex(bodyString);
1363
+ const idemKey = headers["idempotency-key"] ?? "";
1364
+ const canonical = `${method.toUpperCase()}
1365
+ ${path}
1366
+ ${timestamp}
1367
+ ${idemKey}
1368
+ ${bodyHash}`;
1369
+ const signature = await this.cfg.signedRequest.sign(canonical);
1370
+ headers["x-witnium-key"] = this.cfg.signedRequest.publicKeyHex;
1371
+ headers["x-witnium-timestamp"] = timestamp;
1372
+ headers["x-witnium-signature"] = signature;
1373
+ return;
1374
+ }
1375
+ }
1376
+ }
1377
+ parseApiError(status, parsed, rawText) {
1378
+ const body = parsed;
1379
+ const message = Array.isArray(body?.message) ? body.message.join("; ") : typeof body?.message === "string" ? body.message : body?.error ?? `HTTP ${status}`;
1380
+ return new WitniumchainApiError({
1381
+ status,
1382
+ message,
1383
+ errorLabel: body?.error,
1384
+ body: parsed ?? rawText
1385
+ });
1386
+ }
1387
+ async toApiError(res) {
1388
+ const text = await res.text();
1389
+ let parsed = null;
1390
+ if (text.length > 0) {
1391
+ try {
1392
+ parsed = JSON.parse(text);
1393
+ } catch {
1394
+ }
1395
+ }
1396
+ return this.parseApiError(res.status, parsed, text);
1397
+ }
1398
+ };
1399
+ var Subscriptions = class {
1400
+ constructor(client) {
1401
+ this.client = client;
1402
+ }
1403
+ client;
1404
+ /**
1405
+ * Start a Stripe Checkout session for the supplied price. Returns the
1406
+ * hosted Checkout URL; redirect the user to it. Stripe's
1407
+ * `checkout.session.completed` webhook grants credits on success.
1408
+ */
1409
+ subscribe(body) {
1410
+ return this.client.createCheckoutSession(body);
1411
+ }
1412
+ /**
1413
+ * Open the Stripe Billing Portal for the calling user's org. Returns the
1414
+ * hosted portal URL — redirect the user there for subscription /
1415
+ * payment-method management.
1416
+ */
1417
+ manage() {
1418
+ return this.client.createPortalSession();
1419
+ }
1420
+ /** Recent credit-ledger entries (most recent 200). */
1421
+ getLedger() {
1422
+ return this.client.getLedger();
1423
+ }
1424
+ };
1425
+ var DelegatedKeys = class {
1426
+ constructor(client) {
1427
+ this.client = client;
1428
+ }
1429
+ client;
1430
+ /** List the caller's delegated keys, optionally filtered by contract or active flag. */
1431
+ list(query) {
1432
+ return this.client.listDelegatedKeys(query);
1433
+ }
1434
+ /**
1435
+ * One-call delegated-key provisioning: prepare → owner-sign → submit →
1436
+ * poll until the on-chain `addSigningKey` tx confirms (or the polling
1437
+ * budget elapses). The server mints the delegated key in Vault; the caller
1438
+ * never sees its private key.
1439
+ *
1440
+ * Failure modes that surface as thrown {@link WitniumchainApiError}:
1441
+ * - 409 from prepare → an active key already exists for this contract;
1442
+ * caller must revoke the existing one first.
1443
+ * - 400 from submit → ownerSignature didn't verify against the prepared
1444
+ * message (wrong owner key, or the on-chain nonce shifted between
1445
+ * prepare and submit and the caller must re-provision).
1446
+ *
1447
+ * Returns `confirmed: false` (without throwing) when the on-chain tx is
1448
+ * still pending after `pollTimeoutMs` — caller can keep polling via
1449
+ * {@link list} or chain-api's receipt endpoint.
1450
+ */
1451
+ async provision(args) {
1452
+ const prep = await this.client.prepareDelegatedKey({
1453
+ contractAddress: args.contractAddress
1454
+ });
1455
+ const ownerSignature = await args.ownerSigner.sign(prep.messageToSign);
1456
+ let res = await this.client.submitDelegatedKey(prep.id, { ownerSignature });
1457
+ if (!res.confirmed) {
1458
+ const interval = args.pollIntervalMs ?? 2e3;
1459
+ const timeout = args.pollTimeoutMs ?? 6e4;
1460
+ const deadline = Date.now() + timeout;
1461
+ while (!res.confirmed && Date.now() < deadline) {
1462
+ await sleep(interval);
1463
+ res = await this.client.submitDelegatedKey(prep.id, {});
1464
+ }
1465
+ }
1466
+ return {
1467
+ id: prep.id,
1468
+ publicKey: prep.publicKey,
1469
+ transactionHash: res.transactionHash,
1470
+ confirmed: res.confirmed,
1471
+ blockNumber: res.blockNumber
1472
+ };
1473
+ }
1474
+ /**
1475
+ * Locally revoke a delegated key. Wipes the Vault Transit key and sets
1476
+ * `revoked_at` on the row. The on-chain trust record persists — the caller
1477
+ * must invoke `WitnessRegistryV3.revokeSigningKey` with their owner key to
1478
+ * fully un-trust the key on the contract.
1479
+ */
1480
+ revoke(id) {
1481
+ return this.client.revokeDelegatedKey(id);
1482
+ }
1483
+ };
1484
+ var SigningKeys = class {
1485
+ constructor(client) {
1486
+ this.client = client;
1487
+ }
1488
+ client;
1489
+ /**
1490
+ * The signing keys attached to the calling user's contract. There is no
1491
+ * dedicated list endpoint; this method calls {@link
1492
+ * WitniumchainClient.getAccount} and returns the `signingKeys` slice.
1493
+ */
1494
+ async list() {
1495
+ const account = await this.client.getAccount();
1496
+ return account.signingKeys;
1497
+ }
1498
+ add(body) {
1499
+ return this.client.addSigningKey(body);
1500
+ }
1501
+ revoke(body) {
1502
+ return this.client.revokeSigningKey(body);
1503
+ }
1504
+ };
1505
+ var OauthNamespace = class {
1506
+ sessions;
1507
+ constructor(client) {
1508
+ this.sessions = new OauthSessions(client);
1509
+ }
1510
+ };
1511
+ var OauthSessions = class {
1512
+ constructor(client) {
1513
+ this.client = client;
1514
+ }
1515
+ client;
1516
+ list() {
1517
+ return this.client.listOauthSessions();
1518
+ }
1519
+ revoke(jti) {
1520
+ return this.client.revokeOauthSession(jti);
1521
+ }
1522
+ revokeAll() {
1523
+ return this.client.revokeAllOauthSessions();
1524
+ }
1525
+ };
1526
+ var Enrollment = class {
1527
+ constructor(client) {
1528
+ this.client = client;
1529
+ }
1530
+ client;
1531
+ state() {
1532
+ return this.client.call("GET", "/v1/auth/enrollment", { auth: "Public" });
1533
+ }
1534
+ /** An account from before D16 proves its existing authenticator first (`totpProofRequired`). */
1535
+ proveTotp(code) {
1536
+ return this.client.call("POST", "/v1/auth/enrollment/totp-proof", { auth: "Public", body: { code } });
1537
+ }
1538
+ passkeyOptions() {
1539
+ return this.client.call("POST", "/v1/auth/enrollment/passkey/options", { auth: "Public" });
1540
+ }
1541
+ completeWithPasskey(credential, name) {
1542
+ return this.client.call(
1543
+ "POST",
1544
+ "/v1/auth/enrollment/passkey",
1545
+ { auth: "Public", body: { credential, name } },
1546
+ "session-changed"
1547
+ );
1548
+ }
1549
+ /** 400 when too short or found in a breach; 503 when the breach check is unavailable. */
1550
+ setPassword(password) {
1551
+ return this.client.call("POST", "/v1/auth/enrollment/password", { auth: "Public", body: { password } });
1552
+ }
1553
+ completeWithTotp(code) {
1554
+ return this.client.call("POST", "/v1/auth/enrollment/totp", { auth: "Public", body: { code } }, "session-changed");
1555
+ }
1556
+ };
1557
+ var Recovery = class {
1558
+ constructor(client) {
1559
+ this.client = client;
1560
+ }
1561
+ client;
1562
+ start(email) {
1563
+ return this.client.call("POST", "/v1/auth/recovery/start", { auth: "Public", body: { email } });
1564
+ }
1565
+ /** The emailed link: opens the request (the waiting period starts). */
1566
+ open(token) {
1567
+ return this.client.call("POST", "/v1/auth/recovery/open", { auth: "Public", body: { token } });
1568
+ }
1569
+ status() {
1570
+ return this.client.call("GET", "/v1/auth/recovery", { auth: "Public" });
1571
+ }
1572
+ /** Skips the wait; existing methods stay. Continue with {@link Enrollment}. */
1573
+ useRecoveryCode(recoveryCode) {
1574
+ return this.client.call("POST", "/v1/auth/recovery/code", { auth: "Public", body: { recoveryCode } });
1575
+ }
1576
+ /** After the wait: removes every sign-in method. Continue with {@link Enrollment}. */
1577
+ complete() {
1578
+ return this.client.call("POST", "/v1/auth/recovery/complete", { auth: "Public" }, "session-changed");
1579
+ }
1580
+ /** The cancel link from the notice email. */
1581
+ cancel(token) {
1582
+ return this.client.call("POST", "/v1/auth/recovery/cancel", { auth: "Public", body: { token } });
1583
+ }
1584
+ };
1585
+ var AccountSecurity = class {
1586
+ constructor(client) {
1587
+ this.client = client;
1588
+ }
1589
+ client;
1590
+ get() {
1591
+ return this.client.call("GET", "/v1/account/security", { auth: "SessionCookie" });
1592
+ }
1593
+ stepUpOptions() {
1594
+ return this.client.call("POST", "/v1/account/security/step-up/options", { auth: "SessionCookie" });
1595
+ }
1596
+ stepUp(proof) {
1597
+ return this.client.call("POST", "/v1/account/security/step-up", { auth: "SessionCookie", body: proof });
1598
+ }
1599
+ addPasskeyOptions() {
1600
+ return this.client.call("POST", "/v1/account/security/passkeys/options", { auth: "SessionCookie" });
1601
+ }
1602
+ addPasskey(credential, name) {
1603
+ return this.client.call("POST", "/v1/account/security/passkeys", { auth: "SessionCookie", body: { credential, name } });
1604
+ }
1605
+ renamePasskey(id, name) {
1606
+ return this.client.call("PATCH", `/v1/account/security/passkeys/${encodeURIComponent(id)}`, {
1607
+ auth: "SessionCookie",
1608
+ body: { name }
1609
+ });
1610
+ }
1611
+ removePasskey(id) {
1612
+ return this.client.call("DELETE", `/v1/account/security/passkeys/${encodeURIComponent(id)}`, {
1613
+ auth: "SessionCookie"
1614
+ });
1615
+ }
1616
+ /** Returns the QR secret and a `pendingToken` for {@link confirmPasswordTotp}. */
1617
+ startPasswordTotp(password) {
1618
+ return this.client.call("POST", "/v1/account/security/password-totp", { auth: "SessionCookie", body: { password } });
1619
+ }
1620
+ confirmPasswordTotp(pendingToken, code) {
1621
+ return this.client.call("POST", "/v1/account/security/password-totp/confirm", {
1622
+ auth: "SessionCookie",
1623
+ body: { pendingToken, code }
1624
+ });
1625
+ }
1626
+ removePasswordTotp() {
1627
+ return this.client.call("DELETE", "/v1/account/security/password-totp", { auth: "SessionCookie" });
1628
+ }
1629
+ /** Replaces every recovery code; the new ones are returned once. */
1630
+ regenerateRecoveryCodes() {
1631
+ return this.client.call("POST", "/v1/account/security/recovery-codes", { auth: "SessionCookie" });
1632
+ }
1633
+ };
1634
+ var DashboardKey = class {
1635
+ constructor(client) {
1636
+ this.client = client;
1637
+ }
1638
+ client;
1639
+ get() {
1640
+ return this.client.getDashboardKey();
1641
+ }
1642
+ ensure() {
1643
+ return this.client.ensureDashboardKey();
1644
+ }
1645
+ revoke() {
1646
+ return this.client.revokeDashboardKey();
1647
+ }
1648
+ };
1649
+ var SigningKeyRequests = class {
1650
+ constructor(client) {
1651
+ this.client = client;
1652
+ }
1653
+ client;
1654
+ create(body) {
1655
+ return this.client.createSigningKeyRequest(body);
1656
+ }
1657
+ /** Admins: the org's open requests. Members: their own. */
1658
+ list() {
1659
+ return this.client.listSigningKeyRequests();
1660
+ }
1661
+ /**
1662
+ * Approve with an owner signature over `addSigningKey` of the request's
1663
+ * key. A 502 means the outcome isn't known yet: retry with the same
1664
+ * signature, or list again later.
1665
+ */
1666
+ approve(id, body) {
1667
+ return this.client.approveSigningKeyRequest(id, body);
1668
+ }
1669
+ decline(id) {
1670
+ return this.client.declineSigningKeyRequest(id);
1671
+ }
1672
+ };
1673
+ var OrgContract = class {
1674
+ constructor(client) {
1675
+ this.client = client;
1676
+ }
1677
+ client;
1678
+ pause() {
1679
+ return this.client.pauseOrgContract();
1680
+ }
1681
+ resume() {
1682
+ return this.client.resumeOrgContract();
1683
+ }
1684
+ activity(limit) {
1685
+ return this.client.getContractActivity(limit);
1686
+ }
1687
+ addKey(body) {
1688
+ return this.client.addOrgContractKey(body);
1689
+ }
1690
+ removeKey(publicKey) {
1691
+ return this.client.removeOrgContractKey(publicKey);
1692
+ }
1693
+ };
1694
+ var OrgApiKeys = class {
1695
+ constructor(client) {
1696
+ this.client = client;
1697
+ }
1698
+ client;
1699
+ create(body) {
1700
+ return this.client.createApiKey(body);
1701
+ }
1702
+ list() {
1703
+ return this.client.listApiKeys();
1704
+ }
1705
+ revoke(id) {
1706
+ return this.client.revokeApiKey(id);
1707
+ }
1708
+ };
1709
+ var OrgMembers = class {
1710
+ constructor(client) {
1711
+ this.client = client;
1712
+ }
1713
+ client;
1714
+ /** List the caller's org members (role, suspendedAt, isOwner, keys). */
1715
+ list() {
1716
+ return this.client.listMembers();
1717
+ }
1718
+ /**
1719
+ * Invite a member by email (default role `member`). `inviteEmailSent` says
1720
+ * whether the invitation (with the verify link) was mailed; the token is
1721
+ * never returned. A 502 means the membership was recorded but the mail
1722
+ * failed; retry.
1723
+ */
1724
+ invite(body) {
1725
+ return this.client.inviteMember(body);
1726
+ }
1727
+ /** Suspend a member (reversible). The owner cannot be suspended. */
1728
+ suspend(userId) {
1729
+ return this.client.suspendMember(userId);
1730
+ }
1731
+ /** Lift a member's suspension. */
1732
+ unsuspend(userId) {
1733
+ return this.client.unsuspendMember(userId);
1734
+ }
1735
+ /** Set a member's role. Refuses to demote the owner. */
1736
+ setRole(userId, role) {
1737
+ return this.client.setMemberRole(userId, { role });
1738
+ }
1739
+ /** Remove a member (terminal; revokes their delegated keys). Owner protected. */
1740
+ remove(userId) {
1741
+ return this.client.removeMember(userId);
1742
+ }
1743
+ /**
1744
+ * Re-send the invitation email to a pending member. Returns `{ email }`;
1745
+ * the fresh verify token is mailed, never returned.
1746
+ */
1747
+ resendInvite(userId) {
1748
+ return this.client.resendMemberInvite(userId);
1749
+ }
1750
+ };
1751
+ function redirectUriKey(state) {
1752
+ return `${state}.redirect_uri`;
1753
+ }
1754
+ function sleep(ms) {
1755
+ return new Promise((resolve) => setTimeout(resolve, ms));
1756
+ }
1757
+ function stableStringify(value) {
1758
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1759
+ if (Array.isArray(value)) {
1760
+ return "[" + value.map(stableStringify).join(",") + "]";
1761
+ }
1762
+ const obj = value;
1763
+ const keys = Object.keys(obj).sort();
1764
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}";
1765
+ }
1766
+ async function deriveBodyKey(namespace, contractAddress, body) {
1767
+ const canonical = `${namespace}|${contractAddress.toLowerCase()}|${stableStringify(body)}`;
1768
+ return await sha256Hex(canonical);
1769
+ }
1770
+ async function sha256Hex(input) {
1771
+ const subtle2 = globalThis.crypto?.subtle;
1772
+ if (!subtle2) {
1773
+ throw new Error(
1774
+ "WitniumchainClient: SubtleCrypto is not available. Polyfill `globalThis.crypto.subtle` for SignedRequest auth."
1775
+ );
1776
+ }
1777
+ const data = new TextEncoder().encode(input);
1778
+ const digest = await subtle2.digest("SHA-256", data);
1779
+ const bytes = new Uint8Array(digest);
1780
+ let out = "";
1781
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
1782
+ return out;
1783
+ }
1784
+
1785
+ // src/chain-admin-client.ts
1786
+ var WitniumchainChainAdminClient = class {
1787
+ baseUrl;
1788
+ adminToken;
1789
+ adminTokenProvider;
1790
+ timeout;
1791
+ fetchImpl;
1792
+ constructor(config) {
1793
+ if (!config.baseUrl) {
1794
+ throw new Error("WitniumchainChainAdminClient: baseUrl is required");
1795
+ }
1796
+ if (config.adminToken && config.adminTokenProvider) {
1797
+ throw new Error(
1798
+ "WitniumchainChainAdminClient: pass either adminToken (static) or adminTokenProvider (OAuth), not both"
1799
+ );
1800
+ }
1801
+ if (!config.adminToken && !config.adminTokenProvider) {
1802
+ throw new Error(
1803
+ "WitniumchainChainAdminClient: one of adminToken or adminTokenProvider is required"
1804
+ );
1805
+ }
1806
+ this.baseUrl = config.baseUrl.replace(/\/+$/, "");
1807
+ this.adminToken = config.adminToken;
1808
+ this.adminTokenProvider = config.adminTokenProvider;
1809
+ this.timeout = config.timeout ?? 3e4;
1810
+ this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);
1811
+ }
1812
+ async deployContract(body) {
1813
+ return this.req("POST", "/v5/contracts/deploy", body);
1814
+ }
1815
+ async addSigningKey(contractAddress, body) {
1816
+ return this.req(
1817
+ "POST",
1818
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/keys`,
1819
+ body
1820
+ );
1821
+ }
1822
+ async revokeSigningKey(contractAddress, body) {
1823
+ return this.req(
1824
+ "POST",
1825
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/keys/revoke`,
1826
+ body
1827
+ );
1828
+ }
1829
+ async pauseContract(contractAddress, body) {
1830
+ return this.req(
1831
+ "POST",
1832
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/pause`,
1833
+ body
1834
+ );
1835
+ }
1836
+ async unpauseContract(contractAddress, body) {
1837
+ return this.req(
1838
+ "POST",
1839
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/unpause`,
1840
+ body
1841
+ );
1842
+ }
1843
+ async resolveToken() {
1844
+ if (this.adminTokenProvider) return this.adminTokenProvider();
1845
+ return this.adminToken;
1846
+ }
1847
+ async req(method, path, body) {
1848
+ const token = await this.resolveToken();
1849
+ const controller = new AbortController();
1850
+ const timer = setTimeout(() => controller.abort(), this.timeout);
1851
+ try {
1852
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
1853
+ method,
1854
+ headers: {
1855
+ accept: "application/json",
1856
+ "content-type": "application/json",
1857
+ authorization: `Bearer ${token}`
1858
+ },
1859
+ body: JSON.stringify(body),
1860
+ signal: controller.signal
1861
+ });
1862
+ const text = await response.text();
1863
+ const parsed = text ? safeParse(text) : void 0;
1864
+ if (!response.ok) {
1865
+ throw new WitniumchainApiError({
1866
+ status: response.status,
1867
+ message: parsed?.message ?? `${method} ${path} failed: ${response.status}`,
1868
+ body: parsed
1869
+ });
1870
+ }
1871
+ return parsed;
1872
+ } finally {
1873
+ clearTimeout(timer);
1874
+ }
1875
+ }
1876
+ };
1877
+ function safeParse(text) {
1878
+ try {
1879
+ return JSON.parse(text);
1880
+ } catch {
1881
+ return text;
1882
+ }
1883
+ }
1884
+
1885
+ // src/api-key-client.ts
1886
+ var API_KEY_FORMAT = /^wcak_[0-9a-f]{64}$/;
1887
+ var WitniumchainApiKeyClient = class {
1888
+ inner;
1889
+ constructor(config) {
1890
+ if (!API_KEY_FORMAT.test(config.apiKey)) {
1891
+ throw new Error("WitniumchainApiKeyClient: apiKey must be `wcak_` and 64 lowercase hex");
1892
+ }
1893
+ this.inner = new WitniumchainClient({
1894
+ baseUrl: config.baseUrl,
1895
+ apiKey: config.apiKey,
1896
+ timeout: config.timeout,
1897
+ fetch: config.fetch
1898
+ });
1899
+ }
1900
+ /** The key's organization, contract and signing key. 409 while it is still being added to the contract. */
1901
+ me() {
1902
+ return this.inner.getApiKeySelf();
1903
+ }
1904
+ /** Sign a payload with the key's own signing key (`delegatedKeyId` from {@link me}). */
1905
+ sign(body, requestId) {
1906
+ return this.inner.sign(body, requestId);
1907
+ }
1908
+ /** Propose a witness on the org's contract; reserves one credit. */
1909
+ proposeWitnessV5(contractAddress, body, idempotencyKey) {
1910
+ return this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
1911
+ }
1912
+ /** Submit the signature for an intent this key proposed. */
1913
+ signWitnessV5(contractAddress, intentId, body) {
1914
+ return this.inner.signWitnessV5(contractAddress, intentId, body);
1915
+ }
1916
+ /** Finalize an intent this key proposed; returns the witness id. */
1917
+ finalizeWitnessV5(contractAddress, intentId) {
1918
+ return this.inner.finalizeWitnessV5(contractAddress, intentId);
1919
+ }
1920
+ };
1921
+
1922
+ // src/owner-ops.ts
1923
+ var OWNER_OP = {
1924
+ addSigningKey: 1,
1925
+ revokeSigningKey: 2,
1926
+ pause: 3,
1927
+ unpause: 4
1928
+ };
1929
+ function build(op, contractAddress, nonce, payload = {}) {
1930
+ if (!/^0x[0-9a-fA-F]{40}$/.test(contractAddress)) {
1931
+ throw new Error("contractAddress must be 0x + 40 hex chars");
1932
+ }
1933
+ if (!Number.isInteger(nonce) || nonce < 0) {
1934
+ throw new Error("nonce must be a non-negative integer");
1935
+ }
1936
+ return JSON.stringify({
1937
+ op,
1938
+ contract: contractAddress.toLowerCase(),
1939
+ nonce,
1940
+ ...payload
1941
+ });
1942
+ }
1943
+ function buildPausePayload(args) {
1944
+ return build(OWNER_OP.pause, args.contractAddress, args.nonce);
1945
+ }
1946
+ function buildUnpausePayload(args) {
1947
+ return build(OWNER_OP.unpause, args.contractAddress, args.nonce);
1948
+ }
1949
+ function buildAddSigningKeyPayload(args) {
1950
+ if (!/^[0-9a-fA-F]{64}$/.test(args.newKey)) {
1951
+ throw new Error("newKey must be 64 hex chars (no 0x)");
1952
+ }
1953
+ return build(OWNER_OP.addSigningKey, args.contractAddress, args.nonce, {
1954
+ newKey: args.newKey
1955
+ });
1956
+ }
1957
+ function buildRevokeSigningKeyPayload(args) {
1958
+ if (!/^[0-9a-fA-F]{64}$/.test(args.key)) {
1959
+ throw new Error("key must be 64 hex chars (no 0x)");
1960
+ }
1961
+ return build(OWNER_OP.revokeSigningKey, args.contractAddress, args.nonce, {
1962
+ key: args.key
1963
+ });
1964
+ }
1965
+
1966
+ // src/owner-key-file.ts
1967
+ var OWNER_KEY_FILE_FORMAT = "witnium-owner-key/1";
1968
+ var PKCS8_ED25519_PREFIX = "302e020100300506032b657004220420";
1969
+ var FIELDS = ["format", "scheme", "publicKey", "privateKey", "createdAt"];
1970
+ var HEX64 = /^[0-9a-f]{64}$/;
1971
+ var ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
1972
+ function subtle() {
1973
+ const s = globalThis.crypto?.subtle;
1974
+ if (!s) throw new Error("WebCrypto is not available in this environment");
1975
+ return s;
1976
+ }
1977
+ function hexToBytes(hex) {
1978
+ const out = new Uint8Array(new ArrayBuffer(hex.length / 2));
1979
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
1980
+ return out;
1981
+ }
1982
+ function bytesToHex(bytes) {
1983
+ return Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join("");
1984
+ }
1985
+ function base64UrlToHex(b64url) {
1986
+ const b64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
1987
+ return bytesToHex(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)));
1988
+ }
1989
+ async function importSeed(seedHex, extractable) {
1990
+ return subtle().importKey("pkcs8", hexToBytes(PKCS8_ED25519_PREFIX + seedHex), { name: "Ed25519" }, extractable, ["sign"]);
1991
+ }
1992
+ async function derivePublicKey(seedHex) {
1993
+ const jwk = await subtle().exportKey("jwk", await importSeed(seedHex, true));
1994
+ if (typeof jwk.x !== "string") throw new Error("Could not derive the public key");
1995
+ return base64UrlToHex(jwk.x);
1996
+ }
1997
+ async function generateOwnerKeyFile(now = /* @__PURE__ */ new Date()) {
1998
+ const pair = await subtle().generateKey({ name: "Ed25519" }, true, ["sign", "verify"]);
1999
+ const pkcs8 = bytesToHex(await subtle().exportKey("pkcs8", pair.privateKey));
2000
+ if (!pkcs8.startsWith(PKCS8_ED25519_PREFIX) || pkcs8.length !== PKCS8_ED25519_PREFIX.length + 64) {
2001
+ throw new Error("Unexpected PKCS#8 encoding of the generated key");
2002
+ }
2003
+ return {
2004
+ format: OWNER_KEY_FILE_FORMAT,
2005
+ scheme: "ed25519",
2006
+ publicKey: bytesToHex(await subtle().exportKey("raw", pair.publicKey)),
2007
+ privateKey: pkcs8.slice(PKCS8_ED25519_PREFIX.length),
2008
+ createdAt: now.toISOString()
2009
+ };
2010
+ }
2011
+ function serializeOwnerKeyFile(file) {
2012
+ return `${JSON.stringify(Object.fromEntries(FIELDS.map((f) => [f, file[f]])), null, 2)}
2013
+ `;
2014
+ }
2015
+ function ownerKeyFileName(file) {
2016
+ return `witnium-owner-key-${file.publicKey.slice(0, 8)}.json`;
2017
+ }
2018
+ async function parseOwnerKeyFile(text) {
2019
+ let raw;
2020
+ try {
2021
+ raw = JSON.parse(text);
2022
+ } catch {
2023
+ throw new Error("This is not a Witnium owner key file (not JSON)");
2024
+ }
2025
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
2026
+ throw new Error("This is not a Witnium owner key file");
2027
+ }
2028
+ const obj = raw;
2029
+ if (obj.format !== OWNER_KEY_FILE_FORMAT) throw new Error(`Unknown owner key file format (expected ${OWNER_KEY_FILE_FORMAT})`);
2030
+ const extra = Object.keys(obj).filter((k) => !FIELDS.includes(k));
2031
+ if (extra.length > 0) throw new Error(`Unexpected fields in the owner key file: ${extra.join(", ")}`);
2032
+ if (obj.scheme !== "ed25519") throw new Error("Unsupported owner key scheme");
2033
+ const { publicKey, privateKey, createdAt } = obj;
2034
+ if (typeof publicKey !== "string" || !HEX64.test(publicKey)) throw new Error("The owner key file has an invalid public key");
2035
+ if (typeof privateKey !== "string" || !HEX64.test(privateKey)) throw new Error("The owner key file has an invalid private key");
2036
+ if (typeof createdAt !== "string" || !ISO_UTC.test(createdAt) || new Date(createdAt).toISOString() !== createdAt) {
2037
+ throw new Error("The owner key file has an invalid date");
2038
+ }
2039
+ if (await derivePublicKey(privateKey) !== publicKey) {
2040
+ throw new Error("The owner key file is damaged: its private key doesn't match its public key");
2041
+ }
2042
+ return { format: OWNER_KEY_FILE_FORMAT, scheme: "ed25519", publicKey, privateKey, createdAt };
2043
+ }
2044
+ async function signWithOwnerKeyFile(file, message) {
2045
+ const key = await importSeed(file.privateKey, false);
2046
+ return bytesToHex(await subtle().sign({ name: "Ed25519" }, key, new TextEncoder().encode(message)));
2047
+ }
2048
+ var ownerKeyFile = {
2049
+ generate: generateOwnerKeyFile,
2050
+ serialize: serializeOwnerKeyFile,
2051
+ fileName: ownerKeyFileName,
2052
+ parse: parseOwnerKeyFile,
2053
+ sign: signWithOwnerKeyFile
2054
+ };
2055
+
2056
+ export { AccountSecurity, DashboardKey, DelegatedKeys, Enrollment, OWNER_KEY_FILE_FORMAT, OWNER_OP, OauthNamespace, OauthSessions, OrgApiKeys, OrgContract, OrgMembers, Recovery, SigningKeys, Subscriptions, WitniumchainApiError, WitniumchainApiKeyClient, WitniumchainChainAdminClient, WitniumchainClient, buildAddSigningKeyPayload, buildPausePayload, buildRevokeSigningKeyPayload, buildUnpausePayload, defaultVerifierStorage, generateOwnerKeyFile, ownerKeyFile, ownerKeyFileName, parseOwnerKeyFile, serializeOwnerKeyFile, signWithOwnerKeyFile };
2057
+ //# sourceMappingURL=index.mjs.map
2058
+ //# sourceMappingURL=index.mjs.map