@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.mjs CHANGED
@@ -65,6 +65,9 @@ var NAuthErrorCode = /* @__PURE__ */ ((NAuthErrorCode2) => {
65
65
  NAuthErrorCode2["PASSWORD_RESET_MAX_ATTEMPTS"] = "PASSWORD_RESET_MAX_ATTEMPTS";
66
66
  NAuthErrorCode2["RATE_LIMIT_PASSWORD_RESET"] = "RATE_LIMIT_PASSWORD_RESET";
67
67
  NAuthErrorCode2["SIGNIN_BLOCKED_HIGH_RISK"] = "SIGNIN_BLOCKED_HIGH_RISK";
68
+ NAuthErrorCode2["OIDC_INTERACTION_NOT_FOUND"] = "OIDC_INTERACTION_NOT_FOUND";
69
+ NAuthErrorCode2["OIDC_LOGIN_REQUIRED"] = "OIDC_LOGIN_REQUIRED";
70
+ NAuthErrorCode2["OIDC_ACCESS_DENIED"] = "OIDC_ACCESS_DENIED";
68
71
  NAuthErrorCode2["RESOURCE_NOT_FOUND"] = "RESOURCE_NOT_FOUND";
69
72
  NAuthErrorCode2["FORBIDDEN"] = "FORBIDDEN";
70
73
  NAuthErrorCode2["INTERNAL_ERROR"] = "INTERNAL_ERROR";
@@ -1599,19 +1602,246 @@ var ApiKeyOperations = class {
1599
1602
  }
1600
1603
  };
1601
1604
 
1605
+ // src/core/oidc-operations.ts
1606
+ var hasWindow3 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1607
+ var PENDING_INTERACTION_KEY = "nauth_pending_interaction";
1608
+ var DEFAULT_INTERACTION_ROUTE = "/interaction";
1609
+ var OIDCOperations = class {
1610
+ /**
1611
+ * @param config - Resolved client configuration
1612
+ * @param storage - Ephemeral (session-scoped) storage for the pending interaction
1613
+ * @param basePath - Base path for the interaction routes (default: `{baseUrl}/oidc/interaction`)
1614
+ */
1615
+ constructor(config, storage, basePath) {
1616
+ __publicField(this, "config");
1617
+ __publicField(this, "storage");
1618
+ __publicField(this, "basePath");
1619
+ /** Frontend route rendering the consent screen, with the id appended. */
1620
+ __publicField(this, "interactionPath");
1621
+ this.config = config;
1622
+ this.storage = storage;
1623
+ this.basePath = basePath ?? config.oidc?.basePath ?? `${config.baseUrl}/oidc/interaction`;
1624
+ this.interactionPath = config.oidc?.interactionPath ?? DEFAULT_INTERACTION_ROUTE;
1625
+ }
1626
+ /**
1627
+ * The in-app route that renders the consent screen for a given interaction.
1628
+ *
1629
+ * One place for the convention, so a route guard, a navigation handler and a
1630
+ * component all agree on where the consent screen lives.
1631
+ *
1632
+ * @param uid - The pending interaction id
1633
+ * @returns A route path such as `/interaction/abc123`
1634
+ */
1635
+ interactionRoute(uid) {
1636
+ return `${this.interactionPath.replace(/\/$/, "")}/${encodeURIComponent(uid)}`;
1637
+ }
1638
+ /**
1639
+ * Read a pending interaction, so the page can decide what to render.
1640
+ *
1641
+ * Answers for a signed-out caller too — a `login_required` gate is precisely the
1642
+ * signal to send the user through login.
1643
+ *
1644
+ * @param uid - The pending interaction id, from the route the provider redirected to
1645
+ * @returns What the request needs, and nauth's verdict on the current session
1646
+ */
1647
+ async getInteraction(uid) {
1648
+ return this.get(this.url(uid));
1649
+ }
1650
+ /**
1651
+ * Complete the login step for the currently authenticated user.
1652
+ *
1653
+ * Used when `getInteraction` reports `prompt === 'login'` and the gate is
1654
+ * `authenticated`: nothing needs showing, the interaction just needs resolving.
1655
+ *
1656
+ * @param uid - The pending interaction id
1657
+ * @returns Where to send the browser to resume the authorization request
1658
+ */
1659
+ async completeLogin(uid) {
1660
+ return this.post(this.url(uid, "login"), {});
1661
+ }
1662
+ /**
1663
+ * Grant the client what it asked for.
1664
+ *
1665
+ * @param uid - The pending interaction id
1666
+ * @param scopes - A narrowed set of scopes to grant; omit to grant everything asked for
1667
+ * @returns Where to send the browser next
1668
+ */
1669
+ async approve(uid, scopes) {
1670
+ const body = { approve: true };
1671
+ if (scopes) {
1672
+ body.scopes = scopes;
1673
+ }
1674
+ return this.post(this.url(uid, "confirm"), body);
1675
+ }
1676
+ /**
1677
+ * Refuse the request. The client is told `access_denied`.
1678
+ *
1679
+ * @param uid - The pending interaction id
1680
+ * @returns Where to send the browser next
1681
+ */
1682
+ async deny(uid) {
1683
+ return this.post(this.url(uid, "confirm"), { approve: false });
1684
+ }
1685
+ /**
1686
+ * Abandon a pending interaction, so the client gets a clean protocol error rather
1687
+ * than waiting on a browser tab that is never coming back.
1688
+ *
1689
+ * @param uid - The pending interaction id
1690
+ * @returns Where to send the browser
1691
+ */
1692
+ async abort(uid) {
1693
+ return this.post(this.url(uid, "abort"), {});
1694
+ }
1695
+ // ==========================================================================
1696
+ // The login detour
1697
+ // ==========================================================================
1698
+ /**
1699
+ * Remember an interaction to return to once the user has finished logging in.
1700
+ *
1701
+ * Stored in session-scoped storage rather than a query parameter, because the login
1702
+ * that follows may run several challenge steps — forced password change, email or
1703
+ * phone verification, MFA setup — each with its own URL. A query parameter does not
1704
+ * survive that; this does.
1705
+ *
1706
+ * @param uid - The pending interaction id
1707
+ */
1708
+ async setPendingInteraction(uid) {
1709
+ try {
1710
+ await this.storage.setItem(PENDING_INTERACTION_KEY, uid);
1711
+ } catch {
1712
+ }
1713
+ }
1714
+ /**
1715
+ * The interaction waiting to be resumed, if any.
1716
+ *
1717
+ * @returns The pending interaction id, or null
1718
+ */
1719
+ async getPendingInteraction() {
1720
+ try {
1721
+ return await this.storage.getItem(PENDING_INTERACTION_KEY);
1722
+ } catch {
1723
+ return null;
1724
+ }
1725
+ }
1726
+ /**
1727
+ * Forget the pending interaction.
1728
+ *
1729
+ * Call this once you have acted on it, so a later visit to the same page is not
1730
+ * diverted a second time.
1731
+ */
1732
+ async clearPendingInteraction() {
1733
+ try {
1734
+ await this.storage.removeItem(PENDING_INTERACTION_KEY);
1735
+ } catch {
1736
+ }
1737
+ }
1738
+ /**
1739
+ * Take the pending interaction and forget it in one step.
1740
+ *
1741
+ * The read-then-clear a navigation handler or route guard wants: whoever gets the id
1742
+ * owns the resumption, and no one else is sent there afterwards.
1743
+ *
1744
+ * @returns The pending interaction id, or null
1745
+ */
1746
+ async takePendingInteraction() {
1747
+ const uid = await this.getPendingInteraction();
1748
+ if (uid) {
1749
+ await this.clearPendingInteraction();
1750
+ }
1751
+ return uid;
1752
+ }
1753
+ // ==========================================================================
1754
+ // Internal request helpers (mirror ApiKeyOperations)
1755
+ // ==========================================================================
1756
+ url(uid, action) {
1757
+ const base = `${this.basePath}/${encodeURIComponent(uid)}`;
1758
+ return action ? `${base}/${action}` : base;
1759
+ }
1760
+ async buildHeaders(method) {
1761
+ const headers = { ...this.config.headers };
1762
+ if (method !== "GET") {
1763
+ headers["Content-Type"] = "application/json";
1764
+ }
1765
+ if (this.config.tokenDelivery === "json") {
1766
+ try {
1767
+ const token = await this.config.storage.getItem("nauth_access_token");
1768
+ if (token) {
1769
+ headers["Authorization"] = `Bearer ${token}`;
1770
+ }
1771
+ } catch {
1772
+ }
1773
+ }
1774
+ if (this.config.tokenDelivery === "cookies" && hasWindow3() && method === "POST") {
1775
+ const csrfToken = this.getCsrfToken();
1776
+ if (csrfToken) {
1777
+ headers[this.config.csrf.headerName] = csrfToken;
1778
+ }
1779
+ }
1780
+ return headers;
1781
+ }
1782
+ getCsrfToken() {
1783
+ if (!hasWindow3() || typeof document === "undefined") return null;
1784
+ const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
1785
+ return match ? decodeURIComponent(match[2]) : null;
1786
+ }
1787
+ async get(path) {
1788
+ const headers = await this.buildHeaders("GET");
1789
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1790
+ try {
1791
+ const response = await this.config.httpAdapter.request({ method: "GET", url: path, headers, credentials });
1792
+ return response.data;
1793
+ } catch (error) {
1794
+ throw this.handleError(error);
1795
+ }
1796
+ }
1797
+ async post(path, body) {
1798
+ const headers = await this.buildHeaders("POST");
1799
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1800
+ try {
1801
+ const response = await this.config.httpAdapter.request({
1802
+ method: "POST",
1803
+ url: path,
1804
+ headers,
1805
+ body,
1806
+ credentials
1807
+ });
1808
+ return response.data;
1809
+ } catch (error) {
1810
+ throw this.handleError(error);
1811
+ }
1812
+ }
1813
+ handleError(error) {
1814
+ if (error instanceof NAuthClientError) {
1815
+ return error;
1816
+ }
1817
+ if (error && typeof error === "object" && "response" in error) {
1818
+ const httpError = error;
1819
+ const status = httpError.response?.status ?? 500;
1820
+ const errorData = typeof httpError.response?.data === "object" && httpError.response.data !== null ? httpError.response.data : {};
1821
+ const code = typeof errorData["code"] === "string" ? errorData["code"] : "INTERNAL_ERROR" /* INTERNAL_ERROR */;
1822
+ const message = typeof errorData["message"] === "string" ? errorData["message"] : `Request failed with status ${status}`;
1823
+ return new NAuthClientError(code, message, { statusCode: status, details: errorData });
1824
+ }
1825
+ return new NAuthClientError(
1826
+ "INTERNAL_ERROR" /* INTERNAL_ERROR */,
1827
+ error instanceof Error ? error.message : "Unknown error"
1828
+ );
1829
+ }
1830
+ };
1831
+
1602
1832
  // src/core/client.ts
1603
1833
  var USER_KEY2 = "nauth_user";
1604
1834
  var CHALLENGE_KEY2 = "nauth_challenge_session";
1605
1835
  var OAUTH_STATE_KEY2 = "nauth_oauth_state";
1606
- var hasWindow3 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1836
+ var hasWindow4 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1607
1837
  var getOauthStorage = (mainStorage) => {
1608
- if (hasWindow3() && typeof window.sessionStorage !== "undefined") {
1838
+ if (hasWindow4() && typeof window.sessionStorage !== "undefined") {
1609
1839
  return new BrowserStorage(window.sessionStorage);
1610
1840
  }
1611
1841
  return mainStorage;
1612
1842
  };
1613
1843
  var defaultStorage = () => {
1614
- if (hasWindow3() && typeof window.localStorage !== "undefined") {
1844
+ if (hasWindow4() && typeof window.localStorage !== "undefined") {
1615
1845
  return new BrowserStorage();
1616
1846
  }
1617
1847
  return new InMemoryStorage();
@@ -1675,6 +1905,27 @@ var NAuthClient = class {
1675
1905
  * ```
1676
1906
  */
1677
1907
  __publicField(this, "apiKeys");
1908
+ /**
1909
+ * OpenID Connect interaction operations (consent screen, login step, abort).
1910
+ *
1911
+ * Only meaningful when this application *is* an OpenID Connect provider — one
1912
+ * running `@nauth-toolkit/oidc-provider`. Calls the interaction routes the backend
1913
+ * mounts (default base path `{baseUrl}/oidc/interaction`; override with
1914
+ * `oidc.basePath`).
1915
+ *
1916
+ * @example
1917
+ * ```typescript
1918
+ * const state = await client.oidc.getInteraction(uid);
1919
+ * if (state.gate === 'login_required') {
1920
+ * await client.oidc.setPendingInteraction(uid);
1921
+ * router.navigate(['/login']);
1922
+ * } else {
1923
+ * const { redirectTo } = await client.oidc.approve(uid);
1924
+ * window.location.assign(redirectTo);
1925
+ * }
1926
+ * ```
1927
+ */
1928
+ __publicField(this, "oidc");
1678
1929
  /**
1679
1930
  * Handle cross-tab storage updates.
1680
1931
  */
@@ -1698,7 +1949,8 @@ var NAuthClient = class {
1698
1949
  this.admin = new AdminOperations(this.config);
1699
1950
  }
1700
1951
  this.apiKeys = new ApiKeyOperations(this.config);
1701
- if (hasWindow3()) {
1952
+ this.oidc = new OIDCOperations(this.config, this.oauthStorage);
1953
+ if (hasWindow4()) {
1702
1954
  window.addEventListener("storage", this.handleStorageEvent);
1703
1955
  }
1704
1956
  }
@@ -1706,7 +1958,7 @@ var NAuthClient = class {
1706
1958
  * Clean up resources.
1707
1959
  */
1708
1960
  dispose() {
1709
- if (hasWindow3()) {
1961
+ if (hasWindow4()) {
1710
1962
  window.removeEventListener("storage", this.handleStorageEvent);
1711
1963
  }
1712
1964
  }
@@ -2368,7 +2620,7 @@ var NAuthClient = class {
2368
2620
  */
2369
2621
  async loginWithSocial(provider, options) {
2370
2622
  this.eventEmitter.emit({ type: "oauth:started", data: { provider }, timestamp: Date.now() });
2371
- if (hasWindow3()) {
2623
+ if (hasWindow4()) {
2372
2624
  const startPath = this.config.endpoints.socialRedirectStart.replace(":provider", provider);
2373
2625
  const fullUrl = this.buildUrl(startPath);
2374
2626
  const startUrl = new URL(fullUrl);
@@ -2702,7 +2954,7 @@ var NAuthClient = class {
2702
2954
  }
2703
2955
  }
2704
2956
  const mutatingMethods = ["POST", "PUT", "PATCH", "DELETE"];
2705
- if (this.config.tokenDelivery === "cookies" && hasWindow3() && mutatingMethods.includes(method)) {
2957
+ if (this.config.tokenDelivery === "cookies" && hasWindow4() && mutatingMethods.includes(method)) {
2706
2958
  const csrfToken = this.getCsrfToken();
2707
2959
  if (csrfToken) {
2708
2960
  headers[this.config.csrf.headerName] = csrfToken;
@@ -2715,7 +2967,7 @@ var NAuthClient = class {
2715
2967
  * @private
2716
2968
  */
2717
2969
  getCsrfToken() {
2718
- if (!hasWindow3() || typeof document === "undefined") return null;
2970
+ if (!hasWindow4() || typeof document === "undefined") return null;
2719
2971
  const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
2720
2972
  return match ? decodeURIComponent(match[2]) : null;
2721
2973
  }
@@ -2900,12 +3152,15 @@ export {
2900
3152
  AuthChallenge,
2901
3153
  BrowserStorage,
2902
3154
  ChallengeRouter,
3155
+ DEFAULT_INTERACTION_ROUTE,
2903
3156
  EventEmitter,
2904
3157
  FetchAdapter,
2905
3158
  InMemoryStorage,
2906
3159
  NAuthClient,
2907
3160
  NAuthClientError,
2908
3161
  NAuthErrorCode,
3162
+ OIDCOperations,
3163
+ PENDING_INTERACTION_KEY,
2909
3164
  apiKeyHeader,
2910
3165
  defaultAdminEndpoints,
2911
3166
  defaultEndpoints,