@mosano-product-framework/sdk 0.2.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.
Files changed (74) hide show
  1. package/README.md +827 -0
  2. package/README.react.md +348 -0
  3. package/dist/auth/claims-types.d.ts +89 -0
  4. package/dist/auth/claims.d.ts +125 -0
  5. package/dist/auth/cross-tab.d.ts +114 -0
  6. package/dist/auth/errors.d.ts +40 -0
  7. package/dist/auth/index.d.ts +18 -0
  8. package/dist/auth/index.js +5 -0
  9. package/dist/auth/index.js.map +1 -0
  10. package/dist/auth/oauth-state.d.ts +93 -0
  11. package/dist/auth/session-manager.d.ts +253 -0
  12. package/dist/auth/storage.d.ts +36 -0
  13. package/dist/auth/tenant-directory.d.ts +59 -0
  14. package/dist/auth/tenant-selection.d.ts +92 -0
  15. package/dist/chunk-7WAV52EO.js +621 -0
  16. package/dist/chunk-7WAV52EO.js.map +1 -0
  17. package/dist/chunk-AJWM5MDZ.js +410 -0
  18. package/dist/chunk-AJWM5MDZ.js.map +1 -0
  19. package/dist/chunk-EXPYHNPV.js +212 -0
  20. package/dist/chunk-EXPYHNPV.js.map +1 -0
  21. package/dist/chunk-GPWGOYCA.js +85 -0
  22. package/dist/chunk-GPWGOYCA.js.map +1 -0
  23. package/dist/chunk-GQJ3QQPH.js +339 -0
  24. package/dist/chunk-GQJ3QQPH.js.map +1 -0
  25. package/dist/chunk-K2ELAI2X.js +64 -0
  26. package/dist/chunk-K2ELAI2X.js.map +1 -0
  27. package/dist/chunk-LRM6JJ63.js +616 -0
  28. package/dist/chunk-LRM6JJ63.js.map +1 -0
  29. package/dist/chunk-XAXFIIRT.js +959 -0
  30. package/dist/chunk-XAXFIIRT.js.map +1 -0
  31. package/dist/client/core/client-factory.d.ts +61 -0
  32. package/dist/client/core/client.d.ts +144 -0
  33. package/dist/client/core/errors.d.ts +105 -0
  34. package/dist/client/core/index.d.ts +9 -0
  35. package/dist/client/core/middleware.d.ts +67 -0
  36. package/dist/client/core/types.d.ts +99 -0
  37. package/dist/client/graphql/client.d.ts +66 -0
  38. package/dist/client/graphql/factory.d.ts +84 -0
  39. package/dist/client/graphql/operation.d.ts +24 -0
  40. package/dist/client/graphql/types.d.ts +60 -0
  41. package/dist/client/graphql/ws-client.d.ts +116 -0
  42. package/dist/client/index.d.ts +17 -0
  43. package/dist/client/index.js +227 -0
  44. package/dist/client/index.js.map +1 -0
  45. package/dist/client/middlewares/admin-auth.d.ts +90 -0
  46. package/dist/client/middlewares/auth.d.ts +81 -0
  47. package/dist/client/middlewares/index.d.ts +12 -0
  48. package/dist/client/middlewares/logging.d.ts +102 -0
  49. package/dist/client/middlewares/retry.d.ts +138 -0
  50. package/dist/client/middlewares/tenant.d.ts +60 -0
  51. package/dist/client/middlewares/turnstile.d.ts +41 -0
  52. package/dist/client/peer-free.d.ts +25 -0
  53. package/dist/client/utils/url.d.ts +19 -0
  54. package/dist/identity/index.d.ts +85 -0
  55. package/dist/identity/index.js +6 -0
  56. package/dist/identity/index.js.map +1 -0
  57. package/dist/identity/types.d.ts +690 -0
  58. package/dist/identity/v0.d.ts +594 -0
  59. package/dist/index.d.ts +50 -0
  60. package/dist/index.js +24 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/react/context.d.ts +47 -0
  63. package/dist/react/hooks.d.ts +120 -0
  64. package/dist/react/index.d.ts +19 -0
  65. package/dist/react/index.js +308 -0
  66. package/dist/react/index.js.map +1 -0
  67. package/dist/react/provider.d.ts +68 -0
  68. package/dist/react/store.d.ts +85 -0
  69. package/dist/storage/index.d.ts +31 -0
  70. package/dist/storage/index.js +5 -0
  71. package/dist/storage/index.js.map +1 -0
  72. package/dist/storage/types.d.ts +107 -0
  73. package/dist/storage/v0.d.ts +120 -0
  74. package/package.json +99 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/identity/index.ts","../src/identity/v0.ts","../src/identity/types.ts"],"names":[],"mappings":";;;;;AAAA,IAAA,gBAAA,GAAA;AAAA,QAA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AAA;AAC7E;;;AF1rBA,IAAM,yBAAA,GAA4B;AAAA,EAChC,yBAAA;AAAA,EACA,yBAAA;AAAA,EACA,6BAAA;AAAA,EACA,2BAAA;AAAA,EACA,iBAAA;AAAA,EACA,sBAAA;AAAA,EACA,uBAAA;AAAA,EACA,wBAAA;AAAA,EACA,SAAA;AAAA;AAAA,EACA;AAAA;AACF,CAAA;AAEO,SAAS,iBAAiB,OAAA,EAA0C;AACzE,EAAA,MAAM,EAAE,aAAA,EAAe,iBAAA,EAAmB,cAAA,EAAgB,GAAG,cAAa,GAAI,OAAA;AAC9E,EAAA,MAAM,MAAA,GAAS,IAAI,YAAA,CAAa,YAAY,CAAA;AAE5C,EAAA,yBAAA,CAA0B,MAAA,EAAQ,EAAE,aAAA,EAAe,cAAA,EAAgB,CAAA;AAEnE,EAAA,IAAI,iBAAA,EAAmB;AACrB,IAAA,MAAA,CAAO,IAAI,yBAAA,CAA0B;AAAA,MACnC,UAAU,iBAAA,CAAkB,QAAA;AAAA,MAC5B,cAAA,EAAgB;AAAA,KACjB,CAAC,CAAA;AAAA,EACJ;AAEA,EAAA,OAAO,MAAA;AACT;AA+CO,SAAS,kBAAkB,OAAA,EAA2C;AAC3E,EAAA,MAAM,EAAE,KAAA,EAAO,GAAG,YAAA,EAAa,GAAI,OAAA;AACnC,EAAA,MAAM,MAAA,GAAS,IAAI,YAAA,CAAa,YAAY,CAAA;AAC5C,EAAA,MAAA,CAAO,GAAA,CAAI,yBAAA,CAA0B,KAAK,CAAC,CAAA;AAC3C,EAAA,OAAO,MAAA;AACT","file":"chunk-XAXFIIRT.js","sourcesContent":["import type { ClientConfig, TokenProvider } from '../client/core/types.js';\nimport { attachStandardMiddlewares } from '../client/core/client-factory.js';\nimport { createTurnstileMiddleware } from '../client/middlewares/turnstile.js';\nimport {\n createAdminAuthMiddleware,\n type AdminAuthMiddlewareOptions,\n} from '../client/middlewares/admin-auth.js';\nimport type { TenantSelectionStore } from '../auth/tenant-selection.js';\nimport type { OAuthStateStore } from '../auth/oauth-state.js';\nimport { AuthClientV0 } from './v0.js';\n\n/**\n * Provider for minting single-use Cloudflare Turnstile tokens.\n */\nexport interface TurnstileProvider {\n /** Mint a fresh single-use Turnstile token. */\n getToken: () => Promise<string>;\n}\n\n/**\n * Configuration options for the Auth client\n */\nexport interface AuthClientOptions extends Omit<ClientConfig, 'baseUrl'> {\n /**\n * Base URL for the Auth service\n */\n baseUrl: string;\n /** Optional token provider. Auto-wires auth middleware when provided. */\n tokenProvider?: TokenProvider;\n /** Optional Turnstile token provider for bot protection. */\n turnstileProvider?: TurnstileProvider;\n /**\n * Optional shared tenant selection. When provided, every request carries the\n * selected tenant headers. Construct it with `createTenantSelection()` and\n * share the same instance across identity/storage/graphql clients.\n */\n tenantProvider?: TenantSelectionStore;\n /**\n * Optional store for the OAuth CSRF state. When provided,\n * `getGoogleOAuthURL` persists the minted state so it survives the redirect.\n * Build one with `createOAuthStateStore()`.\n */\n oauthStateStore?: OAuthStateStore;\n}\n\n/**\n * Creates an Auth client for API v0\n *\n * @param options - Client configuration options\n * @returns AuthClientV0 instance\n *\n * @example\n * ```typescript\n * import { createAuthClient } from '@mosano-product-framework/sdk/identity';\n *\n * // Create client without authentication (for public endpoints)\n * const auth = createAuthClient({\n * baseUrl: 'https://api.example.com/auth',\n * });\n *\n * // Register a new user\n * const { access_token, refresh_token } = await auth.signUpEmailPassword({\n * name: 'John Doe',\n * email: 'john@example.com',\n * password: 'securePassword123',\n * });\n *\n * // Create authenticated client with token provider\n * const authenticatedAuth = createAuthClient({\n * baseUrl: 'https://api.example.com/auth',\n * tokenProvider: {\n * getAccessToken: () => localStorage.getItem('accessToken'),\n * onTokenExpired: () => { window.location.href = '/login'; },\n * },\n * });\n *\n * // Get user profile\n * const profile = await authenticatedAuth.getMe();\n * ```\n */\n/**\n * SDK endpoint paths that require a Turnstile token.\n * Must match the go-identity routes with turnstile.Verify() middleware.\n */\nconst TURNSTILE_PROTECTED_PATHS = [\n '/sign-up-email-password',\n '/sign-in-email-password',\n '/forgot-password-with-email',\n '/password/recovery/verify',\n '/password/reset',\n '/passkey/login/begin',\n '/passkey/login/finish',\n '/oauth/google/callback',\n '/accept', // matches /invitations/{token}/accept\n '/invite', // matches /tenants/{id}/members/invite\n];\n\nexport function createAuthClient(options: AuthClientOptions): AuthClientV0 {\n const { tokenProvider, turnstileProvider, tenantProvider, ...clientConfig } = options;\n const client = new AuthClientV0(clientConfig);\n\n attachStandardMiddlewares(client, { tokenProvider, tenantProvider });\n\n if (turnstileProvider) {\n client.use(createTurnstileMiddleware({\n getToken: turnstileProvider.getToken,\n protectedPaths: TURNSTILE_PROTECTED_PATHS,\n }));\n }\n\n return client;\n}\n\n/**\n * Configuration options for an admin-authenticated Auth client.\n *\n * SECURITY: Admin authentication uses the shared `ADMIN_JWT_SECRET`, which can\n * impersonate any user. Only construct an admin client server-side / in trusted\n * services. NEVER ship the secret to a browser.\n */\nexport interface AdminClientOptions extends Omit<ClientConfig, 'baseUrl'> {\n /** Base URL for the Auth service. */\n baseUrl: string;\n /** Admin auth options: either a pre-minted `token` or a minting `config`. */\n admin: AdminAuthMiddlewareOptions;\n}\n\n/**\n * Creates an admin-authenticated Auth client for API v0.\n *\n * The returned client sends `Authorization: Admin <jwt>` on every request,\n * acting on behalf of the configured principal. Mirrors {@link createAuthClient}\n * but wires the admin auth middleware instead of the Bearer one.\n *\n * SECURITY: Requires the shared `ADMIN_JWT_SECRET` (when using a minting\n * `config`). Server-side / trusted-service use ONLY — never expose the secret\n * to a browser.\n *\n * @param options - Client configuration options.\n * @returns AuthClientV0 instance authenticated as an admin.\n *\n * @example\n * ```typescript\n * import { createAdminClient } from '@mosano-product-framework/sdk/identity';\n *\n * // Mint a fresh admin token per request (server-side only).\n * const admin = createAdminClient({\n * baseUrl: 'https://api.example.com/auth',\n * admin: {\n * config: {\n * secret: process.env.ADMIN_JWT_SECRET!,\n * actOnBehalfOf: { userId, onTenantId: tenantId },\n * ttlSeconds: 60,\n * },\n * },\n * });\n * ```\n */\nexport function createAdminClient(options: AdminClientOptions): AuthClientV0 {\n const { admin, ...clientConfig } = options;\n const client = new AuthClientV0(clientConfig);\n client.use(createAdminAuthMiddleware(admin));\n return client;\n}\n\nexport { AuthClientV0, type AuthClientV0Config } from './v0.js';\nexport * from './types.js';\n","import { MPFClient } from '../client/core/client.js';\nimport type { ClientConfig, RequestOptions } from '../client/core/types.js';\nimport { MPFValidationError } from '../client/core/errors.js';\nimport type { OAuthStateStore } from '../auth/oauth-state.js';\nimport type * as Types from './types.js';\n\n/**\n * Configuration for the identity client.\n */\nexport interface AuthClientV0Config extends ClientConfig {\n /**\n * Optional store for the OAuth CSRF state. When provided,\n * `getGoogleOAuthURL` persists the minted state automatically so it survives\n * the redirect.\n *\n * Sending it back stays explicit — `GoogleOAuthCallbackRequest.state` is\n * required — because a security parameter should not be injected invisibly.\n */\n oauthStateStore?: OAuthStateStore;\n}\n\n/**\n * Auth API v0 client\n *\n * Provides methods for authentication, user management, sessions,\n * password recovery, and multi-tenant operations.\n */\nexport class AuthClientV0 extends MPFClient {\n /** Optional OAuth state store; see {@link AuthClientV0Config.oauthStateStore}. */\n private readonly oauthStateStore?: OAuthStateStore;\n\n constructor(config: AuthClientV0Config) {\n const { oauthStateStore, ...clientConfig } = config;\n super({\n ...clientConfig,\n baseUrl: `${clientConfig.baseUrl}/v0`,\n });\n this.oauthStateStore = oauthStateStore;\n }\n\n /**\n * Wraps request options with skipAuth: true for public endpoints\n * that do not require authentication headers.\n */\n private publicOptions(options?: RequestOptions): RequestOptions {\n return { ...options, skipAuth: true };\n }\n\n // ============================================================================\n // Public Endpoints - Authentication\n // ============================================================================\n\n /**\n * Register a new user with email and password\n *\n * Creates a new user account and returns access and refresh tokens.\n *\n * @param data - User registration data\n * @param options - Optional request options\n * @returns Access and refresh tokens\n */\n async signUpEmailPassword(\n data: Types.CreateUserRequest,\n options?: RequestOptions\n ): Promise<Types.AccessDataResponse> {\n const cleanedData = {\n email: data.email,\n password: data.password,\n ...(data.first_name ? { first_name: data.first_name } : {}),\n ...(data.last_name ? { last_name: data.last_name } : {}),\n ...(data.display_name ? { display_name: data.display_name } : {}),\n };\n return this.post<Types.AccessDataResponse>(\n '/sign-up-email-password',\n cleanedData,\n this.publicOptions(options)\n );\n }\n\n /**\n * Login with email and password\n *\n * Authenticates a user and returns access and refresh tokens.\n *\n * @param data - Login credentials\n * @param options - Optional request options\n * @returns Access and refresh tokens\n */\n async signInEmailPassword(\n data: Types.LoginRequest,\n options?: RequestOptions\n ): Promise<Types.LoginResponse> {\n return this.post<Types.LoginResponse>(\n '/sign-in-email-password',\n data,\n this.publicOptions(options)\n );\n }\n\n /**\n * Verify MFA code to complete login\n *\n * After a login attempt returns mfa_required, submit the TOTP code\n * along with the MFA ticket to complete authentication.\n *\n * @param data - MFA ticket and TOTP code\n * @param options - Optional request options\n * @returns Access and refresh tokens\n */\n async verifyMFA(\n data: Types.MFAVerifyRequest,\n options?: RequestOptions\n ): Promise<Types.AccessDataResponse> {\n return this.post<Types.AccessDataResponse>(\n '/mfa/verify',\n data,\n this.publicOptions(options)\n );\n }\n\n /**\n * Verify MFA setup to complete first-time enrollment and login\n *\n * After a login attempt returns mfa_setup_required, verify the TOTP\n * setup by submitting a code from the authenticator app.\n *\n * @param data - MFA ticket and verification code\n * @param options - Optional request options\n * @returns Access and refresh tokens\n */\n async verifyMFASetup(\n data: Types.MFASetupVerifyRequest,\n options?: RequestOptions\n ): Promise<Types.AccessDataResponse> {\n return this.post<Types.AccessDataResponse>(\n '/mfa/setup/verify',\n data,\n this.publicOptions(options)\n );\n }\n\n // ============================================================================\n // Public Endpoints - Password Recovery\n // ============================================================================\n\n /**\n * Send password recovery code to email\n *\n * Initiates the password recovery process by sending a verification code.\n *\n * @param data - Email address for recovery\n * @param options - Optional request options\n * @returns Success response\n */\n async forgotPasswordWithEmail(\n data: Types.SendRecoveryCodeRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>(\n '/forgot-password-with-email',\n data,\n this.publicOptions(options)\n );\n }\n\n /**\n * Verify password recovery code\n *\n * Verifies the recovery code and returns a recovery token for password reset.\n *\n * @param data - Email and verification code\n * @param options - Optional request options\n * @returns Recovery token for password reset\n */\n async verifyRecoveryCode(\n data: Types.VerifyRecoveryCodeRequest,\n options?: RequestOptions\n ): Promise<Types.RecoveryTokenResponse> {\n return this.post<Types.RecoveryTokenResponse>(\n '/password/recovery/verify',\n data,\n this.publicOptions(options)\n );\n }\n\n /**\n * Reset password with recovery token\n *\n * Resets the user's password and returns new access and refresh tokens.\n *\n * @param data - Recovery token and new password\n * @param options - Optional request options\n * @returns Access and refresh tokens\n */\n async resetPassword(\n data: Types.ResetPasswordRequest,\n options?: RequestOptions\n ): Promise<Types.AccessDataResponse> {\n return this.post<Types.AccessDataResponse>(\n '/password/reset',\n data,\n this.publicOptions(options)\n );\n }\n\n // ============================================================================\n // Public Endpoints - Sessions\n // ============================================================================\n\n /**\n * Renew session with refresh token\n *\n * Exchanges a valid refresh token for new access and refresh tokens.\n *\n * Tenant is selected per request via the `X-MPF-Tenant` header, so a renewal\n * neither takes nor changes a tenant.\n *\n * @param data - Refresh token\n * @param options - Optional request options\n * @returns Access and refresh tokens\n */\n async renewSession(\n data: Types.RenewSessionRequest,\n options?: RequestOptions\n ): Promise<Types.AccessDataResponse> {\n return this.post<Types.AccessDataResponse>(\n '/sessions/renew',\n data,\n this.publicOptions(options)\n );\n }\n\n /**\n * Revoke session (logout)\n *\n * Revokes the session associated with the provided refresh token.\n * Requires authentication.\n *\n * @param data - Refresh token to revoke\n * @param options - Optional request options\n * @returns Success response\n */\n async revokeSession(\n data: Types.RevokeSessionRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>(\n '/sessions/revoke',\n data,\n options\n );\n }\n\n // ============================================================================\n // Public Endpoints - Invitations\n // ============================================================================\n\n /**\n * List pending invitations for the authenticated user\n *\n * Returns all pending invitations for the currently authenticated user.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns Array of pending invitations\n */\n async listMyInvitations(\n options?: RequestOptions\n ): Promise<Types.PendingInvitationResponse[]> {\n return this.get<Types.PendingInvitationResponse[]>(\n '/users/me/invitations',\n options\n );\n }\n\n /**\n * Preview an invitation (public, pre-auth).\n *\n * Returns the tenant, role, and inviter display name for the\n * invitation-acceptance page. Email is intentionally omitted. Use this\n * to render the accept page before the user signs in.\n *\n * @param token - Invitation token\n * @param options - Optional request options\n * @returns Public-safe invitation preview\n */\n async previewInvitation(\n token: string,\n options?: RequestOptions\n ): Promise<Types.InvitationPreviewResponse> {\n return this.get<Types.InvitationPreviewResponse>(\n `/invitations/${encodeURIComponent(token)}`,\n this.publicOptions(options)\n );\n }\n\n /**\n * Accept an invitation.\n *\n * Requires the user to be authenticated. The user's primary verified\n * email must match the invitation. Creates the membership row.\n *\n * @param token - Invitation token\n * @param options - Optional request options\n * @returns Acceptance result (invitation + new membership)\n */\n async acceptInvitation(\n token: string,\n options?: RequestOptions\n ): Promise<Types.AcceptInvitationResponse> {\n return this.post<Types.AcceptInvitationResponse>(\n `/invitations/${encodeURIComponent(token)}/accept`,\n undefined,\n options\n );\n }\n\n /**\n * Revoke a pending invitation. Caller must be a manager of the tenant\n * that issued the invitation.\n *\n * @param invitationId - Invitation ID (not the token)\n * @param options - Optional request options\n */\n async revokeInvitation(\n invitationId: string,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.delete<Types.SuccessResponse>(\n `/invitations/${encodeURIComponent(invitationId)}`,\n options\n );\n }\n\n // ============================================================================\n // Public Endpoints - Health\n // ============================================================================\n\n /**\n * Health check endpoint\n *\n * Returns the health status of the service.\n *\n * @param options - Optional request options\n * @returns Health status\n */\n async healthCheck(options?: RequestOptions): Promise<Types.HealthResponse> {\n return this.get<Types.HealthResponse>('/healthz', this.publicOptions(options));\n }\n\n // ============================================================================\n // Protected Endpoints - User Profile\n // ============================================================================\n\n /**\n * Get current user profile\n *\n * Returns the authenticated user's profile information.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns User profile\n */\n async getMe(options?: RequestOptions): Promise<Types.UserProfileResponse> {\n return this.get<Types.UserProfileResponse>('/users/me', options);\n }\n\n /**\n * Update current user profile\n *\n * Updates the authenticated user's profile information.\n * Requires authentication.\n *\n * @param data - Profile update data\n * @param options - Optional request options\n * @returns Updated user profile\n */\n async updateMe(\n data: Types.UpdateProfileRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.patch<Types.SuccessResponse>('/users/me', data, options);\n }\n\n // ============================================================================\n // Protected Endpoints - Emails\n // ============================================================================\n\n /**\n * List user emails\n *\n * Returns all email addresses associated with the authenticated user.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns Array of email addresses\n */\n async listEmails(options?: RequestOptions): Promise<Types.EmailResponse[]> {\n const response = await this.get<Types.EmailsResponse>('/users/me/emails', options);\n return response.emails;\n }\n\n /**\n * Add a new email address\n *\n * Adds a new email address to the authenticated user's account.\n * A verification code will be sent to the email.\n * Requires authentication.\n *\n * @param data - Email address to add\n * @param options - Optional request options\n * @returns Added email information\n */\n async addEmail(\n data: Types.AddEmailRequest,\n options?: RequestOptions\n ): Promise<Types.EmailResponse> {\n return this.post<Types.EmailResponse>('/users/me/emails', data, options);\n }\n\n /**\n * Verify an email address\n *\n * Verifies an email address using a verification code.\n * Requires authentication.\n *\n * @param emailId - Email ID to verify\n * @param data - Verification code\n * @param options - Optional request options\n * @returns Success response\n */\n async verifyEmail(\n emailId: string,\n data: Types.VerifyContactRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>(\n `/users/me/emails/${encodeURIComponent(emailId)}/verify`,\n data,\n options\n );\n }\n\n /**\n * Delete an email address\n *\n * Removes an email address from the authenticated user's account.\n * Cannot delete the primary email.\n * Requires authentication.\n *\n * @param emailId - Email ID to delete\n * @param options - Optional request options\n * @returns Success response\n */\n async deleteEmail(\n emailId: string,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.delete<Types.SuccessResponse>(\n `/users/me/emails/${encodeURIComponent(emailId)}`,\n undefined,\n options\n );\n }\n\n /**\n * Set email as primary\n *\n * Sets the specified email address as the primary email for the user.\n * Email must be verified before it can be set as primary.\n * Requires authentication.\n *\n * @param emailId - Email ID to set as primary\n * @param options - Optional request options\n * @returns Success response\n */\n async setPrimaryEmail(\n emailId: string,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>(\n `/users/me/emails/${encodeURIComponent(emailId)}/set-primary`,\n undefined,\n options\n );\n }\n\n /**\n * Send email verification code\n *\n * Sends a verification code to the authenticated user's primary email address.\n * Use verifyEmail() to complete the verification.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns Success response\n */\n async sendEmailVerification(\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>(\n '/email/send-verification',\n undefined,\n options\n );\n }\n\n // ============================================================================\n // Protected Endpoints - Phones\n // ============================================================================\n\n /**\n * List user phones\n *\n * Returns all phone numbers associated with the authenticated user.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns Array of phone numbers\n */\n async listPhones(options?: RequestOptions): Promise<Types.PhoneResponse[]> {\n const response = await this.get<Types.PhonesResponse>('/users/me/phones', options);\n return response.phones;\n }\n\n /**\n * Add a new phone number\n *\n * Adds a new phone number to the authenticated user's account.\n * A verification code will be sent to the phone.\n * Requires authentication.\n *\n * @param data - Phone number to add (E.164 format)\n * @param options - Optional request options\n * @returns Added phone information\n */\n async addPhone(\n data: Types.AddPhoneRequest,\n options?: RequestOptions\n ): Promise<Types.PhoneResponse> {\n return this.post<Types.PhoneResponse>('/users/me/phones', data, options);\n }\n\n /**\n * Verify a phone number\n *\n * Verifies a phone number using a verification code.\n * Requires authentication.\n *\n * @param phoneId - Phone ID to verify\n * @param data - Verification code\n * @param options - Optional request options\n * @returns Success response\n */\n async verifyPhone(\n phoneId: string,\n data: Types.VerifyContactRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>(\n `/users/me/phones/${encodeURIComponent(phoneId)}/verify`,\n data,\n options\n );\n }\n\n /**\n * Delete a phone number\n *\n * Removes a phone number from the authenticated user's account.\n * Cannot delete the primary phone.\n * Requires authentication.\n *\n * @param phoneId - Phone ID to delete\n * @param options - Optional request options\n * @returns Success response\n */\n async deletePhone(\n phoneId: string,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.delete<Types.SuccessResponse>(\n `/users/me/phones/${encodeURIComponent(phoneId)}`,\n undefined,\n options\n );\n }\n\n /**\n * Set phone as primary\n *\n * Sets the specified phone number as the primary phone for the user.\n * Phone must be verified before it can be set as primary.\n * Requires authentication.\n *\n * @param phoneId - Phone ID to set as primary\n * @param options - Optional request options\n * @returns Success response\n */\n async setPrimaryPhone(\n phoneId: string,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>(\n `/users/me/phones/${encodeURIComponent(phoneId)}/set-primary`,\n undefined,\n options\n );\n }\n\n // ============================================================================\n // Protected Endpoints - Sessions\n // ============================================================================\n\n /**\n * List user sessions\n *\n * Returns all active sessions for the authenticated user.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns Array of sessions\n */\n async listSessions(\n options?: RequestOptions\n ): Promise<Types.SessionResponse[]> {\n const response = await this.get<Types.SessionsResponse>('/users/me/sessions', options);\n return response.sessions;\n }\n\n /**\n * Delete a session\n *\n * Revokes a specific session for the authenticated user.\n * Requires authentication.\n *\n * @param sessionId - Session ID to delete\n * @param options - Optional request options\n * @returns Success response\n */\n async deleteSession(\n sessionId: string,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.delete<Types.SuccessResponse>(\n `/users/me/sessions/${encodeURIComponent(sessionId)}`,\n undefined,\n options\n );\n }\n\n // ============================================================================\n // Protected Endpoints - Clients\n // ============================================================================\n\n /**\n * List authorized OAuth clients\n *\n * Returns all OAuth clients authorized by the authenticated user.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns Array of OAuth clients\n */\n async listClients(options?: RequestOptions): Promise<Types.ClientResponse[]> {\n const response = await this.get<Types.ClientsResponse>('/users/me/clients', options);\n return response.clients;\n }\n\n /**\n * Revoke OAuth client authorization\n *\n * Revokes authorization for a specific OAuth client.\n * Requires authentication.\n *\n * @param clientId - Client ID to revoke\n * @param options - Optional request options\n * @returns Success response\n */\n async deleteClient(\n clientId: string,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.delete<Types.SuccessResponse>(\n `/users/me/clients/${encodeURIComponent(clientId)}`,\n undefined,\n options\n );\n }\n\n // ============================================================================\n // Protected Endpoints - Password\n // ============================================================================\n\n /**\n * Update password (authenticated)\n *\n * Updates the authenticated user's password.\n * Requires authentication.\n *\n * @param data - Current and new password\n * @param options - Optional request options\n * @returns Success response\n */\n async updatePassword(\n data: Types.UpdatePasswordRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>(\n '/password/update',\n data,\n options\n );\n }\n\n // ============================================================================\n // Protected Endpoints - Tenants\n // ============================================================================\n\n /**\n * Create a new tenant\n *\n * Creates a new tenant organization. The authenticated user becomes the owner.\n * Requires authentication.\n *\n * @param data - Tenant creation data\n * @param options - Optional request options\n * @returns Created tenant information\n */\n async createTenant(\n data: Types.CreateTenantRequest,\n options?: RequestOptions\n ): Promise<Types.TenantResponse> {\n return this.post<Types.TenantResponse>('/tenants', data, options);\n }\n\n /**\n * List current user's tenants\n *\n * Returns all tenants the authenticated user is a member of.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns Array of tenant information\n */\n async listMyTenants(\n options?: RequestOptions\n ): Promise<Types.TenantResponse[]> {\n return this.get<Types.TenantResponse[]>('/users/me/tenants', options);\n }\n\n // ============================================================================\n // Protected Endpoints - Tenant Members\n // ============================================================================\n\n /**\n * List tenant members\n *\n * Returns all members of the specified tenant.\n * Requires authentication and membership in the tenant.\n *\n * @param tenantId - Tenant ID\n * @param options - Optional request options\n * @returns Array of tenant members\n */\n async listTenantMembers(\n tenantId: string,\n options?: RequestOptions\n ): Promise<Types.MembershipResponse[]> {\n const response = await this.get<Types.MembersResponse>(\n `/tenants/${encodeURIComponent(tenantId)}/members`,\n options\n );\n return response.members;\n }\n\n /**\n * Invite a member to tenant\n *\n * Sends an invitation to join the tenant. Requires authentication and\n * owner/admin role on the tenant.\n *\n * @param tenantId - Target tenant ID\n * @param data - Invitation data\n * @param options - Optional request options\n * @returns Invitation result, including a copyable accept_url\n */\n async inviteTenantMember(\n tenantId: string,\n data: Types.InviteMemberRequest,\n options?: RequestOptions\n ): Promise<Types.InvitationResponse> {\n return this.post<Types.InvitationResponse>(\n `/tenants/${encodeURIComponent(tenantId)}/members/invite`,\n data,\n options\n );\n }\n\n /**\n * List pending invitations issued by the authenticated caller for a tenant.\n *\n * Returns only invitations whose `invited_by` matches the caller. Lets the\n * caller copy the `accept_url` of an invite they previously sent (for\n * example, to re-share if email delivery failed). Callers without a\n * membership, and members who never issued an invite for this tenant,\n * get an empty array.\n *\n * @param tenantId - Tenant ID\n * @param options - Optional request options\n * @returns Array of invitations issued by the caller\n */\n async listTenantInvitationsIssuedByMe(\n tenantId: string,\n options?: RequestOptions\n ): Promise<Types.IssuedInvitationResponse[]> {\n const response = await this.get<Types.IssuedInvitationsResponse>(\n `/tenants/${encodeURIComponent(tenantId)}/invitations`,\n options\n );\n return response.invitations;\n }\n\n /**\n * Update member role\n *\n * Updates the role of a tenant member.\n * Requires authentication and owner role in the tenant.\n *\n * @param tenantId - Tenant ID\n * @param userId - User ID of the member\n * @param data - New role\n * @param options - Optional request options\n * @returns Updated membership information\n */\n async updateTenantMemberRole(\n tenantId: string,\n userId: string,\n data: Types.UpdateMemberRoleRequest,\n options?: RequestOptions\n ): Promise<Types.MembershipResponse> {\n return this.patch<Types.MembershipResponse>(\n `/tenants/${encodeURIComponent(tenantId)}/members/${encodeURIComponent(userId)}`,\n data,\n options\n );\n }\n\n /**\n * Remove member from tenant\n *\n * Removes a member from the tenant.\n * Cannot remove the last owner.\n * Requires authentication and admin/owner role in the tenant.\n *\n * @param tenantId - Tenant ID\n * @param userId - User ID of the member to remove\n * @param options - Optional request options\n * @returns Success response\n */\n async removeTenantMember(\n tenantId: string,\n userId: string,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.delete<Types.SuccessResponse>(\n `/tenants/${encodeURIComponent(tenantId)}/members/${encodeURIComponent(userId)}`,\n undefined,\n options\n );\n }\n\n // ============================================================================\n // Protected Endpoints - TOTP (Two-Factor Authentication)\n // ============================================================================\n\n /**\n * Setup TOTP two-factor authentication\n *\n * Initializes TOTP setup and returns the secret, QR code URL, and backup codes.\n * The setup must be verified with verifyTOTP() before it becomes active.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns TOTP setup data including secret and backup codes\n */\n async setupTOTP(\n options?: RequestOptions\n ): Promise<Types.TOTPSetupResponse> {\n return this.post<Types.TOTPSetupResponse>(\n '/totp/setup',\n undefined,\n options\n );\n }\n\n /**\n * Verify TOTP setup\n *\n * Verifies a TOTP code to complete the 2FA setup process.\n * After verification, TOTP will be required on future logins.\n * Requires authentication.\n *\n * @param data - TOTP verification code\n * @param options - Optional request options\n * @returns Success response\n */\n async verifyTOTP(\n data: Types.VerifyTOTPRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>('/totp/verify', data, options);\n }\n\n /**\n * Disable TOTP two-factor authentication\n *\n * Disables TOTP 2FA. Requires a valid TOTP code to confirm.\n * Requires authentication.\n *\n * @param data - TOTP code to confirm disable\n * @param options - Optional request options\n * @returns Success response\n */\n async disableTOTP(\n data: Types.DisableTOTPRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.post<Types.SuccessResponse>('/totp/disable', data, options);\n }\n\n // ============================================================================\n // Passkey / WebAuthn - Public Endpoints\n // ============================================================================\n\n /**\n * Begin passkey login\n *\n * Starts the WebAuthn authentication process.\n * Returns options to pass to navigator.credentials.get().\n *\n * @param options - Optional request options\n * @returns WebAuthn request options\n */\n async beginPasskeyLogin(\n options?: RequestOptions\n ): Promise<Types.BeginPasskeyLoginResponse> {\n const response = await this.post<Types.BeginPasskeyLoginResponse & { session_key?: string }>(\n '/passkey/login/begin',\n undefined,\n this.publicOptions(options)\n );\n // Handle both shapes: server may return { publicKey: {...} } or flat { challenge, ... }\n const raw = response.options as unknown as Record<string, unknown>;\n const opts = ('publicKey' in raw ? raw.publicKey : raw) as Types.WebAuthnRequestOptions;\n return { options: opts, session_key: response.session_key ?? '' };\n }\n\n /**\n * Complete passkey login\n *\n * Completes the WebAuthn authentication and returns access tokens.\n *\n * @param data - WebAuthn assertion result from navigator.credentials.get()\n * @param options - Optional request options\n * @returns Access and refresh tokens\n */\n async finishPasskeyLogin(\n data: Types.FinishPasskeyLoginRequest,\n options?: RequestOptions\n ): Promise<Types.AccessDataResponse> {\n return this.post<Types.AccessDataResponse>(\n '/passkey/login/finish',\n data,\n this.publicOptions(options)\n );\n }\n\n // ============================================================================\n // Passkey / WebAuthn - Protected Endpoints\n // ============================================================================\n\n /**\n * Begin passkey registration\n *\n * Starts the WebAuthn registration process for the authenticated user.\n * Returns options to pass to navigator.credentials.create().\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns WebAuthn creation options\n */\n async beginPasskeyRegistration(\n options?: RequestOptions\n ): Promise<Types.BeginPasskeyRegistrationResponse> {\n const response = await this.post<Types.BeginPasskeyRegistrationResponse>(\n '/passkeys/register/begin',\n undefined,\n options\n );\n // Handle both shapes: server may return { publicKey: {...} } or flat { rp, user, ... }\n const raw = response.options as unknown as Record<string, unknown>;\n const opts = ('publicKey' in raw ? raw.publicKey : raw) as Types.WebAuthnCreationOptions;\n return { options: opts };\n }\n\n /**\n * Complete passkey registration\n *\n * Completes the WebAuthn registration with the attestation result.\n * Requires authentication.\n *\n * @param data - WebAuthn attestation result and optional passkey name\n * @param options - Optional request options\n * @returns Success response\n */\n async finishPasskeyRegistration(\n data: Types.FinishPasskeyRegistrationRequest,\n options?: RequestOptions\n ): Promise<Types.PasskeyResponse> {\n return this.post<Types.PasskeyResponse>(\n '/passkeys/register/finish',\n data,\n options\n );\n }\n\n /**\n * List registered passkeys\n *\n * Returns all passkeys registered by the authenticated user.\n * Requires authentication.\n *\n * @param options - Optional request options\n * @returns Array of passkey information\n */\n async listPasskeys(\n options?: RequestOptions\n ): Promise<Types.PasskeyResponse[]> {\n const response = await this.get<Types.PasskeysResponse>('/passkeys', options);\n return response.passkeys;\n }\n\n /**\n * Delete a passkey\n *\n * Removes a registered passkey from the authenticated user's account.\n * If the user has TOTP 2FA enabled, a valid TOTP code must be provided.\n * Requires authentication.\n *\n * @param passkeyId - Passkey ID to delete\n * @param data - Optional request body with TOTP code for 2FA verification\n * @param options - Optional request options\n * @returns Success response\n */\n async deletePasskey(\n passkeyId: string,\n data?: Types.DeletePasskeyRequest,\n options?: RequestOptions\n ): Promise<Types.SuccessResponse> {\n return this.delete<Types.SuccessResponse>(\n `/passkeys/${encodeURIComponent(passkeyId)}`,\n data,\n options\n );\n }\n\n // ============================================================================\n // Google OAuth - Public Endpoints\n // ============================================================================\n\n /**\n * Get Google OAuth authorization URL and its CSRF state.\n *\n * Returns `{ url, state }`. Redirect the user to `url`, and keep `state` —\n * `handleGoogleOAuthCallback` requires it. When the client was constructed\n * with an `oauthStateStore`, the state is persisted here automatically.\n *\n * @param params - Query parameters including redirect_uri\n * @param options - Optional request options\n * @returns The authorization URL and the single-use state to round-trip\n */\n async getGoogleOAuthURL(\n params: { redirect_uri: string },\n options?: RequestOptions\n ): Promise<Types.GoogleOAuthURLResponse> {\n const queryParams = new URLSearchParams({ redirect_uri: params.redirect_uri });\n const response = await this.get<Types.GoogleOAuthURLResponse>(\n `/oauth/google/url?${queryParams.toString()}`,\n this.publicOptions(options)\n );\n\n // Persist before the caller redirects. Done here rather than left to the\n // caller because \"remember to store this across a full-page redirect\" is\n // exactly the step whose omission made this flow exploitable.\n if (this.oauthStateStore && response.state) {\n this.oauthStateStore.save(response.state);\n }\n\n return response;\n }\n\n /**\n * Handle Google OAuth callback\n *\n * Exchanges the Google OAuth authorization code for access tokens.\n * Creates a new user if one doesn't exist with the Google email.\n *\n * The `state` from `getGoogleOAuthURL` is **required**: the server validates\n * it before exchanging the code, and rejects a mismatch, absence, expiry or\n * reuse. See {@link Types.GoogleOAuthCallbackRequest.state}.\n *\n * @param data - OAuth callback data: code, redirect_uri and state\n * @param options - Optional request options\n * @returns Access and refresh tokens\n * @throws {MPFValidationError} If `state` is missing or empty (client-side).\n */\n async handleGoogleOAuthCallback(\n data: Types.GoogleOAuthCallbackRequest,\n options?: RequestOptions\n ): Promise<Types.AccessDataResponse> {\n // Fail here rather than sending a request the server must reject. A caller\n // reaching this with no state has lost the pending flow (wrong tab, cleared\n // storage, or a hand-rolled callback that dropped it) and the local error\n // names the cause; a server-side rejection would not.\n if (typeof data.state !== 'string' || data.state === '') {\n throw new MPFValidationError(\n 'OAuth callback requires the `state` returned by getGoogleOAuthURL. ' +\n 'It is the CSRF defence for this flow: without it a callback carrying ' +\n \"an attacker's authorization code would be accepted. Persist it across \" +\n 'the redirect with createOAuthStateStore().',\n { field: 'state' },\n { state: ['state is required'] }\n );\n }\n\n return this.post<Types.AccessDataResponse>(\n '/oauth/google/callback',\n data,\n this.publicOptions(options)\n );\n }\n}\n","import type { MPFRole } from '../auth/claims-types.js';\n\n// NOTE: deliberately NOT re-exported (`export type { MPFRole }`).\n//\n// This module is namespace-re-exported from the root barrel as `AuthTypes`, and\n// tsup's declaration bundler mis-compiles a type re-export in that position: it\n// emitted `declare const types_MPFRole: typeof MPFRole;` — a *value* declaration\n// for a type — which makes the shipped .d.ts fail to compile with\n// `TS2693: 'MPFRole' only refers to a type, but is being used as a value here`.\n//\n// Invisible in this repo because our tsconfig sets `skipLibCheck: true`; a\n// consumer building with `skipLibCheck: false` gets a hard error. Found by\n// typechecking the packed tarball from outside the workspace.\n//\n// `MPFRole` is still exported from the root barrel and from the `/auth` subpath\n// via `src/auth/claims-types.ts`, which is where it belongs.\n\n/**\n * Roles accepted when WRITING a membership (inviting a member, updating a\n * role).\n *\n * Closed on purpose, and only here: on a request, autocomplete earns its keep\n * and an unknown role is a client bug worth catching at compile time.\n *\n * On RESPONSES the role is {@link MPFRole} (= `string`) instead. Roles are\n * database rows (`identity.tenant_membership_valid_roles`), so closing the union\n * on server output means a newly seeded role forces an SDK release — and it is\n * exactly how the fictional `'viewer'` role ended up in these types in five\n * places while the DB actually seeds `guest`.\n */\nexport type MPFTenantRoleInput = 'owner' | 'admin' | 'member' | 'guest';\n\n// ============================================================================\n// Request Types\n// ============================================================================\n\n/**\n * Request body for user registration\n */\nexport interface CreateUserRequest {\n /** User's email address */\n email: string;\n /** User's password (minimum 8 characters) */\n password: string;\n /** User's display name */\n display_name?: string;\n /** User's first name */\n first_name?: string;\n /** User's last name */\n last_name?: string;\n}\n\n/**\n * Request body for user login\n */\nexport interface LoginRequest {\n /** User's email address */\n email: string;\n /** User's password */\n password: string;\n}\n\n/**\n * Request body for profile update\n */\nexport interface UpdateProfileRequest {\n /** User's display name */\n display_name?: string;\n /** User's first name */\n first_name?: string;\n /** User's last name */\n last_name?: string;\n /** Custom user metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Request body for adding an email\n */\nexport interface AddEmailRequest {\n /** Email address to add */\n email: string;\n}\n\n/**\n * Request body for adding a phone number\n */\nexport interface AddPhoneRequest {\n /** Phone number in E.164 format */\n phone_number: string;\n}\n\n/**\n * Request body for verifying email or phone\n */\nexport interface VerifyContactRequest {\n /** 6-digit verification code */\n code: string;\n}\n\n/**\n * Request body for sending password recovery code\n */\nexport interface SendRecoveryCodeRequest {\n /** User's email address */\n email: string;\n}\n\n/**\n * Request body for verifying recovery code\n */\nexport interface VerifyRecoveryCodeRequest {\n /** User's email address */\n email: string;\n /** 6-digit verification code */\n verification_code: string;\n}\n\n/**\n * Request body for password reset\n */\nexport interface ResetPasswordRequest {\n /** Recovery token obtained from verification step */\n recovery_token: string;\n /** New password to set (minimum 8 characters) */\n new_password: string;\n}\n\n/**\n * Request body for authenticated password update\n */\nexport interface UpdatePasswordRequest {\n /** Current password for verification */\n current_password: string;\n /** New password to set (minimum 8 characters) */\n new_password: string;\n}\n\n/**\n * Request body for session renewal\n */\nexport interface RenewSessionRequest {\n /** The refresh token from the current session */\n refresh_token: string;\n}\n\n/**\n * Request body for session revocation\n */\nexport interface RevokeSessionRequest {\n /** The refresh token of the session to revoke */\n refresh_token: string;\n}\n\n/**\n * Request body for tenant creation\n */\nexport interface CreateTenantRequest {\n /** Name of the tenant organization */\n name: string;\n /** URL-friendly slug (auto-generated from name if omitted) */\n slug?: string;\n /** Optional description of the tenant */\n description?: string;\n}\n\n/**\n * Request body for inviting a member\n */\nexport interface InviteMemberRequest {\n /** Email address of the person to invite */\n email: string;\n /** Role to assign to the invited member */\n role: MPFTenantRoleInput;\n /**\n * Optional override for the configured accept URL template. The literal\n * \"{token}\" is replaced with the invitation token.\n */\n accept_url_template?: string;\n}\n\n/**\n * Result of POST /tenants/{id}/members/invite.\n */\nexport interface InvitationResponse {\n invitation_id: string;\n invite_token: string;\n /** Copyable URL the invitee can use; safe fallback if email delivery fails. */\n accept_url: string;\n email: string;\n role: string;\n expires_at: string;\n /** True when no existing user matches the invited email. */\n is_new_user: boolean;\n /** True when the invitation email was successfully dispatched. */\n email_sent: boolean;\n /** Legacy field. Always empty in the new invitation flow. */\n membership_id?: string;\n}\n\n/**\n * Public, pre-auth view of an invitation. Email is intentionally omitted.\n */\nexport interface InvitationPreviewResponse {\n tenant_id: string;\n tenant_name: string;\n tenant_slug?: string;\n role: string;\n inviter_display_name?: string;\n expires_at: string;\n /** True when the invitee has no verified account yet. */\n requires_signup: boolean;\n}\n\n/**\n * Result of POST /invitations/{token}/accept.\n */\nexport interface AcceptInvitationResponse {\n invitation_id: string;\n tenant_id: string;\n role: string;\n membership_id: string;\n accepted_at: string;\n}\n\n/**\n * Request body for updating member role\n */\nexport interface UpdateMemberRoleRequest {\n /** New role for the member */\n role: MPFTenantRoleInput;\n}\n\n// ============================================================================\n// TOTP (Two-Factor Authentication) Types\n// ============================================================================\n\n/**\n * Request body for verifying a TOTP code\n */\nexport interface VerifyTOTPRequest {\n /** 6-digit TOTP code from authenticator app */\n code: string;\n}\n\n/**\n * Request body for disabling TOTP\n */\nexport interface DisableTOTPRequest {\n /** 6-digit TOTP code to confirm disable */\n code: string;\n}\n\n/**\n * Request body for deleting a passkey (optional, required when user has TOTP 2FA enabled)\n */\nexport interface DeletePasskeyRequest {\n /** 6-digit TOTP code from authenticator app */\n totp_code?: string;\n}\n\n// ============================================================================\n// Passkey / WebAuthn Types\n// ============================================================================\n\n/** WebAuthn credential descriptor as serialized by the API */\nexport interface WebAuthnCredentialDescriptor {\n type: string;\n id: string;\n transports?: string[];\n}\n\n/** WebAuthn creation options as serialized by the API (base64url strings, not ArrayBuffers) */\nexport interface WebAuthnCreationOptions {\n rp: { id: string; name: string };\n user: { id: string; name: string; displayName: string };\n challenge: string;\n pubKeyCredParams: Array<{ type: string; alg: number }>;\n timeout?: number;\n excludeCredentials?: WebAuthnCredentialDescriptor[];\n authenticatorSelection?: {\n authenticatorAttachment?: string;\n residentKey?: string;\n requireResidentKey?: boolean;\n userVerification?: string;\n };\n attestation?: string;\n hints?: string[];\n extensions?: Record<string, unknown>;\n}\n\n/** WebAuthn request options as serialized by the API (base64url strings, not ArrayBuffers) */\nexport interface WebAuthnRequestOptions {\n challenge: string;\n rpId?: string;\n timeout?: number;\n allowCredentials?: WebAuthnCredentialDescriptor[];\n userVerification?: string;\n hints?: string[];\n extensions?: Record<string, unknown>;\n}\n\n/** Encoded credential sent back to the server after navigator.credentials.create/get */\nexport interface WebAuthnEncodedCredential {\n id: string;\n rawId: string;\n type: string;\n response: {\n clientDataJSON: string;\n attestationObject?: string;\n authenticatorData?: string;\n signature?: string;\n userHandle?: string | null;\n };\n}\n\n/**\n * Request body for completing passkey registration\n */\nexport interface FinishPasskeyRegistrationRequest {\n /** Raw WebAuthn credential from navigator.credentials.create() */\n credential: WebAuthnEncodedCredential;\n /** Optional human-readable name for the passkey */\n name?: string;\n}\n\n/**\n * Request body for completing passkey login\n */\nexport interface FinishPasskeyLoginRequest {\n /** Raw WebAuthn credential from navigator.credentials.get() */\n credential: WebAuthnEncodedCredential;\n /** Session key returned from begin login */\n session_key: string;\n}\n\n// ============================================================================\n// Google OAuth Types\n// ============================================================================\n\n/**\n * Request body for Google OAuth callback\n */\nexport interface GoogleOAuthCallbackRequest {\n /** Authorization code from Google */\n code: string;\n /** Redirect URI used in the initial auth request */\n redirect_uri: string;\n /**\n * The `state` returned by `getGoogleOAuthURL`, round-tripped through the\n * redirect.\n *\n * **Required, and required for a reason.** It is the CSRF defence for this\n * flow: the server validates it before exchanging the code, so a callback\n * carrying an attacker's `code` but not the victim's `state` is rejected.\n * Without it, an attacker can sign a victim into the attacker's own account —\n * confirmed exploitable, not hypothetical.\n *\n * Persist it across the redirect with `createOAuthStateStore()` (web storage:\n * a full-page redirect discards anything held in memory).\n */\n state: string;\n}\n\n// ============================================================================\n// Response Types\n// ============================================================================\n\n/**\n * Response containing access and refresh tokens\n */\nexport interface AccessDataResponse {\n /** JWT access token for API authentication */\n access_token: string;\n /** Refresh token for session renewal */\n refresh_token: string;\n}\n\n/**\n * User profile information\n */\nexport interface UserProfileResponse {\n /** User's unique identifier */\n id: string;\n /** User's display name */\n display_name?: string;\n /** User's first name */\n first_name?: string;\n /** User's last name */\n last_name?: string;\n /** User's avatar URL */\n avatar_url?: string;\n /** User's email addresses */\n emails: EmailResponse[];\n /** User's phone numbers */\n phones: PhoneResponse[];\n}\n\n/**\n * Email address information\n */\nexport interface EmailResponse {\n /** Email's unique identifier */\n id: string;\n /** Email address */\n email: string;\n /** Whether this is the primary email */\n is_primary: boolean;\n /** When the email was verified (ISO 8601), undefined if not verified */\n verified_at?: string;\n}\n\n/**\n * Phone number information\n */\nexport interface PhoneResponse {\n /** Phone's unique identifier */\n id: string;\n /** Phone number in E.164 format */\n phone_number: string;\n /** Whether this is the primary phone */\n is_primary: boolean;\n /** When the phone was verified (ISO 8601), undefined if not verified */\n verified_at?: string;\n}\n\n/**\n * Session client information\n */\nexport interface SessionClientInfo {\n /** Client name */\n name?: string;\n /** Client user agent string */\n user_agent?: string;\n /** Client IP address */\n ip_address?: string;\n /** When the client was last seen (ISO 8601) */\n last_seen_at?: string;\n}\n\n/**\n * Session information\n */\nexport interface SessionResponse {\n /** Session's unique identifier */\n id: string;\n /** Client ID associated with the session */\n client_id: string;\n /** Client information */\n client?: SessionClientInfo;\n /** When the session expires (ISO 8601) */\n expires_at: string;\n /** When the session was created (ISO 8601) */\n created_at: string;\n /** Whether this is the current session */\n is_current: boolean;\n}\n\n/**\n * OAuth client information\n */\nexport interface ClientResponse {\n /** Client's unique identifier */\n id: string;\n /** Client name */\n name?: string;\n /** Client user agent string */\n user_agent?: string;\n /** Client IP address */\n ip_address?: string;\n /** When the client was last seen (ISO 8601) */\n last_seen_at?: string;\n}\n\n/**\n * Tenant information\n */\nexport interface TenantResponse {\n /** Tenant's unique identifier */\n id: string;\n /** Tenant name */\n name: string;\n /** Tenant description */\n description?: string;\n /** Tenant slug (URL-friendly identifier) */\n slug?: string;\n /** When the tenant was created (ISO 8601) */\n created_at: string;\n}\n\n/**\n * Tenant membership information\n */\nexport interface MembershipResponse {\n /** Membership unique identifier */\n id: string;\n /** User's unique identifier */\n user_id: string;\n /** Member's role in the tenant */\n role: MPFRole;\n /** When the member was invited (ISO 8601) */\n invited_at?: string;\n /** When the invitation was accepted (ISO 8601) */\n accepted_at?: string;\n /** Member's display name */\n display_name?: string;\n /** Member's email address */\n email?: string;\n}\n\n/**\n * Response containing recovery token\n */\nexport interface RecoveryTokenResponse {\n /** Token to use for password reset */\n recovery_token: string;\n}\n\n/**\n * Simple success response\n */\nexport interface SuccessResponse {\n /** Indicates if the operation was successful */\n success: boolean;\n}\n\n/**\n * Error response from the API\n */\nexport interface ErrorResponse {\n /** Human-readable error message */\n error: string;\n /** Machine-readable error code */\n code?: string;\n /** Additional error details (validation errors, etc.) */\n details?: unknown;\n}\n\n/**\n * Validation error detail for a specific field\n */\nexport interface ValidationErrorDetail {\n /** Name of the field with validation error */\n field: string;\n /** Validation error message */\n message: string;\n}\n\n/**\n * Service health status response\n */\nexport interface HealthResponse {\n /** Health status */\n status: string;\n /** Service name */\n service: string;\n /** Current server timestamp (ISO 8601) */\n timestamp: string;\n}\n\n// ============================================================================\n// TOTP Response Types\n// ============================================================================\n\n/**\n * Response from TOTP setup containing secret and backup codes\n */\nexport interface TOTPSetupResponse {\n /** TOTP secret key for manual entry */\n secret: string;\n /** otpauth:// URL for QR code generation */\n qr_url: string;\n /** One-time backup codes for account recovery */\n backup_codes: string[];\n}\n\n// ============================================================================\n// Passkey Response Types\n// ============================================================================\n\n/**\n * Response from begin passkey registration\n */\nexport interface BeginPasskeyRegistrationResponse {\n /** WebAuthn PublicKeyCredentialCreationOptions */\n options: WebAuthnCreationOptions;\n}\n\n/**\n * Response from begin passkey login\n */\nexport interface BeginPasskeyLoginResponse {\n /** WebAuthn PublicKeyCredentialRequestOptions */\n options: WebAuthnRequestOptions;\n /** Session key to pass back in finish login */\n session_key: string;\n}\n\n/**\n * Passkey credential information\n */\nexport interface PasskeyResponse {\n /** Passkey's unique identifier */\n id: string;\n /** Human-readable name for the passkey */\n name?: string;\n /** When the passkey was registered (ISO 8601) */\n created_at: string;\n /** When the passkey was last used (ISO 8601) */\n last_used_at?: string;\n}\n\n// ============================================================================\n// OAuth Response Types\n// ============================================================================\n\n/**\n * A pending invitation for the current user\n */\nexport interface PendingInvitationResponse {\n /** Invitation/membership ID */\n id: string;\n /** Tenant ID the invitation is for */\n tenant_id: string;\n /** Tenant name */\n tenant_name: string;\n /** Tenant slug */\n tenant_slug?: string;\n /** Role assigned in the invitation */\n role: MPFRole;\n /** User ID of the person who sent the invitation */\n invited_by: string;\n /** When the invitation was sent (ISO 8601) */\n invited_at: string;\n /** Invitation token for accepting */\n token: string;\n}\n\n/**\n * A pending invitation issued by the authenticated caller, returned by\n * GET /tenants/{id}/invitations.\n */\nexport interface IssuedInvitationResponse {\n /** Invitation ID */\n id: string;\n /** Tenant the invitation was issued for */\n tenant_id: string;\n /** Email the invitation was sent to */\n email: string;\n /** Role the invitee will receive on accept */\n role: MPFRole;\n /** User ID of the inviter (always the authenticated caller) */\n invited_by: string;\n /** When the invitation was sent (ISO 8601) */\n invited_at: string;\n /** Expiration time (ISO 8601) */\n expires_at: string;\n /** Raw token. Most callers should use accept_url instead. */\n token: string;\n /**\n * Copyable URL the invitee can paste into a browser. Empty if the server\n * has no accept-URL template configured.\n */\n accept_url: string;\n /** Display name of the invitee, if they already have an account */\n display_name?: string;\n}\n\n/**\n * Response containing Google OAuth authorization URL\n */\nexport interface GoogleOAuthURLResponse {\n /** Full Google OAuth authorization URL to redirect user to */\n url: string;\n /**\n * Single-use CSRF state minted and recorded by the server.\n *\n * Persist this before redirecting and send it back on\n * `handleGoogleOAuthCallback`. Dropping it makes the callback trivially\n * forgeable — see {@link GoogleOAuthCallbackRequest.state}.\n */\n state: string;\n}\n\n// ============================================================================\n// List Wrapper Response Types\n// ============================================================================\n\n/**\n * Wrapper response for email list\n */\nexport interface EmailsResponse {\n emails: EmailResponse[];\n}\n\n/**\n * Wrapper response for phone list\n */\nexport interface PhonesResponse {\n phones: PhoneResponse[];\n}\n\n/**\n * Wrapper response for session list\n */\nexport interface SessionsResponse {\n sessions: SessionResponse[];\n}\n\n/**\n * Wrapper response for passkey list\n */\nexport interface PasskeysResponse {\n passkeys: PasskeyResponse[];\n}\n\n/**\n * Wrapper response for client list\n */\nexport interface ClientsResponse {\n clients: ClientResponse[];\n}\n\n/**\n * Wrapper response for member list\n */\nexport interface MembersResponse {\n members: MembershipResponse[];\n}\n\n/**\n * Wrapper response for pending-invitations-issued-by-caller list\n */\nexport interface IssuedInvitationsResponse {\n invitations: IssuedInvitationResponse[];\n}\n\n// ============================================================================\n// MFA Response Types\n// ============================================================================\n\n/**\n * Returned when MFA verification is needed to complete login\n */\nexport interface MFARequiredResponse {\n /** Always true for this response type */\n mfa_required: true;\n /** Short-lived JWT ticket for MFA verification */\n mfa_ticket: string;\n /** Available MFA methods (e.g., [\"totp\"]) */\n mfa_methods: string[];\n}\n\n/**\n * Returned when MFA setup is enforced and user hasn't set up TOTP yet\n */\nexport interface MFASetupRequiredResponse {\n /** Always true for this response type */\n mfa_setup_required: true;\n /** Short-lived JWT ticket for MFA setup verification */\n mfa_ticket: string;\n /** TOTP setup data including secret and QR code */\n totp_setup: TOTPSetupResponse;\n}\n\n/**\n * Union type for all possible login responses\n */\nexport type LoginResponse = AccessDataResponse | MFARequiredResponse | MFASetupRequiredResponse;\n\n/**\n * Type guard to check if login response requires MFA verification\n */\nexport function isMFARequired(response: LoginResponse): response is MFARequiredResponse {\n return 'mfa_required' in response && response.mfa_required === true;\n}\n\n/**\n * Type guard to check if login response requires MFA setup\n */\nexport function isMFASetupRequired(response: LoginResponse): response is MFASetupRequiredResponse {\n return 'mfa_setup_required' in response && response.mfa_setup_required === true;\n}\n\n// ============================================================================\n// MFA Request Types\n// ============================================================================\n\n/**\n * Request body for verifying MFA during login\n */\nexport interface MFAVerifyRequest {\n /** MFA ticket from login response */\n mfa_ticket: string;\n /** 6-digit TOTP code from authenticator app */\n totp_code: string;\n}\n\n/**\n * Request body for verifying MFA setup during first-time enrollment\n */\nexport interface MFASetupVerifyRequest {\n /** MFA ticket from login response */\n mfa_ticket: string;\n /** 6-digit TOTP code to verify setup */\n code: string;\n}\n"]}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Generic HTTP client factory.
3
+ *
4
+ * `createAuthClient`, `createStorageClient` and `createGraphQLClient` all wire
5
+ * the SAME two middlewares (auth, tenant) by hand today, which is how they
6
+ * drift: three copies of "if tokenProvider, use(createAuthMiddleware(...))".
7
+ * This is the single place that wiring happens now; the three factories
8
+ * become thin wrappers that just pick the right `MPFClient` subclass.
9
+ *
10
+ * The point of pulling this out is reuse, NOT a new concept: a `tokenProvider`
11
+ * here is still just `{ getAccessToken, onTokenExpired?, onUnauthorized? }` —
12
+ * typically `{ getAccessToken: () => sessionManager.getAccessToken(), ... }`
13
+ * from ONE shared `SessionManager` (see `auth/session-manager.ts`), so every
14
+ * client built through this factory (REST or GraphQL) shares the same
15
+ * proactive/reactive renewal, coalesced to one network call across the whole
16
+ * browser — not per client, not just per tab.
17
+ */
18
+ import { MPFClient } from './client.js';
19
+ import type { ClientConfig, TokenProvider } from './types.js';
20
+ import type { TenantSelectionStore } from '../../auth/tenant-selection.js';
21
+ /**
22
+ * Configuration shared by every client built through this factory.
23
+ */
24
+ export interface HttpClientOptions extends ClientConfig {
25
+ /**
26
+ * Optional token provider. When provided, auto-wires the auth middleware so
27
+ * every request carries `Authorization: Bearer <token>` and 401s trigger
28
+ * renewal per {@link TokenProvider.onUnauthorized}.
29
+ *
30
+ * Share ONE instance (backed by ONE `SessionManager`) across every client an
31
+ * app constructs — that is what makes renewal happen once per browser
32
+ * rather than once per client.
33
+ */
34
+ tokenProvider?: TokenProvider;
35
+ /**
36
+ * Optional shared tenant selection. When provided, every request carries the
37
+ * selected tenant headers. Construct it once with `createTenantSelection()`
38
+ * and share the same instance across every client.
39
+ */
40
+ tenantProvider?: TenantSelectionStore;
41
+ }
42
+ /**
43
+ * Attach the standard auth + tenant middlewares to an already-constructed
44
+ * client, in the standard order (auth before tenant — the tenant middleware's
45
+ * under-scoping warning needs a token to decode).
46
+ *
47
+ * Exists as its own function (not inlined in {@link createHttpClient}) so a
48
+ * subclass-specific factory (`createAuthClient`, `createStorageClient`,
49
+ * `createGraphQLClient`) can construct its own `MPFClient` subclass and still
50
+ * reuse this exact wiring instead of re-deriving it.
51
+ */
52
+ export declare function attachStandardMiddlewares(client: MPFClient, options: Pick<HttpClientOptions, 'tokenProvider' | 'tenantProvider'>): void;
53
+ /**
54
+ * Create a generic HTTP client with the standard auth + tenant middlewares
55
+ * pre-wired.
56
+ *
57
+ * Use this directly for a plain REST client; `createAuthClient` and
58
+ * `createStorageClient` use it internally for their typed `MPFClient`
59
+ * subclasses, and `createGraphQLClient` uses it for its HTTP transport.
60
+ */
61
+ export declare function createHttpClient(options: HttpClientOptions): MPFClient;
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Base HTTP client for the MPF SDK
3
+ */
4
+ import type { ClientConfig, RequestOptions } from './types.js';
5
+ import type { Middleware } from './middleware.js';
6
+ /**
7
+ * Hard ceiling on the number of attempts a single `request()` call may make
8
+ * (the initial attempt plus retries).
9
+ *
10
+ * This is deliberately independent of any middleware's own `maxRetries`: a
11
+ * misbehaving or misconfigured middleware can keep asking for retries, and this
12
+ * bound guarantees the loop terminates. 4 attempts = 1 initial + 3 retries,
13
+ * matching the retry middleware's default `maxRetries: 3`.
14
+ */
15
+ export declare const MAX_REQUEST_ATTEMPTS = 4;
16
+ /**
17
+ * Base client for making HTTP requests with middleware support
18
+ */
19
+ export declare class MPFClient {
20
+ protected readonly baseUrl: string;
21
+ protected readonly defaultHeaders: Record<string, string>;
22
+ protected readonly middlewares: Middleware[];
23
+ constructor(config: ClientConfig);
24
+ /**
25
+ * Add a middleware to the client
26
+ * Middlewares are executed in the order they are added for requests,
27
+ * and in reverse order for responses.
28
+ *
29
+ * @param middleware - The middleware to add
30
+ * @returns The client instance for chaining
31
+ */
32
+ use(middleware: Middleware): this;
33
+ /**
34
+ * Build a full URL with query parameters
35
+ *
36
+ * @param path - The API path (e.g., "/users" or "users")
37
+ * @param params - Optional query parameters
38
+ * @returns The full URL with query string
39
+ */
40
+ protected buildUrl(path: string, params?: Record<string, string | number | boolean | undefined>): string;
41
+ /**
42
+ * Merge headers from different sources
43
+ *
44
+ * @param requestHeaders - Headers specific to this request
45
+ * @returns Merged headers object
46
+ */
47
+ protected mergeHeaders(requestHeaders?: Record<string, string>): Record<string, string>;
48
+ /**
49
+ * Build the headers for a single attempt.
50
+ *
51
+ * Rebuilt per attempt so request middlewares (auth, turnstile, ...) always
52
+ * inject a fresh token instead of replaying a stale one.
53
+ *
54
+ * For a `FormData` body the default JSON `Content-Type` is dropped so that
55
+ * fetch sets `multipart/form-data` with the correct boundary.
56
+ */
57
+ private buildAttemptHeaders;
58
+ /**
59
+ * Parse the response body based on content type
60
+ *
61
+ * @param response - The fetch Response object
62
+ * @returns Parsed response data
63
+ */
64
+ protected parseResponse<T>(response: Response): Promise<T>;
65
+ /**
66
+ * Handle error responses from the API
67
+ *
68
+ * @param response - The fetch Response object
69
+ * @throws MPFAuthError for 401/403, MPFAPIError for other errors
70
+ */
71
+ protected handleErrorResponse(response: Response): Promise<never>;
72
+ /**
73
+ * Execute an HTTP request with the full middleware chain, retrying when a
74
+ * middleware asks for it.
75
+ *
76
+ * Retry contract:
77
+ * - `metadata` is created once and shared by every attempt. Middlewares keep
78
+ * their per-request state there (retry counter, auth-renew flag); rebuilding
79
+ * it per attempt would reset those counters and loop forever.
80
+ * - `init.headers` are rebuilt per attempt so request middlewares re-inject a
81
+ * fresh token rather than replaying the first attempt's headers.
82
+ * - `MAX_REQUEST_ATTEMPTS` bounds the loop regardless of middleware config.
83
+ * - Bodies that cannot be re-sent (`ReadableStream`) disable retrying.
84
+ *
85
+ * @param path - The API path
86
+ * @param init - Fetch RequestInit options
87
+ * @returns The parsed response data
88
+ * @throws MPFNetworkError for network failures
89
+ * @throws MPFAuthError for 401/403 responses
90
+ * @throws MPFAPIError for other error responses
91
+ */
92
+ request<T>(path: string, init?: RequestInit, params?: Record<string, string | number | boolean | undefined>, options?: RequestOptions): Promise<T>;
93
+ /**
94
+ * Execute a single request attempt through the middleware chain.
95
+ *
96
+ * On failure the error middleware chain runs before the error propagates, so
97
+ * the caller can inspect `ctx.metadata` for a retry request.
98
+ */
99
+ private attempt;
100
+ /**
101
+ * Make a GET request
102
+ *
103
+ * @param path - The API path
104
+ * @param options - Request options
105
+ * @returns The parsed response data
106
+ */
107
+ get<T>(path: string, options?: RequestOptions): Promise<T>;
108
+ /**
109
+ * Make a POST request
110
+ *
111
+ * @param path - The API path
112
+ * @param body - Request body (will be JSON stringified)
113
+ * @param options - Request options
114
+ * @returns The parsed response data
115
+ */
116
+ post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
117
+ /**
118
+ * Make a PUT request
119
+ *
120
+ * @param path - The API path
121
+ * @param body - Request body (will be JSON stringified)
122
+ * @param options - Request options
123
+ * @returns The parsed response data
124
+ */
125
+ put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
126
+ /**
127
+ * Make a PATCH request
128
+ *
129
+ * @param path - The API path
130
+ * @param body - Request body (will be JSON stringified)
131
+ * @param options - Request options
132
+ * @returns The parsed response data
133
+ */
134
+ patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
135
+ /**
136
+ * Make a DELETE request
137
+ *
138
+ * @param path - The API path
139
+ * @param body - Optional request body (will be JSON stringified)
140
+ * @param options - Request options
141
+ * @returns The parsed response data
142
+ */
143
+ delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
144
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Custom error classes for the MPF SDK
3
+ */
4
+ /**
5
+ * Base error class for all MPF SDK errors
6
+ */
7
+ export declare class MPFError extends Error {
8
+ /** Machine-readable error code */
9
+ readonly code: string;
10
+ /** HTTP status code if applicable */
11
+ readonly status?: number;
12
+ /** Additional error details from the API */
13
+ readonly details?: unknown;
14
+ constructor(message: string, code: string, status?: number, details?: unknown);
15
+ /**
16
+ * Convert error to a plain object for logging/serialization
17
+ */
18
+ toJSON(): Record<string, unknown>;
19
+ }
20
+ /**
21
+ * Error thrown when a network request fails (e.g., no connection, DNS failure)
22
+ */
23
+ export declare class MPFNetworkError extends MPFError {
24
+ /** The original error that caused the network failure */
25
+ readonly cause?: Error;
26
+ constructor(message: string, cause?: Error);
27
+ toJSON(): Record<string, unknown>;
28
+ }
29
+ /**
30
+ * Error thrown when the API returns an error response
31
+ */
32
+ export declare class MPFAPIError extends MPFError {
33
+ /** The raw response body if available */
34
+ readonly body?: unknown;
35
+ constructor(message: string, code: string, status: number, details?: unknown, body?: unknown);
36
+ toJSON(): Record<string, unknown>;
37
+ }
38
+ /**
39
+ * Error thrown when request validation fails (e.g., invalid parameters)
40
+ */
41
+ export declare class MPFValidationError extends MPFError {
42
+ /** Field-specific validation errors */
43
+ readonly fieldErrors?: Record<string, string[]>;
44
+ constructor(message: string, details?: unknown, fieldErrors?: Record<string, string[]>);
45
+ toJSON(): Record<string, unknown>;
46
+ }
47
+ /**
48
+ * Error thrown when authentication or authorization fails (401/403)
49
+ */
50
+ export declare class MPFAuthError extends MPFError {
51
+ /** The type of auth error (e.g., 'unauthorized', 'forbidden', 'token_expired') */
52
+ readonly authErrorType: 'unauthorized' | 'forbidden' | 'token_expired' | 'invalid_token';
53
+ /**
54
+ * The machine-readable code the server actually sent, when it sent one.
55
+ *
56
+ * `code` is derived from {@link authErrorType} and therefore collapses every
57
+ * 401 to `UNAUTHORIZED`, which loses information the server deliberately
58
+ * provides — `REFRESH_TOKEN_SUPERSEDED` being the case that matters: it means
59
+ * "another tab renewed first", which is recoverable by adopting that tab's
60
+ * token, and must not be treated as a dead session.
61
+ *
62
+ * Kept as a separate field rather than overwriting `code` so that existing
63
+ * consumers switching on `code` are unaffected.
64
+ */
65
+ readonly serverCode?: string;
66
+ constructor(message: string, authErrorType: 'unauthorized' | 'forbidden' | 'token_expired' | 'invalid_token', status?: 401 | 403, details?: unknown, serverCode?: string);
67
+ /**
68
+ * Check if the error is due to an expired token
69
+ */
70
+ isTokenExpired(): boolean;
71
+ /**
72
+ * Check if the error is a 403 Forbidden
73
+ */
74
+ isForbidden(): boolean;
75
+ toJSON(): Record<string, unknown>;
76
+ }
77
+ /**
78
+ * Error thrown when a request times out
79
+ */
80
+ export declare class MPFTimeoutError extends MPFError {
81
+ /** The timeout duration in milliseconds */
82
+ readonly timeoutMs: number;
83
+ constructor(message: string, timeoutMs: number);
84
+ toJSON(): Record<string, unknown>;
85
+ }
86
+ /**
87
+ * Type guard to check if an error is an MPFError
88
+ */
89
+ export declare function isMPFError(error: unknown): error is MPFError;
90
+ /**
91
+ * Type guard to check if an error is an MPFAuthError
92
+ */
93
+ export declare function isMPFAuthError(error: unknown): error is MPFAuthError;
94
+ /**
95
+ * Type guard to check if an error is an MPFAPIError
96
+ */
97
+ export declare function isMPFAPIError(error: unknown): error is MPFAPIError;
98
+ /**
99
+ * Type guard to check if an error is an MPFNetworkError
100
+ */
101
+ export declare function isMPFNetworkError(error: unknown): error is MPFNetworkError;
102
+ /**
103
+ * Type guard to check if an error is an MPFValidationError
104
+ */
105
+ export declare function isMPFValidationError(error: unknown): error is MPFValidationError;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Core module exports for MPF SDK
3
+ */
4
+ export type { RequestContext, ResponseContext, ClientConfig, RequestOptions, APIErrorResponse, TokenProvider, } from './types.js';
5
+ export type { Middleware } from './middleware.js';
6
+ export { executeRequestMiddlewares, executeResponseMiddlewares, executeErrorMiddlewares, } from './middleware.js';
7
+ export { MPFError, MPFNetworkError, MPFAPIError, MPFValidationError, MPFAuthError, MPFTimeoutError, isMPFError, isMPFAuthError, isMPFAPIError, isMPFNetworkError, isMPFValidationError, } from './errors.js';
8
+ export { MPFClient, MAX_REQUEST_ATTEMPTS } from './client.js';
9
+ export { createHttpClient, attachStandardMiddlewares, type HttpClientOptions, } from './client-factory.js';
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Middleware system for request/response interceptors
3
+ */
4
+ import type { RequestContext, ResponseContext } from './types.js';
5
+ /**
6
+ * Middleware interface for intercepting requests and responses
7
+ */
8
+ export interface Middleware {
9
+ /** Unique identifier for the middleware */
10
+ name: string;
11
+ /**
12
+ * Called before the request is sent
13
+ * Can modify the request context or throw to abort
14
+ */
15
+ onRequest?: (ctx: RequestContext) => Promise<RequestContext> | RequestContext;
16
+ /**
17
+ * Called after a successful response is received
18
+ * Can modify the response context or throw to trigger error handling
19
+ */
20
+ onResponse?: <T>(ctx: ResponseContext<T>) => Promise<ResponseContext<T>> | ResponseContext<T>;
21
+ /**
22
+ * Called when an error occurs during the request lifecycle
23
+ * Can transform the error or re-throw
24
+ */
25
+ onError?: (error: Error, ctx: RequestContext) => Promise<never> | never;
26
+ }
27
+ /**
28
+ * Execute the request middleware chain in order
29
+ *
30
+ * Middlewares are executed in the order they were added.
31
+ * Each middleware can modify the context before passing it to the next.
32
+ *
33
+ * @param middlewares - Array of middlewares to execute
34
+ * @param ctx - Initial request context
35
+ * @returns Modified request context after all middlewares
36
+ */
37
+ export declare function executeRequestMiddlewares(middlewares: Middleware[], ctx: RequestContext): Promise<RequestContext>;
38
+ /**
39
+ * Execute the response middleware chain in reverse order
40
+ *
41
+ * Middlewares are executed in reverse order (last added runs first).
42
+ * This allows middlewares to "unwrap" their effects in the correct order.
43
+ *
44
+ * @param middlewares - Array of middlewares to execute
45
+ * @param ctx - Initial response context
46
+ * @returns Modified response context after all middlewares
47
+ */
48
+ export declare function executeResponseMiddlewares<T>(middlewares: Middleware[], ctx: ResponseContext<T>): Promise<ResponseContext<T>>;
49
+ /**
50
+ * Execute error handlers in the middleware chain
51
+ *
52
+ * EVERY middleware's `onError` handler runs, in registration order. Because
53
+ * `onError` is typed `never` it signals completion by throwing, so a thrown
54
+ * error is its normal exit path and must NOT terminate the chain — otherwise
55
+ * the first handler that throws (e.g. the retry middleware, which always
56
+ * throws) would silently swallow every handler registered after it.
57
+ *
58
+ * A handler may transform the error by throwing a different one; the
59
+ * transformed error is passed to the remaining handlers and is what finally
60
+ * propagates to the caller.
61
+ *
62
+ * @param middlewares - Array of middlewares to try
63
+ * @param error - The error that occurred
64
+ * @param ctx - The request context when the error occurred
65
+ * @throws The original or transformed error
66
+ */
67
+ export declare function executeErrorMiddlewares(middlewares: Middleware[], error: Error, ctx: RequestContext): Promise<never>;