@nauth-toolkit/client 0.3.0 → 0.3.2

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.d.mts CHANGED
@@ -1778,6 +1778,72 @@ interface AdminAuditHistoryRequest {
1778
1778
  eventStatus?: string;
1779
1779
  }
1780
1780
 
1781
+ /**
1782
+ * API Key types for the NAuth client SDK.
1783
+ *
1784
+ * These mirror the backend `@nauth-toolkit/core` API key DTOs.
1785
+ */
1786
+ /**
1787
+ * Sanitized API key metadata returned by list/update operations.
1788
+ * Never contains the plaintext key.
1789
+ */
1790
+ interface ApiKeyInfo {
1791
+ /** External key identifier (UUID) */
1792
+ keyId: string;
1793
+ /** User-friendly label */
1794
+ name?: string | null;
1795
+ /** Last few characters of the key (display hint) */
1796
+ lastFour?: string | null;
1797
+ /** Allowed source IPs / CIDR ranges (empty/null = any IP) */
1798
+ allowedIps?: string[] | null;
1799
+ /** ISO expiry timestamp, or null if the key never expires */
1800
+ expiresAt?: string | null;
1801
+ /** Whether the key is active */
1802
+ isActive: boolean;
1803
+ /** Whether the key was created by an administrator */
1804
+ createdByAdmin: boolean;
1805
+ /** ISO timestamp of the last successful use, or null */
1806
+ lastUsedAt?: string | null;
1807
+ /** IP of the last successful use (when usage IP tracking is enabled) */
1808
+ lastUsedIp?: string | null;
1809
+ /** Total number of successful authentications */
1810
+ usageCount: number;
1811
+ /** ISO creation timestamp */
1812
+ createdAt: string;
1813
+ }
1814
+ /**
1815
+ * Request body for creating an API key.
1816
+ *
1817
+ * `expiresInDays` is mandatory: a positive integer for a finite expiry, or `null`
1818
+ * for a never-expiring key (only allowed when the server permits it).
1819
+ */
1820
+ interface CreateApiKeyRequest {
1821
+ /** Optional label */
1822
+ name?: string;
1823
+ /** Expiry in days, or null for never */
1824
+ expiresInDays: number | null;
1825
+ /** Optional IP allowlist (IPs / IPv4 CIDR ranges) */
1826
+ allowedIps?: string[];
1827
+ }
1828
+ /**
1829
+ * Request body for updating an API key's mutable fields (label and IP allowlist).
1830
+ */
1831
+ interface UpdateApiKeyRequest {
1832
+ /** New label */
1833
+ name?: string;
1834
+ /** Replacement IP allowlist (empty array clears restrictions) */
1835
+ allowedIps?: string[];
1836
+ }
1837
+ /**
1838
+ * Result of creating a key. The plaintext `key` is shown once.
1839
+ */
1840
+ interface CreateApiKeyResult {
1841
+ /** Full plaintext API key (store securely; shown only once) */
1842
+ key: string;
1843
+ /** Sanitized metadata for the created key */
1844
+ apiKey: ApiKeyInfo;
1845
+ }
1846
+
1781
1847
  /**
1782
1848
  * Client-side error wrapper for SDK operations.
1783
1849
  *
@@ -2694,6 +2760,82 @@ declare class AdminOperations {
2694
2760
  private handleError;
2695
2761
  }
2696
2762
 
2763
+ /**
2764
+ * Build a headers object that attaches an API key for machine-to-machine calls.
2765
+ *
2766
+ * Useful when a script or service authenticates with an API key instead of a session.
2767
+ *
2768
+ * @param key - The plaintext API key
2769
+ * @param headerName - Header name (defaults to 'X-API-Key'; must match server config)
2770
+ * @returns A headers object to merge into requests
2771
+ *
2772
+ * @example
2773
+ * ```typescript
2774
+ * const client = new NAuthClient({
2775
+ * baseUrl: 'https://api.example.com/auth',
2776
+ * tokenDelivery: 'json',
2777
+ * headers: apiKeyHeader(process.env.NAUTH_API_KEY!),
2778
+ * });
2779
+ * ```
2780
+ */
2781
+ declare function apiKeyHeader(key: string, headerName?: string): Record<string, string>;
2782
+ /**
2783
+ * API key management operations. Accessed via `client.apiKeys.*`.
2784
+ *
2785
+ * Calls the API-key management endpoints your backend mounts (defaults to `{baseUrl}/api-keys`).
2786
+ * The backend `ApiKeyService` powers these; there are no built-in routes, so ensure your
2787
+ * controllers are mounted at the expected paths (or pass a custom `basePath`).
2788
+ */
2789
+ declare class ApiKeyOperations {
2790
+ private readonly config;
2791
+ private readonly basePath;
2792
+ /**
2793
+ * @param config - Resolved client configuration
2794
+ * @param basePath - Base path for API-key endpoints (default: `{baseUrl}/api-keys`)
2795
+ */
2796
+ constructor(config: ResolvedNAuthClientConfig, basePath?: string);
2797
+ /**
2798
+ * Create a new API key. The plaintext key is returned once.
2799
+ *
2800
+ * @param request - Key options (mandatory expiry; optional IP allowlist)
2801
+ */
2802
+ create(request: CreateApiKeyRequest): Promise<CreateApiKeyResult>;
2803
+ /**
2804
+ * List the current user's API keys (sanitized).
2805
+ */
2806
+ list(): Promise<ApiKeyInfo[]>;
2807
+ /**
2808
+ * Update a key's label and/or IP allowlist.
2809
+ *
2810
+ * @param keyId - External key identifier
2811
+ * @param request - Fields to update
2812
+ */
2813
+ update(keyId: string, request: UpdateApiKeyRequest): Promise<ApiKeyInfo>;
2814
+ /**
2815
+ * Revoke (soft-delete) a key.
2816
+ *
2817
+ * @param keyId - External key identifier
2818
+ */
2819
+ revoke(keyId: string): Promise<{
2820
+ success: boolean;
2821
+ }>;
2822
+ /**
2823
+ * Permanently delete a key.
2824
+ *
2825
+ * @param keyId - External key identifier
2826
+ */
2827
+ remove(keyId: string): Promise<{
2828
+ success: boolean;
2829
+ }>;
2830
+ private buildHeaders;
2831
+ private getCsrfToken;
2832
+ private get;
2833
+ private post;
2834
+ private patch;
2835
+ private delete;
2836
+ private handleError;
2837
+ }
2838
+
2697
2839
  /**
2698
2840
  * Primary client for interacting with nauth-toolkit backend.
2699
2841
  */
