@witnium-tech/witniumchain 0.3.0 → 0.5.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 CHANGED
@@ -14,12 +14,103 @@ var WitniumchainApiError = class extends Error {
14
14
  }
15
15
  };
16
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
+
17
69
  // src/client.ts
18
70
  var WitniumchainClient = class {
19
71
  baseUrl;
72
+ chainBaseUrl;
20
73
  cfg;
21
74
  timeout;
22
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
+ // The redirect URI the most recent `beginOAuthLogin` issued, alongside the
98
+ // PKCE verifier. `completeOAuthLogin` reads it back so the token-exchange
99
+ // request matches the original /auth request (RFC 6749 §4.1.3 requires
100
+ // redirect_uri at /token to equal the one at /auth). Keyed by state.
101
+ pendingLogins = /* @__PURE__ */ new Map();
102
+ verifierStorage;
103
+ // Cache of the parsed OIDC discovery document keyed by issuer URL. Saves a
104
+ // round trip on every OAuth call after the first. oidc-provider's discovery
105
+ // doc is static for the life of an issuer; cache is per-client-instance, so
106
+ // it dies with the SDK consumer's lifecycle.
107
+ discoveryCache;
108
+ // Single-flight gate for refresh. When a 401 fans out to N concurrent retries
109
+ // (or the consumer calls refreshAccessToken directly while another refresh
110
+ // is mid-flight), all callers await the same in-flight promise — refresh
111
+ // tokens rotate on use (D10), so a second concurrent refresh would race the
112
+ // first and one of them would 401.
113
+ refreshInFlight;
23
114
  /** Subscriptions / billing helpers. See {@link Subscriptions}. */
24
115
  subscriptions;
25
116
  /** Delegated-key namespace including the one-call {@link DelegatedKeys.provision} flow. */
@@ -28,12 +119,15 @@ var WitniumchainClient = class {
28
119
  keys;
29
120
  /** OAuth session management. Accessed as `client.oauth.sessions.*`. */
30
121
  oauth;
122
+ /** MFA self-management. Accessed as `client.mfa.totp.*` and `client.mfa.recoveryCodes.*`. */
123
+ mfa;
31
124
  constructor(config) {
32
125
  if (!config.baseUrl) {
33
126
  throw new Error("WitniumchainClient: baseUrl is required");
34
127
  }
35
128
  this.cfg = config;
36
129
  this.baseUrl = config.baseUrl.replace(/\/$/, "");
130
+ this.chainBaseUrl = config.chainBaseUrl?.replace(/\/$/, "");
37
131
  this.timeout = config.timeout ?? 3e4;
38
132
  this.fetchImpl = config.fetch ?? globalThis.fetch;
39
133
  if (!this.fetchImpl) {
@@ -41,10 +135,14 @@ var WitniumchainClient = class {
41
135
  "WitniumchainClient: no fetch implementation available. Pass `config.fetch`."
42
136
  );
43
137
  }
138
+ this.accessToken = config.accessToken;
139
+ this.oauthClientId = config.oauthClientId;
140
+ this.verifierStorage = config.verifierStorage;
44
141
  this.subscriptions = new Subscriptions(this);
45
142
  this.delegatedKeys = new DelegatedKeys(this);
46
143
  this.keys = new SigningKeys(this);
47
144
  this.oauth = new OauthNamespace(this);
145
+ this.mfa = new MfaNamespace(this);
48
146
  }
49
147
  /**
50
148
  * Convenience alias for {@link getAccount} — returns the authenticated
@@ -212,8 +310,8 @@ var WitniumchainClient = class {
212
310
  // ────────────────────────────────────────────────────────────────────────
213
311
  // Witnesses (/v1/contracts/{addr}/witnesses/*)
214
312
  // ────────────────────────────────────────────────────────────────────────
215
- proposeWitness(contractAddress, body, idempotencyKey) {
216
- const key = idempotencyKey ?? randomUUID();
313
+ async proposeWitness(contractAddress, body, idempotencyKey) {
314
+ const key = idempotencyKey ?? await deriveBodyKey("v1:propose", contractAddress, body);
217
315
  return this.req(
218
316
  "POST",
219
317
  `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
@@ -234,8 +332,8 @@ var WitniumchainClient = class {
234
332
  { auth: "SignedRequest" }
235
333
  );
236
334
  }
237
- revokeWitness(contractAddress, witnessId, body, idempotencyKey) {
238
- const key = idempotencyKey ?? randomUUID();
335
+ async revokeWitness(contractAddress, witnessId, body, idempotencyKey) {
336
+ const key = idempotencyKey ?? await deriveBodyKey("v1:revoke", contractAddress, { witnessId, body });
239
337
  return this.req(
240
338
  "POST",
241
339
  `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}/revoke`,
@@ -257,12 +355,15 @@ var WitniumchainClient = class {
257
355
  // chain-api with the admin token. Auth is OAuth Bearer; the URL
258
356
  // contract must match the user's bound contract.
259
357
  //
260
- // The propose/revoke methods auto-generate an Idempotency-Key when the
261
- // caller doesn't supply one server side that header is part of the
262
- // billing identity and is required.
358
+ // The propose/revoke methods default Idempotency-Key to a stable hash
359
+ // of the request body so an application-level retry with the same
360
+ // arguments dedupes against the original reservation instead of
361
+ // burning a second credit. Pass an explicit `idempotencyKey` to
362
+ // override (e.g. if you genuinely want two witnesses for the same
363
+ // body).
263
364
  // ────────────────────────────────────────────────────────────────────────
264
- proposeWitnessV5(contractAddress, body, idempotencyKey) {
265
- const key = idempotencyKey ?? randomUUID();
365
+ async proposeWitnessV5(contractAddress, body, idempotencyKey) {
366
+ const key = idempotencyKey ?? await deriveBodyKey("v5:propose", contractAddress, body);
266
367
  return this.req(
267
368
  "POST",
268
369
  `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
@@ -283,8 +384,8 @@ var WitniumchainClient = class {
283
384
  { auth: "BearerJWT" }
284
385
  );
285
386
  }
286
- revokeWitnessV5(contractAddress, witnessId, body, idempotencyKey) {
287
- const key = idempotencyKey ?? randomUUID();
387
+ async revokeWitnessV5(contractAddress, witnessId, body, idempotencyKey) {
388
+ const key = idempotencyKey ?? await deriveBodyKey("v5:revoke", contractAddress, { witnessId, body });
288
389
  return this.req(
289
390
  "POST",
290
391
  `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}/revoke`,
@@ -301,6 +402,37 @@ var WitniumchainClient = class {
301
402
  return this.req("GET", "/v1/account/ledger", { auth: "SessionCookie" });
302
403
  }
303
404
  // ────────────────────────────────────────────────────────────────────────
405
+ // MFA (/v1/account/mfa/*)
406
+ //
407
+ // SessionCookie auth (self-management). Returns the same shapes the
408
+ // dashboard renders directly; the SDK is also a viable consumer for any
409
+ // Node-side tooling that needs to programmatically enrol a service account.
410
+ //
411
+ // The MFA challenge step that runs inside the OAuth interaction (Thread E)
412
+ // is NOT here — it's a server-rendered HTML form, not a JSON surface.
413
+ // ────────────────────────────────────────────────────────────────────────
414
+ enrollTotp() {
415
+ return this.req("POST", "/v1/account/mfa/totp/enroll", {
416
+ auth: "SessionCookie"
417
+ });
418
+ }
419
+ confirmTotp(body) {
420
+ return this.req("POST", "/v1/account/mfa/totp/confirm", {
421
+ auth: "SessionCookie",
422
+ body
423
+ });
424
+ }
425
+ disableTotp() {
426
+ return this.req("DELETE", "/v1/account/mfa/totp", {
427
+ auth: "SessionCookie"
428
+ });
429
+ }
430
+ regenerateRecoveryCodes() {
431
+ return this.req("POST", "/v1/account/mfa/recovery-codes/regenerate", {
432
+ auth: "SessionCookie"
433
+ });
434
+ }
435
+ // ────────────────────────────────────────────────────────────────────────
304
436
  // OAuth sessions (/v1/oauth/sessions*)
305
437
  // ────────────────────────────────────────────────────────────────────────
306
438
  listOauthSessions() {
@@ -327,12 +459,408 @@ var WitniumchainClient = class {
327
459
  healthReady() {
328
460
  return this.req("GET", "/health/ready", { auth: "Public" });
329
461
  }
462
+ // ════════════════════════════════════════════════════════════════════════
463
+ // Chain-api reads (called against chainBaseUrl, e.g. api.witniumchain.com)
464
+ //
465
+ // Routing: every method here passes `service: 'chain'` to `req()`. Calls
466
+ // throw at call time if `chainBaseUrl` wasn't configured.
467
+ //
468
+ // Auth: BearerJWT. The accounts-issued OAuth access token already carries
469
+ // `aud=https://api.witniumchain.com`, so the same `accessToken` works
470
+ // unchanged against both services.
471
+ //
472
+ // What's NOT here: chain-api v5 WRITES (propose/sign/finalize/revoke). Those
473
+ // are proxied by accounts (proposeWitnessV5, etc.) so credits get reserved
474
+ // and idempotency is enforced. See docs/PLAN-PHASE-SDK-UNIFIED.md for the
475
+ // routing rules; calling chain-api writes directly would burn credits
476
+ // without billing them.
477
+ // ════════════════════════════════════════════════════════════════════════
478
+ getContractInfo(contractAddress) {
479
+ return this.req(
480
+ "GET",
481
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/info`,
482
+ { auth: "BearerJWT", service: "chain" }
483
+ );
484
+ }
485
+ getContractVerification(contractAddress) {
486
+ return this.req(
487
+ "GET",
488
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/verify`,
489
+ { auth: "BearerJWT", service: "chain" }
490
+ );
491
+ }
492
+ listWitnessesV5(contractAddress, params) {
493
+ return this.req(
494
+ "GET",
495
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses`,
496
+ { auth: "BearerJWT", service: "chain", query: params }
497
+ );
498
+ }
499
+ getWitnessV5(contractAddress, witnessId) {
500
+ return this.req(
501
+ "GET",
502
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}`,
503
+ { auth: "BearerJWT", service: "chain" }
504
+ );
505
+ }
506
+ getContractTransaction(contractAddress, txHash) {
507
+ return this.req(
508
+ "GET",
509
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/transactions/${encodeURIComponent(txHash)}`,
510
+ { auth: "BearerJWT", service: "chain" }
511
+ );
512
+ }
513
+ getTransaction(txHash) {
514
+ return this.req(
515
+ "GET",
516
+ `/v5/transactions/${encodeURIComponent(txHash)}`,
517
+ { auth: "BearerJWT", service: "chain" }
518
+ );
519
+ }
520
+ getWalletBalance(address) {
521
+ return this.req(
522
+ "GET",
523
+ `/v5/wallets/${encodeURIComponent(address)}/balance`,
524
+ { auth: "BearerJWT", service: "chain" }
525
+ );
526
+ }
527
+ getDashboardContract() {
528
+ return this.req("GET", "/v5/dashboard/contract", {
529
+ auth: "BearerJWT",
530
+ service: "chain"
531
+ });
532
+ }
533
+ getDashboardWitnesses(params) {
534
+ return this.req("GET", "/v5/dashboard/witnesses", {
535
+ auth: "BearerJWT",
536
+ service: "chain",
537
+ query: params
538
+ });
539
+ }
540
+ // ════════════════════════════════════════════════════════════════════════
541
+ // OAuth 2.1 + PKCE flow helpers (Phase AUTH Thread A)
542
+ //
543
+ // Designed for browser SPAs without a backend ("Sign in with Witnium" for a
544
+ // Lovable customer). The flow:
545
+ //
546
+ // 1. App calls `beginOAuthLogin({ redirectUri })`, gets a URL, redirects.
547
+ // 2. User authenticates at auth.witniumchain.com, server redirects back
548
+ // to the app's redirectUri with `?code=…&state=…`.
549
+ // 3. App calls `completeOAuthLogin(window.location.href)`, gets back an
550
+ // access token. The SDK stashes it in memory; subsequent `BearerJWT`
551
+ // calls use it transparently.
552
+ // 4. When a `BearerJWT` call returns 401 (token expired), `req()` calls
553
+ // `refreshAccessToken` once and retries. Caller never sees the 401.
554
+ //
555
+ // Access tokens live in memory only — never localStorage. They die on tab
556
+ // close; the refresh token (held in memory today, planned to migrate to an
557
+ // HttpOnly cookie set by /token server-side) survives long enough for a
558
+ // silent refresh on the next /completeOAuthLogin or 401-retry. Refresh
559
+ // tokens rotate on every use, so a single-flight gate avoids racing two
560
+ // concurrent refreshes against the same token.
561
+ //
562
+ // Endpoint discovery: the SDK fetches /.well-known/openid-configuration
563
+ // from `baseUrl` once and reuses the parsed result. oidc-provider's paths
564
+ // (/auth, /token, /jwks, etc.) are not hard-coded — if accounts ever moves
565
+ // them, only the discovery doc has to be right.
566
+ // ════════════════════════════════════════════════════════════════════════
567
+ /**
568
+ * Build the authorization-server URL for the start of an OAuth login flow.
569
+ *
570
+ * Generates a fresh PKCE verifier + challenge, stashes the verifier in the
571
+ * configured {@link PkceVerifierStorage} under the `state` key, and returns
572
+ * the URL the caller should redirect the user to. Side-effects:
573
+ *
574
+ * - sessionStorage gets a PKCE entry under `witniumchain.pkce.<state>`.
575
+ * - The client instance remembers the `redirectUri` for this `state`
576
+ * so {@link completeOAuthLogin} can rebuild the matching token request
577
+ * without the caller threading the URI through twice.
578
+ *
579
+ * The caller is responsible for the redirect itself
580
+ * (`window.location.assign(result.authorizationUrl)`); the SDK doesn't
581
+ * touch `window` directly so SSR + non-browser callers are not broken.
582
+ */
583
+ async beginOAuthLogin(args) {
584
+ if (!this.oauthClientId) {
585
+ throw new WitniumchainApiError({
586
+ status: 0,
587
+ message: "WitniumchainClient: beginOAuthLogin requires `oauthClientId` to be set on the constructor."
588
+ });
589
+ }
590
+ const discovery = await this.fetchDiscovery();
591
+ const state = args.state ?? generateState();
592
+ const verifier = generateCodeVerifier();
593
+ const challenge = await deriveCodeChallenge(verifier);
594
+ const scope = (args.scope ?? ["openid", "profile", "email"]).join(" ");
595
+ const url = new URL(discovery.authorization_endpoint);
596
+ url.searchParams.set("response_type", "code");
597
+ url.searchParams.set("client_id", this.oauthClientId);
598
+ url.searchParams.set("redirect_uri", args.redirectUri);
599
+ url.searchParams.set("scope", scope);
600
+ url.searchParams.set("state", state);
601
+ url.searchParams.set("code_challenge", challenge);
602
+ url.searchParams.set("code_challenge_method", "S256");
603
+ if (args.prompt) url.searchParams.set("prompt", args.prompt);
604
+ this.verifierStorageOrDefault().set(state, verifier);
605
+ this.pendingLogins.set(state, { redirectUri: args.redirectUri });
606
+ return { authorizationUrl: url.toString(), state };
607
+ }
608
+ /**
609
+ * Exchange an authorization-code callback for an access token.
610
+ *
611
+ * Reads `code` and `state` from the callback URL, validates the state
612
+ * against a stored verifier, exchanges the code at the token endpoint,
613
+ * and stores the access token (and refresh token) in the client's
614
+ * in-memory state. Returns the access token + its expiry for callers
615
+ * who want to display the session or schedule a proactive refresh.
616
+ *
617
+ * Throws (without consuming the verifier) when the callback URL is
618
+ * missing `code` or `state`, or when the state has no matching verifier
619
+ * — the latter happens when the user opens an old/forged callback URL,
620
+ * or when sessionStorage was cleared between authorize and callback.
621
+ *
622
+ * The caller is responsible for stripping `code` and `state` from the
623
+ * browser URL afterwards (`window.history.replaceState`) so a refresh
624
+ * doesn't re-trigger the exchange against an already-consumed code.
625
+ */
626
+ async completeOAuthLogin(callbackUrl) {
627
+ if (!this.oauthClientId) {
628
+ throw new WitniumchainApiError({
629
+ status: 0,
630
+ message: "WitniumchainClient: completeOAuthLogin requires `oauthClientId` to be set on the constructor."
631
+ });
632
+ }
633
+ const url = callbackUrl instanceof URL ? callbackUrl : new URL(callbackUrl);
634
+ const code = url.searchParams.get("code");
635
+ const state = url.searchParams.get("state");
636
+ const error = url.searchParams.get("error");
637
+ if (error) {
638
+ throw new WitniumchainApiError({
639
+ status: 0,
640
+ message: `OAuth authorize returned error: ${error}${url.searchParams.get("error_description") ? ` (${url.searchParams.get("error_description")})` : ""}`,
641
+ errorLabel: error
642
+ });
643
+ }
644
+ if (!code || !state) {
645
+ throw new WitniumchainApiError({
646
+ status: 0,
647
+ message: "WitniumchainClient: callbackUrl missing required `code` and/or `state` parameters."
648
+ });
649
+ }
650
+ const storage = this.verifierStorageOrDefault();
651
+ const verifier = storage.get(state);
652
+ if (!verifier) {
653
+ throw new WitniumchainApiError({
654
+ status: 0,
655
+ 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."
656
+ });
657
+ }
658
+ const pending = this.pendingLogins.get(state);
659
+ if (!pending) {
660
+ storage.remove(state);
661
+ throw new WitniumchainApiError({
662
+ status: 0,
663
+ message: "WitniumchainClient: PKCE verifier exists but the redirectUri for this `state` was not found in client memory (the client instance was replaced between beginOAuthLogin and completeOAuthLogin)."
664
+ });
665
+ }
666
+ const discovery = await this.fetchDiscovery();
667
+ const form = new URLSearchParams();
668
+ form.set("grant_type", "authorization_code");
669
+ form.set("code", code);
670
+ form.set("redirect_uri", pending.redirectUri);
671
+ form.set("client_id", this.oauthClientId);
672
+ form.set("code_verifier", verifier);
673
+ const tokens = await this.postTokenEndpoint(discovery.token_endpoint, form);
674
+ storage.remove(state);
675
+ this.pendingLogins.delete(state);
676
+ return this.persistTokenResponse(tokens);
677
+ }
678
+ /**
679
+ * Refresh the access token. Sends `grant_type=refresh_token` to the token
680
+ * endpoint with the in-memory refresh token, and updates `accessToken`
681
+ * (and the rotated refresh token) on success.
682
+ *
683
+ * Concurrent callers — including the 401-retry interceptor inside `req()`
684
+ * fanning out N parallel calls — share a single in-flight refresh promise:
685
+ * refresh tokens rotate on use, so issuing two concurrent refreshes would
686
+ * race and one would 401 with `invalid_grant`.
687
+ *
688
+ * Throws `WitniumchainApiError` if the refresh token is missing (the SDK
689
+ * was constructed without one and `completeOAuthLogin` was never called)
690
+ * or if the AS rejects the refresh (token revoked / expired). On rejection
691
+ * the in-memory tokens are cleared so subsequent BearerJWT calls fail fast
692
+ * instead of retrying with a now-invalid token.
693
+ */
694
+ async refreshAccessToken() {
695
+ if (this.refreshInFlight) return this.refreshInFlight;
696
+ this.refreshInFlight = (async () => {
697
+ try {
698
+ return await this.refreshAccessTokenInternal();
699
+ } finally {
700
+ this.refreshInFlight = void 0;
701
+ }
702
+ })();
703
+ return this.refreshInFlight;
704
+ }
705
+ /**
706
+ * End the OAuth session.
707
+ *
708
+ * Clears the in-memory access + refresh tokens. Best-effort revocation of
709
+ * the server-side session would require a server endpoint that accepts a
710
+ * Bearer-token-authenticated DELETE (today's `/v1/oauth/sessions` requires
711
+ * the first-party `wac_session` cookie, see oauth-sessions.controller.ts).
712
+ * That endpoint will arrive with Phase AUTH Thread E; until then,
713
+ * `signOut` clears local state only and the access token's natural TTL
714
+ * (currently 60 min) bounds residual risk if the refresh token is also
715
+ * dropped — which it is, here.
716
+ */
717
+ signOut() {
718
+ this.accessToken = void 0;
719
+ this.refreshToken = void 0;
720
+ this.hasRefreshCookie = false;
721
+ this.pendingLogins.clear();
722
+ }
723
+ // ────────────────────────────────────────────────────────────────────────
724
+ // Internal: OAuth flow helpers
725
+ // ────────────────────────────────────────────────────────────────────────
726
+ verifierStorageOrDefault() {
727
+ if (this.verifierStorage) return this.verifierStorage;
728
+ return defaultVerifierStorage();
729
+ }
730
+ async fetchDiscovery() {
731
+ if (this.discoveryCache) return this.discoveryCache;
732
+ this.discoveryCache = (async () => {
733
+ const url = `${this.baseUrl}/.well-known/openid-configuration`;
734
+ let res;
735
+ try {
736
+ res = await this.fetchImpl(url, {
737
+ method: "GET",
738
+ headers: { accept: "application/json" }
739
+ });
740
+ } catch (err) {
741
+ this.discoveryCache = void 0;
742
+ throw new WitniumchainApiError({
743
+ status: 0,
744
+ message: err instanceof Error ? `OIDC discovery fetch failed: ${err.message}` : "OIDC discovery fetch failed"
745
+ });
746
+ }
747
+ if (!res.ok) {
748
+ this.discoveryCache = void 0;
749
+ throw new WitniumchainApiError({
750
+ status: res.status,
751
+ message: `OIDC discovery fetch failed: HTTP ${res.status}`
752
+ });
753
+ }
754
+ const parsed = await res.json();
755
+ if (!parsed.authorization_endpoint || !parsed.token_endpoint) {
756
+ this.discoveryCache = void 0;
757
+ throw new WitniumchainApiError({
758
+ status: 0,
759
+ message: "OIDC discovery doc is missing `authorization_endpoint` or `token_endpoint`."
760
+ });
761
+ }
762
+ return {
763
+ authorization_endpoint: parsed.authorization_endpoint,
764
+ token_endpoint: parsed.token_endpoint,
765
+ issuer: parsed.issuer ?? this.baseUrl
766
+ };
767
+ })();
768
+ return this.discoveryCache;
769
+ }
770
+ async postTokenEndpoint(endpoint, form) {
771
+ const controller = new AbortController();
772
+ const timer = setTimeout(() => controller.abort(), this.timeout);
773
+ let res;
774
+ try {
775
+ res = await this.fetchImpl(endpoint, {
776
+ method: "POST",
777
+ headers: {
778
+ accept: "application/json",
779
+ "content-type": "application/x-www-form-urlencoded"
780
+ },
781
+ body: form.toString(),
782
+ signal: controller.signal,
783
+ // Sends the HttpOnly refresh-token cookie when the server starts
784
+ // setting it (planned server-side change); a no-op until then.
785
+ credentials: "include"
786
+ });
787
+ } catch (err) {
788
+ throw new WitniumchainApiError({
789
+ status: 0,
790
+ message: err instanceof Error ? `Token endpoint fetch failed: ${err.message}` : "Token endpoint fetch failed"
791
+ });
792
+ } finally {
793
+ clearTimeout(timer);
794
+ }
795
+ const text = await res.text();
796
+ let parsed = null;
797
+ if (text.length > 0) {
798
+ try {
799
+ parsed = JSON.parse(text);
800
+ } catch {
801
+ }
802
+ }
803
+ if (!res.ok) {
804
+ throw this.parseApiError(res.status, parsed, text);
805
+ }
806
+ return parsed;
807
+ }
808
+ persistTokenResponse(tokens) {
809
+ if (!tokens.access_token) {
810
+ throw new WitniumchainApiError({
811
+ status: 0,
812
+ message: "Token endpoint response missing `access_token`."
813
+ });
814
+ }
815
+ this.accessToken = tokens.access_token;
816
+ if (tokens.refresh_token) {
817
+ this.refreshToken = tokens.refresh_token;
818
+ } else {
819
+ this.refreshToken = void 0;
820
+ this.hasRefreshCookie = true;
821
+ }
822
+ const ttlSeconds = typeof tokens.expires_in === "number" ? tokens.expires_in : 3600;
823
+ const expiresAt = Math.floor(Date.now() / 1e3) + ttlSeconds;
824
+ return { accessToken: tokens.access_token, expiresAt };
825
+ }
826
+ async refreshAccessTokenInternal() {
827
+ if (!this.oauthClientId) {
828
+ throw new WitniumchainApiError({
829
+ status: 0,
830
+ message: "WitniumchainClient: refreshAccessToken requires `oauthClientId` to be set on the constructor."
831
+ });
832
+ }
833
+ if (!this.refreshToken && !this.hasRefreshCookie) {
834
+ throw new WitniumchainApiError({
835
+ status: 0,
836
+ 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)."
837
+ });
838
+ }
839
+ const discovery = await this.fetchDiscovery();
840
+ const form = new URLSearchParams();
841
+ form.set("grant_type", "refresh_token");
842
+ form.set("client_id", this.oauthClientId);
843
+ if (this.refreshToken) {
844
+ form.set("refresh_token", this.refreshToken);
845
+ }
846
+ try {
847
+ const tokens = await this.postTokenEndpoint(discovery.token_endpoint, form);
848
+ return this.persistTokenResponse(tokens);
849
+ } catch (err) {
850
+ this.accessToken = void 0;
851
+ this.refreshToken = void 0;
852
+ this.hasRefreshCookie = false;
853
+ throw err;
854
+ }
855
+ }
330
856
  // ────────────────────────────────────────────────────────────────────────
331
857
  // Internal: fetch wrapper that maps non-2xx → WitniumchainApiError
332
858
  // and applies the configured credential to the request.
333
859
  // ────────────────────────────────────────────────────────────────────────
334
860
  async req(method, path, opts) {
335
- const url = this.buildUrl(path, opts.query);
861
+ const pathWithQuery = this.buildPathWithQuery(path, opts.query);
862
+ const base = this.resolveBaseUrl(opts.service);
863
+ const url = `${base}${pathWithQuery}`;
336
864
  const headers = {
337
865
  accept: "application/json",
338
866
  ...opts.headers ?? {}
@@ -341,7 +869,13 @@ var WitniumchainClient = class {
341
869
  headers["content-type"] = "application/json";
342
870
  }
343
871
  const bodyString = opts.body !== void 0 ? JSON.stringify(opts.body) : void 0;
344
- await this.applyAuth(headers, opts.auth, method, path, bodyString ?? "");
872
+ await this.applyAuth(
873
+ headers,
874
+ opts.auth,
875
+ method,
876
+ pathWithQuery,
877
+ bodyString ?? ""
878
+ );
345
879
  const controller = new AbortController();
346
880
  const timer = setTimeout(() => controller.abort(), this.timeout);
347
881
  let res;
@@ -358,13 +892,16 @@ var WitniumchainClient = class {
358
892
  } catch (err) {
359
893
  throw new WitniumchainApiError({
360
894
  status: 0,
361
- message: err instanceof Error ? `Network error contacting ${this.baseUrl}: ${err.message}` : `Network error contacting ${this.baseUrl}`
895
+ message: err instanceof Error ? `Network error contacting ${base}: ${err.message}` : `Network error contacting ${base}`
362
896
  });
363
897
  } finally {
364
898
  clearTimeout(timer);
365
899
  }
366
900
  if (opts.expectNoContent) {
367
901
  if (!res.ok) {
902
+ if (await this.shouldRefreshAndRetry(res, opts)) {
903
+ return this.req(method, path, { ...opts, _isRetry: true });
904
+ }
368
905
  throw await this.toApiError(res);
369
906
  }
370
907
  return void 0;
@@ -378,18 +915,93 @@ var WitniumchainClient = class {
378
915
  }
379
916
  }
380
917
  if (!res.ok) {
918
+ if (await this.shouldRefreshAndRetryParsed(res.status, parsed, opts)) {
919
+ return this.req(method, path, { ...opts, _isRetry: true });
920
+ }
381
921
  throw this.parseApiError(res.status, parsed, text);
382
922
  }
383
923
  return parsed;
384
924
  }
385
- buildUrl(path, query) {
386
- if (!query) return `${this.baseUrl}${path}`;
925
+ /**
926
+ * Decide whether a non-2xx response on a `BearerJWT` route should trigger
927
+ * a refresh + single retry. Returns false (no retry) when:
928
+ *
929
+ * - this call IS the retry — never recurse,
930
+ * - the auth mode isn't BearerJWT — refresh only helps Bearer tokens,
931
+ * - the status isn't 401 — refresh doesn't unstick 403/404/500/etc,
932
+ * - we don't have a refresh token in memory — nothing to refresh with,
933
+ * - the response body doesn't look like an expired-token signal.
934
+ *
935
+ * On a positive answer, the method ALSO performs the refresh in-line:
936
+ * the caller just gets back `true` and replays the original request,
937
+ * which picks up the freshly-rotated `accessToken` via `applyAuth`.
938
+ * Refresh failures are swallowed here (the caller falls through to the
939
+ * regular error path); `refreshAccessTokenInternal` already cleared the
940
+ * in-memory tokens so the retry won't have anything to send.
941
+ */
942
+ async shouldRefreshAndRetry(res, opts) {
943
+ if (opts._isRetry) return false;
944
+ if (opts.auth !== "BearerJWT") return false;
945
+ if (res.status !== 401) return false;
946
+ if (!this.refreshToken && !this.hasRefreshCookie) return false;
947
+ try {
948
+ await this.refreshAccessToken();
949
+ return true;
950
+ } catch {
951
+ return false;
952
+ }
953
+ }
954
+ /**
955
+ * Same decision as `shouldRefreshAndRetry` but for the JSON-parsed path,
956
+ * where we have the body. Adds one extra gate: only retry when the parsed
957
+ * body looks like a "token expired" signal (`error: 'token_expired'` per
958
+ * the AUTH plan, or `error: 'invalid_token'` per RFC 6750 §3.1). A 401
959
+ * with any other `error` label is a real authn/authz failure that refresh
960
+ * won't fix — surface it instead of burning a refresh token.
961
+ */
962
+ async shouldRefreshAndRetryParsed(status, parsed, opts) {
963
+ if (opts._isRetry) return false;
964
+ if (opts.auth !== "BearerJWT") return false;
965
+ if (status !== 401) return false;
966
+ if (!this.refreshToken && !this.hasRefreshCookie) return false;
967
+ const body = parsed;
968
+ const label = typeof body?.error === "string" ? body.error : void 0;
969
+ if (label !== void 0 && label !== "token_expired" && label !== "invalid_token") {
970
+ return false;
971
+ }
972
+ try {
973
+ await this.refreshAccessToken();
974
+ return true;
975
+ } catch {
976
+ return false;
977
+ }
978
+ }
979
+ /**
980
+ * Resolve which base URL to call. Default is accounts (`baseUrl`). When a
981
+ * method opts into 'chain', `chainBaseUrl` must be configured — throw at call
982
+ * time with a clear message rather than fall back silently to accounts (no
983
+ * defaults: a wrong base URL is a real bug and would mask itself as a 404).
984
+ */
985
+ resolveBaseUrl(service) {
986
+ if (service === "chain") {
987
+ if (!this.chainBaseUrl) {
988
+ throw new WitniumchainApiError({
989
+ status: 0,
990
+ 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.'
991
+ });
992
+ }
993
+ return this.chainBaseUrl;
994
+ }
995
+ return this.baseUrl;
996
+ }
997
+ buildPathWithQuery(path, query) {
998
+ if (!query) return path;
387
999
  const qs = new URLSearchParams();
388
1000
  for (const [k, v] of Object.entries(query)) {
389
1001
  if (v !== void 0) qs.set(k, String(v));
390
1002
  }
391
1003
  const suffix = qs.toString();
392
- return suffix ? `${this.baseUrl}${path}?${suffix}` : `${this.baseUrl}${path}`;
1004
+ return suffix ? `${path}?${suffix}` : path;
393
1005
  }
394
1006
  async applyAuth(headers, auth, method, path, bodyString) {
395
1007
  switch (auth) {
@@ -402,12 +1014,12 @@ var WitniumchainClient = class {
402
1014
  return;
403
1015
  }
404
1016
  case "BearerJWT": {
405
- if (!this.cfg.accessToken) {
1017
+ if (!this.accessToken) {
406
1018
  throw new Error(
407
- `WitniumchainClient: ${method} ${path} requires an OAuth access token. Pass \`accessToken\` to the constructor.`
1019
+ `WitniumchainClient: ${method} ${path} requires an OAuth access token. Pass \`accessToken\` to the constructor, or call \`beginOAuthLogin\`/\`completeOAuthLogin\` to obtain one.`
408
1020
  );
409
1021
  }
410
- headers["authorization"] = `Bearer ${this.cfg.accessToken}`;
1022
+ headers["authorization"] = `Bearer ${this.accessToken}`;
411
1023
  return;
412
1024
  }
413
1025
  case "OrgApiKey": {
@@ -599,17 +1211,71 @@ var OauthSessions = class {
599
1211
  return this.client.revokeAllOauthSessions();
600
1212
  }
601
1213
  };
1214
+ var MfaNamespace = class {
1215
+ totp;
1216
+ recoveryCodes;
1217
+ constructor(client) {
1218
+ this.totp = new MfaTotp(client);
1219
+ this.recoveryCodes = new MfaRecoveryCodes(client);
1220
+ }
1221
+ };
1222
+ var MfaTotp = class {
1223
+ constructor(client) {
1224
+ this.client = client;
1225
+ }
1226
+ client;
1227
+ /**
1228
+ * Start enrolment. Returns the secret + otpauth URL — render the URL as a
1229
+ * QR code in your dashboard (any QR library will do; the SDK doesn't bundle
1230
+ * one). The enrolment is NOT yet a usable second factor: call
1231
+ * {@link confirm} with the first 6-digit code from the authenticator app
1232
+ * to activate it AND receive the recovery codes.
1233
+ */
1234
+ enroll() {
1235
+ return this.client.enrollTotp();
1236
+ }
1237
+ /**
1238
+ * Confirm enrolment with the first user-supplied code. Returns the 10
1239
+ * single-use recovery codes — show them to the user ONCE; the server never
1240
+ * returns them again. Throws `WitniumchainApiError` with status 400 when
1241
+ * the code is invalid or the enrolment is already confirmed.
1242
+ */
1243
+ confirm(code) {
1244
+ return this.client.confirmTotp({ code });
1245
+ }
1246
+ /** Disable TOTP, wiping both the secret and all recovery codes. */
1247
+ disable() {
1248
+ return this.client.disableTotp();
1249
+ }
1250
+ };
1251
+ var MfaRecoveryCodes = class {
1252
+ constructor(client) {
1253
+ this.client = client;
1254
+ }
1255
+ client;
1256
+ /**
1257
+ * Issue a fresh set of 10 recovery codes, invalidating the prior ones.
1258
+ * Same as `confirm` — codes are returned ONCE and never readable again.
1259
+ */
1260
+ regenerate() {
1261
+ return this.client.regenerateRecoveryCodes();
1262
+ }
1263
+ };
602
1264
  function sleep(ms) {
603
1265
  return new Promise((resolve) => setTimeout(resolve, ms));
604
1266
  }
605
- function randomUUID() {
606
- const c = globalThis.crypto;
607
- if (!c?.randomUUID) {
608
- throw new Error(
609
- "WitniumchainClient: globalThis.crypto.randomUUID is required (Node 19+ or modern browser). Polyfill for older runtimes."
610
- );
611
- }
612
- return c.randomUUID();
1267
+ function stableStringify(value) {
1268
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1269
+ if (Array.isArray(value)) {
1270
+ return "[" + value.map(stableStringify).join(",") + "]";
1271
+ }
1272
+ const obj = value;
1273
+ const keys = Object.keys(obj).sort();
1274
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}";
1275
+ }
1276
+ async function deriveBodyKey(namespace, contractAddress, body) {
1277
+ const canonical = `${namespace}|${contractAddress.toLowerCase()}|${stableStringify(body)}`;
1278
+ return await sha256Hex(canonical);
613
1279
  }
614
1280
  async function sha256Hex(input) {
615
1281
  const subtle = globalThis.crypto?.subtle;
@@ -727,6 +1393,9 @@ var OrgUsers = class {
727
1393
  };
728
1394
 
729
1395
  exports.DelegatedKeys = DelegatedKeys;
1396
+ exports.MfaNamespace = MfaNamespace;
1397
+ exports.MfaRecoveryCodes = MfaRecoveryCodes;
1398
+ exports.MfaTotp = MfaTotp;
730
1399
  exports.OauthNamespace = OauthNamespace;
731
1400
  exports.OauthSessions = OauthSessions;
732
1401
  exports.OrgUsers = OrgUsers;
@@ -736,5 +1405,6 @@ exports.WitniumchainAdminClient = WitniumchainAdminClient;
736
1405
  exports.WitniumchainApiError = WitniumchainApiError;
737
1406
  exports.WitniumchainClient = WitniumchainClient;
738
1407
  exports.WitniumchainOrgClient = WitniumchainOrgClient;
1408
+ exports.defaultVerifierStorage = defaultVerifierStorage;
739
1409
  //# sourceMappingURL=index.js.map
740
1410
  //# sourceMappingURL=index.js.map