@witnium-tech/witniumchain 0.3.0 → 0.6.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
@@ -59,6 +157,19 @@ var WitniumchainClient = class {
59
157
  signup(body) {
60
158
  return this.req("POST", "/v1/auth/signup", { auth: "Public", body });
61
159
  }
160
+ /**
161
+ * Self-serve org creation (Phase RBAC Thread D). One public call that
162
+ * creates the admin user, the org, the org-admin membership, and deploys
163
+ * the contract with the caller's client-generated `ownerPublicKey` +
164
+ * `initialSigningPublicKey`. Witnium never sees the private bytes.
165
+ *
166
+ * Returns `{ orgId, userId, contractAddress, contractVersion,
167
+ * emailVerifyToken }`. The verify token is also emailed; it's echoed here
168
+ * for UIs that prefer to render the verify link themselves.
169
+ */
170
+ createOrg(body) {
171
+ return this.req("POST", "/v1/orgs", { auth: "Public", body });
172
+ }
62
173
  verifyEmail(token) {
63
174
  return this.req("GET", "/v1/auth/verify", {
64
175
  auth: "Public",
@@ -212,8 +323,8 @@ var WitniumchainClient = class {
212
323
  // ────────────────────────────────────────────────────────────────────────
213
324
  // Witnesses (/v1/contracts/{addr}/witnesses/*)
214
325
  // ────────────────────────────────────────────────────────────────────────
215
- proposeWitness(contractAddress, body, idempotencyKey) {
216
- const key = idempotencyKey ?? randomUUID();
326
+ async proposeWitness(contractAddress, body, idempotencyKey) {
327
+ const key = idempotencyKey ?? await deriveBodyKey("v1:propose", contractAddress, body);
217
328
  return this.req(
218
329
  "POST",
219
330
  `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
@@ -234,8 +345,8 @@ var WitniumchainClient = class {
234
345
  { auth: "SignedRequest" }
235
346
  );
236
347
  }
237
- revokeWitness(contractAddress, witnessId, body, idempotencyKey) {
238
- const key = idempotencyKey ?? randomUUID();
348
+ async revokeWitness(contractAddress, witnessId, body, idempotencyKey) {
349
+ const key = idempotencyKey ?? await deriveBodyKey("v1:revoke", contractAddress, { witnessId, body });
239
350
  return this.req(
240
351
  "POST",
241
352
  `/v1/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}/revoke`,
@@ -257,12 +368,15 @@ var WitniumchainClient = class {
257
368
  // chain-api with the admin token. Auth is OAuth Bearer; the URL
258
369
  // contract must match the user's bound contract.
259
370
  //
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.
371
+ // The propose/revoke methods default Idempotency-Key to a stable hash
372
+ // of the request body so an application-level retry with the same
373
+ // arguments dedupes against the original reservation instead of
374
+ // burning a second credit. Pass an explicit `idempotencyKey` to
375
+ // override (e.g. if you genuinely want two witnesses for the same
376
+ // body).
263
377
  // ────────────────────────────────────────────────────────────────────────
264
- proposeWitnessV5(contractAddress, body, idempotencyKey) {
265
- const key = idempotencyKey ?? randomUUID();
378
+ async proposeWitnessV5(contractAddress, body, idempotencyKey) {
379
+ const key = idempotencyKey ?? await deriveBodyKey("v5:propose", contractAddress, body);
266
380
  return this.req(
267
381
  "POST",
268
382
  `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
@@ -283,8 +397,8 @@ var WitniumchainClient = class {
283
397
  { auth: "BearerJWT" }
284
398
  );
285
399
  }
286
- revokeWitnessV5(contractAddress, witnessId, body, idempotencyKey) {
287
- const key = idempotencyKey ?? randomUUID();
400
+ async revokeWitnessV5(contractAddress, witnessId, body, idempotencyKey) {
401
+ const key = idempotencyKey ?? await deriveBodyKey("v5:revoke", contractAddress, { witnessId, body });
288
402
  return this.req(
289
403
  "POST",
290
404
  `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}/revoke`,
@@ -301,6 +415,37 @@ var WitniumchainClient = class {
301
415
  return this.req("GET", "/v1/account/ledger", { auth: "SessionCookie" });
302
416
  }
303
417
  // ────────────────────────────────────────────────────────────────────────
418
+ // MFA (/v1/account/mfa/*)
419
+ //
420
+ // SessionCookie auth (self-management). Returns the same shapes the
421
+ // dashboard renders directly; the SDK is also a viable consumer for any
422
+ // Node-side tooling that needs to programmatically enrol a service account.
423
+ //
424
+ // The MFA challenge step that runs inside the OAuth interaction (Thread E)
425
+ // is NOT here — it's a server-rendered HTML form, not a JSON surface.
426
+ // ────────────────────────────────────────────────────────────────────────
427
+ enrollTotp() {
428
+ return this.req("POST", "/v1/account/mfa/totp/enroll", {
429
+ auth: "SessionCookie"
430
+ });
431
+ }
432
+ confirmTotp(body) {
433
+ return this.req("POST", "/v1/account/mfa/totp/confirm", {
434
+ auth: "SessionCookie",
435
+ body
436
+ });
437
+ }
438
+ disableTotp() {
439
+ return this.req("DELETE", "/v1/account/mfa/totp", {
440
+ auth: "SessionCookie"
441
+ });
442
+ }
443
+ regenerateRecoveryCodes() {
444
+ return this.req("POST", "/v1/account/mfa/recovery-codes/regenerate", {
445
+ auth: "SessionCookie"
446
+ });
447
+ }
448
+ // ────────────────────────────────────────────────────────────────────────
304
449
  // OAuth sessions (/v1/oauth/sessions*)
305
450
  // ────────────────────────────────────────────────────────────────────────
306
451
  listOauthSessions() {
@@ -327,12 +472,408 @@ var WitniumchainClient = class {
327
472
  healthReady() {
328
473
  return this.req("GET", "/health/ready", { auth: "Public" });
329
474
  }
475
+ // ════════════════════════════════════════════════════════════════════════
476
+ // Chain-api reads (called against chainBaseUrl, e.g. api.witniumchain.com)
477
+ //
478
+ // Routing: every method here passes `service: 'chain'` to `req()`. Calls
479
+ // throw at call time if `chainBaseUrl` wasn't configured.
480
+ //
481
+ // Auth: BearerJWT. The accounts-issued OAuth access token already carries
482
+ // `aud=https://api.witniumchain.com`, so the same `accessToken` works
483
+ // unchanged against both services.
484
+ //
485
+ // What's NOT here: chain-api v5 WRITES (propose/sign/finalize/revoke). Those
486
+ // are proxied by accounts (proposeWitnessV5, etc.) so credits get reserved
487
+ // and idempotency is enforced. See docs/PLAN-PHASE-SDK-UNIFIED.md for the
488
+ // routing rules; calling chain-api writes directly would burn credits
489
+ // without billing them.
490
+ // ════════════════════════════════════════════════════════════════════════
491
+ getContractInfo(contractAddress) {
492
+ return this.req(
493
+ "GET",
494
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/info`,
495
+ { auth: "BearerJWT", service: "chain" }
496
+ );
497
+ }
498
+ getContractVerification(contractAddress) {
499
+ return this.req(
500
+ "GET",
501
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/verify`,
502
+ { auth: "BearerJWT", service: "chain" }
503
+ );
504
+ }
505
+ listWitnessesV5(contractAddress, params) {
506
+ return this.req(
507
+ "GET",
508
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses`,
509
+ { auth: "BearerJWT", service: "chain", query: params }
510
+ );
511
+ }
512
+ getWitnessV5(contractAddress, witnessId) {
513
+ return this.req(
514
+ "GET",
515
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/${encodeURIComponent(witnessId)}`,
516
+ { auth: "BearerJWT", service: "chain" }
517
+ );
518
+ }
519
+ getContractTransaction(contractAddress, txHash) {
520
+ return this.req(
521
+ "GET",
522
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/transactions/${encodeURIComponent(txHash)}`,
523
+ { auth: "BearerJWT", service: "chain" }
524
+ );
525
+ }
526
+ getTransaction(txHash) {
527
+ return this.req(
528
+ "GET",
529
+ `/v5/transactions/${encodeURIComponent(txHash)}`,
530
+ { auth: "BearerJWT", service: "chain" }
531
+ );
532
+ }
533
+ getWalletBalance(address) {
534
+ return this.req(
535
+ "GET",
536
+ `/v5/wallets/${encodeURIComponent(address)}/balance`,
537
+ { auth: "BearerJWT", service: "chain" }
538
+ );
539
+ }
540
+ getDashboardContract() {
541
+ return this.req("GET", "/v5/dashboard/contract", {
542
+ auth: "BearerJWT",
543
+ service: "chain"
544
+ });
545
+ }
546
+ getDashboardWitnesses(params) {
547
+ return this.req("GET", "/v5/dashboard/witnesses", {
548
+ auth: "BearerJWT",
549
+ service: "chain",
550
+ query: params
551
+ });
552
+ }
553
+ // ════════════════════════════════════════════════════════════════════════
554
+ // OAuth 2.1 + PKCE flow helpers (Phase AUTH Thread A)
555
+ //
556
+ // Designed for browser SPAs without a backend ("Sign in with Witnium" for a
557
+ // Lovable customer). The flow:
558
+ //
559
+ // 1. App calls `beginOAuthLogin({ redirectUri })`, gets a URL, redirects.
560
+ // 2. User authenticates at auth.witniumchain.com, server redirects back
561
+ // to the app's redirectUri with `?code=…&state=…`.
562
+ // 3. App calls `completeOAuthLogin(window.location.href)`, gets back an
563
+ // access token. The SDK stashes it in memory; subsequent `BearerJWT`
564
+ // calls use it transparently.
565
+ // 4. When a `BearerJWT` call returns 401 (token expired), `req()` calls
566
+ // `refreshAccessToken` once and retries. Caller never sees the 401.
567
+ //
568
+ // Access tokens live in memory only — never localStorage. They die on tab
569
+ // close; the refresh token (held in memory today, planned to migrate to an
570
+ // HttpOnly cookie set by /token server-side) survives long enough for a
571
+ // silent refresh on the next /completeOAuthLogin or 401-retry. Refresh
572
+ // tokens rotate on every use, so a single-flight gate avoids racing two
573
+ // concurrent refreshes against the same token.
574
+ //
575
+ // Endpoint discovery: the SDK fetches /.well-known/openid-configuration
576
+ // from `baseUrl` once and reuses the parsed result. oidc-provider's paths
577
+ // (/auth, /token, /jwks, etc.) are not hard-coded — if accounts ever moves
578
+ // them, only the discovery doc has to be right.
579
+ // ════════════════════════════════════════════════════════════════════════
580
+ /**
581
+ * Build the authorization-server URL for the start of an OAuth login flow.
582
+ *
583
+ * Generates a fresh PKCE verifier + challenge, stashes the verifier in the
584
+ * configured {@link PkceVerifierStorage} under the `state` key, and returns
585
+ * the URL the caller should redirect the user to. Side-effects:
586
+ *
587
+ * - sessionStorage gets a PKCE entry under `witniumchain.pkce.<state>`.
588
+ * - The client instance remembers the `redirectUri` for this `state`
589
+ * so {@link completeOAuthLogin} can rebuild the matching token request
590
+ * without the caller threading the URI through twice.
591
+ *
592
+ * The caller is responsible for the redirect itself
593
+ * (`window.location.assign(result.authorizationUrl)`); the SDK doesn't
594
+ * touch `window` directly so SSR + non-browser callers are not broken.
595
+ */
596
+ async beginOAuthLogin(args) {
597
+ if (!this.oauthClientId) {
598
+ throw new WitniumchainApiError({
599
+ status: 0,
600
+ message: "WitniumchainClient: beginOAuthLogin requires `oauthClientId` to be set on the constructor."
601
+ });
602
+ }
603
+ const discovery = await this.fetchDiscovery();
604
+ const state = args.state ?? generateState();
605
+ const verifier = generateCodeVerifier();
606
+ const challenge = await deriveCodeChallenge(verifier);
607
+ const scope = (args.scope ?? ["openid", "profile", "email"]).join(" ");
608
+ const url = new URL(discovery.authorization_endpoint);
609
+ url.searchParams.set("response_type", "code");
610
+ url.searchParams.set("client_id", this.oauthClientId);
611
+ url.searchParams.set("redirect_uri", args.redirectUri);
612
+ url.searchParams.set("scope", scope);
613
+ url.searchParams.set("state", state);
614
+ url.searchParams.set("code_challenge", challenge);
615
+ url.searchParams.set("code_challenge_method", "S256");
616
+ if (args.prompt) url.searchParams.set("prompt", args.prompt);
617
+ this.verifierStorageOrDefault().set(state, verifier);
618
+ this.pendingLogins.set(state, { redirectUri: args.redirectUri });
619
+ return { authorizationUrl: url.toString(), state };
620
+ }
621
+ /**
622
+ * Exchange an authorization-code callback for an access token.
623
+ *
624
+ * Reads `code` and `state` from the callback URL, validates the state
625
+ * against a stored verifier, exchanges the code at the token endpoint,
626
+ * and stores the access token (and refresh token) in the client's
627
+ * in-memory state. Returns the access token + its expiry for callers
628
+ * who want to display the session or schedule a proactive refresh.
629
+ *
630
+ * Throws (without consuming the verifier) when the callback URL is
631
+ * missing `code` or `state`, or when the state has no matching verifier
632
+ * — the latter happens when the user opens an old/forged callback URL,
633
+ * or when sessionStorage was cleared between authorize and callback.
634
+ *
635
+ * The caller is responsible for stripping `code` and `state` from the
636
+ * browser URL afterwards (`window.history.replaceState`) so a refresh
637
+ * doesn't re-trigger the exchange against an already-consumed code.
638
+ */
639
+ async completeOAuthLogin(callbackUrl) {
640
+ if (!this.oauthClientId) {
641
+ throw new WitniumchainApiError({
642
+ status: 0,
643
+ message: "WitniumchainClient: completeOAuthLogin requires `oauthClientId` to be set on the constructor."
644
+ });
645
+ }
646
+ const url = callbackUrl instanceof URL ? callbackUrl : new URL(callbackUrl);
647
+ const code = url.searchParams.get("code");
648
+ const state = url.searchParams.get("state");
649
+ const error = url.searchParams.get("error");
650
+ if (error) {
651
+ throw new WitniumchainApiError({
652
+ status: 0,
653
+ message: `OAuth authorize returned error: ${error}${url.searchParams.get("error_description") ? ` (${url.searchParams.get("error_description")})` : ""}`,
654
+ errorLabel: error
655
+ });
656
+ }
657
+ if (!code || !state) {
658
+ throw new WitniumchainApiError({
659
+ status: 0,
660
+ message: "WitniumchainClient: callbackUrl missing required `code` and/or `state` parameters."
661
+ });
662
+ }
663
+ const storage = this.verifierStorageOrDefault();
664
+ const verifier = storage.get(state);
665
+ if (!verifier) {
666
+ throw new WitniumchainApiError({
667
+ status: 0,
668
+ 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."
669
+ });
670
+ }
671
+ const pending = this.pendingLogins.get(state);
672
+ if (!pending) {
673
+ storage.remove(state);
674
+ throw new WitniumchainApiError({
675
+ status: 0,
676
+ 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)."
677
+ });
678
+ }
679
+ const discovery = await this.fetchDiscovery();
680
+ const form = new URLSearchParams();
681
+ form.set("grant_type", "authorization_code");
682
+ form.set("code", code);
683
+ form.set("redirect_uri", pending.redirectUri);
684
+ form.set("client_id", this.oauthClientId);
685
+ form.set("code_verifier", verifier);
686
+ const tokens = await this.postTokenEndpoint(discovery.token_endpoint, form);
687
+ storage.remove(state);
688
+ this.pendingLogins.delete(state);
689
+ return this.persistTokenResponse(tokens);
690
+ }
691
+ /**
692
+ * Refresh the access token. Sends `grant_type=refresh_token` to the token
693
+ * endpoint with the in-memory refresh token, and updates `accessToken`
694
+ * (and the rotated refresh token) on success.
695
+ *
696
+ * Concurrent callers — including the 401-retry interceptor inside `req()`
697
+ * fanning out N parallel calls — share a single in-flight refresh promise:
698
+ * refresh tokens rotate on use, so issuing two concurrent refreshes would
699
+ * race and one would 401 with `invalid_grant`.
700
+ *
701
+ * Throws `WitniumchainApiError` if the refresh token is missing (the SDK
702
+ * was constructed without one and `completeOAuthLogin` was never called)
703
+ * or if the AS rejects the refresh (token revoked / expired). On rejection
704
+ * the in-memory tokens are cleared so subsequent BearerJWT calls fail fast
705
+ * instead of retrying with a now-invalid token.
706
+ */
707
+ async refreshAccessToken() {
708
+ if (this.refreshInFlight) return this.refreshInFlight;
709
+ this.refreshInFlight = (async () => {
710
+ try {
711
+ return await this.refreshAccessTokenInternal();
712
+ } finally {
713
+ this.refreshInFlight = void 0;
714
+ }
715
+ })();
716
+ return this.refreshInFlight;
717
+ }
718
+ /**
719
+ * End the OAuth session.
720
+ *
721
+ * Clears the in-memory access + refresh tokens. Best-effort revocation of
722
+ * the server-side session would require a server endpoint that accepts a
723
+ * Bearer-token-authenticated DELETE (today's `/v1/oauth/sessions` requires
724
+ * the first-party `wac_session` cookie, see oauth-sessions.controller.ts).
725
+ * That endpoint will arrive with Phase AUTH Thread E; until then,
726
+ * `signOut` clears local state only and the access token's natural TTL
727
+ * (currently 60 min) bounds residual risk if the refresh token is also
728
+ * dropped — which it is, here.
729
+ */
730
+ signOut() {
731
+ this.accessToken = void 0;
732
+ this.refreshToken = void 0;
733
+ this.hasRefreshCookie = false;
734
+ this.pendingLogins.clear();
735
+ }
736
+ // ────────────────────────────────────────────────────────────────────────
737
+ // Internal: OAuth flow helpers
738
+ // ────────────────────────────────────────────────────────────────────────
739
+ verifierStorageOrDefault() {
740
+ if (this.verifierStorage) return this.verifierStorage;
741
+ return defaultVerifierStorage();
742
+ }
743
+ async fetchDiscovery() {
744
+ if (this.discoveryCache) return this.discoveryCache;
745
+ this.discoveryCache = (async () => {
746
+ const url = `${this.baseUrl}/.well-known/openid-configuration`;
747
+ let res;
748
+ try {
749
+ res = await this.fetchImpl(url, {
750
+ method: "GET",
751
+ headers: { accept: "application/json" }
752
+ });
753
+ } catch (err) {
754
+ this.discoveryCache = void 0;
755
+ throw new WitniumchainApiError({
756
+ status: 0,
757
+ message: err instanceof Error ? `OIDC discovery fetch failed: ${err.message}` : "OIDC discovery fetch failed"
758
+ });
759
+ }
760
+ if (!res.ok) {
761
+ this.discoveryCache = void 0;
762
+ throw new WitniumchainApiError({
763
+ status: res.status,
764
+ message: `OIDC discovery fetch failed: HTTP ${res.status}`
765
+ });
766
+ }
767
+ const parsed = await res.json();
768
+ if (!parsed.authorization_endpoint || !parsed.token_endpoint) {
769
+ this.discoveryCache = void 0;
770
+ throw new WitniumchainApiError({
771
+ status: 0,
772
+ message: "OIDC discovery doc is missing `authorization_endpoint` or `token_endpoint`."
773
+ });
774
+ }
775
+ return {
776
+ authorization_endpoint: parsed.authorization_endpoint,
777
+ token_endpoint: parsed.token_endpoint,
778
+ issuer: parsed.issuer ?? this.baseUrl
779
+ };
780
+ })();
781
+ return this.discoveryCache;
782
+ }
783
+ async postTokenEndpoint(endpoint, form) {
784
+ const controller = new AbortController();
785
+ const timer = setTimeout(() => controller.abort(), this.timeout);
786
+ let res;
787
+ try {
788
+ res = await this.fetchImpl(endpoint, {
789
+ method: "POST",
790
+ headers: {
791
+ accept: "application/json",
792
+ "content-type": "application/x-www-form-urlencoded"
793
+ },
794
+ body: form.toString(),
795
+ signal: controller.signal,
796
+ // Sends the HttpOnly refresh-token cookie when the server starts
797
+ // setting it (planned server-side change); a no-op until then.
798
+ credentials: "include"
799
+ });
800
+ } catch (err) {
801
+ throw new WitniumchainApiError({
802
+ status: 0,
803
+ message: err instanceof Error ? `Token endpoint fetch failed: ${err.message}` : "Token endpoint fetch failed"
804
+ });
805
+ } finally {
806
+ clearTimeout(timer);
807
+ }
808
+ const text = await res.text();
809
+ let parsed = null;
810
+ if (text.length > 0) {
811
+ try {
812
+ parsed = JSON.parse(text);
813
+ } catch {
814
+ }
815
+ }
816
+ if (!res.ok) {
817
+ throw this.parseApiError(res.status, parsed, text);
818
+ }
819
+ return parsed;
820
+ }
821
+ persistTokenResponse(tokens) {
822
+ if (!tokens.access_token) {
823
+ throw new WitniumchainApiError({
824
+ status: 0,
825
+ message: "Token endpoint response missing `access_token`."
826
+ });
827
+ }
828
+ this.accessToken = tokens.access_token;
829
+ if (tokens.refresh_token) {
830
+ this.refreshToken = tokens.refresh_token;
831
+ } else {
832
+ this.refreshToken = void 0;
833
+ this.hasRefreshCookie = true;
834
+ }
835
+ const ttlSeconds = typeof tokens.expires_in === "number" ? tokens.expires_in : 3600;
836
+ const expiresAt = Math.floor(Date.now() / 1e3) + ttlSeconds;
837
+ return { accessToken: tokens.access_token, expiresAt };
838
+ }
839
+ async refreshAccessTokenInternal() {
840
+ if (!this.oauthClientId) {
841
+ throw new WitniumchainApiError({
842
+ status: 0,
843
+ message: "WitniumchainClient: refreshAccessToken requires `oauthClientId` to be set on the constructor."
844
+ });
845
+ }
846
+ if (!this.refreshToken && !this.hasRefreshCookie) {
847
+ throw new WitniumchainApiError({
848
+ status: 0,
849
+ 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)."
850
+ });
851
+ }
852
+ const discovery = await this.fetchDiscovery();
853
+ const form = new URLSearchParams();
854
+ form.set("grant_type", "refresh_token");
855
+ form.set("client_id", this.oauthClientId);
856
+ if (this.refreshToken) {
857
+ form.set("refresh_token", this.refreshToken);
858
+ }
859
+ try {
860
+ const tokens = await this.postTokenEndpoint(discovery.token_endpoint, form);
861
+ return this.persistTokenResponse(tokens);
862
+ } catch (err) {
863
+ this.accessToken = void 0;
864
+ this.refreshToken = void 0;
865
+ this.hasRefreshCookie = false;
866
+ throw err;
867
+ }
868
+ }
330
869
  // ────────────────────────────────────────────────────────────────────────
331
870
  // Internal: fetch wrapper that maps non-2xx → WitniumchainApiError
332
871
  // and applies the configured credential to the request.
333
872
  // ────────────────────────────────────────────────────────────────────────
334
873
  async req(method, path, opts) {
335
- const url = this.buildUrl(path, opts.query);
874
+ const pathWithQuery = this.buildPathWithQuery(path, opts.query);
875
+ const base = this.resolveBaseUrl(opts.service);
876
+ const url = `${base}${pathWithQuery}`;
336
877
  const headers = {
337
878
  accept: "application/json",
338
879
  ...opts.headers ?? {}
@@ -341,7 +882,13 @@ var WitniumchainClient = class {
341
882
  headers["content-type"] = "application/json";
342
883
  }
343
884
  const bodyString = opts.body !== void 0 ? JSON.stringify(opts.body) : void 0;
344
- await this.applyAuth(headers, opts.auth, method, path, bodyString ?? "");
885
+ await this.applyAuth(
886
+ headers,
887
+ opts.auth,
888
+ method,
889
+ pathWithQuery,
890
+ bodyString ?? ""
891
+ );
345
892
  const controller = new AbortController();
346
893
  const timer = setTimeout(() => controller.abort(), this.timeout);
347
894
  let res;
@@ -358,13 +905,16 @@ var WitniumchainClient = class {
358
905
  } catch (err) {
359
906
  throw new WitniumchainApiError({
360
907
  status: 0,
361
- message: err instanceof Error ? `Network error contacting ${this.baseUrl}: ${err.message}` : `Network error contacting ${this.baseUrl}`
908
+ message: err instanceof Error ? `Network error contacting ${base}: ${err.message}` : `Network error contacting ${base}`
362
909
  });
363
910
  } finally {
364
911
  clearTimeout(timer);
365
912
  }
366
913
  if (opts.expectNoContent) {
367
914
  if (!res.ok) {
915
+ if (await this.shouldRefreshAndRetry(res, opts)) {
916
+ return this.req(method, path, { ...opts, _isRetry: true });
917
+ }
368
918
  throw await this.toApiError(res);
369
919
  }
370
920
  return void 0;
@@ -378,18 +928,93 @@ var WitniumchainClient = class {
378
928
  }
379
929
  }
380
930
  if (!res.ok) {
931
+ if (await this.shouldRefreshAndRetryParsed(res.status, parsed, opts)) {
932
+ return this.req(method, path, { ...opts, _isRetry: true });
933
+ }
381
934
  throw this.parseApiError(res.status, parsed, text);
382
935
  }
383
936
  return parsed;
384
937
  }
385
- buildUrl(path, query) {
386
- if (!query) return `${this.baseUrl}${path}`;
938
+ /**
939
+ * Decide whether a non-2xx response on a `BearerJWT` route should trigger
940
+ * a refresh + single retry. Returns false (no retry) when:
941
+ *
942
+ * - this call IS the retry — never recurse,
943
+ * - the auth mode isn't BearerJWT — refresh only helps Bearer tokens,
944
+ * - the status isn't 401 — refresh doesn't unstick 403/404/500/etc,
945
+ * - we don't have a refresh token in memory — nothing to refresh with,
946
+ * - the response body doesn't look like an expired-token signal.
947
+ *
948
+ * On a positive answer, the method ALSO performs the refresh in-line:
949
+ * the caller just gets back `true` and replays the original request,
950
+ * which picks up the freshly-rotated `accessToken` via `applyAuth`.
951
+ * Refresh failures are swallowed here (the caller falls through to the
952
+ * regular error path); `refreshAccessTokenInternal` already cleared the
953
+ * in-memory tokens so the retry won't have anything to send.
954
+ */
955
+ async shouldRefreshAndRetry(res, opts) {
956
+ if (opts._isRetry) return false;
957
+ if (opts.auth !== "BearerJWT") return false;
958
+ if (res.status !== 401) return false;
959
+ if (!this.refreshToken && !this.hasRefreshCookie) return false;
960
+ try {
961
+ await this.refreshAccessToken();
962
+ return true;
963
+ } catch {
964
+ return false;
965
+ }
966
+ }
967
+ /**
968
+ * Same decision as `shouldRefreshAndRetry` but for the JSON-parsed path,
969
+ * where we have the body. Adds one extra gate: only retry when the parsed
970
+ * body looks like a "token expired" signal (`error: 'token_expired'` per
971
+ * the AUTH plan, or `error: 'invalid_token'` per RFC 6750 §3.1). A 401
972
+ * with any other `error` label is a real authn/authz failure that refresh
973
+ * won't fix — surface it instead of burning a refresh token.
974
+ */
975
+ async shouldRefreshAndRetryParsed(status, parsed, opts) {
976
+ if (opts._isRetry) return false;
977
+ if (opts.auth !== "BearerJWT") return false;
978
+ if (status !== 401) return false;
979
+ if (!this.refreshToken && !this.hasRefreshCookie) return false;
980
+ const body = parsed;
981
+ const label = typeof body?.error === "string" ? body.error : void 0;
982
+ if (label !== void 0 && label !== "token_expired" && label !== "invalid_token") {
983
+ return false;
984
+ }
985
+ try {
986
+ await this.refreshAccessToken();
987
+ return true;
988
+ } catch {
989
+ return false;
990
+ }
991
+ }
992
+ /**
993
+ * Resolve which base URL to call. Default is accounts (`baseUrl`). When a
994
+ * method opts into 'chain', `chainBaseUrl` must be configured — throw at call
995
+ * time with a clear message rather than fall back silently to accounts (no
996
+ * defaults: a wrong base URL is a real bug and would mask itself as a 404).
997
+ */
998
+ resolveBaseUrl(service) {
999
+ if (service === "chain") {
1000
+ if (!this.chainBaseUrl) {
1001
+ throw new WitniumchainApiError({
1002
+ status: 0,
1003
+ 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.'
1004
+ });
1005
+ }
1006
+ return this.chainBaseUrl;
1007
+ }
1008
+ return this.baseUrl;
1009
+ }
1010
+ buildPathWithQuery(path, query) {
1011
+ if (!query) return path;
387
1012
  const qs = new URLSearchParams();
388
1013
  for (const [k, v] of Object.entries(query)) {
389
1014
  if (v !== void 0) qs.set(k, String(v));
390
1015
  }
391
1016
  const suffix = qs.toString();
392
- return suffix ? `${this.baseUrl}${path}?${suffix}` : `${this.baseUrl}${path}`;
1017
+ return suffix ? `${path}?${suffix}` : path;
393
1018
  }
394
1019
  async applyAuth(headers, auth, method, path, bodyString) {
395
1020
  switch (auth) {
@@ -402,12 +1027,12 @@ var WitniumchainClient = class {
402
1027
  return;
403
1028
  }
404
1029
  case "BearerJWT": {
405
- if (!this.cfg.accessToken) {
1030
+ if (!this.accessToken) {
406
1031
  throw new Error(
407
- `WitniumchainClient: ${method} ${path} requires an OAuth access token. Pass \`accessToken\` to the constructor.`
1032
+ `WitniumchainClient: ${method} ${path} requires an OAuth access token. Pass \`accessToken\` to the constructor, or call \`beginOAuthLogin\`/\`completeOAuthLogin\` to obtain one.`
408
1033
  );
409
1034
  }
410
- headers["authorization"] = `Bearer ${this.cfg.accessToken}`;
1035
+ headers["authorization"] = `Bearer ${this.accessToken}`;
411
1036
  return;
412
1037
  }
413
1038
  case "OrgApiKey": {
@@ -599,17 +1224,71 @@ var OauthSessions = class {
599
1224
  return this.client.revokeAllOauthSessions();
600
1225
  }
601
1226
  };
1227
+ var MfaNamespace = class {
1228
+ totp;
1229
+ recoveryCodes;
1230
+ constructor(client) {
1231
+ this.totp = new MfaTotp(client);
1232
+ this.recoveryCodes = new MfaRecoveryCodes(client);
1233
+ }
1234
+ };
1235
+ var MfaTotp = class {
1236
+ constructor(client) {
1237
+ this.client = client;
1238
+ }
1239
+ client;
1240
+ /**
1241
+ * Start enrolment. Returns the secret + otpauth URL — render the URL as a
1242
+ * QR code in your dashboard (any QR library will do; the SDK doesn't bundle
1243
+ * one). The enrolment is NOT yet a usable second factor: call
1244
+ * {@link confirm} with the first 6-digit code from the authenticator app
1245
+ * to activate it AND receive the recovery codes.
1246
+ */
1247
+ enroll() {
1248
+ return this.client.enrollTotp();
1249
+ }
1250
+ /**
1251
+ * Confirm enrolment with the first user-supplied code. Returns the 10
1252
+ * single-use recovery codes — show them to the user ONCE; the server never
1253
+ * returns them again. Throws `WitniumchainApiError` with status 400 when
1254
+ * the code is invalid or the enrolment is already confirmed.
1255
+ */
1256
+ confirm(code) {
1257
+ return this.client.confirmTotp({ code });
1258
+ }
1259
+ /** Disable TOTP, wiping both the secret and all recovery codes. */
1260
+ disable() {
1261
+ return this.client.disableTotp();
1262
+ }
1263
+ };
1264
+ var MfaRecoveryCodes = class {
1265
+ constructor(client) {
1266
+ this.client = client;
1267
+ }
1268
+ client;
1269
+ /**
1270
+ * Issue a fresh set of 10 recovery codes, invalidating the prior ones.
1271
+ * Same as `confirm` — codes are returned ONCE and never readable again.
1272
+ */
1273
+ regenerate() {
1274
+ return this.client.regenerateRecoveryCodes();
1275
+ }
1276
+ };
602
1277
  function sleep(ms) {
603
1278
  return new Promise((resolve) => setTimeout(resolve, ms));
604
1279
  }
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();
1280
+ function stableStringify(value) {
1281
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1282
+ if (Array.isArray(value)) {
1283
+ return "[" + value.map(stableStringify).join(",") + "]";
1284
+ }
1285
+ const obj = value;
1286
+ const keys = Object.keys(obj).sort();
1287
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}";
1288
+ }
1289
+ async function deriveBodyKey(namespace, contractAddress, body) {
1290
+ const canonical = `${namespace}|${contractAddress.toLowerCase()}|${stableStringify(body)}`;
1291
+ return await sha256Hex(canonical);
613
1292
  }
614
1293
  async function sha256Hex(input) {
615
1294
  const subtle = globalThis.crypto?.subtle;
@@ -680,6 +1359,106 @@ var WitniumchainAdminClient = class {
680
1359
  }
681
1360
  };
682
1361
 
1362
+ // src/chain-admin-client.ts
1363
+ var WitniumchainChainAdminClient = class {
1364
+ baseUrl;
1365
+ adminToken;
1366
+ adminTokenProvider;
1367
+ timeout;
1368
+ fetchImpl;
1369
+ constructor(config) {
1370
+ if (!config.baseUrl) {
1371
+ throw new Error("WitniumchainChainAdminClient: baseUrl is required");
1372
+ }
1373
+ if (config.adminToken && config.adminTokenProvider) {
1374
+ throw new Error(
1375
+ "WitniumchainChainAdminClient: pass either adminToken (static) or adminTokenProvider (OAuth), not both"
1376
+ );
1377
+ }
1378
+ if (!config.adminToken && !config.adminTokenProvider) {
1379
+ throw new Error(
1380
+ "WitniumchainChainAdminClient: one of adminToken or adminTokenProvider is required"
1381
+ );
1382
+ }
1383
+ this.baseUrl = config.baseUrl.replace(/\/+$/, "");
1384
+ this.adminToken = config.adminToken;
1385
+ this.adminTokenProvider = config.adminTokenProvider;
1386
+ this.timeout = config.timeout ?? 3e4;
1387
+ this.fetchImpl = config.fetch ?? globalThis.fetch;
1388
+ }
1389
+ async deployContract(body) {
1390
+ return this.req("POST", "/v5/contracts/deploy", body);
1391
+ }
1392
+ async addSigningKey(contractAddress, body) {
1393
+ return this.req(
1394
+ "POST",
1395
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/keys`,
1396
+ body
1397
+ );
1398
+ }
1399
+ async revokeSigningKey(contractAddress, body) {
1400
+ return this.req(
1401
+ "POST",
1402
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/keys/revoke`,
1403
+ body
1404
+ );
1405
+ }
1406
+ async pauseContract(contractAddress, body) {
1407
+ return this.req(
1408
+ "POST",
1409
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/pause`,
1410
+ body
1411
+ );
1412
+ }
1413
+ async unpauseContract(contractAddress, body) {
1414
+ return this.req(
1415
+ "POST",
1416
+ `/v5/contracts/${encodeURIComponent(contractAddress)}/unpause`,
1417
+ body
1418
+ );
1419
+ }
1420
+ async resolveToken() {
1421
+ if (this.adminTokenProvider) return this.adminTokenProvider();
1422
+ return this.adminToken;
1423
+ }
1424
+ async req(method, path, body) {
1425
+ const token = await this.resolveToken();
1426
+ const controller = new AbortController();
1427
+ const timer = setTimeout(() => controller.abort(), this.timeout);
1428
+ try {
1429
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
1430
+ method,
1431
+ headers: {
1432
+ accept: "application/json",
1433
+ "content-type": "application/json",
1434
+ authorization: `Bearer ${token}`
1435
+ },
1436
+ body: JSON.stringify(body),
1437
+ signal: controller.signal
1438
+ });
1439
+ const text = await response.text();
1440
+ const parsed = text ? safeParse(text) : void 0;
1441
+ if (!response.ok) {
1442
+ throw new WitniumchainApiError({
1443
+ status: response.status,
1444
+ message: parsed?.message ?? `${method} ${path} failed: ${response.status}`,
1445
+ body: parsed
1446
+ });
1447
+ }
1448
+ return parsed;
1449
+ } finally {
1450
+ clearTimeout(timer);
1451
+ }
1452
+ }
1453
+ };
1454
+ function safeParse(text) {
1455
+ try {
1456
+ return JSON.parse(text);
1457
+ } catch {
1458
+ return text;
1459
+ }
1460
+ }
1461
+
683
1462
  // src/org-client.ts
684
1463
  var WitniumchainOrgClient = class {
685
1464
  inner;
@@ -727,6 +1506,9 @@ var OrgUsers = class {
727
1506
  };
728
1507
 
729
1508
  exports.DelegatedKeys = DelegatedKeys;
1509
+ exports.MfaNamespace = MfaNamespace;
1510
+ exports.MfaRecoveryCodes = MfaRecoveryCodes;
1511
+ exports.MfaTotp = MfaTotp;
730
1512
  exports.OauthNamespace = OauthNamespace;
731
1513
  exports.OauthSessions = OauthSessions;
732
1514
  exports.OrgUsers = OrgUsers;
@@ -734,7 +1516,9 @@ exports.SigningKeys = SigningKeys;
734
1516
  exports.Subscriptions = Subscriptions;
735
1517
  exports.WitniumchainAdminClient = WitniumchainAdminClient;
736
1518
  exports.WitniumchainApiError = WitniumchainApiError;
1519
+ exports.WitniumchainChainAdminClient = WitniumchainChainAdminClient;
737
1520
  exports.WitniumchainClient = WitniumchainClient;
738
1521
  exports.WitniumchainOrgClient = WitniumchainOrgClient;
1522
+ exports.defaultVerifierStorage = defaultVerifierStorage;
739
1523
  //# sourceMappingURL=index.js.map
740
1524
  //# sourceMappingURL=index.js.map