@@ -2736,6 +2878,20 @@ declare class NAuthClient {
2736
2878
  * ```
2737
2879
  */
2738
2880
  readonly admin?: AdminOperations;
2881
+ /**
2882
+ * API key management operations (create/list/update/revoke/delete).
2883
+ *
2884
+ * Calls your backend's API-key endpoints (default base path `{baseUrl}/api-keys`).
2885
+ *
2886
+ * @example
2887
+ * ```typescript
2888
+ * const { key } = await client.apiKeys.create({ expiresInDays: 90, allowedIps: ['203.0.113.0/24'] });
2889
+ * const keys = await client.apiKeys.list();
2890
+ * await client.apiKeys.update(keyId, { allowedIps: ['203.0.113.5'] });
2891
+ * await client.apiKeys.revoke(keyId);
2892
+ * ```
2893
+ */
2894
+ readonly apiKeys: ApiKeyOperations;
2739
2895
  /**
2740
2896
  * Create a new client instance.
2741
2897
  *
@@ -3552,4 +3708,4 @@ declare class FetchAdapter implements HttpAdapter {
3552
3708
  request<T>(config: HttpRequest): Promise<HttpResponse<T>>;
3553
3709
  }
3554
3710
 
3555
- export { type AdminAuditHistoryRequest, AdminOperations, type AdminResetPasswordRequest, type AdminResetPasswordResponse, type AdminSignupRequest, type AdminSignupResponse, type AdminSignupSocialRequest, type AdminSignupSocialResponse, type AuditHistoryResponse, type AuthAuditEvent, type AuthAuditEventStatus, AuthAuditEventType, AuthChallenge, type AuthChallengeEvent, type AuthErrorEvent, type AuthEvent, type AuthEventListener, type AuthEventType, type AuthLoginEvent, type AuthLogoutEvent, type AuthRefreshEvent, type AuthResponse, type AuthResponseContext, type AuthSessionExpiredEvent, type AuthSignupEvent, type AuthSuccessEvent, type AuthUser, type AuthUserSummary, type BackupCodesResponse, type BaseChallengeResponse, BrowserStorage, type ChallengeResponse, ChallengeRouter, type ChangePasswordRequest, type ConfirmForgotPasswordRequest, type ConfirmForgotPasswordResponse, type DateFilter, type DeleteUserResponse, type DisableUserResponse, type EnableUserResponse, EventEmitter, FetchAdapter, type ForceChangePasswordResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetChallengeDataRequest, type GetChallengeDataResponse, type GetMFADevicesResponse, type GetSetupDataRequest, type GetSetupDataResponse, type GetUserSessionsResponse, type GetUsersRequest, type GetUsersResponse, type HttpAdapter, type HttpRequest, type HttpResponse, InMemoryStorage, type LinkedAccountsResponse, type LoginRequest, type LogoutAllRequest, type LogoutRequest, type MFAChallengeMethod, type MFACodeResponse, type MFADevice, type MFADeviceMethod, type MFAMethod, type MFAPasskeyResponse, type MFASetupData, type MFASetupResponse, type MFAStatus, type MfaRoutesConfig, type NAuthAdminEndpoints, NAuthClient, type NAuthClientConfig, NAuthClientError, type NAuthEndpoints, type NAuthError, NAuthErrorCode, type NAuthRedirectsConfig, type NAuthStorageAdapter, type OAuthCallbackEvent, type OAuthCompletedEvent, type OAuthErrorEvent, type OAuthStartedEvent, type RecaptchaConfig, type RecaptchaVersion, type RemoveMFADeviceResponse, type ResendCodeRequest, type ResetPasswordWithCodeRequest, type ResetPasswordWithCodeResponse, type ResolvedNAuthClientConfig, type SignupRequest, type SocialLoginOptions, type SocialProvider, type SocialVerifyRequest, type TokenDeliveryMode, type TokenResponse, type UpdateProfileRequest, type UserSessionInfo, type VerifyEmailResponse, type VerifyPhoneCodeResponse, type VerifyPhoneCollectResponse, defaultAdminEndpoints, defaultEndpoints, getChallengeInstructions, getMFAMethod, getMaskedDestination, isOTPChallenge, requiresPhoneCollection, resolveConfig };
3711
+ export { type AdminAuditHistoryRequest, AdminOperations, type AdminResetPasswordRequest, type AdminResetPasswordResponse, type AdminSignupRequest, type AdminSignupResponse, type AdminSignupSocialRequest, type AdminSignupSocialResponse, type ApiKeyInfo, ApiKeyOperations, type AuditHistoryResponse, type AuthAuditEvent, type AuthAuditEventStatus, AuthAuditEventType, AuthChallenge, type AuthChallengeEvent, type AuthErrorEvent, type AuthEvent, type AuthEventListener, type AuthEventType, type AuthLoginEvent, type AuthLogoutEvent, type AuthRefreshEvent, type AuthResponse, type AuthResponseContext, type AuthSessionExpiredEvent, type AuthSignupEvent, type AuthSuccessEvent, type AuthUser, type AuthUserSummary, type BackupCodesResponse, type BaseChallengeResponse, BrowserStorage, type ChallengeResponse, ChallengeRouter, type ChangePasswordRequest, type ConfirmForgotPasswordRequest, type ConfirmForgotPasswordResponse, type CreateApiKeyRequest, type CreateApiKeyResult, type DateFilter, type DeleteUserResponse, type DisableUserResponse, type EnableUserResponse, EventEmitter, FetchAdapter, type ForceChangePasswordResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetChallengeDataRequest, type GetChallengeDataResponse, type GetMFADevicesResponse, type GetSetupDataRequest, type GetSetupDataResponse, type GetUserSessionsResponse, type GetUsersRequest, type GetUsersResponse, type HttpAdapter, type HttpRequest, type HttpResponse, InMemoryStorage, type LinkedAccountsResponse, type LoginRequest, type LogoutAllRequest, type LogoutRequest, type MFAChallengeMethod, type MFACodeResponse, type MFADevice, type MFADeviceMethod, type MFAMethod, type MFAPasskeyResponse, type MFASetupData, type MFASetupResponse, type MFAStatus, type MfaRoutesConfig, type NAuthAdminEndpoints, NAuthClient, type NAuthClientConfig, NAuthClientError, type NAuthEndpoints, type NAuthError, NAuthErrorCode, type NAuthRedirectsConfig, type NAuthStorageAdapter, type OAuthCallbackEvent, type OAuthCompletedEvent, type OAuthErrorEvent, type OAuthStartedEvent, type RecaptchaConfig, type RecaptchaVersion, type RemoveMFADeviceResponse, type ResendCodeRequest, type ResetPasswordWithCodeRequest, type ResetPasswordWithCodeResponse, type ResolvedNAuthClientConfig, type SignupRequest, type SocialLoginOptions, type SocialProvider, type SocialVerifyRequest, type TokenDeliveryMode, type TokenResponse, type UpdateApiKeyRequest, type UpdateProfileRequest, type UserSessionInfo, type VerifyEmailResponse, type VerifyPhoneCodeResponse, type VerifyPhoneCollectResponse, apiKeyHeader, defaultAdminEndpoints, defaultEndpoints, getChallengeInstructions, getMFAMethod, getMaskedDestination, isOTPChallenge, requiresPhoneCollection, resolveConfig };
package/dist/index.d.ts CHANGED
@@ -1778,6 +1778,72 @@ interface AdminAuditHistoryRequest {
1778
1778
  eventStatus?: string;
1779
1779
  }
1780
1780
 
1781
+ /**
1782
+ * API Key types for the NAuth client SDK.
1783
+ *
1784
+ * These mirror the backend `@nauth-toolkit/core` API key DTOs.
1785
+ */
1786
+ /**
1787
+ * Sanitized API key metadata returned by list/update operations.
1788
+ * Never contains the plaintext key.
1789
+ */
1790
+ interface ApiKeyInfo {
1791
+ /** External key identifier (UUID) */
1792
+ keyId: string;
1793
+ /** User-friendly label */
1794
+ name?: string | null;
1795
+ /** Last few characters of the key (display hint) */
1796
+ lastFour?: string | null;
1797
+ /** Allowed source IPs / CIDR ranges (empty/null = any IP) */
1798
+ allowedIps?: string[] | null;
1799
+ /** ISO expiry timestamp, or null if the key never expires */
1800
+ expiresAt?: string | null;
1801
+ /** Whether the key is active */
1802
+ isActive: boolean;
1803
+ /** Whether the key was created by an administrator */
1804
+ createdByAdmin: boolean;
1805
+ /** ISO timestamp of the last successful use, or null */
1806
+ lastUsedAt?: string | null;
1807
+ /** IP of the last successful use (when usage IP tracking is enabled) */
1808
+ lastUsedIp?: string | null;
1809
+ /** Total number of successful authentications */
1810
+ usageCount: number;
1811
+ /** ISO creation timestamp */
1812
+ createdAt: string;
1813
+ }
1814
+ /**
1815
+ * Request body for creating an API key.
1816
+ *
1817
+ * `expiresInDays` is mandatory: a positive integer for a finite expiry, or `null`
1818
+ * for a never-expiring key (only allowed when the server permits it).
1819
+ */
1820
+ interface CreateApiKeyRequest {
1821
+ /** Optional label */
1822
+ name?: string;
1823
+ /** Expiry in days, or null for never */
1824
+ expiresInDays: number | null;
1825
+ /** Optional IP allowlist (IPs / IPv4 CIDR ranges) */
1826
+ allowedIps?: string[];
1827
+ }
1828
+ /**
1829
+ * Request body for updating an API key's mutable fields (label and IP allowlist).
1830
+ */
1831
+ interface UpdateApiKeyRequest {
1832
+ /** New label */
1833
+ name?: string;
1834
+ /** Replacement IP allowlist (empty array clears restrictions) */
1835
+ allowedIps?: string[];
1836
+ }
1837
+ /**
1838
+ * Result of creating a key. The plaintext `key` is shown once.
1839
+ */
1840
+ interface CreateApiKeyResult {
1841
+ /** Full plaintext API key (store securely; shown only once) */
1842
+ key: string;
1843
+ /** Sanitized metadata for the created key */
1844
+ apiKey: ApiKeyInfo;
1845
+ }
1846
+
1781
1847
  /**
1782
1848
  * Client-side error wrapper for SDK operations.
1783
1849
  *
@@ -2694,6 +2760,82 @@ declare class AdminOperations {
2694
2760
  private handleError;
2695
2761
  }
2696
2762
 
2763
+ /**
2764
+ * Build a headers object that attaches an API key for machine-to-machine calls.
2765
+ *
2766
+ * Useful when a script or service authenticates with an API key instead of a session.
2767
+ *
2768
+ * @param key - The plaintext API key
2769
+ * @param headerName - Header name (defaults to 'X-API-Key'; must match server config)
2770
+ * @returns A headers object to merge into requests
2771
+ *
2772
+ * @example
2773
+ * ```typescript
2774
+ * const client = new NAuthClient({
2775
+ * baseUrl: 'https://api.example.com/auth',
2776
+ * tokenDelivery: 'json',
2777
+ * headers: apiKeyHeader(process.env.NAUTH_API_KEY!),
2778
+ * });
2779
+ * ```
2780
+ */
2781
+ declare function apiKeyHeader(key: string, headerName?: string): Record<string, string>;
2782
+ /**
2783
+ * API key management operations. Accessed via `client.apiKeys.*`.
2784
+ *
2785
+ * Calls the API-key management endpoints your backend mounts (defaults to `{baseUrl}/api-keys`).
2786
+ * The backend `ApiKeyService` powers these; there are no built-in routes, so ensure your
2787
+ * controllers are mounted at the expected paths (or pass a custom `basePath`).
2788
+ */
2789
+ declare class ApiKeyOperations {
2790
+ private readonly config;
2791
+ private readonly basePath;
2792
+ /**
2793
+ * @param config - Resolved client configuration
2794
+ * @param basePath - Base path for API-key endpoints (default: `{baseUrl}/api-keys`)
2795
+ */
2796
+ constructor(config: ResolvedNAuthClientConfig, basePath?: string);
2797
+ /**
2798
+ * Create a new API key. The plaintext key is returned once.
2799
+ *
2800
+ * @param request - Key options (mandatory expiry; optional IP allowlist)
2801
+ */
2802
+ create(request: CreateApiKeyRequest): Promise<CreateApiKeyResult>;
2803
+ /**
2804
+ * List the current user's API keys (sanitized).
2805
+ */
2806
+ list(): Promise<ApiKeyInfo[]>;
2807
+ /**
2808
+ * Update a key's label and/or IP allowlist.
2809
+ *
2810
+ * @param keyId - External key identifier
2811
+ * @param request - Fields to update
2812
+ */
2813
+ update(keyId: string, request: UpdateApiKeyRequest): Promise<ApiKeyInfo>;
2814
+ /**
2815
+ * Revoke (soft-delete) a key.
2816
+ *
2817
+ * @param keyId - External key identifier
2818
+ */
2819
+ revoke(keyId: string): Promise<{
2820
+ success: boolean;
2821
+ }>;
2822
+ /**
2823
+ * Permanently delete a key.
2824
+ *
2825
+ * @param keyId - External key identifier
2826
+ */
2827
+ remove(keyId: string): Promise<{
2828
+ success: boolean;
2829
+ }>;
2830
+ private buildHeaders;
2831
+ private getCsrfToken;
2832
+ private get;
2833
+ private post;
2834
+ private patch;
2835
+ private delete;
2836
+ private handleError;
2837
+ }
2838
+
2697
2839
  /**
2698
2840
  * Primary client for interacting with nauth-toolkit backend.
2699
2841
  */
@@ -2736,6 +2878,20 @@ declare class NAuthClient {
2736
2878
  * ```
2737
2879
  */
2738
2880
  readonly admin?: AdminOperations;
2881
+ /**
2882
+ * API key management operations (create/list/update/revoke/delete).
2883
+ *
2884
+ * Calls your backend's API-key endpoints (default base path `{baseUrl}/api-keys`).
2885
+ *
2886
+ * @example
2887
+ * ```typescript
2888
+ * const { key } = await client.apiKeys.create({ expiresInDays: 90, allowedIps: ['203.0.113.0/24'] });
2889
+ * const keys = await client.apiKeys.list();
2890
+ * await client.apiKeys.update(keyId, { allowedIps: ['203.0.113.5'] });
2891
+ * await client.apiKeys.revoke(keyId);
2892
+ * ```
2893
+ */
2894
+ readonly apiKeys: ApiKeyOperations;
2739
2895
  /**
2740
2896
  * Create a new client instance.
2741
2897
  *
@@ -3552,4 +3708,4 @@ declare class FetchAdapter implements HttpAdapter {
3552
3708
  request<T>(config: HttpRequest): Promise<HttpResponse<T>>;
3553
3709
  }
3554
3710
 
3555
- export { type AdminAuditHistoryRequest, AdminOperations, type AdminResetPasswordRequest, type AdminResetPasswordResponse, type AdminSignupRequest, type AdminSignupResponse, type AdminSignupSocialRequest, type AdminSignupSocialResponse, type AuditHistoryResponse, type AuthAuditEvent, type AuthAuditEventStatus, AuthAuditEventType, AuthChallenge, type AuthChallengeEvent, type AuthErrorEvent, type AuthEvent, type AuthEventListener, type AuthEventType, type AuthLoginEvent, type AuthLogoutEvent, type AuthRefreshEvent, type AuthResponse, type AuthResponseContext, type AuthSessionExpiredEvent, type AuthSignupEvent, type AuthSuccessEvent, type AuthUser, type AuthUserSummary, type BackupCodesResponse, type BaseChallengeResponse, BrowserStorage, type ChallengeResponse, ChallengeRouter, type ChangePasswordRequest, type ConfirmForgotPasswordRequest, type ConfirmForgotPasswordResponse, type DateFilter, type DeleteUserResponse, type DisableUserResponse, type EnableUserResponse, EventEmitter, FetchAdapter, type ForceChangePasswordResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetChallengeDataRequest, type GetChallengeDataResponse, type GetMFADevicesResponse, type GetSetupDataRequest, type GetSetupDataResponse, type GetUserSessionsResponse, type GetUsersRequest, type GetUsersResponse, type HttpAdapter, type HttpRequest, type HttpResponse, InMemoryStorage, type LinkedAccountsResponse, type LoginRequest, type LogoutAllRequest, type LogoutRequest, type MFAChallengeMethod, type MFACodeResponse, type MFADevice, type MFADeviceMethod, type MFAMethod, type MFAPasskeyResponse, type MFASetupData, type MFASetupResponse, type MFAStatus, type MfaRoutesConfig, type NAuthAdminEndpoints, NAuthClient, type NAuthClientConfig, NAuthClientError, type NAuthEndpoints, type NAuthError, NAuthErrorCode, type NAuthRedirectsConfig, type NAuthStorageAdapter, type OAuthCallbackEvent, type OAuthCompletedEvent, type OAuthErrorEvent, type OAuthStartedEvent, type RecaptchaConfig, type RecaptchaVersion, type RemoveMFADeviceResponse, type ResendCodeRequest, type ResetPasswordWithCodeRequest, type ResetPasswordWithCodeResponse, type ResolvedNAuthClientConfig, type SignupRequest, type SocialLoginOptions, type SocialProvider, type SocialVerifyRequest, type TokenDeliveryMode, type TokenResponse, type UpdateProfileRequest, type UserSessionInfo, type VerifyEmailResponse, type VerifyPhoneCodeResponse, type VerifyPhoneCollectResponse, defaultAdminEndpoints, defaultEndpoints, getChallengeInstructions, getMFAMethod, getMaskedDestination, isOTPChallenge, requiresPhoneCollection, resolveConfig };
3711
+ export { type AdminAuditHistoryRequest, AdminOperations, type AdminResetPasswordRequest, type AdminResetPasswordResponse, type AdminSignupRequest, type AdminSignupResponse, type AdminSignupSocialRequest, type AdminSignupSocialResponse, type ApiKeyInfo, ApiKeyOperations, type AuditHistoryResponse, type AuthAuditEvent, type AuthAuditEventStatus, AuthAuditEventType, AuthChallenge, type AuthChallengeEvent, type AuthErrorEvent, type AuthEvent, type AuthEventListener, type AuthEventType, type AuthLoginEvent, type AuthLogoutEvent, type AuthRefreshEvent, type AuthResponse, type AuthResponseContext, type AuthSessionExpiredEvent, type AuthSignupEvent, type AuthSuccessEvent, type AuthUser, type AuthUserSummary, type BackupCodesResponse, type BaseChallengeResponse, BrowserStorage, type ChallengeResponse, ChallengeRouter, type ChangePasswordRequest, type ConfirmForgotPasswordRequest, type ConfirmForgotPasswordResponse, type CreateApiKeyRequest, type CreateApiKeyResult, type DateFilter, type DeleteUserResponse, type DisableUserResponse, type EnableUserResponse, EventEmitter, FetchAdapter, type ForceChangePasswordResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetChallengeDataRequest, type GetChallengeDataResponse, type GetMFADevicesResponse, type GetSetupDataRequest, type GetSetupDataResponse, type GetUserSessionsResponse, type GetUsersRequest, type GetUsersResponse, type HttpAdapter, type HttpRequest, type HttpResponse, InMemoryStorage, type LinkedAccountsResponse, type LoginRequest, type LogoutAllRequest, type LogoutRequest, type MFAChallengeMethod, type MFACodeResponse, type MFADevice, type MFADeviceMethod, type MFAMethod, type MFAPasskeyResponse, type MFASetupData, type MFASetupResponse, type MFAStatus, type MfaRoutesConfig, type NAuthAdminEndpoints, NAuthClient, type NAuthClientConfig, NAuthClientError, type NAuthEndpoints, type NAuthError, NAuthErrorCode, type NAuthRedirectsConfig, type NAuthStorageAdapter, type OAuthCallbackEvent, type OAuthCompletedEvent, type OAuthErrorEvent, type OAuthStartedEvent, type RecaptchaConfig, type RecaptchaVersion, type RemoveMFADeviceResponse, type ResendCodeRequest, type ResetPasswordWithCodeRequest, type ResetPasswordWithCodeResponse, type ResolvedNAuthClientConfig, type SignupRequest, type SocialLoginOptions, type SocialProvider, type SocialVerifyRequest, type TokenDeliveryMode, type TokenResponse, type UpdateApiKeyRequest, type UpdateProfileRequest, type UserSessionInfo, type VerifyEmailResponse, type VerifyPhoneCodeResponse, type VerifyPhoneCollectResponse, apiKeyHeader, defaultAdminEndpoints, defaultEndpoints, getChallengeInstructions, getMFAMethod, getMaskedDestination, isOTPChallenge, requiresPhoneCollection, resolveConfig };
package/dist/index.mjs CHANGED
@@ -1436,19 +1436,182 @@ var AdminOperations = class {
1436
1436
  }
1437
1437
  };
1438
1438
 
1439
+ // src/core/api-key-operations.ts
1440
+ var hasWindow2 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1441
+ function apiKeyHeader(key, headerName = "X-API-Key") {
1442
+ return { [headerName]: key };
1443
+ }
1444
+ var ApiKeyOperations = class {
1445
+ /**
1446
+ * @param config - Resolved client configuration
1447
+ * @param basePath - Base path for API-key endpoints (default: `{baseUrl}/api-keys`)
1448
+ */
1449
+ constructor(config, basePath) {
1450
+ __publicField(this, "config");
1451
+ __publicField(this, "basePath");
1452
+ this.config = config;
1453
+ this.basePath = basePath ?? `${config.baseUrl}/api-keys`;
1454
+ }
1455
+ /**
1456
+ * Create a new API key. The plaintext key is returned once.
1457
+ *
1458
+ * @param request - Key options (mandatory expiry; optional IP allowlist)
1459
+ */
1460
+ async create(request) {
1461
+ return this.post(this.basePath, request);
1462
+ }
1463
+ /**
1464
+ * List the current user's API keys (sanitized).
1465
+ */
1466
+ async list() {
1467
+ const res = await this.get(this.basePath);
1468
+ return res.apiKeys ?? [];
1469
+ }
1470
+ /**
1471
+ * Update a key's label and/or IP allowlist.
1472
+ *
1473
+ * @param keyId - External key identifier
1474
+ * @param request - Fields to update
1475
+ */
1476
+ async update(keyId, request) {
1477
+ return this.patch(`${this.basePath}/${encodeURIComponent(keyId)}`, request);
1478
+ }
1479
+ /**
1480
+ * Revoke (soft-delete) a key.
1481
+ *
1482
+ * @param keyId - External key identifier
1483
+ */
1484
+ async revoke(keyId) {
1485
+ return this.post(`${this.basePath}/${encodeURIComponent(keyId)}/revoke`, {});
1486
+ }
1487
+ /**
1488
+ * Permanently delete a key.
1489
+ *
1490
+ * @param keyId - External key identifier
1491
+ */
1492
+ async remove(keyId) {
1493
+ return this.delete(`${this.basePath}/${encodeURIComponent(keyId)}`);
1494
+ }
1495
+ // ==========================================================================
1496
+ // Internal request helpers (mirror AdminOperations)
1497
+ // ==========================================================================
1498
+ async buildHeaders(method) {
1499
+ const headers = { ...this.config.headers };
1500
+ if (method !== "GET") {
1501
+ headers["Content-Type"] = "application/json";
1502
+ }
1503
+ if (this.config.tokenDelivery === "json") {
1504
+ try {
1505
+ const token = await this.config.storage.getItem("nauth_access_token");
1506
+ if (token) {
1507
+ headers["Authorization"] = `Bearer ${token}`;
1508
+ }
1509
+ } catch {
1510
+ }
1511
+ }
1512
+ const mutating = ["POST", "PATCH", "DELETE"];
1513
+ if (this.config.tokenDelivery === "cookies" && hasWindow2() && mutating.includes(method)) {
1514
+ const csrfToken = this.getCsrfToken();
1515
+ if (csrfToken) {
1516
+ headers[this.config.csrf.headerName] = csrfToken;
1517
+ }
1518
+ }
1519
+ return headers;
1520
+ }
1521
+ getCsrfToken() {
1522
+ if (!hasWindow2() || typeof document === "undefined") return null;
1523
+ const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
1524
+ return match ? decodeURIComponent(match[2]) : null;
1525
+ }
1526
+ async get(path) {
1527
+ const headers = await this.buildHeaders("GET");
1528
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1529
+ try {
1530
+ const response = await this.config.httpAdapter.request({ method: "GET", url: path, headers, credentials });
1531
+ return response.data;
1532
+ } catch (error) {
1533
+ throw this.handleError(error);
1534
+ }
1535
+ }
1536
+ async post(path, body) {
1537
+ const headers = await this.buildHeaders("POST");
1538
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1539
+ try {
1540
+ const response = await this.config.httpAdapter.request({
1541
+ method: "POST",
1542
+ url: path,
1543
+ headers,
1544
+ body,
1545
+ credentials
1546
+ });
1547
+ return response.data;
1548
+ } catch (error) {
1549
+ throw this.handleError(error);
1550
+ }
1551
+ }
1552
+ async patch(path, body) {
1553
+ const headers = await this.buildHeaders("PATCH");
1554
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1555
+ try {
1556
+ const response = await this.config.httpAdapter.request({
1557
+ method: "PATCH",
1558
+ url: path,
1559
+ headers,
1560
+ body,
1561
+ credentials
1562
+ });
1563
+ return response.data;
1564
+ } catch (error) {
1565
+ throw this.handleError(error);
1566
+ }
1567
+ }
1568
+ async delete(path) {
1569
+ const headers = await this.buildHeaders("DELETE");
1570
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1571
+ try {
1572
+ const response = await this.config.httpAdapter.request({
1573
+ method: "DELETE",
1574
+ url: path,
1575
+ headers,
1576
+ credentials
1577
+ });
1578
+ return response.data;
1579
+ } catch (error) {
1580
+ throw this.handleError(error);
1581
+ }
1582
+ }
1583
+ handleError(error) {
1584
+ if (error instanceof NAuthClientError) {
1585
+ return error;
1586
+ }
1587
+ if (error && typeof error === "object" && "response" in error) {
1588
+ const httpError = error;
1589
+ const status = httpError.response?.status ?? 500;
1590
+ const errorData = typeof httpError.response?.data === "object" && httpError.response.data !== null ? httpError.response.data : {};
1591
+ const code = typeof errorData["code"] === "string" ? errorData["code"] : "INTERNAL_ERROR" /* INTERNAL_ERROR */;
1592
+ const message = typeof errorData["message"] === "string" ? errorData["message"] : `Request failed with status ${status}`;
1593
+ return new NAuthClientError(code, message, { statusCode: status, details: errorData });
1594
+ }
1595
+ return new NAuthClientError(
1596
+ "INTERNAL_ERROR" /* INTERNAL_ERROR */,
1597
+ error instanceof Error ? error.message : "Unknown error"
1598
+ );
1599
+ }
1600
+ };
1601
+
1439
1602
  // src/core/client.ts
