@nauth-toolkit/client 0.2.7 → 0.3.1

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
@@ -23,6 +23,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
23
23
  var index_exports = {};
24
24
  __export(index_exports, {
25
25
  AdminOperations: () => AdminOperations,
26
+ ApiKeyOperations: () => ApiKeyOperations,
26
27
  AuthAuditEventType: () => AuthAuditEventType,
27
28
  AuthChallenge: () => AuthChallenge,
28
29
  BrowserStorage: () => BrowserStorage,
@@ -33,6 +34,7 @@ __export(index_exports, {
33
34
  NAuthClient: () => NAuthClient,
34
35
  NAuthClientError: () => NAuthClientError,
35
36
  NAuthErrorCode: () => NAuthErrorCode,
37
+ apiKeyHeader: () => apiKeyHeader,
36
38
  defaultAdminEndpoints: () => defaultAdminEndpoints,
37
39
  defaultEndpoints: () => defaultEndpoints,
38
40
  getChallengeInstructions: () => getChallengeInstructions,
@@ -1478,19 +1480,181 @@ var AdminOperations = class {
1478
1480
  }
1479
1481
  };
1480
1482
 
1483
+ // src/core/api-key-operations.ts
1484
+ var hasWindow2 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1485
+ function apiKeyHeader(key, headerName = "X-API-Key") {
1486
+ return { [headerName]: key };
1487
+ }
1488
+ var ApiKeyOperations = class {
1489
+ /**
1490
+ * @param config - Resolved client configuration
1491
+ * @param basePath - Base path for API-key endpoints (default: `{baseUrl}/api-keys`)
1492
+ */
1493
+ constructor(config, basePath) {
1494
+ __publicField(this, "config");
1495
+ __publicField(this, "basePath");
1496
+ this.config = config;
1497
+ this.basePath = basePath ?? `${config.baseUrl}/api-keys`;
1498
+ }
1499
+ /**
1500
+ * Create a new API key. The plaintext key is returned once.
1501
+ *
1502
+ * @param request - Key options (mandatory expiry; optional IP allowlist)
1503
+ */
1504
+ async create(request) {
1505
+ return this.post(this.basePath, request);
1506
+ }
1507
+ /**
1508
+ * List the current user's API keys (sanitized).
1509
+ */
1510
+ async list() {
1511
+ return this.get(this.basePath);
1512
+ }
1513
+ /**
1514
+ * Update a key's label and/or IP allowlist.
1515
+ *
1516
+ * @param keyId - External key identifier
1517
+ * @param request - Fields to update
1518
+ */
1519
+ async update(keyId, request) {
1520
+ return this.patch(`${this.basePath}/${encodeURIComponent(keyId)}`, request);
1521
+ }
1522
+ /**
1523
+ * Revoke (soft-delete) a key.
1524
+ *
1525
+ * @param keyId - External key identifier
1526
+ */
1527
+ async revoke(keyId) {
1528
+ return this.post(`${this.basePath}/${encodeURIComponent(keyId)}/revoke`, {});
1529
+ }
1530
+ /**
1531
+ * Permanently delete a key.
1532
+ *
1533
+ * @param keyId - External key identifier
1534
+ */
1535
+ async remove(keyId) {
1536
+ return this.delete(`${this.basePath}/${encodeURIComponent(keyId)}`);
1537
+ }
1538
+ // ==========================================================================
1539
+ // Internal request helpers (mirror AdminOperations)
1540
+ // ==========================================================================
1541
+ async buildHeaders(method) {
1542
+ const headers = { ...this.config.headers };
1543
+ if (method !== "GET") {
1544
+ headers["Content-Type"] = "application/json";
1545
+ }
1546
+ if (this.config.tokenDelivery === "json") {
1547
+ try {
1548
+ const token = await this.config.storage.getItem("nauth_access_token");
1549
+ if (token) {
1550
+ headers["Authorization"] = `Bearer ${token}`;
1551
+ }
1552
+ } catch {
1553
+ }
1554
+ }
1555
+ const mutating = ["POST", "PATCH", "DELETE"];
1556
+ if (this.config.tokenDelivery === "cookies" && hasWindow2() && mutating.includes(method)) {
1557
+ const csrfToken = this.getCsrfToken();
1558
+ if (csrfToken) {
1559
+ headers[this.config.csrf.headerName] = csrfToken;
1560
+ }
1561
+ }
1562
+ return headers;
1563
+ }
1564
+ getCsrfToken() {
1565
+ if (!hasWindow2() || typeof document === "undefined") return null;
1566
+ const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
1567
+ return match ? decodeURIComponent(match[2]) : null;
1568
+ }
1569
+ async get(path) {
1570
+ const headers = await this.buildHeaders("GET");
1571
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1572
+ try {
1573
+ const response = await this.config.httpAdapter.request({ method: "GET", url: path, headers, credentials });
1574
+ return response.data;
1575
+ } catch (error) {
1576
+ throw this.handleError(error);
1577
+ }
1578
+ }
1579
+ async post(path, body) {
1580
+ const headers = await this.buildHeaders("POST");
1581
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1582
+ try {
1583
+ const response = await this.config.httpAdapter.request({
1584
+ method: "POST",
1585
+ url: path,
1586
+ headers,
1587
+ body,
1588
+ credentials
1589
+ });
1590
+ return response.data;
1591
+ } catch (error) {
1592
+ throw this.handleError(error);
1593
+ }
1594
+ }
1595
+ async patch(path, body) {
1596
+ const headers = await this.buildHeaders("PATCH");
1597
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1598
+ try {
1599
+ const response = await this.config.httpAdapter.request({
1600
+ method: "PATCH",
1601
+ url: path,
1602
+ headers,
1603
+ body,
1604
+ credentials
1605
+ });
1606
+ return response.data;
1607
+ } catch (error) {
1608
+ throw this.handleError(error);
1609
+ }
1610
+ }
1611
+ async delete(path) {
1612
+ const headers = await this.buildHeaders("DELETE");
1613
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1614
+ try {
1615
+ const response = await this.config.httpAdapter.request({
1616
+ method: "DELETE",
1617
+ url: path,
1618
+ headers,
1619
+ credentials
1620
+ });
1621
+ return response.data;
1622
+ } catch (error) {
1623
+ throw this.handleError(error);
1624
+ }
1625
+ }
1626
+ handleError(error) {
1627
+ if (error instanceof NAuthClientError) {
1628
+ return error;
1629
+ }
1630
+ if (error && typeof error === "object" && "response" in error) {
1631
+ const httpError = error;
1632
+ const status = httpError.response?.status ?? 500;
1633
+ const errorData = typeof httpError.response?.data === "object" && httpError.response.data !== null ? httpError.response.data : {};
1634
+ const code = typeof errorData["code"] === "string" ? errorData["code"] : "INTERNAL_ERROR" /* INTERNAL_ERROR */;
1635
+ const message = typeof errorData["message"] === "string" ? errorData["message"] : `Request failed with status ${status}`;
1636
+ return new NAuthClientError(code, message, { statusCode: status, details: errorData });
1637
+ }
1638
+ return new NAuthClientError(
1639
+ "INTERNAL_ERROR" /* INTERNAL_ERROR */,
1640
+ error instanceof Error ? error.message : "Unknown error"
1641
+ );
1642
+ }
1643
+ };
1644
+
1481
1645
  // src/core/client.ts
1482
1646
  var USER_KEY2 = "nauth_user";
1483
1647
  var CHALLENGE_KEY2 = "nauth_challenge_session";
1484
1648
  var OAUTH_STATE_KEY2 = "nauth_oauth_state";
1485
- var hasWindow2 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1649
+ var hasWindow3 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1486
1650
  var getOauthStorage = (mainStorage) => {
1487
- if (hasWindow2() && typeof window.sessionStorage !== "undefined") {
1651
+ if (hasWindow3() && typeof window.sessionStorage !== "undefined") {
1488
1652
  return new BrowserStorage(window.sessionStorage);
1489
1653
  }
1490
1654
  return mainStorage;
1491
1655
  };
1492
1656
  var defaultStorage = () => {
1493
- if (hasWindow2() && typeof window.localStorage !== "undefined") {
1657
+ if (hasWindow3() && typeof window.localStorage !== "undefined") {
1494
1658
  return new BrowserStorage();
1495
1659
  }
1496
1660
  return new InMemoryStorage();
@@ -1540,6 +1704,20 @@ var NAuthClient = class {
1540
1704
  * ```
1541
1705
  */
1542
1706
  __publicField(this, "admin");
1707
+ /**
1708
+ * API key management operations (create/list/update/revoke/delete).
1709
+ *
1710
+ * Calls your backend's API-key endpoints (default base path `{baseUrl}/api-keys`).
1711
+ *
1712
+ * @example
1713
+ * ```typescript
1714
+ * const { key } = await client.apiKeys.create({ expiresInDays: 90, allowedIps: ['203.0.113.0/24'] });
1715
+ * const keys = await client.apiKeys.list();
1716
+ * await client.apiKeys.update(keyId, { allowedIps: ['203.0.113.5'] });
1717
+ * await client.apiKeys.revoke(keyId);
1718
+ * ```
1719
+ */
1720
+ __publicField(this, "apiKeys");
1543
1721
  /**
1544
1722
  * Handle cross-tab storage updates.
1545
1723
  */
@@ -1562,7 +1740,8 @@ var NAuthClient = class {
1562
1740
  if (this.config.admin) {
1563
1741
  this.admin = new AdminOperations(this.config);
1564
1742
  }
1565
- if (hasWindow2()) {
1743
+ this.apiKeys = new ApiKeyOperations(this.config);
1744
+ if (hasWindow3()) {
1566
1745
  window.addEventListener("storage", this.handleStorageEvent);
1567
1746
  }
1568
1747
  }
@@ -1570,7 +1749,7 @@ var NAuthClient = class {
1570
1749
  * Clean up resources.
1571
1750
  */
1572
1751
  dispose() {
1573
- if (hasWindow2()) {
1752
+ if (hasWindow3()) {
1574
1753
  window.removeEventListener("storage", this.handleStorageEvent);
1575
1754
  }
1576
1755
  }
@@ -2232,7 +2411,7 @@ var NAuthClient = class {
2232
2411
  */
2233
2412
  async loginWithSocial(provider, options) {
2234
2413
  this.eventEmitter.emit({ type: "oauth:started", data: { provider }, timestamp: Date.now() });
2235
- if (hasWindow2()) {
2414
+ if (hasWindow3()) {
2236
2415
  const startPath = this.config.endpoints.socialRedirectStart.replace(":provider", provider);
2237
2416
  const fullUrl = this.buildUrl(startPath);
2238
2417
  const startUrl = new URL(fullUrl);
@@ -2566,7 +2745,7 @@ var NAuthClient = class {
2566
2745
  }
2567
2746
  }
2568
2747
  const mutatingMethods = ["POST", "PUT", "PATCH", "DELETE"];
2569
- if (this.config.tokenDelivery === "cookies" && hasWindow2() && mutatingMethods.includes(method)) {
2748
+ if (this.config.tokenDelivery === "cookies" && hasWindow3() && mutatingMethods.includes(method)) {
2570
2749
  const csrfToken = this.getCsrfToken();
2571
2750
  if (csrfToken) {
2572
2751
  headers[this.config.csrf.headerName] = csrfToken;
@@ -2579,7 +2758,7 @@ var NAuthClient = class {
2579
2758
  * @private
2580
2759
  */
2581
2760
  getCsrfToken() {
2582
- if (!hasWindow2() || typeof document === "undefined") return null;
2761
+ if (!hasWindow3() || typeof document === "undefined") return null;
2583
2762
  const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
2584
2763
  return match ? decodeURIComponent(match[2]) : null;
2585
2764
  }
@@ -2760,6 +2939,7 @@ function isOTPChallenge(challenge) {
2760
2939
  // Annotate the CommonJS export names for ESM import in node:
2761
2940
  0 && (module.exports = {
2762
2941
  AdminOperations,
2942
+ ApiKeyOperations,
2763
2943
  AuthAuditEventType,
2764
2944
  AuthChallenge,
2765
2945
  BrowserStorage,
@@ -2770,6 +2950,7 @@ function isOTPChallenge(challenge) {
2770
2950
  NAuthClient,
2771
2951
  NAuthClientError,
2772
2952
  NAuthErrorCode,
2953
+ apiKeyHeader,
2773
2954
  defaultAdminEndpoints,
2774
2955
  defaultEndpoints,
2775
2956
  getChallengeInstructions,