@nauth-toolkit/client 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -28,12 +28,15 @@ __export(index_exports, {
28
28
  AuthChallenge: () => AuthChallenge,
29
29
  BrowserStorage: () => BrowserStorage,
30
30
  ChallengeRouter: () => ChallengeRouter,
31
+ DEFAULT_INTERACTION_ROUTE: () => DEFAULT_INTERACTION_ROUTE,
31
32
  EventEmitter: () => EventEmitter,
32
33
  FetchAdapter: () => FetchAdapter,
33
34
  InMemoryStorage: () => InMemoryStorage,
34
35
  NAuthClient: () => NAuthClient,
35
36
  NAuthClientError: () => NAuthClientError,
36
37
  NAuthErrorCode: () => NAuthErrorCode,
38
+ OIDCOperations: () => OIDCOperations,
39
+ PENDING_INTERACTION_KEY: () => PENDING_INTERACTION_KEY,
37
40
  apiKeyHeader: () => apiKeyHeader,
38
41
  defaultAdminEndpoints: () => defaultAdminEndpoints,
39
42
  defaultEndpoints: () => defaultEndpoints,
@@ -109,6 +112,9 @@ var NAuthErrorCode = /* @__PURE__ */ ((NAuthErrorCode2) => {
109
112
  NAuthErrorCode2["PASSWORD_RESET_MAX_ATTEMPTS"] = "PASSWORD_RESET_MAX_ATTEMPTS";
110
113
  NAuthErrorCode2["RATE_LIMIT_PASSWORD_RESET"] = "RATE_LIMIT_PASSWORD_RESET";
111
114
  NAuthErrorCode2["SIGNIN_BLOCKED_HIGH_RISK"] = "SIGNIN_BLOCKED_HIGH_RISK";
115
+ NAuthErrorCode2["OIDC_INTERACTION_NOT_FOUND"] = "OIDC_INTERACTION_NOT_FOUND";
116
+ NAuthErrorCode2["OIDC_LOGIN_REQUIRED"] = "OIDC_LOGIN_REQUIRED";
117
+ NAuthErrorCode2["OIDC_ACCESS_DENIED"] = "OIDC_ACCESS_DENIED";
112
118
  NAuthErrorCode2["RESOURCE_NOT_FOUND"] = "RESOURCE_NOT_FOUND";
113
119
  NAuthErrorCode2["FORBIDDEN"] = "FORBIDDEN";
114
120
  NAuthErrorCode2["INTERNAL_ERROR"] = "INTERNAL_ERROR";
@@ -1643,19 +1649,246 @@ var ApiKeyOperations = class {
1643
1649
  }
1644
1650
  };
1645
1651
 
1652
+ // src/core/oidc-operations.ts
1653
+ var hasWindow3 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1654
+ var PENDING_INTERACTION_KEY = "nauth_pending_interaction";
1655
+ var DEFAULT_INTERACTION_ROUTE = "/interaction";
1656
+ var OIDCOperations = class {
1657
+ /**
1658
+ * @param config - Resolved client configuration
1659
+ * @param storage - Ephemeral (session-scoped) storage for the pending interaction
1660
+ * @param basePath - Base path for the interaction routes (default: `{baseUrl}/oidc/interaction`)
1661
+ */
1662
+ constructor(config, storage, basePath) {
1663
+ __publicField(this, "config");
1664
+ __publicField(this, "storage");
1665
+ __publicField(this, "basePath");
1666
+ /** Frontend route rendering the consent screen, with the id appended. */
1667
+ __publicField(this, "interactionPath");
1668
+ this.config = config;
1669
+ this.storage = storage;
1670
+ this.basePath = basePath ?? config.oidc?.basePath ?? `${config.baseUrl}/oidc/interaction`;
1671
+ this.interactionPath = config.oidc?.interactionPath ?? DEFAULT_INTERACTION_ROUTE;
1672
+ }
1673
+ /**
1674
+ * The in-app route that renders the consent screen for a given interaction.
1675
+ *
1676
+ * One place for the convention, so a route guard, a navigation handler and a
1677
+ * component all agree on where the consent screen lives.
1678
+ *
1679
+ * @param uid - The pending interaction id
1680
+ * @returns A route path such as `/interaction/abc123`
1681
+ */
1682
+ interactionRoute(uid) {
1683
+ return `${this.interactionPath.replace(/\/$/, "")}/${encodeURIComponent(uid)}`;
1684
+ }
1685
+ /**
1686
+ * Read a pending interaction, so the page can decide what to render.
1687
+ *
1688
+ * Answers for a signed-out caller too — a `login_required` gate is precisely the
1689
+ * signal to send the user through login.
1690
+ *
1691
+ * @param uid - The pending interaction id, from the route the provider redirected to
1692
+ * @returns What the request needs, and nauth's verdict on the current session
1693
+ */
1694
+ async getInteraction(uid) {
1695
+ return this.get(this.url(uid));
1696
+ }
1697
+ /**
1698
+ * Complete the login step for the currently authenticated user.
1699
+ *
1700
+ * Used when `getInteraction` reports `prompt === 'login'` and the gate is
1701
+ * `authenticated`: nothing needs showing, the interaction just needs resolving.
1702
+ *
1703
+ * @param uid - The pending interaction id
1704
+ * @returns Where to send the browser to resume the authorization request
1705
+ */
1706
+ async completeLogin(uid) {
1707
+ return this.post(this.url(uid, "login"), {});
1708
+ }
1709
+ /**
1710
+ * Grant the client what it asked for.
1711
+ *
1712
+ * @param uid - The pending interaction id
1713
+ * @param scopes - A narrowed set of scopes to grant; omit to grant everything asked for
1714
+ * @returns Where to send the browser next
1715
+ */
1716
+ async approve(uid, scopes) {
1717
+ const body = { approve: true };
1718
+ if (scopes) {
1719
+ body.scopes = scopes;
1720
+ }
1721
+ return this.post(this.url(uid, "confirm"), body);
1722
+ }
1723
+ /**
1724
+ * Refuse the request. The client is told `access_denied`.
1725
+ *
1726
+ * @param uid - The pending interaction id
1727
+ * @returns Where to send the browser next
1728
+ */
1729
+ async deny(uid) {
1730
+ return this.post(this.url(uid, "confirm"), { approve: false });
1731
+ }
1732
+ /**
1733
+ * Abandon a pending interaction, so the client gets a clean protocol error rather
1734
+ * than waiting on a browser tab that is never coming back.
1735
+ *
1736
+ * @param uid - The pending interaction id
1737
+ * @returns Where to send the browser
1738
+ */
1739
+ async abort(uid) {
1740
+ return this.post(this.url(uid, "abort"), {});
1741
+ }
1742
+ // ==========================================================================
1743
+ // The login detour
1744
+ // ==========================================================================
1745
+ /**
1746
+ * Remember an interaction to return to once the user has finished logging in.
1747
+ *
1748
+ * Stored in session-scoped storage rather than a query parameter, because the login
1749
+ * that follows may run several challenge steps — forced password change, email or
1750
+ * phone verification, MFA setup — each with its own URL. A query parameter does not
1751
+ * survive that; this does.
1752
+ *
1753
+ * @param uid - The pending interaction id
1754
+ */
1755
+ async setPendingInteraction(uid) {
1756
+ try {
1757
+ await this.storage.setItem(PENDING_INTERACTION_KEY, uid);
1758
+ } catch {
1759
+ }
1760
+ }
1761
+ /**
1762
+ * The interaction waiting to be resumed, if any.
1763
+ *
1764
+ * @returns The pending interaction id, or null
1765
+ */
1766
+ async getPendingInteraction() {
1767
+ try {
1768
+ return await this.storage.getItem(PENDING_INTERACTION_KEY);
1769
+ } catch {
1770
+ return null;
1771
+ }
1772
+ }
1773
+ /**
1774
+ * Forget the pending interaction.
1775
+ *
1776
+ * Call this once you have acted on it, so a later visit to the same page is not
1777
+ * diverted a second time.
1778
+ */
1779
+ async clearPendingInteraction() {
1780
+ try {
1781
+ await this.storage.removeItem(PENDING_INTERACTION_KEY);
1782
+ } catch {
1783
+ }
1784
+ }
1785
+ /**
1786
+ * Take the pending interaction and forget it in one step.
1787
+ *
1788
+ * The read-then-clear a navigation handler or route guard wants: whoever gets the id
1789
+ * owns the resumption, and no one else is sent there afterwards.
1790
+ *
1791
+ * @returns The pending interaction id, or null
1792
+ */
1793
+ async takePendingInteraction() {
1794
+ const uid = await this.getPendingInteraction();
1795
+ if (uid) {
1796
+ await this.clearPendingInteraction();
1797
+ }
1798
+ return uid;
1799
+ }
1800
+ // ==========================================================================
1801
+ // Internal request helpers (mirror ApiKeyOperations)
1802
+ // ==========================================================================
1803
+ url(uid, action) {
1804
+ const base = `${this.basePath}/${encodeURIComponent(uid)}`;
1805
+ return action ? `${base}/${action}` : base;
1806
+ }
1807
+ async buildHeaders(method) {
1808
+ const headers = { ...this.config.headers };
1809
+ if (method !== "GET") {
1810
+ headers["Content-Type"] = "application/json";
1811
+ }
1812
+ if (this.config.tokenDelivery === "json") {
1813
+ try {
1814
+ const token = await this.config.storage.getItem("nauth_access_token");
1815
+ if (token) {
1816
+ headers["Authorization"] = `Bearer ${token}`;
1817
+ }
1818
+ } catch {
1819
+ }
1820
+ }
1821
+ if (this.config.tokenDelivery === "cookies" && hasWindow3() && method === "POST") {
1822
+ const csrfToken = this.getCsrfToken();
1823
+ if (csrfToken) {
1824
+ headers[this.config.csrf.headerName] = csrfToken;
1825
+ }
1826
+ }
1827
+ return headers;
1828
+ }
1829
+ getCsrfToken() {
1830
+ if (!hasWindow3() || typeof document === "undefined") return null;
1831
+ const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
1832
+ return match ? decodeURIComponent(match[2]) : null;
1833
+ }
1834
+ async get(path) {
1835
+ const headers = await this.buildHeaders("GET");
1836
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1837
+ try {
1838
+ const response = await this.config.httpAdapter.request({ method: "GET", url: path, headers, credentials });
1839
+ return response.data;
1840
+ } catch (error) {
1841
+ throw this.handleError(error);
1842
+ }
1843
+ }
1844
+ async post(path, body) {
1845
+ const headers = await this.buildHeaders("POST");
1846
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1847
+ try {
1848
+ const response = await this.config.httpAdapter.request({
1849
+ method: "POST",
1850
+ url: path,
1851
+ headers,
1852
+ body,
1853
+ credentials
1854
+ });
1855
+ return response.data;
1856
+ } catch (error) {
1857
+ throw this.handleError(error);
1858
+ }
1859
+ }
1860
+ handleError(error) {
1861
+ if (error instanceof NAuthClientError) {
1862
+ return error;
1863
+ }
1864
+ if (error && typeof error === "object" && "response" in error) {
1865
+ const httpError = error;
1866
+ const status = httpError.response?.status ?? 500;
1867
+ const errorData = typeof httpError.response?.data === "object" && httpError.response.data !== null ? httpError.response.data : {};
1868
+ const code = typeof errorData["code"] === "string" ? errorData["code"] : "INTERNAL_ERROR" /* INTERNAL_ERROR */;
1869
+ const message = typeof errorData["message"] === "string" ? errorData["message"] : `Request failed with status ${status}`;
1870
+ return new NAuthClientError(code, message, { statusCode: status, details: errorData });
1871
+ }
1872
+ return new NAuthClientError(
1873
+ "INTERNAL_ERROR" /* INTERNAL_ERROR */,
1874
+ error instanceof Error ? error.message : "Unknown error"
1875
+ );
1876
+ }
1877
+ };
1878
+
1646
1879
  // src/core/client.ts
1647
1880
  var USER_KEY2 = "nauth_user";
1648
1881
  var CHALLENGE_KEY2 = "nauth_challenge_session";
1649
1882
  var OAUTH_STATE_KEY2 = "nauth_oauth_state";
1650
- var hasWindow3 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1883
+ var hasWindow4 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1651
1884
  var getOauthStorage = (mainStorage) => {
1652
- if (hasWindow3() && typeof window.sessionStorage !== "undefined") {
1885
+ if (hasWindow4() && typeof window.sessionStorage !== "undefined") {
1653
1886
  return new BrowserStorage(window.sessionStorage);
1654
1887
  }
1655
1888
  return mainStorage;
1656
1889
  };
1657
1890
  var defaultStorage = () => {
1658
- if (hasWindow3() && typeof window.localStorage !== "undefined") {
1891
+ if (hasWindow4() && typeof window.localStorage !== "undefined") {
1659
1892
  return new BrowserStorage();
1660
1893
  }
1661
1894
  return new InMemoryStorage();
@@ -1719,6 +1952,27 @@ var NAuthClient = class {
1719
1952
  * ```
1720
1953
  */
1721
1954
  __publicField(this, "apiKeys");
1955
+ /**
1956
+ * OpenID Connect interaction operations (consent screen, login step, abort).
1957
+ *
1958
+ * Only meaningful when this application *is* an OpenID Connect provider — one
1959
+ * running `@nauth-toolkit/oidc-provider`. Calls the interaction routes the backend
1960
+ * mounts (default base path `{baseUrl}/oidc/interaction`; override with
1961
+ * `oidc.basePath`).
1962
+ *
1963
+ * @example
1964
+ * ```typescript
1965
+ * const state = await client.oidc.getInteraction(uid);
1966
+ * if (state.gate === 'login_required') {
1967
+ * await client.oidc.setPendingInteraction(uid);
1968
+ * router.navigate(['/login']);
1969
+ * } else {
1970
+ * const { redirectTo } = await client.oidc.approve(uid);
1971
+ * window.location.assign(redirectTo);
1972
+ * }
1973
+ * ```
1974
+ */
1975
+ __publicField(this, "oidc");
1722
1976
  /**
1723
1977
  * Handle cross-tab storage updates.
1724
1978
  */
@@ -1742,7 +1996,8 @@ var NAuthClient = class {
1742
1996
  this.admin = new AdminOperations(this.config);
1743
1997
  }
1744
1998
  this.apiKeys = new ApiKeyOperations(this.config);
1745
- if (hasWindow3()) {
1999
+ this.oidc = new OIDCOperations(this.config, this.oauthStorage);
2000
+ if (hasWindow4()) {
1746
2001
  window.addEventListener("storage", this.handleStorageEvent);
1747
2002
  }
1748
2003
  }
@@ -1750,7 +2005,7 @@ var NAuthClient = class {
1750
2005
  * Clean up resources.
1751
2006
  */
1752
2007
  dispose() {
1753
- if (hasWindow3()) {
2008
+ if (hasWindow4()) {
1754
2009
  window.removeEventListener("storage", this.handleStorageEvent);
1755
2010
  }
1756
2011
  }
@@ -2412,7 +2667,7 @@ var NAuthClient = class {
2412
2667
  */
2413
2668
  async loginWithSocial(provider, options) {
2414
2669
  this.eventEmitter.emit({ type: "oauth:started", data: { provider }, timestamp: Date.now() });
2415
- if (hasWindow3()) {
2670
+ if (hasWindow4()) {
2416
2671
  const startPath = this.config.endpoints.socialRedirectStart.replace(":provider", provider);
2417
2672
  const fullUrl = this.buildUrl(startPath);
2418
2673
  const startUrl = new URL(fullUrl);
@@ -2746,7 +3001,7 @@ var NAuthClient = class {
2746
3001
  }
2747
3002
  }
2748
3003
  const mutatingMethods = ["POST", "PUT", "PATCH", "DELETE"];
2749
- if (this.config.tokenDelivery === "cookies" && hasWindow3() && mutatingMethods.includes(method)) {
3004
+ if (this.config.tokenDelivery === "cookies" && hasWindow4() && mutatingMethods.includes(method)) {
2750
3005
  const csrfToken = this.getCsrfToken();
2751
3006
  if (csrfToken) {
2752
3007
  headers[this.config.csrf.headerName] = csrfToken;
@@ -2759,7 +3014,7 @@ var NAuthClient = class {
2759
3014
  * @private
2760
3015
  */
2761
3016
  getCsrfToken() {
2762
- if (!hasWindow3() || typeof document === "undefined") return null;
3017
+ if (!hasWindow4() || typeof document === "undefined") return null;
2763
3018
  const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
2764
3019
  return match ? decodeURIComponent(match[2]) : null;
2765
3020
  }
@@ -2945,12 +3200,15 @@ function isOTPChallenge(challenge) {
2945
3200
  AuthChallenge,
2946
3201
  BrowserStorage,
2947
3202
  ChallengeRouter,
3203
+ DEFAULT_INTERACTION_ROUTE,
2948
3204
  EventEmitter,
2949
3205
  FetchAdapter,
2950
3206
  InMemoryStorage,
2951
3207
  NAuthClient,
2952
3208
  NAuthClientError,
2953
3209
  NAuthErrorCode,
3210
+ OIDCOperations,
3211
+ PENDING_INTERACTION_KEY,
2954
3212
  apiKeyHeader,
2955
3213
  defaultAdminEndpoints,
2956
3214
  defaultEndpoints,