1440
1603
  var USER_KEY2 = "nauth_user";
1441
1604
  var CHALLENGE_KEY2 = "nauth_challenge_session";
1442
1605
  var OAUTH_STATE_KEY2 = "nauth_oauth_state";
1443
- var hasWindow2 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1606
+ var hasWindow3 = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1444
1607
  var getOauthStorage = (mainStorage) => {
1445
- if (hasWindow2() && typeof window.sessionStorage !== "undefined") {
1608
+ if (hasWindow3() && typeof window.sessionStorage !== "undefined") {
1446
1609
  return new BrowserStorage(window.sessionStorage);
1447
1610
  }
1448
1611
  return mainStorage;
1449
1612
  };
1450
1613
  var defaultStorage = () => {
1451
- if (hasWindow2() && typeof window.localStorage !== "undefined") {
1614
+ if (hasWindow3() && typeof window.localStorage !== "undefined") {
1452
1615
  return new BrowserStorage();
1453
1616
  }
1454
1617
  return new InMemoryStorage();
@@ -1498,6 +1661,20 @@ var NAuthClient = class {
1498
1661
  * ```
1499
1662
  */
1500
1663
  __publicField(this, "admin");
1664
+ /**
1665
+ * API key management operations (create/list/update/revoke/delete).
1666
+ *
1667
+ * Calls your backend's API-key endpoints (default base path `{baseUrl}/api-keys`).
1668
+ *
1669
+ * @example
1670
+ * ```typescript
1671
+ * const { key } = await client.apiKeys.create({ expiresInDays: 90, allowedIps: ['203.0.113.0/24'] });
1672
+ * const keys = await client.apiKeys.list();
1673
+ * await client.apiKeys.update(keyId, { allowedIps: ['203.0.113.5'] });
1674
+ * await client.apiKeys.revoke(keyId);
1675
+ * ```
1676
+ */
1677
+ __publicField(this, "apiKeys");
1501
1678
  /**
1502
1679
  * Handle cross-tab storage updates.
1503
1680
  */
@@ -1520,7 +1697,8 @@ var NAuthClient = class {
1520
1697
  if (this.config.admin) {
1521
1698
  this.admin = new AdminOperations(this.config);
1522
1699
  }
1523
- if (hasWindow2()) {
1700
+ this.apiKeys = new ApiKeyOperations(this.config);
1701
+ if (hasWindow3()) {
1524
1702
  window.addEventListener("storage", this.handleStorageEvent);
1525
1703
  }
1526
1704
  }
@@ -1528,7 +1706,7 @@ var NAuthClient = class {
1528
1706
  * Clean up resources.
1529
1707
  */
1530
1708
  dispose() {
1531
- if (hasWindow2()) {
1709
+ if (hasWindow3()) {
1532
1710
  window.removeEventListener("storage", this.handleStorageEvent);
1533
1711
  }
1534
1712
  }
@@ -2190,7 +2368,7 @@ var NAuthClient = class {
2190
2368
  */
2191
2369
  async loginWithSocial(provider, options) {
2192
2370
  this.eventEmitter.emit({ type: "oauth:started", data: { provider }, timestamp: Date.now() });
2193
- if (hasWindow2()) {
2371
+ if (hasWindow3()) {
2194
2372
  const startPath = this.config.endpoints.socialRedirectStart.replace(":provider", provider);
2195
2373
  const fullUrl = this.buildUrl(startPath);
2196
2374
  const startUrl = new URL(fullUrl);
@@ -2524,7 +2702,7 @@ var NAuthClient = class {
2524
2702
  }
2525
2703
  }
2526
2704
  const mutatingMethods = ["POST", "PUT", "PATCH", "DELETE"];
2527
- if (this.config.tokenDelivery === "cookies" && hasWindow2() && mutatingMethods.includes(method)) {
2705
+ if (this.config.tokenDelivery === "cookies" && hasWindow3() && mutatingMethods.includes(method)) {
2528
2706
  const csrfToken = this.getCsrfToken();
2529
2707
  if (csrfToken) {
2530
2708
  headers[this.config.csrf.headerName] = csrfToken;
@@ -2537,7 +2715,7 @@ var NAuthClient = class {
2537
2715
  * @private
2538
2716
  */
2539
2717
  getCsrfToken() {
2540
- if (!hasWindow2() || typeof document === "undefined") return null;
2718
+ if (!hasWindow3() || typeof document === "undefined") return null;
2541
2719
  const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
2542
2720
  return match ? decodeURIComponent(match[2]) : null;
2543
2721
  }
@@ -2717,6 +2895,7 @@ function isOTPChallenge(challenge) {
2717
2895
  }
2718
2896
  export {
2719
2897
  AdminOperations,
2898
+ ApiKeyOperations,
2720
2899
  AuthAuditEventType,
2721
2900
  AuthChallenge,
2722
2901
  BrowserStorage,
@@ -2727,6 +2906,7 @@ export {
2727
2906
  NAuthClient,
2728
2907
  NAuthClientError,
2729
2908
  NAuthErrorCode,
2909
+ apiKeyHeader,
2730
2910
  defaultAdminEndpoints,
2731
2911
  defaultEndpoints,
2732
2912
  getChallengeInstructions,