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