This commit is contained in:
MarcWieland
2026-07-26 23:57:23 +02:00
commit 8b613ec0bc
6300 changed files with 1257646 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
import GoTrueAdminApi from './GoTrueAdminApi';
declare const AuthAdminApi: typeof GoTrueAdminApi;
export default AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"AuthAdminApi.d.ts","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,QAAA,MAAM,YAAY,uBAAiB,CAAA;AAEnC,eAAe,YAAY,CAAA"}
+7
View File
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi"));
const AuthAdminApi = GoTrueAdminApi_1.default;
exports.default = AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"AuthAdminApi.js","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":";;;AAAA,8EAA6C;AAE7C,MAAM,YAAY,GAAG,wBAAc,CAAA;AAEnC,kBAAe,YAAY,CAAA"}
+4
View File
@@ -0,0 +1,4 @@
import GoTrueClient from './GoTrueClient';
declare const AuthClient: typeof GoTrueClient;
export default AuthClient;
//# sourceMappingURL=AuthClient.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"AuthClient.d.ts","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,QAAA,MAAM,UAAU,qBAAe,CAAA;AAE/B,eAAe,UAAU,CAAA"}
+7
View File
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const GoTrueClient_1 = tslib_1.__importDefault(require("./GoTrueClient"));
const AuthClient = GoTrueClient_1.default;
exports.default = AuthClient;
//# sourceMappingURL=AuthClient.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"AuthClient.js","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":";;;AAAA,0EAAyC;AAEzC,MAAM,UAAU,GAAG,sBAAY,CAAA;AAE/B,kBAAe,UAAU,CAAA"}
+713
View File
@@ -0,0 +1,713 @@
import { Fetch } from './lib/fetch';
import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams, SignOutScope, GoTrueAdminOAuthApi, GoTrueAdminCustomProvidersApi, GoTrueAdminPasskeyApi, ExperimentalFeatureFlags } from './lib/types';
import { AuthError } from './lib/errors';
export default class GoTrueAdminApi {
/** Contains all MFA administration methods. */
mfa: GoTrueAdminMFAApi;
/**
* Contains all OAuth client administration methods.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
oauth: GoTrueAdminOAuthApi;
/** Contains all custom OIDC/OAuth provider administration methods. */
customProviders: GoTrueAdminCustomProvidersApi;
/**
* Contains all passkey administration methods.
*
* Requires `auth.experimental.passkey: true`; otherwise all methods throw.
*/
passkey: GoTrueAdminPasskeyApi;
protected url: string;
protected headers: {
[key: string]: string;
};
protected fetch: Fetch;
protected experimental: ExperimentalFeatureFlags;
/**
* Creates an admin API client that can be used to manage users and OAuth clients.
*
* @example Using supabase-js (recommended)
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'your-secret-key')
* const { data, error } = await supabase.auth.admin.listUsers()
* ```
*
* @example Standalone import for bundle-sensitive environments
* ```ts
* import { GoTrueAdminApi } from '@supabase/auth-js'
*
* const admin = new GoTrueAdminApi({
* url: 'https://xyzcompany.supabase.co/auth/v1',
* headers: { Authorization: `Bearer ${process.env.SUPABASE_SECRET_KEY}` },
* })
* ```
*/
constructor({ url, headers, fetch, experimental, }: {
url: string;
headers?: {
[key: string]: string;
};
fetch?: Fetch;
experimental?: ExperimentalFeatureFlags;
});
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*
* @category Auth
* @subcategory Auth Admin
*/
signOut(jwt: string, scope?: SignOutScope): Promise<{
data: null;
error: AuthError | null;
}>;
/**
* Sends an invite link to an email address.
* @param email The email address of the user.
* @param options Additional options to be included when inviting.
*
* @category Auth
* @subcategory Auth Admin
*
* @remarks
* - Sends an invite link to the user's email address.
* - The `inviteUserByEmail()` method is typically used by administrators to invite users to join the application.
* - Note that PKCE is not supported when using `inviteUserByEmail`. This is because the browser initiating the invite is often different from the browser accepting the invite which makes it difficult to provide the security guarantees required of the PKCE flow.
*
* @example Invite a user
* ```js
* const { data, error } = await supabase.auth.admin.inviteUserByEmail('email@example.com')
* ```
*
* @exampleResponse Invite a user
* ```json
* {
* "data": {
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "invited_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "confirmation_sent_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {},
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "example@email.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "is_anonymous": false
* }
* },
* "error": null
* }
* ```
*/
inviteUserByEmail(email: string, options?: {
/** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */
data?: object;
/** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */
redirectTo?: string;
}): Promise<UserResponse>;
/**
* Generates email links and OTPs to be sent via a custom email provider.
* @param params The parameters for generating the link, including the link `type`, the user's `email`, and type-specific options such as `password`, `data`, and `redirectTo`.
*
* @category Auth
* @subcategory Auth Admin
*
* @remarks
* - The following types can be passed into `generateLink()`: `signup`, `magiclink`, `invite`, `recovery`, `email_change_current`, `email_change_new`, `phone_change`.
* - `generateLink()` only generates the email link for `email_change_email` if the **Secure email change** is enabled in your project's [email auth provider settings](/dashboard/project/_/auth/providers).
* - `generateLink()` handles the creation of the user for `signup`, `invite` and `magiclink`.
*
* @example Generate a signup link
* ```js
* const { data, error } = await supabase.auth.admin.generateLink({
* type: 'signup',
* email: 'email@example.com',
* password: 'secret'
* })
* ```
*
* @exampleResponse Generate a signup link
* ```json
* {
* "data": {
* "properties": {
* "action_link": "<LINK_TO_SEND_TO_USER>",
* "email_otp": "999999",
* "hashed_token": "<HASHED_TOKEN",
* "redirect_to": "<REDIRECT_URL>",
* "verification_type": "signup"
* },
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "email@example.com",
* "phone": "",
* "confirmation_sent_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {},
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "email@example.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "email@example.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "is_anonymous": false
* }
* },
* "error": null
* }
* ```
*
* @example Generate an invite link
* ```js
* const { data, error } = await supabase.auth.admin.generateLink({
* type: 'invite',
* email: 'email@example.com'
* })
* ```
*
* @example Generate a magic link
* ```js
* const { data, error } = await supabase.auth.admin.generateLink({
* type: 'magiclink',
* email: 'email@example.com'
* })
* ```
*
* @example Generate a recovery link
* ```js
* const { data, error } = await supabase.auth.admin.generateLink({
* type: 'recovery',
* email: 'email@example.com'
* })
* ```
*
* @example Generate links to change current email address
* ```js
* // generate an email change link to be sent to the current email address
* const { data, error } = await supabase.auth.admin.generateLink({
* type: 'email_change_current',
* email: 'current.email@example.com',
* newEmail: 'new.email@example.com'
* })
*
* // generate an email change link to be sent to the new email address
* const { data, error } = await supabase.auth.admin.generateLink({
* type: 'email_change_new',
* email: 'current.email@example.com',
* newEmail: 'new.email@example.com'
* })
* ```
*/
generateLink(params: GenerateLinkParams): Promise<GenerateLinkResponse>;
/**
* Creates a new user.
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*
* @category Auth
* @subcategory Auth Admin
*
* @remarks
* - To confirm the user's email address or phone number, set `email_confirm` or `phone_confirm` to true. Both arguments default to false.
* - `createUser()` will not send a confirmation email to the user. You can use [`inviteUserByEmail()`](/docs/reference/javascript/auth-admin-inviteuserbyemail) if you want to send them an email invite instead.
* - If you are sure that the created user's email or phone number is legitimate and verified, you can set the `email_confirm` or `phone_confirm` param to `true`.
*
* @example With custom user metadata
* ```js
* const { data, error } = await supabase.auth.admin.createUser({
* email: 'user@email.com',
* password: 'password',
* user_metadata: { name: 'Yoda' }
* })
* ```
*
* @exampleResponse With custom user metadata
* ```json
* {
* data: {
* user: {
* id: '1',
* aud: 'authenticated',
* role: 'authenticated',
* email: 'example@email.com',
* email_confirmed_at: '2024-01-01T00:00:00Z',
* phone: '',
* confirmation_sent_at: '2024-01-01T00:00:00Z',
* confirmed_at: '2024-01-01T00:00:00Z',
* last_sign_in_at: '2024-01-01T00:00:00Z',
* app_metadata: {},
* user_metadata: {},
* identities: [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "1",
* "user_id": "1",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": true,
* "phone_verified": false,
* "sub": "1"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "email@example.com"
* },
* ],
* created_at: '2024-01-01T00:00:00Z',
* updated_at: '2024-01-01T00:00:00Z',
* is_anonymous: false,
* }
* }
* error: null
* }
* ```
*
* @example Auto-confirm the user's email
* ```js
* const { data, error } = await supabase.auth.admin.createUser({
* email: 'user@email.com',
* email_confirm: true
* })
* ```
*
* @example Auto-confirm the user's phone number
* ```js
* const { data, error } = await supabase.auth.admin.createUser({
* phone: '1234567890',
* phone_confirm: true
* })
* ```
*/
createUser(attributes: AdminUserAttributes): Promise<UserResponse>;
/**
* Get a list of users.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
* @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
*
* @category Auth
* @subcategory Auth Admin
*
* @remarks
* - Defaults to return 50 users per page.
*
* @example Get a page of users
* ```js
* const { data: { users }, error } = await supabase.auth.admin.listUsers()
* ```
*
* @example Paginated list of users
* ```js
* const { data: { users }, error } = await supabase.auth.admin.listUsers({
* page: 1,
* perPage: 1000
* })
* ```
*/
listUsers(params?: PageParams): Promise<{
data: {
users: User[];
aud: string;
} & Pagination;
error: null;
} | {
data: {
users: [];
};
error: AuthError;
}>;
/**
* Get user by id.
*
* @param uid The user's unique identifier
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*
* @category Auth
* @subcategory Auth Admin
*
* @remarks
* - Fetches the user object from the database based on the user's id.
* - The `getUserById()` method requires the user's id which maps to the `auth.users.id` column.
*
* @example Fetch the user object using the access_token jwt
* ```js
* const { data, error } = await supabase.auth.admin.getUserById(1)
* ```
*
* @exampleResponse Fetch the user object using the access_token jwt
* ```json
* {
* data: {
* user: {
* id: '1',
* aud: 'authenticated',
* role: 'authenticated',
* email: 'example@email.com',
* email_confirmed_at: '2024-01-01T00:00:00Z',
* phone: '',
* confirmation_sent_at: '2024-01-01T00:00:00Z',
* confirmed_at: '2024-01-01T00:00:00Z',
* last_sign_in_at: '2024-01-01T00:00:00Z',
* app_metadata: {},
* user_metadata: {},
* identities: [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "1",
* "user_id": "1",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": true,
* "phone_verified": false,
* "sub": "1"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "email@example.com"
* },
* ],
* created_at: '2024-01-01T00:00:00Z',
* updated_at: '2024-01-01T00:00:00Z',
* is_anonymous: false,
* }
* }
* error: null
* }
* ```
*/
getUserById(uid: string): Promise<UserResponse>;
/**
* Updates the user data. Changes are applied directly without confirmation flows.
*
* @param uid The user's unique identifier
* @param attributes The data you want to update.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*
* @remarks
* **Important:** This is a server-side operation and does **not** trigger client-side
* `onAuthStateChange` listeners. The admin API has no connection to client state.
*
* To sync changes to the client after calling this method:
* 1. On the client, call `supabase.auth.refreshSession()` to fetch the updated user data
* 2. This will trigger the `TOKEN_REFRESHED` event and notify all listeners
*
* @example
* ```typescript
* // Server-side (Edge Function)
* const { data, error } = await supabase.auth.admin.updateUserById(
* userId,
* { user_metadata: { preferences: { theme: 'dark' } } }
* )
*
* // Client-side (to sync the changes)
* const { data, error } = await supabase.auth.refreshSession()
* // onAuthStateChange listeners will now be notified with updated user
* ```
*
* @see {@link GoTrueClient.refreshSession} for syncing admin changes to the client
* @see {@link GoTrueClient.updateUser} for client-side user updates (triggers listeners automatically)
*
* @category Auth
* @subcategory Auth Admin
*
* @example Updates a user's email
* ```js
* const { data: user, error } = await supabase.auth.admin.updateUserById(
* '11111111-1111-1111-1111-111111111111',
* { email: 'new@email.com' }
* )
* ```
*
* @exampleResponse Updates a user's email
* ```json
* {
* "data": {
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "new@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "confirmed_at": "2024-01-01T00:00:00Z",
* "recovery_sent_at": "2024-01-01T00:00:00Z",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "example@email.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "is_anonymous": false
* }
* },
* "error": null
* }
* ```
*
* @example Updates a user's password
* ```js
* const { data: user, error } = await supabase.auth.admin.updateUserById(
* '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
* { password: 'new_password' }
* )
* ```
*
* @example Updates a user's metadata
* ```js
* const { data: user, error } = await supabase.auth.admin.updateUserById(
* '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
* { user_metadata: { hello: 'world' } }
* )
* ```
*
* @example Updates a user's app_metadata
* ```js
* const { data: user, error } = await supabase.auth.admin.updateUserById(
* '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
* { app_metadata: { plan: 'trial' } }
* )
* ```
*
* @example Confirms a user's email address
* ```js
* const { data: user, error } = await supabase.auth.admin.updateUserById(
* '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
* { email_confirm: true }
* )
* ```
*
* @example Confirms a user's phone number
* ```js
* const { data: user, error } = await supabase.auth.admin.updateUserById(
* '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
* { phone_confirm: true }
* )
* ```
*
* @example Ban a user for 100 years
* ```js
* const { data: user, error } = await supabase.auth.admin.updateUserById(
* '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
* { ban_duration: '876000h' }
* )
* ```
*/
updateUserById(uid: string, attributes: AdminUserAttributes): Promise<UserResponse>;
/**
* Delete a user. Requires a `service_role` key.
*
* @param id The user id you want to remove.
* @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.
* Defaults to false for backward compatibility.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*
* @category Auth
* @subcategory Auth Admin
*
* @remarks
* - The `deleteUser()` method requires the user's ID, which maps to the `auth.users.id` column.
*
* @example Removes a user
* ```js
* const { data, error } = await supabase.auth.admin.deleteUser(
* '715ed5db-f090-4b8c-a067-640ecee36aa0'
* )
* ```
*
* @exampleResponse Removes a user
* ```json
* {
* "data": {
* "user": {}
* },
* "error": null
* }
* ```
*/
deleteUser(id: string, shouldSoftDelete?: boolean): Promise<UserResponse>;
private _listFactors;
private _deleteFactor;
/**
* Lists all OAuth clients with optional pagination.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _listOAuthClients;
/**
* Creates a new OAuth client.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _createOAuthClient;
/**
* Gets details of a specific OAuth client.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _getOAuthClient;
/**
* Updates an existing OAuth client.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _updateOAuthClient;
/**
* Deletes an OAuth client.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _deleteOAuthClient;
/**
* Regenerates the secret for an OAuth client.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _regenerateOAuthClientSecret;
/**
* Lists all custom providers with optional type filter.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _listCustomProviders;
/**
* Creates a new custom OIDC/OAuth provider.
*
* For OIDC providers, the server fetches and validates the OpenID Connect discovery document
* from the issuer's well-known endpoint (or the provided `discovery_url`) at creation time.
* This may return a validation error (`error_code: "validation_failed"`) if the discovery
* document is unreachable, not valid JSON, missing required fields, or if the issuer
* in the document does not match the expected issuer.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _createCustomProvider;
/**
* Gets details of a specific custom provider by identifier.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _getCustomProvider;
/**
* Updates an existing custom provider.
*
* When `issuer` or `discovery_url` is changed on an OIDC provider, the server re-fetches and
* validates the discovery document before persisting. This may return a validation error
* (`error_code: "validation_failed"`) if the discovery document is unreachable, invalid, or
* the issuer does not match.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _updateCustomProvider;
/**
* Deletes a custom provider.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
private _deleteCustomProvider;
/**
* Lists all passkeys for a user.
*
* This function should only be called on a server. Never expose your secret key in the browser.
*
* Requires `auth.experimental.passkey: true`.
*/
private _adminListPasskeys;
/**
* Deletes a user's passkey.
*
* This function should only be called on a server. Never expose your secret key in the browser.
*
* Requires `auth.experimental.passkey: true`.
*/
private _adminDeletePasskey;
}
//# sourceMappingURL=GoTrueAdminApi.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"GoTrueAdminApi.d.ts","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAKN,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EACZ,iBAAiB,EAKjB,UAAU,EAEV,YAAY,EACZ,mBAAmB,EAKnB,6BAA6B,EAM7B,qBAAqB,EAKrB,wBAAwB,EACzB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAe,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,+CAA+C;IAC/C,GAAG,EAAE,iBAAiB,CAAA;IAEtB;;;OAGG;IACH,KAAK,EAAE,mBAAmB,CAAA;IAE1B,sEAAsE;IACtE,eAAe,EAAE,6BAA6B,CAAA;IAE9C;;;;OAIG;IACH,OAAO,EAAE,qBAAqB,CAAA;IAE9B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QACjB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;IACtB,SAAS,CAAC,YAAY,EAAE,wBAAwB,CAAA;IAEhD;;;;;;;;;;;;;;;;;;;;OAoBG;gBACS,EACV,GAAQ,EACR,OAAY,EACZ,KAAK,EACL,YAAY,GACb,EAAE;QACD,GAAG,EAAE,MAAM,CAAA;QACX,OAAO,CAAC,EAAE;YACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;SACtB,CAAA;QACD,KAAK,CAAC,EAAE,KAAK,CAAA;QACb,YAAY,CAAC,EAAE,wBAAwB,C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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6DG;IACG,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAiBrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+IG;IACG,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAkBzF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;IACG,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;YAoB/D,YAAY;YA2BZ,aAAa;IA0B3B;;;;;OAKG;YACW,iBAAiB;IAmC/B;;;;;OAKG;YACW,kBAAkB;IAkBhC;;;;;OAKG;YACW,eAAe;IAiB7B;;;;;OAKG;YACW,kBAAkB;IAqBhC;;;;;OAKG;YACW,kBAAkB;IAkBhC;;;;;OAKG;YACW,4BAA4B;IAsB1C;;;;OAIG;YACW,oBAAoB;IAuBlC;;;;;;;;;;OAUG;YACW,qBAAqB;IAmBnC;;;;OAIG;YACW,kBAAkB;IAgBhC;;;;;;;;;OASG;YACW,qBAAqB;IAoBnC;;;;OAIG;YACW,qBAAqB;IAiBnC;;;;;;OAMG;YACW,kBAAkB;IAqBhC;;;;;;OAMG;YACW,mBAAmB;CAsBlC"}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
import GoTrueAdminApi from './GoTrueAdminApi';
import GoTrueClient from './GoTrueClient';
import AuthAdminApi from './AuthAdminApi';
import AuthClient from './AuthClient';
export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient };
export * from './lib/types';
export * from './lib/errors';
export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, processLock, } from './lib/locks';
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA;AACjE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,EAC1B,WAAW,GACZ,MAAM,aAAa,CAAA"}
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0;
const tslib_1 = require("tslib");
const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi"));
exports.GoTrueAdminApi = GoTrueAdminApi_1.default;
const GoTrueClient_1 = tslib_1.__importDefault(require("./GoTrueClient"));
exports.GoTrueClient = GoTrueClient_1.default;
const AuthAdminApi_1 = tslib_1.__importDefault(require("./AuthAdminApi"));
exports.AuthAdminApi = AuthAdminApi_1.default;
const AuthClient_1 = tslib_1.__importDefault(require("./AuthClient"));
exports.AuthClient = AuthClient_1.default;
tslib_1.__exportStar(require("./lib/types"), exports);
tslib_1.__exportStar(require("./lib/errors"), exports);
var locks_1 = require("./lib/locks");
Object.defineProperty(exports, "navigatorLock", { enumerable: true, get: function () { return locks_1.navigatorLock; } });
Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", { enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } });
Object.defineProperty(exports, "lockInternals", { enumerable: true, get: function () { return locks_1.internals; } });
Object.defineProperty(exports, "processLock", { enumerable: true, get: function () { return locks_1.processLock; } });
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,8EAA6C;AAIpC,yBAJF,wBAAc,CAIE;AAHvB,0EAAyC;AAGhB,uBAHlB,sBAAY,CAGkB;AAFrC,0EAAyC;AAEF,uBAFhC,sBAAY,CAEgC;AADnD,sEAAqC;AACgB,qBAD9C,oBAAU,CAC8C;AAC/D,sDAA2B;AAC3B,uDAA4B;AAC5B,qCAKoB;AAJlB,sGAAA,aAAa,OAAA;AACb,yHAAA,gCAAgC,OAAA;AAChC,sGAAA,SAAS,OAAiB;AAC1B,oGAAA,WAAW,OAAA"}
+76
View File
@@ -0,0 +1,76 @@
/**
* Avoid modifying this file. It's part of
* https://github.com/supabase-community/base64url-js. Submit all fixes on
* that repo!
*/
import { Uint8Array_ } from './webauthn.dom';
/**
* Converts a byte to a Base64-URL string.
*
* @param byte The byte to convert, or null to flush at the end of the byte sequence.
* @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next Base64 character when ready.
*/
export declare function byteToBase64URL(byte: number | null, state: {
queue: number;
queuedBits: number;
}, emit: (char: string) => void): void;
/**
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
*
* @param charCode The char code of the JavaScript string.
* @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next byte.
*/
export declare function byteFromBase64URL(charCode: number, state: {
queue: number;
queuedBits: number;
}, emit: (byte: number) => void): void;
/**
* Converts a JavaScript string (which may include any valid character) into a
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
* then encoded as Base64-URL.
*
* @param str The string to convert.
*/
export declare function stringToBase64URL(str: string): string;
/**
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
* that the underlying string has been encoded as UTF-8.
*
* @param str The Base64-URL encoded string.
*/
export declare function stringFromBase64URL(str: string): string;
/**
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
*
* @param codepoint The Unicode codepoint.
* @param emit Function which will be called for each UTF-8 byte that represents the codepoint.
*/
export declare function codepointToUTF8(codepoint: number, emit: (byte: number) => void): void;
/**
* Converts a JavaScript string to a sequence of UTF-8 bytes.
*
* @param str The string to convert to UTF-8.
* @param emit Function which will be called for each UTF-8 byte of the string.
*/
export declare function stringToUTF8(str: string, emit: (byte: number) => void): void;
/**
* Converts a UTF-8 byte to a Unicode codepoint.
*
* @param byte The UTF-8 byte next in the sequence.
* @param state The shared state between consecutive UTF-8 bytes in the
* sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.
* @param emit Function which will be called for each codepoint.
*/
export declare function stringFromUTF8(byte: number, state: {
utf8seq: number;
codepoint: number;
}, emit: (codepoint: number) => void): void;
/**
* Helper functions to convert different types of strings to Uint8Array
*/
export declare function base64UrlToUint8Array(str: string): Uint8Array_;
export declare function stringToUint8Array(str: string): Uint8Array_;
export declare function bytesToBase64URL(bytes: Uint8Array): string;
//# sourceMappingURL=base64url.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"base64url.d.ts","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAoC5C;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAqB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAmB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,UAgB5C;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,UAuB9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAsB9E;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAgBrE;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,EAC7C,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,QAuClC;AAED;;GAEG;AAEH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAa9D;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAI3D;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,UAAU,UAcjD"}
+269
View File
@@ -0,0 +1,269 @@
"use strict";
/**
* Avoid modifying this file. It's part of
* https://github.com/supabase-community/base64url-js. Submit all fixes on
* that repo!
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.byteToBase64URL = byteToBase64URL;
exports.byteFromBase64URL = byteFromBase64URL;
exports.stringToBase64URL = stringToBase64URL;
exports.stringFromBase64URL = stringFromBase64URL;
exports.codepointToUTF8 = codepointToUTF8;
exports.stringToUTF8 = stringToUTF8;
exports.stringFromUTF8 = stringFromUTF8;
exports.base64UrlToUint8Array = base64UrlToUint8Array;
exports.stringToUint8Array = stringToUint8Array;
exports.bytesToBase64URL = bytesToBase64URL;
/**
* An array of characters that encode 6 bits into a Base64-URL alphabet
* character.
*/
const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split('');
/**
* An array of characters that can appear in a Base64-URL encoded string but
* should be ignored.
*/
const IGNORE_BASE64URL = ' \t\n\r='.split('');
/**
* An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2
* used to skip the character, or if -1 used to error out.
*/
const FROM_BASE64URL = (() => {
const charMap = new Array(128);
for (let i = 0; i < charMap.length; i += 1) {
charMap[i] = -1;
}
for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) {
charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2;
}
for (let i = 0; i < TO_BASE64URL.length; i += 1) {
charMap[TO_BASE64URL[i].charCodeAt(0)] = i;
}
return charMap;
})();
/**
* Converts a byte to a Base64-URL string.
*
* @param byte The byte to convert, or null to flush at the end of the byte sequence.
* @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next Base64 character when ready.
*/
function byteToBase64URL(byte, state, emit) {
if (byte !== null) {
state.queue = (state.queue << 8) | byte;
state.queuedBits += 8;
while (state.queuedBits >= 6) {
const pos = (state.queue >> (state.queuedBits - 6)) & 63;
emit(TO_BASE64URL[pos]);
state.queuedBits -= 6;
}
}
else if (state.queuedBits > 0) {
state.queue = state.queue << (6 - state.queuedBits);
state.queuedBits = 6;
while (state.queuedBits >= 6) {
const pos = (state.queue >> (state.queuedBits - 6)) & 63;
emit(TO_BASE64URL[pos]);
state.queuedBits -= 6;
}
}
}
/**
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
*
* @param charCode The char code of the JavaScript string.
* @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next byte.
*/
function byteFromBase64URL(charCode, state, emit) {
const bits = FROM_BASE64URL[charCode];
if (bits > -1) {
// valid Base64-URL character
state.queue = (state.queue << 6) | bits;
state.queuedBits += 6;
while (state.queuedBits >= 8) {
emit((state.queue >> (state.queuedBits - 8)) & 0xff);
state.queuedBits -= 8;
}
}
else if (bits === -2) {
// ignore spaces, tabs, newlines, =
return;
}
else {
throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`);
}
}
/**
* Converts a JavaScript string (which may include any valid character) into a
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
* then encoded as Base64-URL.
*
* @param str The string to convert.
*/
function stringToBase64URL(str) {
const base64 = [];
const emitter = (char) => {
base64.push(char);
};
const state = { queue: 0, queuedBits: 0 };
stringToUTF8(str, (byte) => {
byteToBase64URL(byte, state, emitter);
});
byteToBase64URL(null, state, emitter);
return base64.join('');
}
/**
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
* that the underlying string has been encoded as UTF-8.
*
* @param str The Base64-URL encoded string.
*/
function stringFromBase64URL(str) {
const conv = [];
const utf8Emit = (codepoint) => {
conv.push(String.fromCodePoint(codepoint));
};
const utf8State = {
utf8seq: 0,
codepoint: 0,
};
const b64State = { queue: 0, queuedBits: 0 };
const byteEmit = (byte) => {
stringFromUTF8(byte, utf8State, utf8Emit);
};
for (let i = 0; i < str.length; i += 1) {
byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit);
}
return conv.join('');
}
/**
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
*
* @param codepoint The Unicode codepoint.
* @param emit Function which will be called for each UTF-8 byte that represents the codepoint.
*/
function codepointToUTF8(codepoint, emit) {
if (codepoint <= 0x7f) {
emit(codepoint);
return;
}
else if (codepoint <= 0x7ff) {
emit(0xc0 | (codepoint >> 6));
emit(0x80 | (codepoint & 0x3f));
return;
}
else if (codepoint <= 0xffff) {
emit(0xe0 | (codepoint >> 12));
emit(0x80 | ((codepoint >> 6) & 0x3f));
emit(0x80 | (codepoint & 0x3f));
return;
}
else if (codepoint <= 0x10ffff) {
emit(0xf0 | (codepoint >> 18));
emit(0x80 | ((codepoint >> 12) & 0x3f));
emit(0x80 | ((codepoint >> 6) & 0x3f));
emit(0x80 | (codepoint & 0x3f));
return;
}
throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`);
}
/**
* Converts a JavaScript string to a sequence of UTF-8 bytes.
*
* @param str The string to convert to UTF-8.
* @param emit Function which will be called for each UTF-8 byte of the string.
*/
function stringToUTF8(str, emit) {
for (let i = 0; i < str.length; i += 1) {
let codepoint = str.charCodeAt(i);
if (codepoint > 0xd7ff && codepoint <= 0xdbff) {
// most UTF-16 codepoints are Unicode codepoints, except values in this
// range where the next UTF-16 codepoint needs to be combined with the
// current one to get the Unicode codepoint
const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff;
const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff;
codepoint = (lowSurrogate | highSurrogate) + 0x10000;
i += 1;
}
codepointToUTF8(codepoint, emit);
}
}
/**
* Converts a UTF-8 byte to a Unicode codepoint.
*
* @param byte The UTF-8 byte next in the sequence.
* @param state The shared state between consecutive UTF-8 bytes in the
* sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.
* @param emit Function which will be called for each codepoint.
*/
function stringFromUTF8(byte, state, emit) {
if (state.utf8seq === 0) {
if (byte <= 0x7f) {
emit(byte);
return;
}
// count the number of 1 leading bits until you reach 0
for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) {
if (((byte >> (7 - leadingBit)) & 1) === 0) {
state.utf8seq = leadingBit;
break;
}
}
if (state.utf8seq === 2) {
state.codepoint = byte & 31;
}
else if (state.utf8seq === 3) {
state.codepoint = byte & 15;
}
else if (state.utf8seq === 4) {
state.codepoint = byte & 7;
}
else {
throw new Error('Invalid UTF-8 sequence');
}
state.utf8seq -= 1;
}
else if (state.utf8seq > 0) {
if (byte <= 0x7f) {
throw new Error('Invalid UTF-8 sequence');
}
state.codepoint = (state.codepoint << 6) | (byte & 63);
state.utf8seq -= 1;
if (state.utf8seq === 0) {
emit(state.codepoint);
}
}
}
/**
* Helper functions to convert different types of strings to Uint8Array
*/
function base64UrlToUint8Array(str) {
const result = [];
const state = { queue: 0, queuedBits: 0 };
const onByte = (byte) => {
result.push(byte);
};
for (let i = 0; i < str.length; i += 1) {
byteFromBase64URL(str.charCodeAt(i), state, onByte);
}
return new Uint8Array(result);
}
function stringToUint8Array(str) {
const result = [];
stringToUTF8(str, (byte) => result.push(byte));
return new Uint8Array(result);
}
function bytesToBase64URL(bytes) {
const result = [];
const state = { queue: 0, queuedBits: 0 };
const onChar = (char) => {
result.push(char);
};
bytes.forEach((byte) => byteToBase64URL(byte, state, onChar));
// always call with `null` after processing all bytes
byteToBase64URL(null, state, onChar);
return result.join('');
}
//# sourceMappingURL=base64url.js.map
File diff suppressed because one or more lines are too long
+34
View File
@@ -0,0 +1,34 @@
/** Current session will be checked for refresh at this interval. */
export declare const AUTO_REFRESH_TICK_DURATION_MS: number;
/**
* A token refresh will be attempted this many ticks before the current session expires. */
export declare const AUTO_REFRESH_TICK_THRESHOLD = 3;
export declare const EXPIRY_MARGIN_MS: number;
/**
* After a refresh fails, serial callers (including the next auto-refresh
* tick) within this window receive the cached failure instead of firing
* another /token request. Two ticks: each outage burns at most one /token
* call per cooldown window. Cleared on any successful refresh (locally or
* via BroadcastChannel from another tab) and on `_removeSession`.
*/
export declare const REFRESH_FAILURE_COOLDOWN_MS: number;
export declare const GOTRUE_URL = "http://localhost:9999";
export declare const STORAGE_KEY = "supabase.auth.token";
export declare const AUDIENCE = "";
export declare const DEFAULT_HEADERS: {
'X-Client-Info': string;
};
export declare const NETWORK_FAILURE: {
MAX_RETRIES: number;
RETRY_INTERVAL: number;
};
export declare const API_VERSION_HEADER_NAME = "X-Supabase-Api-Version";
export declare const API_VERSIONS: {
'2024-01-01': {
timestamp: number;
name: string;
};
};
export declare const BASE64URL_REGEX: RegExp;
export declare const JWKS_TTL: number;
//# sourceMappingURL=constants.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,oEAAoE;AACpE,eAAO,MAAM,6BAA6B,QAAY,CAAA;AAEtD;2FAC2F;AAC3F,eAAO,MAAM,2BAA2B,IAAI,CAAA;AAK5C,eAAO,MAAM,gBAAgB,QAA8D,CAAA;AAE3F;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,QAAoC,CAAA;AAE5E,eAAO,MAAM,UAAU,0BAA0B,CAAA;AACjD,eAAO,MAAM,WAAW,wBAAwB,CAAA;AAChD,eAAO,MAAM,QAAQ,KAAK,CAAA;AAC1B,eAAO,MAAM,eAAe;;CAA8C,CAAA;AAC1E,eAAO,MAAM,eAAe;;;CAG3B,CAAA;AAED,eAAO,MAAM,uBAAuB,2BAA2B,CAAA;AAC/D,eAAO,MAAM,YAAY;;;;;CAKxB,CAAA;AAED,eAAO,MAAM,eAAe,QAAyD,CAAA;AAErF,eAAO,MAAM,QAAQ,QAAiB,CAAA"}
+39
View File
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.REFRESH_FAILURE_COOLDOWN_MS = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0;
const version_1 = require("./version");
/** Current session will be checked for refresh at this interval. */
exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000;
/**
* A token refresh will be attempted this many ticks before the current session expires. */
exports.AUTO_REFRESH_TICK_THRESHOLD = 3;
/*
* Earliest time before an access token expires that the session should be refreshed.
*/
exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS;
/**
* After a refresh fails, serial callers (including the next auto-refresh
* tick) within this window receive the cached failure instead of firing
* another /token request. Two ticks: each outage burns at most one /token
* call per cooldown window. Cleared on any successful refresh (locally or
* via BroadcastChannel from another tab) and on `_removeSession`.
*/
exports.REFRESH_FAILURE_COOLDOWN_MS = 2 * exports.AUTO_REFRESH_TICK_DURATION_MS;
exports.GOTRUE_URL = 'http://localhost:9999';
exports.STORAGE_KEY = 'supabase.auth.token';
exports.AUDIENCE = '';
exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` };
exports.NETWORK_FAILURE = {
MAX_RETRIES: 10,
RETRY_INTERVAL: 2, // in deciseconds
};
exports.API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version';
exports.API_VERSIONS = {
'2024-01-01': {
timestamp: Date.parse('2024-01-01T00:00:00.0Z'),
name: '2024-01-01',
},
};
exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;
exports.JWKS_TTL = 10 * 60 * 1000; // 10 minutes
//# sourceMappingURL=constants.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AAEnC,oEAAoE;AACvD,QAAA,6BAA6B,GAAG,EAAE,GAAG,IAAI,CAAA;AAEtD;2FAC2F;AAC9E,QAAA,2BAA2B,GAAG,CAAC,CAAA;AAE5C;;GAEG;AACU,QAAA,gBAAgB,GAAG,mCAA2B,GAAG,qCAA6B,CAAA;AAE3F;;;;;;GAMG;AACU,QAAA,2BAA2B,GAAG,CAAC,GAAG,qCAA6B,CAAA;AAE/D,QAAA,UAAU,GAAG,uBAAuB,CAAA;AACpC,QAAA,WAAW,GAAG,qBAAqB,CAAA;AACnC,QAAA,QAAQ,GAAG,EAAE,CAAA;AACb,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,aAAa,iBAAO,EAAE,EAAE,CAAA;AAC7D,QAAA,eAAe,GAAG;IAC7B,WAAW,EAAE,EAAE;IACf,cAAc,EAAE,CAAC,EAAE,iBAAiB;CACrC,CAAA;AAEY,QAAA,uBAAuB,GAAG,wBAAwB,CAAA;AAClD,QAAA,YAAY,GAAG;IAC1B,YAAY,EAAE;QACZ,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC;QAC/C,IAAI,EAAE,YAAY;KACnB;CACF,CAAA;AAEY,QAAA,eAAe,GAAG,sDAAsD,CAAA;AAExE,QAAA,QAAQ,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,aAAa"}
+7
View File
@@ -0,0 +1,7 @@
/**
* Known error codes. Note that the server may also return other error codes
* not included in this list (if the SDK is older than the version
* on the server).
*/
export type ErrorCode = 'unexpected_failure' | 'validation_failed' | 'bad_json' | 'email_exists' | 'phone_exists' | 'bad_jwt' | 'not_admin' | 'no_authorization' | 'user_not_found' | 'session_not_found' | 'session_expired' | 'refresh_token_not_found' | 'refresh_token_already_used' | 'flow_state_not_found' | 'flow_state_expired' | 'signup_disabled' | 'user_banned' | 'provider_email_needs_verification' | 'invite_not_found' | 'bad_oauth_state' | 'bad_oauth_callback' | 'oauth_provider_not_supported' | 'unexpected_audience' | 'single_identity_not_deletable' | 'email_conflict_identity_not_deletable' | 'identity_already_exists' | 'email_provider_disabled' | 'phone_provider_disabled' | 'too_many_enrolled_mfa_factors' | 'mfa_factor_name_conflict' | 'mfa_factor_not_found' | 'mfa_ip_address_mismatch' | 'mfa_challenge_expired' | 'mfa_verification_failed' | 'mfa_verification_rejected' | 'insufficient_aal' | 'captcha_failed' | 'saml_provider_disabled' | 'manual_linking_disabled' | 'sms_send_failed' | 'email_not_confirmed' | 'phone_not_confirmed' | 'reauth_nonce_missing' | 'saml_relay_state_not_found' | 'saml_relay_state_expired' | 'saml_idp_not_found' | 'saml_assertion_no_user_id' | 'saml_assertion_no_email' | 'user_already_exists' | 'sso_provider_not_found' | 'saml_metadata_fetch_failed' | 'saml_idp_already_exists' | 'sso_domain_already_exists' | 'saml_entity_id_mismatch' | 'conflict' | 'provider_disabled' | 'user_sso_managed' | 'reauthentication_needed' | 'same_password' | 'reauthentication_not_valid' | 'otp_expired' | 'otp_disabled' | 'identity_not_found' | 'weak_password' | 'over_request_rate_limit' | 'over_email_send_rate_limit' | 'over_sms_send_rate_limit' | 'bad_code_verifier' | 'anonymous_provider_disabled' | 'hook_timeout' | 'hook_timeout_after_retry' | 'hook_payload_over_size_limit' | 'hook_payload_invalid_content_type' | 'request_timeout' | 'mfa_phone_enroll_not_enabled' | 'mfa_phone_verify_not_enabled' | 'mfa_totp_enroll_not_enabled' | 'mfa_totp_verify_not_enabled' | 'mfa_webauthn_enroll_not_enabled' | 'mfa_webauthn_verify_not_enabled' | 'mfa_verified_factor_exists' | 'invalid_credentials' | 'email_address_not_authorized' | 'email_address_invalid';
//# sourceMappingURL=error-codes.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"error-codes.d.ts","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,SAAS,GACjB,oBAAoB,GACpB,mBAAmB,GACnB,UAAU,GACV,cAAc,GACd,cAAc,GACd,SAAS,GACT,WAAW,GACX,kBAAkB,GAClB,gBAAgB,GAChB,mBAAmB,GACnB,iBAAiB,GACjB,yBAAyB,GACzB,4BAA4B,GAC5B,sBAAsB,GACtB,oBAAoB,GACpB,iBAAiB,GACjB,aAAa,GACb,mCAAmC,GACnC,kBAAkB,GAClB,iBAAiB,GACjB,oBAAoB,GACpB,8BAA8B,GAC9B,qBAAqB,GACrB,+BAA+B,GAC/B,uCAAuC,GACvC,yBAAyB,GACzB,yBAAyB,GACzB,yBAAyB,GACzB,+BAA+B,GAC/B,0BAA0B,GAC1B,sBAAsB,GACtB,yBAAyB,GACzB,uBAAuB,GACvB,yBAAyB,GACzB,2BAA2B,GAC3B,kBAAkB,GAClB,gBAAgB,GAChB,wBAAwB,GACxB,yBAAyB,GACzB,iBAAiB,GACjB,qBAAqB,GACrB,qBAAqB,GACrB,sBAAsB,GACtB,4BAA4B,GAC5B,0BAA0B,GAC1B,oBAAoB,GACpB,2BAA2B,GAC3B,yBAAyB,GACzB,qBAAqB,GACrB,wBAAwB,GACxB,4BAA4B,GAC5B,yBAAyB,GACzB,2BAA2B,GAC3B,yBAAyB,GACzB,UAAU,GACV,mBAAmB,GACnB,kBAAkB,GAClB,yBAAyB,GACzB,eAAe,GACf,4BAA4B,GAC5B,aAAa,GACb,cAAc,GACd,oBAAoB,GACpB,eAAe,GACf,yBAAyB,GACzB,4BAA4B,GAC5B,0BAA0B,GAC1B,mBAAmB,GACnB,6BAA6B,GAC7B,cAAc,GACd,0BAA0B,GAC1B,8BAA8B,GAC9B,mCAAmC,GACnC,iBAAiB,GACjB,8BAA8B,GAC9B,8BAA8B,GAC9B,6BAA6B,GAC7B,6BAA6B,GAC7B,iCAAiC,GACjC,iCAAiC,GACjC,4BAA4B,GAC5B,qBAAqB,GACrB,8BAA8B,GAC9B,uBAAuB,CAAA"}
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=error-codes.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"error-codes.js","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":""}
+282
View File
@@ -0,0 +1,282 @@
import { WeakPasswordReasons } from './types';
import { ErrorCode } from './error-codes';
/**
* Base error thrown by Supabase Auth helpers.
*
* @example
* ```ts
* import { AuthError } from '@supabase/auth-js'
*
* throw new AuthError('Unexpected auth error', 500, 'unexpected')
* ```
*/
export declare class AuthError extends Error {
/**
* Error code associated with the error. Most errors coming from
* HTTP responses will have a code, though some errors that occur
* before a response is received will not have one present. In that
* case {@link AuthError.status} will also be undefined.
*/
code: ErrorCode | (string & {}) | undefined;
/** HTTP status code that caused the error. */
status: number | undefined;
protected __isAuthError: boolean;
constructor(message: string, status?: number, code?: string);
toJSON(): {
name: string;
message: string;
status: number | undefined;
code: ErrorCode | (string & {}) | undefined;
};
}
export declare function isAuthError(error: unknown): error is AuthError;
/**
* Error returned directly from the GoTrue REST API.
*
* @example
* ```ts
* import { AuthApiError } from '@supabase/auth-js'
*
* throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials')
* ```
*/
export declare class AuthApiError extends AuthError {
status: number;
constructor(message: string, status: number, code: string | undefined);
}
export declare function isAuthApiError(error: unknown): error is AuthApiError;
/**
* Wraps non-standard errors so callers can inspect the root cause.
*
* @example
* ```ts
* import { AuthUnknownError } from '@supabase/auth-js'
*
* try {
* await someAuthCall()
* } catch (err) {
* throw new AuthUnknownError('Auth failed', err)
* }
* ```
*/
export declare class AuthUnknownError extends AuthError {
originalError: unknown;
constructor(message: string, originalError: unknown);
}
/**
* Flexible error class used to create named auth errors at runtime.
*
* @example
* ```ts
* import { CustomAuthError } from '@supabase/auth-js'
*
* throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code')
* ```
*/
export declare class CustomAuthError extends AuthError {
name: string;
status: number;
constructor(message: string, name: string, status: number, code: string | undefined);
}
/**
* Error thrown when an operation requires a session but none is present.
*
* @example
* ```ts
* import { AuthSessionMissingError } from '@supabase/auth-js'
*
* throw new AuthSessionMissingError()
* ```
*/
export declare class AuthSessionMissingError extends CustomAuthError {
constructor();
}
export declare function isAuthSessionMissingError(error: any): error is AuthSessionMissingError;
/**
* Error thrown when the token response is malformed.
*
* @example
* ```ts
* import { AuthInvalidTokenResponseError } from '@supabase/auth-js'
*
* throw new AuthInvalidTokenResponseError()
* ```
*/
export declare class AuthInvalidTokenResponseError extends CustomAuthError {
constructor();
}
/**
* Error thrown when email/password credentials are invalid.
*
* @example
* ```ts
* import { AuthInvalidCredentialsError } from '@supabase/auth-js'
*
* throw new AuthInvalidCredentialsError('Email or password is incorrect')
* ```
*/
export declare class AuthInvalidCredentialsError extends CustomAuthError {
constructor(message: string);
}
/**
* Error thrown when implicit grant redirects contain an error.
*
* @example
* ```ts
* import { AuthImplicitGrantRedirectError } from '@supabase/auth-js'
*
* throw new AuthImplicitGrantRedirectError('OAuth redirect failed', {
* error: 'access_denied',
* code: 'oauth_error',
* })
* ```
*/
export declare class AuthImplicitGrantRedirectError extends CustomAuthError {
details: {
error: string;
code: string;
} | null;
constructor(message: string, details?: {
error: string;
code: string;
} | null);
toJSON(): {
name: string;
message: string;
status: number | undefined;
code: ErrorCode | (string & {}) | undefined;
details: {
error: string;
code: string;
} | null;
};
}
export declare function isAuthImplicitGrantRedirectError(error: any): error is AuthImplicitGrantRedirectError;
/**
* Error thrown during PKCE code exchanges.
*
* @example
* ```ts
* import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js'
*
* throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed')
* ```
*/
export declare class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
details: {
error: string;
code: string;
} | null;
constructor(message: string, details?: {
error: string;
code: string;
} | null);
toJSON(): {
name: string;
message: string;
status: number | undefined;
code: ErrorCode | (string & {}) | undefined;
details: {
error: string;
code: string;
} | null;
};
}
/**
* Error thrown when the PKCE code verifier is not found in storage.
* This typically happens when the auth flow was initiated in a different
* browser, device, or the storage was cleared.
*
* @example
* ```ts
* import { AuthPKCECodeVerifierMissingError } from '@supabase/auth-js'
*
* throw new AuthPKCECodeVerifierMissingError()
* ```
*/
export declare class AuthPKCECodeVerifierMissingError extends CustomAuthError {
constructor();
}
export declare function isAuthPKCECodeVerifierMissingError(error: unknown): error is AuthPKCECodeVerifierMissingError;
/**
* Error thrown when a transient fetch issue occurs.
*
* @example
* ```ts
* import { AuthRetryableFetchError } from '@supabase/auth-js'
*
* throw new AuthRetryableFetchError('Service temporarily unavailable', 503)
* ```
*/
export declare class AuthRetryableFetchError extends CustomAuthError {
constructor(message: string, status: number);
}
export declare function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError;
/**
* Returned when the server rotated a refresh token successfully but the
* client chose not to persist the rotated tokens because the local session
* changed mid-flight. Usually means a concurrent `signOut` cleared storage
* between when the refresh started and when it came back.
*
* Set on the `error` field of the refresh result so callers can tell "we
* got rotated tokens but threw them away" apart from "the refresh failed."
* The rotated session on the server will be picked up on the next refresh
* via GoTrue's parent-of-active path.
*
* @example
* ```ts
* import { isAuthRefreshDiscardedError } from '@supabase/auth-js'
*
* if (isAuthRefreshDiscardedError(error)) {
* // Concurrent signOut/sign-in raced our refresh. Treat as a no-op.
* }
* ```
*/
export declare class AuthRefreshDiscardedError extends CustomAuthError {
constructor(message?: string);
}
export declare function isAuthRefreshDiscardedError(error: unknown): error is AuthRefreshDiscardedError;
/**
* This error is thrown on certain methods when the password used is deemed
* weak. Inspect the reasons to identify what password strength rules are
* inadequate.
*/
/**
* Error thrown when a supplied password is considered weak.
*
* @example
* ```ts
* import { AuthWeakPasswordError } from '@supabase/auth-js'
*
* throw new AuthWeakPasswordError('Password too short', 400, ['min_length'])
* ```
*/
export declare class AuthWeakPasswordError extends CustomAuthError {
/**
* Reasons why the password is deemed weak.
*/
reasons: WeakPasswordReasons[];
constructor(message: string, status: number, reasons: WeakPasswordReasons[]);
toJSON(): {
name: string;
message: string;
status: number | undefined;
code: ErrorCode | (string & {}) | undefined;
reasons: WeakPasswordReasons[];
};
}
export declare function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswordError;
/**
* Error thrown when a JWT cannot be verified or parsed.
*
* @example
* ```ts
* import { AuthInvalidJwtError } from '@supabase/auth-js'
*
* throw new AuthInvalidJwtError('Token signature is invalid')
* ```
*/
export declare class AuthInvalidJwtError extends CustomAuthError {
constructor(message: string);
}
//# sourceMappingURL=errors.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAEzC;;;;;;;;;GASG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC;;;;;OAKG;IACH,IAAI,EAAE,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,SAAS,CAAA;IAE3C,8CAA8C;IAC9C,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAE1B,SAAS,CAAC,aAAa,UAAO;gBAElB,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM;IAO3D,MAAM,IAAI;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,OAAO,EAAE,MAAM,CAAA;QACf,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;QAC1B,IAAI,EAAE,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,SAAS,CAAA;KAC5C;CAQF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAE9D;AAED;;;;;;;;;GASG;AACH,qBAAa,YAAa,SAAQ,SAAS;IACzC,MAAM,EAAE,MAAM,CAAA;gBAEF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS;CAMtE;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,gBAAiB,SAAQ,SAAS;IAC7C,aAAa,EAAE,OAAO,CAAA;gBAEV,OAAO,EAAE,MAAM,EA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M,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,mBAAmB,EAAE;IAM3E,MAAM,IAAI;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,OAAO,EAAE,MAAM,CAAA;QACf,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;QAC1B,IAAI,EAAE,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,SAAS,CAAA;QAC3C,OAAO,EAAE,mBAAmB,EAAE,CAAA;KAC/B;CAMF;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,qBAAqB,CAEtF;AAED;;;;;;;;;GASG;AACH,qBAAa,mBAAoB,SAAQ,eAAe;gBAC1C,OAAO,EAAE,MAAM;CAG5B"}
+320
View File
@@ -0,0 +1,320 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRefreshDiscardedError = exports.AuthRetryableFetchError = exports.AuthPKCECodeVerifierMissingError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0;
exports.isAuthError = isAuthError;
exports.isAuthApiError = isAuthApiError;
exports.isAuthSessionMissingError = isAuthSessionMissingError;
exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError;
exports.isAuthPKCECodeVerifierMissingError = isAuthPKCECodeVerifierMissingError;
exports.isAuthRetryableFetchError = isAuthRetryableFetchError;
exports.isAuthRefreshDiscardedError = isAuthRefreshDiscardedError;
exports.isAuthWeakPasswordError = isAuthWeakPasswordError;
/**
* Base error thrown by Supabase Auth helpers.
*
* @example
* ```ts
* import { AuthError } from '@supabase/auth-js'
*
* throw new AuthError('Unexpected auth error', 500, 'unexpected')
* ```
*/
class AuthError extends Error {
constructor(message, status, code) {
super(message);
this.__isAuthError = true;
this.name = 'AuthError';
this.status = status;
this.code = code;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status,
code: this.code,
};
}
}
exports.AuthError = AuthError;
function isAuthError(error) {
return typeof error === 'object' && error !== null && '__isAuthError' in error;
}
/**
* Error returned directly from the GoTrue REST API.
*
* @example
* ```ts
* import { AuthApiError } from '@supabase/auth-js'
*
* throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials')
* ```
*/
class AuthApiError extends AuthError {
constructor(message, status, code) {
super(message, status, code);
this.name = 'AuthApiError';
this.status = status;
this.code = code;
}
}
exports.AuthApiError = AuthApiError;
function isAuthApiError(error) {
return isAuthError(error) && error.name === 'AuthApiError';
}
/**
* Wraps non-standard errors so callers can inspect the root cause.
*
* @example
* ```ts
* import { AuthUnknownError } from '@supabase/auth-js'
*
* try {
* await someAuthCall()
* } catch (err) {
* throw new AuthUnknownError('Auth failed', err)
* }
* ```
*/
class AuthUnknownError extends AuthError {
constructor(message, originalError) {
super(message);
this.name = 'AuthUnknownError';
this.originalError = originalError;
}
}
exports.AuthUnknownError = AuthUnknownError;
/**
* Flexible error class used to create named auth errors at runtime.
*
* @example
* ```ts
* import { CustomAuthError } from '@supabase/auth-js'
*
* throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code')
* ```
*/
class CustomAuthError extends AuthError {
constructor(message, name, status, code) {
super(message, status, code);
this.name = name;
this.status = status;
}
}
exports.CustomAuthError = CustomAuthError;
/**
* Error thrown when an operation requires a session but none is present.
*
* @example
* ```ts
* import { AuthSessionMissingError } from '@supabase/auth-js'
*
* throw new AuthSessionMissingError()
* ```
*/
class AuthSessionMissingError extends CustomAuthError {
constructor() {
super('Auth session missing!', 'AuthSessionMissingError', 400, undefined);
}
}
exports.AuthSessionMissingError = AuthSessionMissingError;
function isAuthSessionMissingError(error) {
return isAuthError(error) && error.name === 'AuthSessionMissingError';
}
/**
* Error thrown when the token response is malformed.
*
* @example
* ```ts
* import { AuthInvalidTokenResponseError } from '@supabase/auth-js'
*
* throw new AuthInvalidTokenResponseError()
* ```
*/
class AuthInvalidTokenResponseError extends CustomAuthError {
constructor() {
super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined);
}
}
exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError;
/**
* Error thrown when email/password credentials are invalid.
*
* @example
* ```ts
* import { AuthInvalidCredentialsError } from '@supabase/auth-js'
*
* throw new AuthInvalidCredentialsError('Email or password is incorrect')
* ```
*/
class AuthInvalidCredentialsError extends CustomAuthError {
constructor(message) {
super(message, 'AuthInvalidCredentialsError', 400, undefined);
}
}
exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError;
/**
* Error thrown when implicit grant redirects contain an error.
*
* @example
* ```ts
* import { AuthImplicitGrantRedirectError } from '@supabase/auth-js'
*
* throw new AuthImplicitGrantRedirectError('OAuth redirect failed', {
* error: 'access_denied',
* code: 'oauth_error',
* })
* ```
*/
class AuthImplicitGrantRedirectError extends CustomAuthError {
constructor(message, details = null) {
super(message, 'AuthImplicitGrantRedirectError', 500, undefined);
this.details = null;
this.details = details;
}
toJSON() {
return Object.assign(Object.assign({}, super.toJSON()), { details: this.details });
}
}
exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError;
function isAuthImplicitGrantRedirectError(error) {
return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError';
}
/**
* Error thrown during PKCE code exchanges.
*
* @example
* ```ts
* import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js'
*
* throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed')
* ```
*/
class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
constructor(message, details = null) {
super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined);
this.details = null;
this.details = details;
}
toJSON() {
return Object.assign(Object.assign({}, super.toJSON()), { details: this.details });
}
}
exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError;
/**
* Error thrown when the PKCE code verifier is not found in storage.
* This typically happens when the auth flow was initiated in a different
* browser, device, or the storage was cleared.
*
* @example
* ```ts
* import { AuthPKCECodeVerifierMissingError } from '@supabase/auth-js'
*
* throw new AuthPKCECodeVerifierMissingError()
* ```
*/
class AuthPKCECodeVerifierMissingError extends CustomAuthError {
constructor() {
super('PKCE code verifier not found in storage. ' +
'This can happen if the auth flow was initiated in a different browser or device, ' +
'or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), ' +
'use @supabase/ssr on both the server and client to store the code verifier in cookies.', 'AuthPKCECodeVerifierMissingError', 400, 'pkce_code_verifier_not_found');
}
}
exports.AuthPKCECodeVerifierMissingError = AuthPKCECodeVerifierMissingError;
function isAuthPKCECodeVerifierMissingError(error) {
return isAuthError(error) && error.name === 'AuthPKCECodeVerifierMissingError';
}
/**
* Error thrown when a transient fetch issue occurs.
*
* @example
* ```ts
* import { AuthRetryableFetchError } from '@supabase/auth-js'
*
* throw new AuthRetryableFetchError('Service temporarily unavailable', 503)
* ```
*/
class AuthRetryableFetchError extends CustomAuthError {
constructor(message, status) {
super(message, 'AuthRetryableFetchError', status, undefined);
}
}
exports.AuthRetryableFetchError = AuthRetryableFetchError;
function isAuthRetryableFetchError(error) {
return isAuthError(error) && error.name === 'AuthRetryableFetchError';
}
/**
* Returned when the server rotated a refresh token successfully but the
* client chose not to persist the rotated tokens because the local session
* changed mid-flight. Usually means a concurrent `signOut` cleared storage
* between when the refresh started and when it came back.
*
* Set on the `error` field of the refresh result so callers can tell "we
* got rotated tokens but threw them away" apart from "the refresh failed."
* The rotated session on the server will be picked up on the next refresh
* via GoTrue's parent-of-active path.
*
* @example
* ```ts
* import { isAuthRefreshDiscardedError } from '@supabase/auth-js'
*
* if (isAuthRefreshDiscardedError(error)) {
* // Concurrent signOut/sign-in raced our refresh. Treat as a no-op.
* }
* ```
*/
class AuthRefreshDiscardedError extends CustomAuthError {
constructor(message = 'Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)') {
super(message, 'AuthRefreshDiscardedError', 409, undefined);
}
}
exports.AuthRefreshDiscardedError = AuthRefreshDiscardedError;
function isAuthRefreshDiscardedError(error) {
return isAuthError(error) && error.name === 'AuthRefreshDiscardedError';
}
/**
* This error is thrown on certain methods when the password used is deemed
* weak. Inspect the reasons to identify what password strength rules are
* inadequate.
*/
/**
* Error thrown when a supplied password is considered weak.
*
* @example
* ```ts
* import { AuthWeakPasswordError } from '@supabase/auth-js'
*
* throw new AuthWeakPasswordError('Password too short', 400, ['min_length'])
* ```
*/
class AuthWeakPasswordError extends CustomAuthError {
constructor(message, status, reasons) {
super(message, 'AuthWeakPasswordError', status, 'weak_password');
this.reasons = reasons;
}
toJSON() {
return Object.assign(Object.assign({}, super.toJSON()), { reasons: this.reasons });
}
}
exports.AuthWeakPasswordError = AuthWeakPasswordError;
function isAuthWeakPasswordError(error) {
return isAuthError(error) && error.name === 'AuthWeakPasswordError';
}
/**
* Error thrown when a JWT cannot be verified or parsed.
*
* @example
* ```ts
* import { AuthInvalidJwtError } from '@supabase/auth-js'
*
* throw new AuthInvalidJwtError('Token signature is invalid')
* ```
*/
class AuthInvalidJwtError extends CustomAuthError {
constructor(message) {
super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt');
}
}
exports.AuthInvalidJwtError = AuthInvalidJwtError;
//# sourceMappingURL=errors.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":";;;AAiDA,kCAEC;AAuBD,wCAEC;AA+DD,8DAEC;AAoED,4EAIC;AA4DD,gFAIC;AAkBD,8DAEC;AA8BD,kEAEC;AA2CD,0DAEC;AAnXD;;;;;;;;;GASG;AACH,MAAa,SAAU,SAAQ,KAAK;IAclC,YAAY,OAAe,EAAE,MAAe,EAAE,IAAa;QACzD,KAAK,CAAC,OAAO,CAAC,CAAA;QAHN,kBAAa,GAAG,IAAI,CAAA;QAI5B,IAAI,CAAC,IAAI,GAAG,WAAW,CAAA;QACvB,IAA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,EAAE,SAAS,CAAC,CAAA;IAC7D,CAAC;CACF;AAND,8DAMC;AAED,SAAgB,2BAA2B,CAAC,KAAc;IACxD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,2BAA2B,CAAA;AACzE,CAAC;AAED;;;;GAIG;AACH;;;;;;;;;GASG;AACH,MAAa,qBAAsB,SAAQ,eAAe;IAMxD,YAAY,OAAe,EAAE,MAAc,EAAE,OAA8B;QACzE,KAAK,CAAC,OAAO,EAAE,uBAAuB,EAAE,MAAM,EAAE,eAAe,CAAC,CAAA;QAEhE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,MAAM;QAOJ,uCACK,KAAK,CAAC,MAAM,EAAE,KACjB,OAAO,EAAE,IAAI,CAAC,OAAO,IACtB;IACH,CAAC;CACF;AAxBD,sDAwBC;AAED,SAAgB,uBAAuB,CAAC,KAAc;IACpD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,CAAA;AACrE,CAAC;AAED;;;;;;;;;GASG;AACH,MAAa,mBAAoB,SAAQ,eAAe;IACtD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,EAAE,qBAAqB,EAAE,GAAG,EAAE,aAAa,CAAC,CAAA;IAC3D,CAAC;CACF;AAJD,kDAIC"}
+54
View File
@@ -0,0 +1,54 @@
import { AuthResponse, AuthResponsePassword, SSOResponse, GenerateLinkProperties, GenerateLinkResponse, User, UserResponse, WeakPassword } from './types';
export type Fetch = typeof fetch;
/** Raw session data from GoTrue server response. */
interface GoTrueSessionData {
access_token?: string;
refresh_token?: string;
expires_in?: number;
expires_at?: number;
user?: User;
[key: string]: any;
}
/** Raw session data that includes weak password info (password sign-in endpoints). */
interface GoTrueSessionPasswordData extends GoTrueSessionData {
weak_password?: WeakPassword;
}
/** Raw user data — either `{ user: User }` or the User object itself. */
interface GoTrueUserData {
user?: User;
[key: string]: any;
}
/** Raw generate-link data — link properties + User fields flattened into one object. */
type GoTrueGenerateLinkData = GenerateLinkProperties & Record<string, any>;
export interface FetchOptions {
headers?: {
[key: string]: string;
};
noResolveJson?: boolean;
}
export interface FetchParameters {
signal?: AbortSignal;
}
export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export declare function handleError(error: unknown): Promise<void>;
interface GotrueRequestOptions extends FetchOptions {
jwt?: string;
redirectTo?: string;
body?: object;
query?: {
[key: string]: string;
};
/**
* Function that transforms api response from gotrue into a desirable / standardised format
*/
xform?: (data: any) => any;
}
export declare function _request(fetcher: Fetch, method: RequestMethodType, url: string, options?: GotrueRequestOptions): Promise<any>;
export declare function _sessionResponse(data: GoTrueSessionData): AuthResponse;
export declare function _sessionResponsePassword(data: GoTrueSessionPasswordData): AuthResponsePassword;
export declare function _userResponse(data: GoTrueUserData): UserResponse;
export declare function _ssoResponse(data: Record<string, any>): SSOResponse;
export declare function _generateLinkResponse(data: GoTrueGenerateLinkData): GenerateLinkResponse;
export declare function _noResolveJsonResponse(data: Response): Response;
export {};
//# sourceMappingURL=fetch.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,YAAY,EACZ,oBAAoB,EAEpB,WAAW,EACX,sBAAsB,EACtB,oBAAoB,EACpB,IAAI,EACJ,YAAY,EACZ,YAAY,EACb,MAAM,SAAS,CAAA;AAShB,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,oDAAoD;AACpD,UAAU,iBAAiB;IACzB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,IAAI,CAAA;IACX,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,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AAI,EAAE,yBAAyB,GAAG,oBAAoB,CAiB9F;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,YAAY,CAGhE;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,WAAW,CAEnE;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,sBAAsB,GAAG,oBAAoB,CAmBxF;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,QAAQ,GAAG,QAAQ,CAE/D"}
+206
View File
@@ -0,0 +1,206 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleError = handleError;
exports._request = _request;
exports._sessionResponse = _sessionResponse;
exports._sessionResponsePassword = _sessionResponsePassword;
exports._userResponse = _userResponse;
exports._ssoResponse = _ssoResponse;
exports._generateLinkResponse = _generateLinkResponse;
exports._noResolveJsonResponse = _noResolveJsonResponse;
const tslib_1 = require("tslib");
const constants_1 = require("./constants");
const helpers_1 = require("./helpers");
const errors_1 = require("./errors");
const _getErrorMessage = (err) => {
if (typeof err === 'object' && err !== null) {
const e = err;
if (typeof e.msg === 'string')
return e.msg;
if (typeof e.message === 'string')
return e.message;
if (typeof e.error_description === 'string')
return e.error_description;
if (typeof e.error === 'string')
return e.error;
}
return JSON.stringify(err);
};
// 500, 501, 502, 503, 504: Standard server/gateway errors
// 520-529, 530: Cloudflare-specific error codes (web server down, connection timed out, etc.)
// These are infrastructure errors and should not cause session invalidation.
const NETWORK_ERROR_CODES = [
500, 501, 502, 503, 504, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530,
];
async function handleError(error) {
var _a;
if (!(0, helpers_1.looksLikeFetchResponse)(error)) {
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0);
}
if (NETWORK_ERROR_CODES.includes(error.status)) {
// status in 500...599 range - server had an error, request might be retryed.
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status);
}
let data;
try {
data = await error.json();
}
catch (e) {
throw new errors_1.AuthUnknownError(_getErrorMessage(e), e);
}
let errorCode = undefined;
const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error);
if (responseAPIVersion &&
responseAPIVersion.getTime() >= constants_1.API_VERSIONS['2024-01-01'].timestamp &&
typeof data === 'object' &&
data &&
typeof data.code === 'string') {
errorCode = data.code;
}
else if (typeof data === 'object' && data && typeof data.error_code === 'string') {
errorCode = data.error_code;
}
if (!errorCode) {
// Legacy support for weak password errors, when there were no error codes
if (typeof data === 'object' &&
data &&
typeof data.weak_password === 'object' &&
data.weak_password &&
Array.isArray(data.weak_password.reasons) &&
data.weak_password.reasons.length &&
data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {
throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons);
}
}
else if (errorCode === 'weak_password') {
throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []);
}
else if (errorCode === 'session_not_found') {
// The `session_id` inside the JWT does not correspond to a row in the
// `sessions` table. This usually means the user has signed out, has been
// deleted, or their session has somehow been terminated.
throw new errors_1.AuthSessionMissingError();
}
throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode);
}
const _getRequestParams = (method, options, parameters, body) => {
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
if (method === 'GET') {
return params;
}
params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers);
params.body = JSON.stringify(body);
return Object.assign(Object.assign({}, params), parameters);
};
async function _request(fetcher, method, url, options) {
var _a;
const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);
if (!headers[constants_1.API_VERSION_HEADER_NAME]) {
headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS['2024-01-01'].name;
}
if (options === null || options === void 0 ? void 0 : options.jwt) {
headers['Authorization'] = `Bearer ${options.jwt}`;
}
const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {};
if (options === null || options === void 0 ? void 0 : options.redirectTo) {
qs['redirect_to'] = options.redirectTo;
}
const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : '';
const data = await _handleRequest(fetcher, method, url + queryString, {
headers,
noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson,
}, {}, options === null || options === void 0 ? void 0 : options.body);
return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null };
}
async function _handleRequest(fetcher, method, url, options, parameters, body) {
const requestParams = _getRequestParams(method, options, parameters, body);
let result;
try {
result = await fetcher(url, Object.assign({}, requestParams));
}
catch (e) {
// fetch failed (network / CORS / aborted request) — surfaced to the
// caller as a retryable error below. Deliberately not logged here: an
// aborted in-flight request (e.g. a superseded page navigation) is a
// transient condition, and logging the raw error pollutes the console.
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0);
}
if (!result.ok) {
await handleError(result);
}
if (options === null || options === void 0 ? void 0 : options.noResolveJson) {
return result;
}
try {
return await result.json();
}
catch (e) {
await handleError(e);
}
}
function _sessionResponse(data) {
var _a;
let session = null;
if (hasSession(data)) {
session = Object.assign({}, data);
if (!data.expires_at) {
session.expires_at = (0, helpers_1.expiresAt)(data.expires_in);
}
}
// Some /verify responses (e.g. secure email_change first-confirmation) return
// only `{ msg, code }` with no user and no session. Treat those as null user.
const user = (_a = data.user) !== null && _a !== void 0 ? _a : (typeof (data === null || data === void 0 ? void 0 : data.id) === 'string' ? data : null);
return { data: { session, user }, error: null };
}
function _sessionResponsePassword(data) {
const response = _sessionResponse(data);
if (!response.error &&
data.weak_password &&
typeof data.weak_password === 'object' &&
Array.isArray(data.weak_password.reasons) &&
data.weak_password.reasons.length &&
data.weak_password.message &&
typeof data.weak_password.message === 'string' &&
data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {
response.data.weak_password = data.weak_password;
}
return response;
}
function _userResponse(data) {
var _a;
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
return { data: { user }, error: null };
}
function _ssoResponse(data) {
return { data, error: null };
}
function _generateLinkResponse(data) {
const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]);
const properties = {
action_link,
email_otp,
hashed_token,
redirect_to,
verification_type,
};
const user = Object.assign({}, rest);
return {
data: {
properties,
user,
},
error: null,
};
}
function _noResolveJsonResponse(data) {
return data;
}
/**
* hasSession checks if the response object contains a valid session
* @param data A response object
* @returns true if a session is in the response
*/
function hasSession(data) {
return !!data.access_token && !!data.refresh_token && !!data.expires_in;
}
//# sourceMappingURL=fetch.js.map
File diff suppressed because one or more lines are too long
+94
View File
@@ -0,0 +1,94 @@
import { JwtHeader, JwtPayload, SupportedStorage, User } from './types';
import { Uint8Array_ } from './webauthn.dom';
export declare function expiresAt(expiresIn: number): number;
/**
* Generates a unique identifier for internal callback subscriptions.
*
* This function uses JavaScript Symbols to create guaranteed-unique identifiers
* for auth state change callbacks. Symbols are ideal for this use case because:
* - They are guaranteed unique by the JavaScript runtime
* - They work in all environments (browser, SSR, Node.js)
* - They avoid issues with Next.js 16 deterministic rendering requirements
* - They are perfect for internal, non-serializable identifiers
*
* Note: This function is only used for internal subscription management,
* not for security-critical operations like session tokens.
*/
export declare function generateCallbackId(): symbol;
export declare const isBrowser: () => boolean;
/**
* Checks whether localStorage is supported on this browser.
*/
export declare const supportsLocalStorage: () => boolean;
/**
* Extracts parameters encoded in the URL both in the query and fragment.
*/
export declare function parseParametersFromURL(href: string): {
[parameter: string]: string;
};
type Fetch = typeof fetch;
export declare const resolveFetch: (customFetch?: Fetch) => Fetch;
export declare const looksLikeFetchResponse: (maybeResponse: unknown) => maybeResponse is Response;
export declare const setItemAsync: (storage: SupportedStorage, key: string, data: any) => Promise<void>;
export declare const getItemAsync: (storage: SupportedStorage, key: string) => Promise<unknown>;
export declare const removeItemAsync: (storage: SupportedStorage, key: string) => Promise<void>;
/**
* A deferred represents some asynchronous work that is not yet finished, which
* may or may not culminate in a value.
* Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
*/
export declare class Deferred<T = any> {
static promiseConstructor: PromiseConstructor;
readonly promise: PromiseLike<T>;
readonly resolve: (value?: T | PromiseLike<T>) => void;
readonly reject: (reason?: any) => any;
constructor();
}
export declare function decodeJWT(token: string): {
header: JwtHeader;
payload: JwtPayload;
signature: Uint8Array_;
raw: {
header: string;
payload: string;
};
};
/**
* Creates a promise that resolves to null after some time.
*/
export declare function sleep(time: number): Promise<null>;
/**
* Converts the provided async function into a retryable function. Each result
* or thrown error is sent to the isRetryable function which should return true
* if the function should run again.
*/
export declare function retryable<T>(fn: (attempt: number) => Promise<T>, isRetryable: (attempt: number, error: any | null, result?: T) => boolean): Promise<T>;
export declare function generatePKCEVerifier(): string;
export declare function generatePKCEChallenge(verifier: string): Promise<string>;
export declare function getCodeChallengeAndMethod(storage: SupportedStorage, storageKey: string, isPasswordRecovery?: boolean): Promise<string[]>;
export declare function parseResponseAPIVersion(response: Response): Date | null;
export declare function validateExp(exp: number): void;
export declare function getAlgorithm(alg: 'HS256' | 'RS256' | 'ES256' | (string & {})): RsaHashedImportParams | EcKeyImportParams;
export declare function validateUUID(str: string): void;
export declare function assertPasskeyExperimentalEnabled(experimental: {
passkey?: boolean;
}): void;
export declare function userNotAvailableProxy(): User;
/**
* Creates a proxy around a user object that warns when properties are accessed on the server.
* This is used to alert developers that using user data from getSession() on the server is insecure.
*
* @param user The actual user object to wrap
* @param suppressWarningRef An object with a 'value' property that controls warning suppression
* @returns A proxied user object that warns on property access
*/
export declare function insecureUserWarningProxy(user: User, suppressWarningRef: {
value: boolean;
}): User;
/**
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
* Note: Only works for JSON-safe data.
*/
export declare function deepClone<T>(obj: T): T;
export {};
//# sour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ED,wBAAgB,gCAAgC,CAAC,YAAY,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAM1F;AAED,wBAAgB,qBAAqB,IAAI,IAAI,CAoC5C;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,IAAI,EAAE,kBAAkB,EAAE;IAAE,KAAK,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAkCjG;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAEtC"}
+406
View File
@@ -0,0 +1,406 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0;
exports.expiresAt = expiresAt;
exports.generateCallbackId = generateCallbackId;
exports.parseParametersFromURL = parseParametersFromURL;
exports.decodeJWT = decodeJWT;
exports.sleep = sleep;
exports.retryable = retryable;
exports.generatePKCEVerifier = generatePKCEVerifier;
exports.generatePKCEChallenge = generatePKCEChallenge;
exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod;
exports.parseResponseAPIVersion = parseResponseAPIVersion;
exports.validateExp = validateExp;
exports.getAlgorithm = getAlgorithm;
exports.validateUUID = validateUUID;
exports.assertPasskeyExperimentalEnabled = assertPasskeyExperimentalEnabled;
exports.userNotAvailableProxy = userNotAvailableProxy;
exports.insecureUserWarningProxy = insecureUserWarningProxy;
exports.deepClone = deepClone;
const constants_1 = require("./constants");
const errors_1 = require("./errors");
const base64url_1 = require("./base64url");
function expiresAt(expiresIn) {
const timeNow = Math.round(Date.now() / 1000);
return timeNow + expiresIn;
}
/**
* Generates a unique identifier for internal callback subscriptions.
*
* This function uses JavaScript Symbols to create guaranteed-unique identifiers
* for auth state change callbacks. Symbols are ideal for this use case because:
* - They are guaranteed unique by the JavaScript runtime
* - They work in all environments (browser, SSR, Node.js)
* - They avoid issues with Next.js 16 deterministic rendering requirements
* - They are perfect for internal, non-serializable identifiers
*
* Note: This function is only used for internal subscription management,
* not for security-critical operations like session tokens.
*/
function generateCallbackId() {
return Symbol('auth-callback');
}
const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';
exports.isBrowser = isBrowser;
const localStorageWriteTests = {
tested: false,
writable: false,
};
/**
* Checks whether localStorage is supported on this browser.
*/
const supportsLocalStorage = () => {
if (!(0, exports.isBrowser)()) {
return false;
}
try {
if (typeof globalThis.localStorage !== 'object') {
return false;
}
}
catch (e) {
// DOM exception when accessing `localStorage`
return false;
}
if (localStorageWriteTests.tested) {
return localStorageWriteTests.writable;
}
const randomKey = `lswt-${Math.random()}${Math.random()}`;
try {
globalThis.localStorage.setItem(randomKey, randomKey);
globalThis.localStorage.removeItem(randomKey);
localStorageWriteTests.tested = true;
localStorageWriteTests.writable = true;
}
catch (e) {
// localStorage can't be written to
// https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document
localStorageWriteTests.tested = true;
localStorageWriteTests.writable = false;
}
return localStorageWriteTests.writable;
};
exports.supportsLocalStorage = supportsLocalStorage;
/**
* Extracts parameters encoded in the URL both in the query and fragment.
*/
function parseParametersFromURL(href) {
const result = {};
const url = new URL(href);
if (url.hash && url.hash[0] === '#') {
try {
const hashSearchParams = new URLSearchParams(url.hash.substring(1));
hashSearchParams.forEach((value, key) => {
result[key] = value;
});
}
catch (_e) {
// hash is not a query string
}
}
// search parameters take precedence over hash parameters
url.searchParams.forEach((value, key) => {
result[key] = value;
});
return result;
}
const resolveFetch = (customFetch) => {
if (customFetch) {
return (...args) => customFetch(...args);
}
return (...args) => fetch(...args);
};
exports.resolveFetch = resolveFetch;
const looksLikeFetchResponse = (maybeResponse) => {
return (typeof maybeResponse === 'object' &&
maybeResponse !== null &&
'status' in maybeResponse &&
'ok' in maybeResponse &&
'json' in maybeResponse &&
typeof maybeResponse.json === 'function');
};
exports.looksLikeFetchResponse = looksLikeFetchResponse;
// Storage helpers
const setItemAsync = async (storage, key, data) => {
await storage.setItem(key, JSON.stringify(data));
};
exports.setItemAsync = setItemAsync;
const getItemAsync = async (storage, key) => {
const value = await storage.getItem(key);
if (!value) {
return null;
}
try {
return JSON.parse(value);
}
catch (_a) {
// Storage values are always written as JSON via setItemAsync. A non-JSON
// value means the entry is corrupted (e.g. mismatched chunked cookies in
// SSR contexts). Treat as absent so callers do not mutate or re-save the
// garbage, which would otherwise trigger a TypeError downstream and
// leak the raw value into error logs.
return null;
}
};
exports.getItemAsync = getItemAsync;
const removeItemAsync = async (storage, key) => {
await storage.removeItem(key);
};
exports.removeItemAsync = removeItemAsync;
/**
* A deferred represents some asynchronous work that is not yet finished, which
* may or may not culminate in a value.
* Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
*/
class Deferred {
constructor() {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;
this.promise = new Deferred.promiseConstructor((res, rej) => {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;
this.resolve = res;
this.reject = rej;
});
}
}
exports.Deferred = Deferred;
Deferred.promiseConstructor = Promise;
function decodeJWT(token) {
const parts = token.split('.');
if (parts.length !== 3) {
throw new errors_1.AuthInvalidJwtError('Invalid JWT structure');
}
// Regex checks for base64url format
for (let i = 0; i < parts.length; i++) {
if (!constants_1.BASE64URL_REGEX.test(parts[i])) {
throw new errors_1.AuthInvalidJwtError('JWT not in base64url format');
}
}
const data = {
// using base64url lib
header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])),
payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])),
signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]),
raw: {
header: parts[0],
payload: parts[1],
},
};
return data;
}
/**
* Creates a promise that resolves to null after some time.
*/
async function sleep(time) {
return await new Promise((accept) => {
setTimeout(() => accept(null), time);
});
}
/**
* Converts the provided async function into a retryable function. Each result
* or thrown error is sent to the isRetryable function which should return true
* if the function should run again.
*/
function retryable(fn, isRetryable) {
const promise = new Promise((accept, reject) => {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;
(async () => {
for (let attempt = 0; attempt < Infinity; attempt++) {
try {
const result = await fn(attempt);
if (!isRetryable(attempt, null, result)) {
accept(result);
return;
}
}
catch (e) {
if (!isRetryable(attempt, e)) {
reject(e);
return;
}
}
}
})();
});
return promise;
}
function dec2hex(dec) {
return ('0' + dec.toString(16)).substr(-2);
}
// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs
function generatePKCEVerifier() {
const verifierLength = 56;
const array = new Uint32Array(verifierLength);
if (typeof crypto === 'undefined') {
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
const charSetLen = charSet.length;
let verifier = '';
for (let i = 0; i < verifierLength; i++) {
verifier += charSet.charAt(Math.floor(Math.random() * charSetLen));
}
return verifier;
}
crypto.getRandomValues(array);
return Array.from(array, dec2hex).join('');
}
async function sha256(randomString) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(randomString);
const hash = await crypto.subtle.digest('SHA-256', encodedData);
const bytes = new Uint8Array(hash);
return Array.from(bytes)
.map((c) => String.fromCharCode(c))
.join('');
}
async function generatePKCEChallenge(verifier) {
const hasCryptoSupport = typeof crypto !== 'undefined' &&
typeof crypto.subtle !== 'undefined' &&
typeof TextEncoder !== 'undefined';
if (!hasCryptoSupport) {
console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.');
return verifier;
}
const hashed = await sha256(verifier);
return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) {
const codeVerifier = generatePKCEVerifier();
let storedCodeVerifier = codeVerifier;
if (isPasswordRecovery) {
storedCodeVerifier += '/recovery';
}
await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier);
const codeChallenge = await generatePKCEChallenge(codeVerifier);
const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
return [codeChallenge, codeChallengeMethod];
}
/** Parses the API version which is 2YYY-MM-DD. */
const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;
function parseResponseAPIVersion(response) {
const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME);
if (!apiVersion) {
return null;
}
if (!apiVersion.match(API_VERSION_REGEX)) {
return null;
}
try {
const date = new Date(`${apiVersion}T00:00:00.0Z`);
return date;
}
catch (_e) {
return null;
}
}
function validateExp(exp) {
if (!exp) {
throw new Error('Missing exp claim');
}
const timeNow = Math.floor(Date.now() / 1000);
if (exp <= timeNow) {
throw new Error('JWT has expired');
}
}
function getAlgorithm(alg) {
switch (alg) {
case 'RS256':
return {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
};
case 'ES256':
return {
name: 'ECDSA',
namedCurve: 'P-256',
hash: { name: 'SHA-256' },
};
default:
throw new Error('Invalid alg claim');
}
}
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
function validateUUID(str) {
if (!UUID_REGEX.test(str)) {
throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not');
}
}
function assertPasskeyExperimentalEnabled(experimental) {
if (!experimental.passkey) {
throw new Error('@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).');
}
}
function userNotAvailableProxy() {
const proxyTarget = {};
return new Proxy(proxyTarget, {
get: (target, prop) => {
if (prop === '__isUserNotAvailableProxy') {
return true;
}
// Preventative check for common problematic symbols during cloning/inspection
// These symbols might be accessed by structuredClone or other internal mechanisms.
if (typeof prop === 'symbol') {
const sProp = prop.toString();
if (sProp === 'Symbol(Symbol.toPrimitive)' ||
sProp === 'Symbol(Symbol.toStringTag)' ||
sProp === 'Symbol(util.inspect.custom)') {
// Node.js util.inspect
return undefined;
}
}
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`);
},
set: (_target, prop) => {
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
},
deleteProperty: (_target, prop) => {
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
},
});
}
/**
* Creates a proxy around a user object that warns when properties are accessed on the server.
* This is used to alert developers that using user data from getSession() on the server is insecure.
*
* @param user The actual user object to wrap
* @param suppressWarningRef An object with a 'value' property that controls warning suppression
* @returns A proxied user object that warns on property access
*/
function insecureUserWarningProxy(user, suppressWarningRef) {
return new Proxy(user, {
get: (target, prop, receiver) => {
// Allow internal checks without warning
if (prop === '__isInsecureUserWarningProxy') {
return true;
}
// Preventative check for common problematic symbols during cloning/inspection
// These symbols might be accessed by structuredClone or other internal mechanisms
if (typeof prop === 'symbol') {
const sProp = prop.toString();
if (sProp === 'Symbol(Symbol.toPrimitive)' ||
sProp === 'Symbol(Symbol.toStringTag)' ||
sProp === 'Symbol(util.inspect.custom)' ||
sProp === 'Symbol(nodejs.util.inspect.custom)') {
// Return the actual value for these symbols to allow proper inspection
return Reflect.get(target, prop, receiver);
}
}
// Emit warning on first property access
if (!suppressWarningRef.value && typeof prop === 'string') {
console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.');
suppressWarningRef.value = true;
}
return Reflect.get(target, prop, receiver);
},
});
}
/**
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
* Note: Only works for JSON-safe data.
*/
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
//# sourceMappingURL=helpers.js.map
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
import { SupportedStorage } from './types';
/**
* Returns a localStorage-like object that stores the key-value pairs in
* memory.
*/
export declare function memoryLocalStorageAdapter(store?: {
[key: string]: string;
}): SupportedStorage;
//# sourceMappingURL=local-storage.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"local-storage.d.ts","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE1C;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,GAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CAAO,GAAG,gBAAgB,CAcjG"}
+21
View File
@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter;
/**
* Returns a localStorage-like object that stores the key-value pairs in
* memory.
*/
function memoryLocalStorageAdapter(store = {}) {
return {
getItem: (key) => {
return store[key] || null;
},
setItem: (key, value) => {
store[key] = value;
},
removeItem: (key) => {
delete store[key];
},
};
}
//# sourceMappingURL=local-storage.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":";;AAMA,8DAcC;AAlBD;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,QAAmC,EAAE;IAC7E,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACf,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,IAAI,CAAA;QAC3B,CAAC;QAED,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YACtB,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACpB,CAAC;QAED,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE;YAClB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAA;QACnB,CAAC;KACF,CAAA;AACH,CAAC"}
+101
View File
@@ -0,0 +1,101 @@
/**
* Lock primitives retained for backwards-compatible imports. The auth client
* coordinates refreshes itself (deduping in-instance callers onto a shared
* in-flight promise) and lets the GoTrue server resolve cross-instance races,
* so it does not invoke any primitive from this module. The functions still
* work for direct callers that need a navigator.locks-backed or in-process
* exclusive lock of their own.
*/
/**
* @deprecated Debug flag for `navigatorLock` / `processLock`. The auth
* client ignores both, so this has no client-side effect.
* @experimental
*/
export declare const internals: {
/**
* @experimental
*/
debug: boolean;
};
/**
* An error thrown when a lock cannot be acquired after some amount of time.
*
* @deprecated The auth client doesn't acquire locks around auth operations,
* so this error never originates from `supabase.auth.*` calls. Direct callers
* of `navigatorLock` / `processLock` still receive it on acquire timeout.
*/
export declare abstract class LockAcquireTimeoutError extends Error {
readonly isAcquireTimeout = true;
constructor(message: string);
}
/**
* @deprecated The auth client doesn't call `navigator.locks`, so this error
* never originates from `supabase.auth.*` calls. Direct callers of
* `navigatorLock` still receive it on acquire timeout.
*/
export declare class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
/**
* @deprecated The auth client doesn't run `processLock`, so this error
* never originates from `supabase.auth.*` calls. Direct callers of
* `processLock` still receive it on acquire timeout.
*/
export declare class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
/**
* Implements a global exclusive lock using the Navigator LockManager API. It
* is available on all browsers released after 2022-03-15 with Safari being the
* last one to release support. If the API is not available, this function will
* throw. Make sure you check availablility before configuring {@link
* GoTrueClient}.
*
* You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`
* local storage item to `true`.
*
* Internals:
*
* Since the LockManager API does not preserve stack traces for the async
* function passed in the `request` method, a trick is used where acquiring the
* lock releases a previously started promise to run the operation in the `fn`
* function. The lock waits for that promise to finish (with or without error),
* while the function will finally wait for the result anyway.
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
* will time out after so many milliseconds. An error is
* a timeout if it has `isAcquireTimeout` set to true.
* @param fn The operation to run once the lock is acquired.
*
* @deprecated The auth client coordinates refreshes itself and the server
* resolves concurrent refresh races, so passing `{ lock: navigatorLock }`
* to it has no effect. You can safely drop the import from your client setup.
*/
export declare function navigatorLock<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R>;
/**
* Implements a global exclusive lock that works only in the current process.
* Useful for environments like React Native or other non-browser
* single-process (i.e. no concept of "tabs") environments.
*
* Use {@link navigatorLock} in browser environments.
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
* will time out after so many milliseconds. An error is
* a timeout if it has `isAcquireTimeout` set to true.
* @param fn The operation to run once the lock is acquired.
*
* @deprecated The auth client coordinates refreshes itself and the server
* resolves concurrent refresh races, so passing `{ lock: processLock }`
* to it has no effect. You can safely drop the import from your client setup.
*
* @example
* ```ts
* await processLock('migrate', 5000, async () => {
* await runMigration()
* })
* ```
*/
export declare function processLock<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R>;
//# sourceMappingURL=locks.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH;;;;GAIG;AACH,eAAO,MAAM,SAAS;IACpB;;OAEG;;CAOJ,CAAA;AAED;;;;;;GAMG;AACH,8BAAsB,uBAAwB,SAAQ,KAAK;IACzD,SAAgB,gBAAgB,QAAO;gBAE3B,OAAO,EAAE,MAAM;CAG5B;AAED;;;;GAIG;AACH,qBAAa,gCAAiC,SAAQ,uBAAuB;CAAG;AAChF;;;;GAIG;AACH,qBAAa,8BAA+B,SAAQ,uBAAuB;CAAG;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CA8MZ;AAID;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,WAAW,CAAC,CAAC,EACjC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CAsFZ"}
+343
View File
@@ -0,0 +1,343 @@
"use strict";
/**
* Lock primitives retained for backwards-compatible imports. The auth client
* coordinates refreshes itself (deduping in-instance callers onto a shared
* in-flight promise) and lets the GoTrue server resolve cross-instance races,
* so it does not invoke any primitive from this module. The functions still
* work for direct callers that need a navigator.locks-backed or in-process
* exclusive lock of their own.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0;
exports.navigatorLock = navigatorLock;
exports.processLock = processLock;
const helpers_1 = require("./helpers");
/**
* @deprecated Debug flag for `navigatorLock` / `processLock`. The auth
* client ignores both, so this has no client-side effect.
* @experimental
*/
exports.internals = {
/**
* @experimental
*/
debug: !!(globalThis &&
(0, helpers_1.supportsLocalStorage)() &&
globalThis.localStorage &&
globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'),
};
/**
* An error thrown when a lock cannot be acquired after some amount of time.
*
* @deprecated The auth client doesn't acquire locks around auth operations,
* so this error never originates from `supabase.auth.*` calls. Direct callers
* of `navigatorLock` / `processLock` still receive it on acquire timeout.
*/
class LockAcquireTimeoutError extends Error {
constructor(message) {
super(message);
this.isAcquireTimeout = true;
}
}
exports.LockAcquireTimeoutError = LockAcquireTimeoutError;
/**
* @deprecated The auth client doesn't call `navigator.locks`, so this error
* never originates from `supabase.auth.*` calls. Direct callers of
* `navigatorLock` still receive it on acquire timeout.
*/
class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError;
/**
* @deprecated The auth client doesn't run `processLock`, so this error
* never originates from `supabase.auth.*` calls. Direct callers of
* `processLock` still receive it on acquire timeout.
*/
class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError;
/**
* Implements a global exclusive lock using the Navigator LockManager API. It
* is available on all browsers released after 2022-03-15 with Safari being the
* last one to release support. If the API is not available, this function will
* throw. Make sure you check availablility before configuring {@link
* GoTrueClient}.
*
* You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`
* local storage item to `true`.
*
* Internals:
*
* Since the LockManager API does not preserve stack traces for the async
* function passed in the `request` method, a trick is used where acquiring the
* lock releases a previously started promise to run the operation in the `fn`
* function. The lock waits for that promise to finish (with or without error),
* while the function will finally wait for the result anyway.
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
* will time out after so many milliseconds. An error is
* a timeout if it has `isAcquireTimeout` set to true.
* @param fn The operation to run once the lock is acquired.
*
* @deprecated The auth client coordinates refreshes itself and the server
* resolves concurrent refresh races, so passing `{ lock: navigatorLock }`
* to it has no effect. You can safely drop the import from your client setup.
*/
async function navigatorLock(name, acquireTimeout, fn) {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout);
}
const abortController = new globalThis.AbortController();
let acquireTimeoutTimer;
if (acquireTimeout > 0) {
acquireTimeoutTimer = setTimeout(() => {
abortController.abort();
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name);
}
}, acquireTimeout);
}
// MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request
// Wrapping navigator.locks.request() with a plain Promise is done as some
// libraries like zone.js patch the Promise object to track the execution
// context. However, it appears that most browsers use an internal promise
// implementation when using the navigator.locks.request() API causing them
// to lose context and emit confusing log messages or break certain features.
// This wrapping is believed to help zone.js track the execution context
// better.
await Promise.resolve();
try {
return await globalThis.navigator.locks.request(name, acquireTimeout === 0
? {
mode: 'exclusive',
ifAvailable: true,
}
: {
mode: 'exclusive',
signal: abortController.signal,
}, async (lock) => {
if (lock) {
// Lock acquired — cancel the acquire-timeout timer so it cannot fire
// while fn() is running. Without this, a delayed timeout abort would
// set signal.aborted = true even though we already hold the lock,
// causing a subsequent steal to be misclassified as "our timeout
// fired" and triggering a spurious steal-back cascade.
clearTimeout(acquireTimeoutTimer);
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name);
}
try {
return await fn();
}
finally {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name);
}
}
}
else {
if (acquireTimeout === 0) {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name);
}
throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`);
}
else {
if (exports.internals.debug) {
try {
const result = await globalThis.navigator.locks.query();
console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' '));
}
catch (e) {
console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e);
}
}
// Browser is not following the Navigator LockManager spec, it
// returned a null lock when we didn't use ifAvailable. So we can
// pretend the lock is acquired in the name of backward compatibility
// and user experience and just run the function.
console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request');
clearTimeout(acquireTimeoutTimer);
return await fn();
}
}
});
}
catch (e) {
// Always clear the acquire timeout once the request settles, so it cannot
// fire later and incorrectly abort/log after a rejection.
if (acquireTimeout > 0) {
clearTimeout(acquireTimeoutTimer);
}
// DOMException does not extend Error in Node.js, so use structural check
if (e !== null &&
typeof e === 'object' &&
'name' in e &&
e.name === 'AbortError' &&
acquireTimeout > 0) {
if (abortController.signal.aborted) {
// OUR timeout fired — the lock is genuinely orphaned. Steal it.
//
// The lock acquisition was aborted because the timeout fired while the
// request was still pending. This typically means another lock holder is
// not releasing the lock, possibly due to React Strict Mode's
// double-mount/unmount behavior or a component unmounting mid-operation,
// leaving an orphaned lock.
//
// Recovery: use { steal: true } to forcefully acquire the lock. Per the
// Web Locks API spec, this releases any currently held lock with the same
// name and grants the request immediately, preempting any queued requests.
// The previous holder's callback continues running to completion but no
// longer holds the lock for exclusion purposes.
//
// See: https://github.com/supabase/supabase/issues/42505
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock', name);
}
console.warn(`@supabase/gotrue-js: Lock "${name}" was not released within ${acquireTimeout}ms. ` +
'This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). ' +
'Forcefully acquiring the lock to recover.');
return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, {
mode: 'exclusive',
steal: true,
}, async (lock) => {
if (lock) {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: recovered (stolen)', name, lock.name);
}
try {
return await fn();
}
finally {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: released (stolen)', name, lock.name);
}
}
}
else {
// This should not happen with steal: true, but handle gracefully.
console.warn('@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true');
return await fn();
}
}));
}
else {
// We HELD the lock but another request stole it from us.
// Per the Web Locks spec, our fn() callback is still running as an
// orphaned background task — do NOT steal back. Stealing back would
// cause a cascade (A steals B, B steals A, ...) and run fn() a second
// time concurrently, corrupting auth state.
// Convert to a typed error so callers (e.g. _autoRefreshTokenTick)
// can handle/filter it without it leaking to Sentry as a raw AbortError.
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: lock was stolen by another request', name);
}
throw new NavigatorLockAcquireTimeoutError(`Lock "${name}" was released because another request stole it`);
}
}
throw e;
}
}
const PROCESS_LOCKS = {};
/**
* Implements a global exclusive lock that works only in the current process.
* Useful for environments like React Native or other non-browser
* single-process (i.e. no concept of "tabs") environments.
*
* Use {@link navigatorLock} in browser environments.
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
* will time out after so many milliseconds. An error is
* a timeout if it has `isAcquireTimeout` set to true.
* @param fn The operation to run once the lock is acquired.
*
* @deprecated The auth client coordinates refreshes itself and the server
* resolves concurrent refresh races, so passing `{ lock: processLock }`
* to it has no effect. You can safely drop the import from your client setup.
*
* @example
* ```ts
* await processLock('migrate', 5000, async () => {
* await runMigration()
* })
* ```
*/
async function processLock(name, acquireTimeout, fn) {
var _a;
const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve();
// Wrap previousOperation to handle errors without using .catch()
// This avoids Firefox content script security errors
const previousOperationHandled = (async () => {
try {
await previousOperation;
return null;
}
catch (e) {
// ignore error of previous operation that we're waiting to finish
return null;
}
})();
const currentOperation = (async () => {
let timeoutId = null;
try {
// Wait for either previous operation or timeout
const timeoutPromise = acquireTimeout >= 0
? new Promise((_, reject) => {
timeoutId = setTimeout(() => {
console.warn(`@supabase/gotrue-js: Lock "${name}" acquisition timed out after ${acquireTimeout}ms. ` +
'This may be caused by another operation holding the lock. ' +
'Consider increasing lockAcquireTimeout or checking for stuck operations.');
reject(new ProcessLockAcquireTimeoutError(`Acquiring process lock with name "${name}" timed out`));
}, acquireTimeout);
})
: null;
await Promise.race([previousOperationHandled, timeoutPromise].filter((x) => x));
// If we reach here, previousOperationHandled won the race
// Clear the timeout to prevent false warnings
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
}
catch (e) {
// Clear the timeout on error path as well
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
// Re-throw timeout errors, ignore others
if (e instanceof LockAcquireTimeoutError) {
throw e;
}
// Fall through to run fn() - previous operation finished with error
}
// Previous operations finished and we didn't get a race on the acquire
// timeout, so the current operation can finally start
return await fn();
})();
PROCESS_LOCKS[name] = (async () => {
try {
return await currentOperation;
}
catch (e) {
if (e instanceof LockAcquireTimeoutError) {
// if the current operation timed out, it doesn't mean that the previous
// operation finished, so we need continue waiting for it to finish
try {
await previousOperation;
}
catch (prevError) {
// Ignore previous operation errors
}
return null;
}
throw e;
}
})();
// finally wait for the current operation to finish successfully, with an
// error or with an acquire timeout error
return await currentOperation;
}
//# sourceMappingURL=locks.js.map
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
/**
* https://mathiasbynens.be/notes/globalthis
*/
export declare function polyfillGlobalThis(): void;
//# sourceMappingURL=polyfills.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,kBAAkB,SAmBjC"}
+29
View File
@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.polyfillGlobalThis = polyfillGlobalThis;
/**
* https://mathiasbynens.be/notes/globalthis
*/
function polyfillGlobalThis() {
if (typeof globalThis === 'object')
return;
try {
Object.defineProperty(Object.prototype, '__magic__', {
get: function () {
return this;
},
configurable: true,
});
// @ts-expect-error 'Allow access to magic'
__magic__.globalThis = __magic__;
// @ts-expect-error 'Allow access to magic'
delete Object.prototype.__magic__;
}
catch (e) {
if (typeof self !== 'undefined') {
// @ts-expect-error 'Allow access to globals'
self.globalThis = self;
}
}
}
//# sourceMappingURL=polyfills.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":";;AAGA,gDAmBC;AAtBD;;GAEG;AACH,SAAgB,kBAAkB;IAChC,IAAI,OAAO,UAAU,KAAK,QAAQ;QAAE,OAAM;IAC1C,IAAI,CAAC;QACH,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE;YACnD,GAAG,EAAE;gBACH,OAAO,IAAI,CAAA;YACb,CAAC;YACD,YAAY,EAAE,IAAI;SACnB,CAAC,CAAA;QACF,2CAA2C;QAC3C,SAAS,CAAC,UAAU,GAAG,SAAS,CAAA;QAChC,2CAA2C;QAC3C,OAAO,MAAM,CAAC,SAAS,CAAC,SAAS,CAAA;IACnC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE,CAAC;YAChC,6CAA6C;YAC7C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;QACxB,CAAC;IACH,CAAC;AACH,CAAC"}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+23
View File
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SIGN_OUT_SCOPES = void 0;
const WeakPasswordReasons = ['length', 'characters', 'pwned'];
const AMRMethods = [
'password',
'otp',
'oauth',
'totp',
'mfa/totp',
'mfa/phone',
'mfa/webauthn',
'anonymous',
'sso/saml',
'magiclink',
'web3',
'oauth_provider/authorization_code',
];
const FactorTypes = ['totp', 'phone', 'webauthn'];
const FactorVerificationStatuses = ['verified', 'unverified'];
const MFATOTPChannels = ['sms', 'whatsapp'];
exports.SIGN_OUT_SCOPES = ['global', 'local', 'others'];
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":";;;AAkMA,MAAM,mBAAmB,GAAG,CAAC,QAAQ,EAAE,YAAY,EAAE,OAAO,CAAU,CAAA;AA+ItE,MAAM,UAAU,GAAG;IACjB,UAAU;IACV,KAAK;IACL,OAAO;IACP,MAAM;IACN,UAAU;IACV,WAAW;IACX,cAAc;IACd,WAAW;IACX,UAAU;IACV,WAAW;IACX,MAAM;IACN,mCAAmC;CAC3B,CAAA;AAwCV,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,UAAU,CAAU,CAAA;AAO1D,MAAM,0BAA0B,GAAG,CAAC,UAAU,EAAE,YAAY,CAAU,CAAA;AA2pBtE,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,UAAU,CAAU,CAAA;AAq6BvC,QAAA,eAAe,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAA"}
+2
View File
@@ -0,0 +1,2 @@
export declare const version = "2.110.8";
//# sourceMappingURL=version.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,YAAY,CAAA"}
+11
View File
@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = void 0;
// Generated automatically during releases by scripts/update-version-files.ts
// This file provides runtime access to the package version for:
// - HTTP request headers (e.g., X-Client-Info header for API requests)
// - Debugging and support (identifying which version is running)
// - Telemetry and logging (version reporting in errors/analytics)
// - Ensuring build artifacts match the published package version
exports.version = '2.110.8';
//# sourceMappingURL=version.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACpD,QAAA,OAAO,GAAG,SAAS,CAAA"}
+96
View File
@@ -0,0 +1,96 @@
export type Hex = `0x${string}`;
export type Address = Hex;
export type EIP1193EventMap = {
accountsChanged(accounts: Address[]): void;
chainChanged(chainId: string): void;
connect(connectInfo: {
chainId: string;
}): void;
disconnect(error: {
code: number;
message: string;
}): void;
message(message: {
type: string;
data: unknown;
}): void;
};
export type EIP1193Events = {
on<event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]): void;
removeListener<event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]): void;
};
export type EIP1193RequestFn = (args: {
method: string;
params?: unknown;
}) => Promise<unknown>;
export type EIP1193Provider = EIP1193Events & {
address: string;
request: EIP1193RequestFn;
};
export type EthereumWallet = EIP1193Provider;
/**
* EIP-4361 message fields
*/
export type SiweMessage = {
/**
* The Ethereum address performing the signing.
*/
address: Address;
/**
* The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) Chain ID to which the session is bound,
*/
chainId: number;
/**
* [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
*/
domain: string;
/**
* Time when the signed authentication message is no longer valid.
*/
expirationTime?: Date | undefined;
/**
* Time when the message was generated, typically the current time.
*/
issuedAt?: Date | undefined;
/**
* A random string typically chosen by the relying party and used to prevent replay attacks.
*/
nonce?: string;
/**
* Time when the signed authentication message will become valid.
*/
notBefore?: Date | undefined;
/**
* A system-specific identifier that may be used to uniquely refer to the sign-in request.
*/
requestId?: string | undefined;
/**
* A list of information or references to information the user wishes to have resolved as part of authentication by the relying party.
*/
resources?: string[] | undefined;
/**
* [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
*/
scheme?: string | undefined;
/**
* A human-readable ASCII assertion that the user will sign.
*/
statement?: string | undefined;
/**
* [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI referring to the resource that is the subject of the signing (as in the subject of a claim).
*/
uri: string;
/**
* The current version of the SIWE Message.
*/
version: '1';
};
export type EthereumSignInInput = SiweMessage;
export declare function getAddress(address: string): Address;
export declare function fromHex(hex: Hex): number;
export declare function toHex(value: string): Hex;
/**
* Creates EIP-4361 formatted message.
*/
export declare function createSiweMessage(parameters: SiweMessage): string;
//# sourceMapping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AO,EAAE,gBAAgB,CAAA;CAC1B,CAAA;AAED,MAAM,MAAM,cAAc,GAAG,eAAe,CAAA;AAE5C;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAA;IAChB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAA;IACf;;OAEG;IACH,MAAM,EAAE,MAAM,CAAA;IACd;;OAEG;IACH,cAAc,CAAC,EAAE,IAAI,GAAG,SAAS,CAAA;IACjC;;OAEG;IACH,QAAQ,CAAC,EAAE,IAAI,GAAG,SAAS,CAAA;IAC3B;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd;;OAEG;IACH,SAAS,CAAC,EAAE,IAAI,GAAG,SAAS,CAAA;IAC5B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAA;IAChC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,OAAO,EAAE,GAAG,CAAA;CACb,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAA;AAE7C,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAKnD;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAExC;AAED,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAIxC;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,CAwEjE"}
+66
View File
@@ -0,0 +1,66 @@
"use strict";
// types and functions copied over from viem so this library doesn't depend on it
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAddress = getAddress;
exports.fromHex = fromHex;
exports.toHex = toHex;
exports.createSiweMessage = createSiweMessage;
function getAddress(address) {
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`);
}
return address.toLowerCase();
}
function fromHex(hex) {
return parseInt(hex, 16);
}
function toHex(value) {
const bytes = new TextEncoder().encode(value);
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
return ('0x' + hex);
}
/**
* Creates EIP-4361 formatted message.
*/
function createSiweMessage(parameters) {
var _a;
const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters;
// Validate fields
{
if (!Number.isInteger(chainId))
throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`);
if (!domain)
throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`);
if (nonce && nonce.length < 8)
throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`);
if (!uri)
throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);
if (version !== '1')
throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`);
if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n'))
throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`);
}
// Construct message
const address = getAddress(parameters.address);
const origin = scheme ? `${scheme}://${domain}` : domain;
const statement = parameters.statement ? `${parameters.statement}\n` : '';
const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`;
let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`;
if (expirationTime)
suffix += `\nExpiration Time: ${expirationTime.toISOString()}`;
if (notBefore)
suffix += `\nNot Before: ${notBefore.toISOString()}`;
if (requestId)
suffix += `\nRequest ID: ${requestId}`;
if (resources) {
let content = '\nResources:';
for (const resource of resources) {
if (!resource || typeof resource !== 'string')
throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`);
content += `\n- ${resource}`;
}
suffix += content;
}
return `${prefix}\n${suffix}`;
}
//# sourceMappingURL=ethereum.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ethereum.js","sourceRoot":"","sources":["../../../../src/lib/web3/ethereum.ts"],"names":[],"mappings":";AAAA,iFAAiF;;AA2FjF,gCAKC;AAED,0BAEC;AAED,sBAIC;AAKD,8CAwEC;AA5FD,SAAgB,UAAU,CAAC,OAAe;IACxC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CAAC,+BAA+B,OAAO,eAAe,CAAC,CAAA;IACxE,CAAC;IACD,OAAO,OAAO,CAAC,WAAW,EAAa,CAAA;AACzC,CAAC;AAED,SAAgB,OAAO,CAAC,GAAQ;IAC9B,OAAO,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;AAC1B,CAAC;AAED,SAAgB,KAAK,CAAC,KAAa;IACjC,MAAM,KAAK,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAC7C,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IACpF,OAAO,CAAC,IAAI,GAAG,GAAG,CAAQ,CAAA;AAC5B,CAAC;AAED;;GAEG;AACH,SAAgB,iBAAiB,CAAC,UAAuB;;IACvD,MAAM,EACJ,OAAO,EACP,MAAM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O,eAAe,OAAO,GACjE,KAAK,CAAC,CAAC,CAAC,YAAY,KAAK,EAAE,CAAC,CAAC,CAAC,EAChC,gBAAgB,QAAQ,CAAC,WAAW,EAAE,EAAE,CAAA;IAExC,IAAI,cAAc;QAAE,MAAM,IAAI,sBAAsB,cAAc,CAAC,WAAW,EAAE,EAAE,CAAA;IAClF,IAAI,SAAS;QAAE,MAAM,IAAI,iBAAiB,SAAS,CAAC,WAAW,EAAE,EAAE,CAAA;IACnE,IAAI,SAAS;QAAE,MAAM,IAAI,iBAAiB,SAAS,EAAE,CAAA;IACrD,IAAI,SAAS,EAAE,CAAC;QACd,IAAI,OAAO,GAAG,cAAc,CAAA;QAC5B,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ;gBAC3C,MAAM,IAAI,KAAK,CACb,qHAAqH,QAAQ,EAAE,CAChI,CAAA;YACH,OAAO,IAAI,OAAO,QAAQ,EAAE,CAAA;QAC9B,CAAC;QACD,MAAM,IAAI,OAAO,CAAA;IACnB,CAAC;IAED,OAAO,GAAG,MAAM,KAAK,MAAM,EAAE,CAAA;AAC/B,CAAC"}
+160
View File
@@ -0,0 +1,160 @@
/**
* A namespaced identifier in the format `${namespace}:${reference}`.
*
* Used by {@link IdentifierArray} and {@link IdentifierRecord}.
*
* @group Identifier
*/
export type IdentifierString = `${string}:${string}`;
/**
* A read-only array of namespaced identifiers in the format `${namespace}:${reference}`.
*
* Used by {@link Wallet.chains | Wallet::chains}, {@link WalletAccount.chains | WalletAccount::chains}, and
* {@link WalletAccount.features | WalletAccount::features}.
*
* @group Identifier
*/
export type IdentifierArray = readonly IdentifierString[];
/**
* Version of the Wallet Standard implemented by a {@link Wallet}.
*
* Used by {@link Wallet.version | Wallet::version}.
*
* Note that this is _NOT_ a version of the Wallet, but a version of the Wallet Standard itself that the Wallet
* supports.
*
* This may be used by the app to determine compatibility and feature detect.
*
* @group Wallet
*/
export type WalletVersion = '1.0.0';
/**
* A data URI containing a base64-encoded SVG, WebP, PNG, or GIF image.
*
* Used by {@link Wallet.icon | Wallet::icon} and {@link WalletAccount.icon | WalletAccount::icon}.
*
* @group Wallet
*/
export type WalletIcon = `data:image/${'svg+xml' | 'webp' | 'png' | 'gif'};base64,${string}`;
/**
* Interface of a **WalletAccount**, also referred to as an **Account**.
*
* An account is a _read-only data object_ that is provided from the Wallet to the app, authorizing the app to use it.
*
* The app can use an account to display and query information from a chain.
*
* The app can also act using an account by passing it to {@link Wallet.features | features} of the Wallet.
*
* Wallets may use or extend {@link "@wallet-standard/wallet".ReadonlyWalletAccount} which implements this interface.
*
* @group Wallet
*/
export interface WalletAccount {
/** Address of the account, corresponding with a public key. */
readonly address: string;
/** Public key of the account, corresponding with a secret key to use. */
readonly publicKey: Uint8Array;
/**
* Chains supported by the account.
*
* This must be a subset of the {@link Wallet.chains | chains} of the Wallet.
*/
readonly chains: IdentifierArray;
/**
* Feature names supported by the account.
*
* This must be a subset of the names of {@link Wallet.features | features} of the Wallet.
*/
readonly features: IdentifierArray;
/** Optional user-friendly descriptive label or name for the account. This may be displayed by the app. */
readonly label?: string;
/** Optional user-friendly icon for the account. This may be displayed by the app. */
readonly icon?: WalletIcon;
}
/** Input for signing in. */
export interface SolanaSignInInput {
/**
* Optional EIP-4361 Domain.
* If not provided, the wallet must determine the Domain to include in the message.
*/
readonly domain?: string;
/**
* Optional EIP-4361 Address.
* If not provided, the wallet must determine the Address to include in the message.
*/
readonly address?: string;
/**
* Optional EIP-4361 Statement.
* If not provided, the wallet must not include Statement in the message.
*/
readonly statement?: string;
/**
* Optional EIP-4361 URI.
* If not provided, the wallet must not include URI in the message.
*/
readonly uri?: string;
/**
* Optional EIP-4361 Version.
* If not provided, the wallet must not include Version in the message.
*/
readonly version?: string;
/**
* Optional EIP-4361 Chain ID.
* If not provided, the wallet must not include Chain ID in the message.
*/
readonly chainId?: string;
/**
* Optional EIP-4361 Nonce.
* If not provided, the wallet must not include Nonce in the message.
*/
readonly nonce?: string;
/**
* Optional EIP-4361 Issued At.
* If not provided, the wallet must not include Issued At in the message.
*/
readonly issuedAt?: string;
/**
* Optional EIP-4361 Expiration Time.
* If not provided, the wallet must not include Expiration Time in the message.
*/
readonly expirationTime?: string;
/**
* Optional EIP-4361 Not Before.
* If not provided, the wallet must not include Not Before in the message.
*/
readonly notBefore?: string;
/**
* Optional EIP-4361 Request ID.
* If not provided, the wallet must not include Request ID in the message.
*/
readonly requestId?: string;
/**
* Optional EIP-4361 Resources.
* If not provided, the wallet must not include Resources in the message.
*/
readonly resources?: readonly string[];
}
/** Output of signing in. */
export interface SolanaSignInOutput {
/**
* Account that was signed in.
* The address of the account may be different from the provided input Address.
*/
readonly account: WalletAccount;
/**
* Message bytes that were signed.
* The wallet may prefix or otherwise modify the message before signing it.
*/
readonly signedMessage: Uint8Array;
/**
* Message signature produced.
* If the signature type is provided, the signature must be Ed25519.
*/
readonly signature: Uint8Array;
/**
* Optional type of the message signature produced.
* If not provided, the signature must be Ed25519.
*/
readonly signatureType?: 'ed25519';
}
//# sourceMappingURL=solana.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"solana.d.ts","sourceRoot":"","sources":["../../../../src/lib/web3/solana.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,CAAA;AAEpD;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GAAG,SAAS,gBAAgB,EAAE,CAAA;AAEzD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,CAAA;AAEnC;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAAG,cAAc,SAAS,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,WAAW,MAAM,EAAE,CAAA;AAE5F;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,aAAa;IAC5B,+DAA+D;IAC/D,QAAQ,CAAC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C,OAAO,EAAE,aAAa,CAAA;IAE/B;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,UAAU,CAAA;IAElC;;;OAGG;IACH,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAA;IAE9B;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,CAAA;CACnC"}
+4
View File
@@ -0,0 +1,4 @@
"use strict";
// types copied over from @solana/wallet-standard-features and @wallet-standard/base so this library doesn't depend on them
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=solana.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"solana.js","sourceRoot":"","sources":["../../../../src/lib/web3/solana.ts"],"names":[],"mappings":";AAAA,2HAA2H"}
+284
View File
@@ -0,0 +1,284 @@
import GoTrueClient from '../GoTrueClient';
import { AuthError } from './errors';
import { AuthMFAEnrollWebauthnResponse, AuthMFAVerifyResponse, AuthMFAVerifyResponseData, MFAChallengeWebauthnParams, MFAEnrollWebauthnParams, MFAVerifyWebauthnParamFields, MFAVerifyWebauthnParams, RequestResult, StrictOmit } from './types';
import type { AuthenticationCredential, AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsFuture, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsFuture, PublicKeyCredentialRequestOptionsJSON, RegistrationCredential, RegistrationResponseJSON } from './webauthn.dom';
import { identifyAuthenticationError, identifyRegistrationError, isWebAuthnError, WebAuthnError } from './webauthn.errors';
export { WebAuthnError, isWebAuthnError, identifyRegistrationError, identifyAuthenticationError };
export type { RegistrationResponseJSON, AuthenticationResponseJSON };
/**
* WebAuthn abort service to manage ceremony cancellation.
* Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors.
*
* @experimental This class is experimental and may change in future releases
* @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies}
*/
export declare class WebAuthnAbortService {
private controller;
/**
* Create an abort signal for a new WebAuthn operation.
* Automatically cancels any existing operation.
*
* @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get()
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal}
*/
createNewAbortSignal(): AbortSignal;
/**
* Manually cancel the current WebAuthn operation.
* Useful for cleaning up when user cancels or navigates away.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort}
*/
cancelCeremony(): void;
}
/**
* Singleton instance to ensure only one WebAuthn ceremony is active at a time.
* This prevents "operation already in progress" errors when retrying WebAuthn operations.
*
* @experimental This instance is experimental and may change in future releases
*/
export declare const webAuthnAbortService: WebAuthnAbortService;
/**
* Server response format for WebAuthn credential creation options.
* Uses W3C standard JSON format with base64url-encoded binary fields.
*/
export type ServerCredentialCreationOptions = PublicKeyCredentialCreationOptionsJSON;
/**
* Server response format for WebAuthn credential request options.
* Uses W3C standard JSON format with base64url-encoded binary fields.
*/
export type ServerCredentialRequestOptions = PublicKeyCredentialRequestOptionsJSON;
/**
* Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers
* as required by the WebAuthn browser API.
* Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback.
*
* @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields
* @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create()
* @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON}
*/
export declare function deserializeCredentialCreationOptions(options: ServerCredentialCreationOptions): PublicKeyCredentialCreationOptionsFuture;
/**
* Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers
* as required by the WebAuthn browser API.
* Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback.
*
* @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields
* @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get()
* @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON}
*/
export declare function deserializeCredentialRequestOptions(options: ServerCredentialRequestOptions): PublicKeyCredentialRequestOptionsFuture;
/**
* Server format for credential response with base64url-encoded binary fields
* Can be either a registration or authentication response
*/
export type ServerCredentialResponse = RegistrationResponseJSON | AuthenticationResponseJSON;
/**
* Convert a registration/enrollment credential response to server format.
* Serializes binary fields to base64url for JSON transmission.
* Supports both native WebAuthn Level 3 toJSON and manual fallback.
*
* @param {RegistrationCredential} credential - Credential from navigator.credentials.create()
* @returns {RegistrationResponseJSON} JSON-serializable credential for server
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
*/
export declare function serializeCredentialCreationResponse(credential: RegistrationCredential): RegistrationResponseJSON;
/**
* Convert an authentication/verification credential response to server format.
* Serializes binary fields to base64url for JSON transmission.
* Supports both native WebAuthn Level 3 toJSON and manual fallback.
*
* @param {AuthenticationCredential} credential - Credential from navigator.credentials.get()
* @returns {AuthenticationResponseJSON} JSON-serializable credential for server
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
*/
export declare function serializeCredentialRequestResponse(credential: AuthenticationCredential): AuthenticationResponseJSON;
/**
* A simple test to determine if a hostname is a properly-formatted domain name.
* Considers localhost valid for development environments.
*
* A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain
*
* Regex sourced from here:
* https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html
*
* @param {string} hostname - The hostname to validate
* @returns {boolean} True if valid domain or localhost
* @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain}
*/
export declare function isValidDomain(hostname: string): boolean;
/**
* Determine if the browser is capable of WebAuthn.
* Checks for necessary Web APIs: PublicKeyCredential and Credential Management.
*
* @returns {boolean} True if browser supports WebAuthn
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility}
*/
export declare function browserSupportsWebAuthn(): boolean;
/**
* Create a WebAuthn credential using the browser's credentials API.
* Wraps navigator.credentials.create() with error handling.
*
* @param {CredentialCreationOptions} options - Options including publicKey parameters
* @returns {Promise<RequestResult<RegistrationCredential, WebAuthnError>>} Created credential or error
* @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create}
*/
export declare function createCredential(options: StrictOmit<CredentialCreationOptions, 'publicKey'> & {
publicKey: PublicKeyCredentialCreationOptionsFuture;
}): Promise<RequestResult<RegistrationCredential, WebAuthnError>>;
/**
* Get a WebAuthn credential using the browser's credentials API.
* Wraps navigator.credentials.get() with error handling.
*
* @param {CredentialRequestOptions} options - Options including publicKey parameters
* @returns {Promise<RequestResult<AuthenticationCredential, WebAuthnError>>} Retrieved credential or error
* @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get}
*/
export declare function getCredential(options: StrictOmit<CredentialRequestOptions, 'publicKey'> & {
publicKey: PublicKeyCredentialRequestOptionsFuture;
}): Promise<RequestResult<AuthenticationCredential, WebAuthnError>>;
export declare const DEFAULT_CREATION_OPTIONS: Partial<PublicKeyCredentialCreationOptionsFuture>;
export declare const DEFAULT_REQUEST_OPTIONS: Partial<PublicKeyCredentialRequestOptionsFuture>;
/**
* Merges WebAuthn credential creation options with overrides.
* Sets sensible defaults for authenticator selection and extensions.
*
* @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server
* @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply
* @param {string} friendlyName - Optional friendly name for the credential
* @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options
* @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria}
*/
export declare function mergeCredentialCreationOptions(baseOptions: PublicKeyCredentialCreationOptionsFuture, overrides?: Partial<PublicKeyCredentialCreationOptionsFuture>): PublicKeyCredentialCreationOptionsFuture;
/**
* Merges WebAuthn credential request options with overrides.
* Sets sensible defaults for user verification and hints.
*
* @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server
* @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply
* @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions}
*/
export declare function mergeCredentialRequestOptions(baseOptions: PublicKeyCredentialRequestOptionsFuture, overrides?: Partial<PublicKeyCredentialRequestOptionsFuture>): PublicKeyCredentialRequestOptionsFuture;
/**
* WebAuthn API wrapper for Supabase Auth.
* Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials.
*
* @experimental This API is experimental and may change in future releases
* @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API}
*/
export declare class WebAuthnApi {
private client;
enroll: typeof WebAuthnApi.prototype._enroll;
challenge: typeof WebAuthnApi.prototype._challenge;
verify: typeof WebAuthnApi.prototype._verify;
authenticate: typeof WebAuthnApi.prototype._authenticate;
register: typeof WebAuthnApi.prototype._register;
constructor(client: GoTrueClient);
/**
* Enroll a new WebAuthn factor.
* Creates an unverified WebAuthn factor that must be verified with a credential.
*
* @experimental This method is experimental and may change in future releases
* @param {Omit<MFAEnrollWebauthnParams, 'factorType'>} params - Enrollment parameters (friendlyName required)
* @returns {Promise<AuthMFAEnrollWebauthnResponse>} Enrolled factor details or error
* @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential}
*/
_enroll(params: Omit<MFAEnrollWebauthnParams, 'factorType'>): Promise<AuthMFAEnrollWebauthnResponse>;
/**
* Challenge for WebAuthn credential creation or authentication.
* Combines server challenge with browser credential operations.
* Handles both registration (create) and authentication (request) flows.
*
* @experimental This method is experimental and may change in future releases
* @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId
* @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials
* @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation
* @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request
* @returns {Promise<RequestResult>} Challenge response with credential or error
* @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation}
* @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion}
*/
_challenge({ factorId, webauthn, friendlyName, signal, }: MFAChallengeWebauthnParams & {
friendlyName?: string;
signal?: AbortSignal;
}, overrides?: {
create?: Partial<PublicKeyCredentialCreationOptionsFuture>;
request?: never;
} | {
create?: never;
request?: Partial<PublicKeyCredentialRequestOptionsFuture>;
}): Promise<RequestResult<{
factorId: string;
challengeId: string;
} & {
webauthn: StrictOmit<MFAVerifyWebauthnParamFields<'create' | 'request'>['webauthn'], 'rpId' | 'rpOrigins'>;
}, WebAuthnError | AuthError>>;
/**
* Verify a WebAuthn credential with the server.
* Completes the WebAuthn ceremony by sending the credential to the server for verification.
*
* @experimental This method is experimental and may change in future releases
* @param {Object} params - Verification parameters
* @param {string} params.challengeId - ID of the challenge being verified
* @param {string} params.factorId - ID of the WebAuthn factor
* @param {MFAVerifyWebauthnParams<T>['webauthn']} params.webauthn - WebAuthn credential response
* @returns {Promise<AuthMFAVerifyResponse>} Verification result with session or error
* @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion}
* */
_verify<T extends 'create' | 'request'>({ challengeId, factorId, webauthn, }: {
challengeId: string;
factorId: string;
webauthn: MFAVerifyWebauthnParams<T>['webauthn'];
}): Promise<AuthMFAVerifyResponse>;
/**
* Complete WebAuthn authentication flow.
* Performs challenge and verification in a single operation for existing credentials.
*
* @experimental This method is experimental and may change in future releases
* @param {Object} params - Authentication parameters
* @param {string} params.factorId - ID of the WebAuthn factor to authenticate with
* @param {Object} params.webauthn - WebAuthn configuration
* @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname)
* @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin)
* @param {AbortSignal} params.webauthn.signal - Optional abort signal
* @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get
* @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Authentication result
* @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions}
*/
_authenticate({ factorId, webauthn: { rpId, rpOrigins, signal, }, }: {
factorId: string;
webauthn?: {
rpId?: string;
rpOrigins?: string[];
signal?: AbortSignal;
};
}, overrides?: PublicKeyCredentialRequestOptionsFuture): Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>;
/**
* Complete WebAuthn registration flow.
* Performs enrollment, challenge, and verification in a single operation for new credentials.
*
* @experimental This method is experimental and may change in future releases
* @param {Object} params - Registration parameters
* @param {string} params.friendlyName - User-friendly name for the credential
* @param {string} params.rpId - Relying Party ID (defaults to current hostname)
* @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin)
* @param {AbortSignal} params.signal - Optional abort signal
* @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create
* @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Registration result
* @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions}
*/
_register({ friendlyName, webauthn: { rpId, rpOrigins, signal, }, }: {
friendlyName: string;
webauthn?: {
rpId?: string;
rpOrigins?: string[];
signal?: AbortSignal;
};
}, overrides?: Partial<PublicKeyCredentialCreationOptionsFuture>): Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>;
}
//# sourceMappingURL=webauthn.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webauthn.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,iBAAiB,CAAA;AAE1C,OAAO,EAAE,SAAS,EAAiC,MAAM,UAAU,CAAA;AACnE,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,EACrB,yBAAyB,EACzB,0BAA0B,EAC1B,uBAAuB,EACvB,4BAA4B,EAC5B,uBAAuB,EACvB,aAAa,EACb,UAAU,EACX,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE1B,wCAAwC,EACxC,sCAAsC,EAEtC,uCAAuC,EACvC,qCAAqC,EACrC,sBAAsB,EACtB,wBAAwB,EACzB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EACL,2BAA2B,EAC3B,yBAAyB,EACzB,eAAe,EACf,aAAa,EAEd,MAAM,mBAAmB,CAAA;AAE1B,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,yBAAyB,EAAE,2BAA2B,EAAE,CAAA;AAEjG,YAAY,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,CAAA;AAEpE;;;;;;GAMG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,UAAU,CAA6B;IAE/C;;;;;;OAMG;IACH,oBAAoB,IAAI,WAAW;IAanC;;;;;OAKG;IACH,cAAc,IAAI,IAAI;CAQvB;AAED;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,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YACb,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;YACpB,MAAM,CAAC,EAAE,WAAW,CAAA;SACrB,CAAA;KACF,EACD,SAAS,CAAC,EAAE,OAAO,CAAC,wCAAwC,CAAC,GAC5D,OAAO,CAAC,aAAa,CAAC,yBAAyB,EAAE,aAAa,GAAG,SAAS,CAAC,CAAC;CAwEhF"}
+583
View File
@@ -0,0 +1,583 @@
import { StrictOmit } from './types';
/**
* A variant of PublicKeyCredentialCreationOptions suitable for JSON transmission to the browser to
* (eventually) get passed into navigator.credentials.create(...) in the browser.
*
* This should eventually get replaced with official TypeScript DOM types when WebAuthn Level 3 types
* eventually make it into the language:
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson W3C WebAuthn Spec - PublicKeyCredentialCreationOptionsJSON}
*/
export interface PublicKeyCredentialCreationOptionsJSON {
/**
* Information about the Relying Party responsible for the request.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-rp W3C - rp}
*/
rp: PublicKeyCredentialRpEntity;
/**
* Information about the user account for which the credential is being created.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-user W3C - user}
*/
user: PublicKeyCredentialUserEntityJSON;
/**
* A server-generated challenge in base64url format.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-challenge W3C - challenge}
*/
challenge: Base64URLString;
/**
* Information about desired properties of the credential to be created.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams W3C - pubKeyCredParams}
*/
pubKeyCredParams: PublicKeyCredentialParameters[];
/**
* Time in milliseconds that the caller is willing to wait for the operation to complete.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-timeout W3C - timeout}
*/
timeout?: number;
/**
* Credentials that the authenticator should not create a new credential for.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials W3C - excludeCredentials}
*/
excludeCredentials?: PublicKeyCredentialDescriptorJSON[];
/**
* Criteria for authenticator selection.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection W3C - authenticatorSelection}
*/
authenticatorSelection?: AuthenticatorSelectionCriteria;
/**
* Hints about what types of authenticators the user might want to use.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-hints W3C - hints}
*/
hints?: PublicKeyCredentialHint[];
/**
* How the attestation statement should be transported.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestation W3C - attestation}
*/
attestation?: AttestationConveyancePreference;
/**
* The attestation statement formats that the Relying Party will accept.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestationformats W3C - attestationFormats}
*/
attestationFormats?: AttestationFormat[];
/**
* Additional parameters requesting additional processing by the client and authenticator.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-extensions W3C - extensions}
*/
extensions?: AuthenticationExtensionsClientInputs;
}
/**
* A variant of PublicKeyCredentialRequestOptions suitable for JSON transmission to the browser to
* (eventually) get passed into navigator.credentials.get(...) in the browser.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson W3C WebAuthn Spec - PublicKeyCredentialRequestOptionsJSON}
*/
export interface PublicKeyCredentialRequestOptionsJSON {
/**
* A server-generated challenge in base64url format.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-challenge W3C - challenge}
*/
challenge: Base64URLString;
/**
* Time in milliseconds that the caller is willing to wait for the operation to complete.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-timeout W3C - timeout}
*/
timeout?: number;
/**
* The relying party identifier claimed by the caller.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-rpid W3C - rpId}
*/
rpId?: string;
/**
* A list of credentials acceptable for authentication.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials W3C - allowCredentials}
*/
allowCredentials?: PublicKeyCredentialDescriptorJSON[];
/**
* Whether user verification should be performed by the authenticator.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-userverification W3C - userVerification}
*/
userVerification?: UserVerificationRequirement;
/**
* Hints about what types of authenticators the user might want to use.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-hints W3C - hints}
*/
hints?: PublicKeyCredentialHint[];
/**
* Additional parameters requesting additional processing by the client and authenticator.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-extensions W3C - extensions}
*/
extensions?: AuthenticationExtensionsClientInputs;
}
/**
* Represents a public key credential descriptor in JSON format.
* Used to identify credentials for exclusion or allowance during WebAuthn ceremonies.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialdescriptorjson W3C WebAuthn Spec - PublicKeyCredentialDescriptorJSON}
*/
export interface PublicKeyCredentialDescriptorJSON {
/**
* The credential ID in base64url format.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-id W3C - id}
*/
id: Base64URLString;
/**
* The type of the public key credential (always "public-key").
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-type W3C - type}
*/
type: PublicKeyCredentialType;
/**
* How the authenticator communicates with clients.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-transports W3C - transports}
*/
transports?: AuthenticatorTransportFuture[];
}
/**
* Represents user account information in JSON format for WebAuthn registration.
* Contains identifiers and display information for the user being registered.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentityjson W3C WebAuthn Spec - PublicKeyCredentialUserEntityJSON}
*/
export interface PublicKeyCredentialUserEntityJSON {
/**
* A unique identifier for the user account (base64url encoded).
* Maximum 64 bytes. Should not contain PII.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id W3C - user.id}
*/
id: string;
/**
* A human-readable identifier for the account (e.g., email, username).
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name W3C - user.name}
*/
name: string;
/**
* A human-friendly display name for the user (e.g., "John Doe").
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname W3C - user.displayName}
*/
displayName: string;
}
/**
* Represents user account information for WebAuthn registration with binary data.
* Contains identifiers and display information for the user being registered.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentity W3C WebAuthn Spec - PublicKeyCredentialUserEntity}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialUserEntity MDN - PublicKeyCredentialUserEntity}
*/
export interface PublicKeyCredentialUserEntity {
/**
* A unique identifier for the user account.
* Maximum 64 bytes. Should not contain PII.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id W3C - user.id}
*/
id: BufferSource;
/**
* A human-readable identifier for the account.
* Typically an email, username, or phone number.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name W3C - user.name}
*/
name: string;
/**
* A human-friendly display name for the user.
* Example: "John Doe"
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname W3C - user.displayName}
*/
displayName: string;
}
/**
* The credential returned from navigator.credentials.create() during WebAuthn registration.
* Contains the new credential's public key and attestation information.
*
* @see {@link https://w3c.github.io/webauthn/#registrationceremony W3C WebAuthn Spec - Registration}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential}
*/
export interface RegistrationCredential extends PublicKeyCredentialFuture<RegistrationResponseJSON> {
response: AuthenticatorAttestationResponseFuture;
}
/**
* A slightly-modified RegistrationCredential to simplify working with ArrayBuffers that
* are Base64URL-encoded in the browser so that they can be sent as JSON to the server.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-registrationresponsejson W3C WebAuthn Spec - RegistrationResponseJSON}
*/
export interface RegistrationResponseJSON {
/**
* The credential ID (same as rawId for JSON).
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-id W3C - id}
*/
id: Base64URLString;
/**
* The raw credential ID in base64url format.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-rawid W3C - rawId}
*/
rawId: Base64URLString;
/**
* The authenticator's response to the client's request to create a credential.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-response W3C - response}
*/
response: AuthenticatorAttestationResponseJSON;
/**
* The authenticator attachment modality in effect at the time of credential creation.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment W3C - authenticatorAttachment}
*/
authenticatorAttachment?: AuthenticatorAttachment;
/**
* The results of processing client extensions.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-getclientextensionresults W3C - getClientExtensionResults}
*/
clientExtensionResults: AuthenticationExtensionsClientOutputs;
/**
* The type of the credential (always "public-key").
* @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type}
*/
type: PublicKeyCredentialType;
}
/**
* The credential returned from navigator.credentials.get() during WebAuthn authentication.
* Contains the assertion signature proving possession of the private key.
*
* @see {@link https://w3c.github.io/webauthn/#authentication W3C WebAuthn Spec - Authentication}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential}
*/
export interface AuthenticationCredential extends PublicKeyCredentialFuture<AuthenticationResponseJSON> {
response: AuthenticatorAssertionResponse;
}
/**
* A slightly-modified AuthenticationCredential to simplify working with ArrayBuffers that
* are Base64URL-encoded in the browser so that they can be sent as JSON to the server.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-authenticationresponsejson W3C WebAuthn Spec - AuthenticationResponseJSON}
*/
export interface AuthenticationResponseJSON {
/**
* The credential ID (same as rawId for JSON).
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-id W3C - id}
*/
id: Base64URLString;
/**
* The raw credential ID in base64url format.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-rawid W3C - rawId}
*/
rawId: Base64URLString;
/**
* The authenticator's response to the client's request to authenticate.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-response W3C - response}
*/
response: AuthenticatorAssertionResponseJSON;
/**
* The authenticator attachment modality in effect at the time of authentication.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment W3C - authenticatorAttachment}
*/
authenticatorAttachment?: AuthenticatorAttachment;
/**
* The results of processing client extensions.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-getclientextensionresults W3C - getClientExtensionResults}
*/
clientExtensionResults: AuthenticationExtensionsClientOutputs;
/**
* The type of the credential (always "public-key").
* @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type}
*/
type: PublicKeyCredentialType;
}
/**
* A slightly-modified AuthenticatorAttestationResponse to simplify working with ArrayBuffers that
* are Base64URL-encoded in the browser so that they can be sent as JSON to the server.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorattestationresponsejson W3C WebAuthn Spec - AuthenticatorAttestationResponseJSON}
*/
export interface AuthenticatorAttestationResponseJSON {
/**
* JSON-serialized client data passed to the authenticator.
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorresponse-clientdatajson W3C - clientDataJSON}
*/
clientDataJSON: Base64URLString;
/**
* The attestation object in base64url format.
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-attestationobject W3C - attestationObject}
*/
attestationObject: Base64URLString;
/**
* The authenticator data contained within the attestation object.
* Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getauthenticatordata W3C - getAuthenticatorData}
*/
authenticatorData?: Base64URLString;
/**
* The transports that the authenticator supports.
* Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports}
*/
transports?: AuthenticatorTransportFuture[];
/**
* The COSEAlgorithmIdentifier for the public key.
* Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getpublickeyalgorithm W3C - getPublicKeyAlgorithm}
*/
publicKeyAlgorithm?: COSEAlgorithmIdentifier;
/**
* The public key in base64url format.
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getpublickey W3C - getPublicKey}
*/
publicKey?: Base64URLString;
}
/**
* A slightly-modified AuthenticatorAssertionResponse to simplify working with ArrayBuffers that
* are Base64URL-encoded in the browser so that they can be sent as JSON to the server.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorassertionresponsejson W3C WebAuthn Spec - AuthenticatorAssertionResponseJSON}
*/
export interface AuthenticatorAssertionResponseJSON {
/**
* JSON-serialized client data passed to the authenticator.
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorresponse-clientdatajson W3C - clientDataJSON}
*/
clientDataJSON: Base64URLString;
/**
* The authenticator data returned by the authenticator.
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-authenticatordata W3C - authenticatorData}
*/
authenticatorData: Base64URLString;
/**
* The signature generated by the authenticator.
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-signature W3C - signature}
*/
signature: Base64URLString;
/**
* The user handle returned by the authenticator, if any.
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-userhandle W3C - userHandle}
*/
userHandle?: Base64URLString;
}
/**
* Public key credential information needed to verify authentication responses.
* Stores the credential's public key and metadata for server-side verification.
*
* @see {@link https://w3c.github.io/webauthn/#sctn-credential-storage-modality W3C WebAuthn Spec - Credential Storage}
*/
export type WebAuthnCredential = {
/**
* The credential ID in base64url format.
* @see {@link https://w3c.github.io/webauthn/#credential-id W3C - Credential ID}
*/
id: Base64URLString;
/**
* The credential's public key.
* @see {@link https://w3c.github.io/webauthn/#credential-public-key W3C - Credential Public Key}
*/
publicKey: Uint8Array_;
/**
* Number of times this authenticator is expected to have been used.
* @see {@link https://w3c.github.io/webauthn/#signature-counter W3C - Signature Counter}
*/
counter: number;
/**
* The transports that the authenticator supports.
* From browser's `startRegistration()` -> RegistrationCredentialJSON.transports (API L2 and up)
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports}
*/
transports?: AuthenticatorTransportFuture[];
};
/**
* An attempt to communicate that this isn't just any string, but a Base64URL-encoded string.
* Base64URL encoding is used throughout WebAuthn for binary data transmission.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 RFC 4648 - Base64URL Encoding}
*/
export type Base64URLString = string;
/**
* AuthenticatorAttestationResponse in TypeScript's DOM lib is outdated (up through v3.9.7).
* Maintain an augmented version here so we can implement additional properties as the WebAuthn
* spec evolves.
*
* Properties marked optional are not supported in all browsers.
*
* @see {@link https://www.w3.org/TR/webauthn-2/#iface-authenticatorattestationresponse W3C WebAuthn Spec - AuthenticatorAttestationResponse}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse MDN - AuthenticatorAttestationResponse}
*/
export interface AuthenticatorAttestationResponseFuture extends AuthenticatorAttestationResponse {
/**
* Returns the transports that the authenticator supports.
* @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports}
*/
getTransports(): AuthenticatorTransportFuture[];
}
/**
* A super class of TypeScript's `AuthenticatorTransport` that includes support for the latest
* transports. Should eventually be replaced by TypeScript's when TypeScript gets updated to
* know about it (sometime after 4.6.3)
*
* @see {@link https://w3c.github.io/webauthn/#enum-transport W3C WebAuthn Spec - AuthenticatorTransport}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse/getTransports MDN - getTransports}
*/
export type AuthenticatorTransportFuture = 'ble' | 'cable' | 'hybrid' | 'internal' | 'nfc' | 'smart-card' | 'usb';
/**
* A super class of TypeScript's `PublicKeyCredentialDescriptor` that knows about the latest
* transports. Should eventually be replaced by TypeScript's when TypeScript gets updated to
* know about it (sometime after 4.6.3)
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialdescriptor W3C WebAuthn Spec - PublicKeyCredentialDescriptor}
*/
export interface PublicKeyCredentialDescriptorFuture extends Omit<PublicKeyCredentialDescriptor, 'transports'> {
/**
* How the authenticator communicates with clients.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-transports W3C - transports}
*/
transports?: AuthenticatorTransportFuture[];
}
/**
* Enhanced PublicKeyCredentialCreationOptions that knows about the latest features.
* Used for WebAuthn registration ceremonies.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptions W3C WebAuthn Spec - PublicKeyCredentialCreationOptions}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions}
*/
export interface PublicKeyCredentialCreationOptionsFuture extends StrictOmit<PublicKeyCredentialCreationOptions, 'excludeCredentials' | 'user'> {
/**
* Credentials that the authenticator should not create a new credential for.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials W3C - excludeCredentials}
*/
excludeCredentials?: PublicKeyCredentialDescriptorFuture[];
/**
* Information about the user account for which the credential is being created.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-user W3C - user}
*/
user: PublicKeyCredentialUserEntity;
/**
* Hints about what types of authenticators the user might want to use.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-hints W3C - hints}
*/
hints?: PublicKeyCredentialHint[];
/**
* Criteria for authenticator selection.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection W3C - authenticatorSelection}
*/
authenticatorSelection?: AuthenticatorSelectionCriteria;
/**
* Information about desired properties of the credential to be created.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams W3C - pubKeyCredParams}
*/
pubKeyCredParams: PublicKeyCredentialParameters[];
/**
* Information about the Relying Party responsible for the request.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-rp W3C - rp}
*/
rp: PublicKeyCredentialRpEntity;
}
/**
* Enhanced PublicKeyCredentialRequestOptions that knows about the latest features.
* Used for WebAuthn authentication ceremonies.
*
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions}
*/
export interface PublicKeyCredentialRequestOptionsFuture extends StrictOmit<PublicKeyCredentialRequestOptions, 'allowCredentials'> {
/**
* A list of credentials acceptable for authentication.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials W3C - allowCredentials}
*/
allowCredentials?: PublicKeyCredentialDescriptorFuture[];
/**
* Hints about what types of authenticators the user might want to use.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-hints W3C - hints}
*/
hints?: PublicKeyCredentialHint[];
/**
* The attestation conveyance preference for the authentication ceremony.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestation W3C - attestation}
*/
attestation?: AttestationConveyancePreference;
}
/**
* Union type for all WebAuthn credential responses in JSON format.
* Can be either a registration response (for new credentials) or authentication response (for existing credentials).
*/
export type PublicKeyCredentialJSON = RegistrationResponseJSON | AuthenticationResponseJSON;
/**
* A super class of TypeScript's `PublicKeyCredential` that knows about upcoming WebAuthn features.
* Includes WebAuthn Level 3 methods for JSON serialization and parsing.
*
* @see {@link https://w3c.github.io/webauthn/#publickeycredential W3C WebAuthn Spec - PublicKeyCredential}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential}
*/
export interface PublicKeyCredentialFuture<T extends PublicKeyCredentialJSON = PublicKeyCredentialJSON> extends PublicKeyCredential {
/**
* The type of the credential (always "public-key").
* @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type}
*/
type: PublicKeyCredentialType;
/**
* Checks if conditional mediation is available.
* @see {@link https://github.com/w3c/webauthn/issues/1745 GitHub - Conditional Mediation}
*/
isConditionalMediationAvailable?(): Promise<boolean>;
/**
* Parses JSON to create PublicKeyCredentialCreationOptions.
* @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C - parseCreationOptionsFromJSON}
*/
parseCreationOptionsFromJSON(options: PublicKeyCredentialCreationOptionsJSON): PublicKeyCredentialCreationOptionsFuture;
/**
* Parses JSON to create PublicKeyCredentialRequestOptions.
* @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C - parseRequestOptionsFromJSON}
*/
parseRequestOptionsFromJSON(options: PublicKeyCredentialRequestOptionsJSON): PublicKeyCredentialRequestOptionsFuture;
/**
* Serializes the credential to JSON format.
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C - toJSON}
*/
toJSON(): T;
}
/**
* The two types of credentials as defined by bit 3 ("Backup Eligibility") in authenticator data:
* - `"singleDevice"` credentials will never be backed up
* - `"multiDevice"` credentials can be backed up
*
* @see {@link https://w3c.github.io/webauthn/#sctn-authenticator-data W3C WebAuthn Spec - Authenticator Data}
*/
export type CredentialDeviceType = 'singleDevice' | 'multiDevice' | (string & {});
/**
* Categories of authenticators that Relying Parties can pass along to browsers during
* registration. Browsers that understand these values can optimize their modal experience to
* start the user off in a particular registration flow:
*
* - `hybrid`: A platform authenticator on a mobile device
* - `security-key`: A portable FIDO2 authenticator capable of being used on multiple devices via a USB or NFC connection
* - `client-device`: The device that WebAuthn is being called on. Typically synonymous with platform authenticators
*
* These values are less strict than `authenticatorAttachment`
*
* @see {@link https://w3c.github.io/webauthn/#enumdef-publickeycredentialhint W3C WebAuthn Spec - PublicKeyCredentialHint}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#hints MDN - hints}
*/
export type PublicKeyCredentialHint = 'hybrid' | 'security-key' | 'client-device' | (string & {});
/**
* Values for an attestation object's `fmt`.
* Defines the format of the attestation statement from the authenticator.
*
* @see {@link https://www.iana.org/assignments/webauthn/webauthn.xhtml#webauthn-attestation-statement-format-ids IANA - WebAuthn Attestation Statement Format Identifiers}
* @see {@link https://w3c.github.io/webauthn/#sctn-attestation-formats W3C WebAuthn Spec - Attestation Statement Formats}
*/
export type AttestationFormat = 'fido-u2f' | 'packed' | 'android-safetynet' | 'android-key' | 'tpm' | 'apple' | 'none';
/**
* Equivalent to `Uint8Array` before TypeScript 5.7, and `Uint8Array<ArrayBuffer>` in TypeScript 5.7
* and beyond.
*
* **Context**
*
* `Uint8Array` became a generic type in TypeScript 5.7, requiring types defined simply as
* `Uint8Array` to be refactored to `Uint8Array<ArrayBuffer>` starting in Deno 2.2. `Uint8Array` is
* _not_ generic in Deno 2.1.x and earlier, though, so this type helps bridge this gap.
*
* Inspired by Deno's std library:
*
* https://github.com/denoland/std/blob/b5a5fe4f96b91c1fe8dba5cc0270092dd11d3287/bytes/_types.ts#L11
*/
export type Uint8Array_ = ReturnType<Uint8Array['slice']>;
/**
* Specifies the preferred authenticator attachment modality.
* - `platform`: A platform authenticator attached to the client device (e.g., Touch ID, Windows Hello)
* - `cross-platform`: A roaming authenticator not attached to the client device (e.g., USB security key)
*
* @see {@link https://w3c.github.io/webauthn/#enum-attachment W3C WebAuthn Spec - AuthenticatorAttachment}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions/authenticatorSelection#authenticatorattachment MDN - authenticatorAttachment}
*/
export type AuthenticatorAttachment = 'cross-platform' | 'platform' | (string & {});
//# sourceMappingURL=webauthn.dom.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webauthn.dom.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.dom.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEpC;;;;;;;;GAQG;AACH,MAAM,WAAW,sCAAsC;IACrD;;;OAGG;IACH,EAAE,EAAE,2BAA2B,CAAA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AM,oBAAoB,GAAG,cAAc,GAAG,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAA;AAEjF;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,uBAAuB,GAAG,QAAQ,GAAG,cAAc,GAAG,eAAe,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAA;AAEjG;;;;;;GAMG;AACH,MAAM,MAAM,iBAAiB,GACzB,UAAU,GACV,QAAQ,GACR,mBAAmB,GACnB,aAAa,GACb,KAAK,GACL,OAAO,GACP,MAAM,CAAA;AAEV;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,WAAW,GAAG,UAAU,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA;AAEzD;;;;;;;GAOG;AACH,MAAM,MAAM,uBAAuB,GAAG,gBAAgB,GAAG,UAAU,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAA"}
+4
View File
@@ -0,0 +1,4 @@
"use strict";
// from https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/browser/src/types/index.ts
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=webauthn.dom.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webauthn.dom.js","sourceRoot":"","sources":["../../../src/lib/webauthn.dom.ts"],"names":[],"mappings":";AAAA,oGAAoG"}
+85
View File
@@ -0,0 +1,85 @@
import { StrictOmit } from './types';
import { PublicKeyCredentialCreationOptionsFuture, PublicKeyCredentialRequestOptionsFuture } from './webauthn.dom';
/**
* A custom Error used to return a more nuanced error detailing _why_ one of the eight documented
* errors in the spec was raised after calling `navigator.credentials.create()` or
* `navigator.credentials.get()`:
*
* - `AbortError`
* - `ConstraintError`
* - `InvalidStateError`
* - `NotAllowedError`
* - `NotSupportedError`
* - `SecurityError`
* - `TypeError`
* - `UnknownError`
*
* Error messages were determined through investigation of the spec to determine under which
* scenarios a given error would be raised.
*/
export declare class WebAuthnError extends Error {
code: WebAuthnErrorCode;
protected __isWebAuthnError: boolean;
constructor({ message, code, cause, name, }: {
message: string;
code: WebAuthnErrorCode;
cause?: Error | unknown;
name?: string;
});
toJSON(): {
name: string;
message: string;
code: WebAuthnErrorCode;
};
}
/**
* Error class for unknown WebAuthn errors.
* Wraps unexpected errors that don't match known WebAuthn error conditions.
*/
export declare class WebAuthnUnknownError extends WebAuthnError {
originalError: unknown;
constructor(message: string, originalError: unknown);
}
/**
* Type guard to check if an error is a WebAuthnError.
* @param {unknown} error - The error to check
* @returns {boolean} True if the error is a WebAuthnError
*/
export declare function isWebAuthnError(error: unknown): error is WebAuthnError;
/**
* Error codes for WebAuthn operations.
* These codes provide specific information about why a WebAuthn ceremony failed.
* @see {@link https://w3c.github.io/webauthn/#sctn-defined-errors W3C WebAuthn Spec - Defined Errors}
*/
export type WebAuthnErrorCode = 'ERROR_CEREMONY_ABORTED' | 'ERROR_INVALID_DOMAIN' | 'ERROR_INVALID_RP_ID' | 'ERROR_INVALID_USER_ID_LENGTH' | 'ERROR_MALFORMED_PUBKEYCREDPARAMS' | 'ERROR_AUTHENTICATOR_GENERAL_ERROR' | 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT' | 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT' | 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED' | 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG' | 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE' | 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY';
/**
* Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`.
* Maps browser errors to specific WebAuthn error codes for better debugging.
* @param {Object} params - Error identification parameters
* @param {Error} params.error - The error thrown by the browser
* @param {CredentialCreationOptions} params.options - The options passed to credentials.create()
* @returns {WebAuthnError} A WebAuthnError with a specific error code
* @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}
*/
export declare function identifyRegistrationError({ error, options, }: {
error: Error;
options: StrictOmit<CredentialCreationOptions, 'publicKey'> & {
publicKey: PublicKeyCredentialCreationOptionsFuture;
};
}): WebAuthnError;
/**
* Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`.
* Maps browser errors to specific WebAuthn error codes for better debugging.
* @param {Object} params - Error identification parameters
* @param {Error} params.error - The error thrown by the browser
* @param {CredentialRequestOptions} params.options - The options passed to credentials.get()
* @returns {WebAuthnError} A WebAuthnError with a specific error code
* @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}
*/
export declare function identifyAuthenticationError({ error, options, }: {
error: Error;
options: StrictOmit<CredentialRequestOptions, 'publicKey'> & {
publicKey: PublicKeyCredentialRequestOptionsFuture;
};
}): WebAuthnError;
//# sourceMappingURL=webauthn.errors.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"webauthn.errors.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.errors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEpC,OAAO,EACL,wCAAwC,EACxC,uCAAuC,EACxC,MAAM,gBAAgB,CAAA;AAEvB;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,aAAc,SAAQ,KAAK;IACtC,IAAI,EAAE,iBAAiB,CAAA;IAEvB,SAAS,CAAC,iBAAiB,UAAO;gBAEtB,EACV,OAAO,EACP,IAAI,EACJ,KAAK,EACL,IAAI,GACL,EAAE;QACD,OAAO,EAAE,MAAM,CAAA;QACf,IAAI,EAAE,iBAAiB,CAAA;QACvB,KAAK,CAAC,EAAE,KAAK,GAAG,OAAO,CAAA;QACvB,IAAI,CAAC,EAAE,MAAM,CAAA;KACd;IAOD,MAAM,IAAI;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,OAAO,EAAE,MAAM,CAAA;QACf,IAAI,EAAE,iBAAiB,CAAA;KACxB;CAOF;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,aAAa;IACrD,aAAa,EAAE,OAAO,CAAA;gBAEV,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO;CASpD;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAEtE;AAED;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GACzB,wBAAwB,GACxB,sBAAsB,GACtB,qBAAqB,GACrB,8BAA8B,GAC9B,kCAAkC,GAClC,mCAAmC,GACnC,6DAA6D,GAC7D,uDAAuD,GACvD,2CAA2C,GAC3C,uDAAuD,GACvD,+CAA+C,GAC/C,sCAAsC,CAAA;AAE1C;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,EACxC,KAAK,EACL,OAAO,GACR,EAAE;IACD,KAAK,EAAE,KAAK,CAAA;IACZ,OAAO,EAAE,UAAU,CAAC,yBAAyB,EAAE,WAAW,CAAC,GAAG;QAC5D,SAAS,EAAE,wCAAwC,CAAA;KACpD,CAAA;CACF,GAAG,aAAa,CA8HhB;AAED;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CAAC,EAC1C,KAAK,EACL,OAAO,GACR,EAAE;IACD,KAAK,EAAE,KAAK,CAAA;IACZ,OAAO,EAAE,UAAU,CAAC,wBAAwB,EAAE,WAAW,CAAC,GAAG;QAC3D,SAAS,EAAE,uCAAuC,CAAA;KACnD,CAAA;CACF,GAAG,aAAa,CA2DhB"}
+272
View File
@@ -0,0 +1,272 @@
"use strict";
/* eslint-disable @typescript-eslint/ban-ts-comment */
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebAuthnUnknownError = exports.WebAuthnError = void 0;
exports.isWebAuthnError = isWebAuthnError;
exports.identifyRegistrationError = identifyRegistrationError;
exports.identifyAuthenticationError = identifyAuthenticationError;
const webauthn_1 = require("./webauthn");
/**
* A custom Error used to return a more nuanced error detailing _why_ one of the eight documented
* errors in the spec was raised after calling `navigator.credentials.create()` or
* `navigator.credentials.get()`:
*
* - `AbortError`
* - `ConstraintError`
* - `InvalidStateError`
* - `NotAllowedError`
* - `NotSupportedError`
* - `SecurityError`
* - `TypeError`
* - `UnknownError`
*
* Error messages were determined through investigation of the spec to determine under which
* scenarios a given error would be raised.
*/
class WebAuthnError extends Error {
constructor({ message, code, cause, name, }) {
var _a;
// @ts-ignore: help Rollup understand that `cause` is okay to set
super(message, { cause });
this.__isWebAuthnError = true;
this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error';
this.code = code;
}
toJSON() {
return {
name: this.name,
message: this.message,
code: this.code,
};
}
}
exports.WebAuthnError = WebAuthnError;
/**
* Error class for unknown WebAuthn errors.
* Wraps unexpected errors that don't match known WebAuthn error conditions.
*/
class WebAuthnUnknownError extends WebAuthnError {
constructor(message, originalError) {
super({
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
cause: originalError,
message,
});
this.name = 'WebAuthnUnknownError';
this.originalError = originalError;
}
}
exports.WebAuthnUnknownError = WebAuthnUnknownError;
/**
* Type guard to check if an error is a WebAuthnError.
* @param {unknown} error - The error to check
* @returns {boolean} True if the error is a WebAuthnError
*/
function isWebAuthnError(error) {
return typeof error === 'object' && error !== null && '__isWebAuthnError' in error;
}
/**
* Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`.
* Maps browser errors to specific WebAuthn error codes for better debugging.
* @param {Object} params - Error identification parameters
* @param {Error} params.error - The error thrown by the browser
* @param {CredentialCreationOptions} params.options - The options passed to credentials.create()
* @returns {WebAuthnError} A WebAuthnError with a specific error code
* @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}
*/
function identifyRegistrationError({ error, options, }) {
var _a, _b, _c;
const { publicKey } = options;
if (!publicKey) {
throw Error('options was missing required publicKey property');
}
if (error.name === 'AbortError') {
if (options.signal instanceof AbortSignal) {
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)
return new WebAuthnError({
message: 'Registration ceremony was sent an abort signal',
code: 'ERROR_CEREMONY_ABORTED',
cause: error,
});
}
}
else if (error.name === 'ConstraintError') {
if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) {
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)
return new WebAuthnError({
message: 'Discoverable credentials were required but no available authenticator supported it',
code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',
cause: error,
});
}
else if (
// @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024
options.mediation === 'conditional' &&
((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') {
// https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)
return new WebAuthnError({
message: 'User verification was required during automatic registration but it could not be performed',
code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',
cause: error,
});
}
else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') {
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)
return new WebAuthnError({
message: 'User verification was required but no available authenticator supported it',
code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',
cause: error,
});
}
}
else if (error.name === 'InvalidStateError') {
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)
return new WebAuthnError({
message: 'The authenticator was previously registered',
code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',
cause: error,
});
}
else if (error.name === 'NotAllowedError') {
/**
* Pass the error directly through. Platforms are overloading this error beyond what the spec
* defines and we don't want to overwrite potentially useful error messages.
*/
return new WebAuthnError({
message: error.message,
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
cause: error,
});
}
else if (error.name === 'NotSupportedError') {
const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');
if (validPubKeyCredParams.length === 0) {
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)
return new WebAuthnError({
message: 'No entry in pubKeyCredParams was of type "public-key"',
code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',
cause: error,
});
}
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)
return new WebAuthnError({
message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',
code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',
cause: error,
});
}
else if (error.name === 'SecurityError') {
const effectiveDomain = window.location.hostname;
if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) {
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)
return new WebAuthnError({
message: `${window.location.hostname} is an invalid domain`,
code: 'ERROR_INVALID_DOMAIN',
cause: error,
});
}
else if (publicKey.rp.id !== effectiveDomain) {
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)
return new WebAuthnError({
message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`,
code: 'ERROR_INVALID_RP_ID',
cause: error,
});
}
}
else if (error.name === 'TypeError') {
if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)
return new WebAuthnError({
message: 'User ID was not between 1 and 64 characters',
code: 'ERROR_INVALID_USER_ID_LENGTH',
cause: error,
});
}
}
else if (error.name === 'UnknownError') {
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)
return new WebAuthnError({
message: 'The authenticator was unable to process the specified options, or could not create a new credential',
code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
cause: error,
});
}
return new WebAuthnError({
message: 'a Non-Webauthn related error has occurred',
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
cause: error,
});
}
/**
* Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`.
* Maps browser errors to specific WebAuthn error codes for better debugging.
* @param {Object} params - Error identification parameters
* @param {Error} params.error - The error thrown by the browser
* @param {CredentialRequestOptions} params.options - The options passed to credentials.get()
* @returns {WebAuthnError} A WebAuthnError with a specific error code
* @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}
*/
function identifyAuthenticationError({ error, options, }) {
const { publicKey } = options;
if (!publicKey) {
throw Error('options was missing required publicKey property');
}
if (error.name === 'AbortError') {
if (options.signal instanceof AbortSignal) {
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)
return new WebAuthnError({
message: 'Authentication ceremony was sent an abort signal',
code: 'ERROR_CEREMONY_ABORTED',
cause: error,
});
}
}
else if (error.name === 'NotAllowedError') {
/**
* Pass the error directly through. Platforms are overloading this error beyond what the spec
* defines and we don't want to overwrite potentially useful error messages.
*/
return new WebAuthnError({
message: error.message,
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
cause: error,
});
}
else if (error.name === 'SecurityError') {
const effectiveDomain = window.location.hostname;
if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) {
// https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)
return new WebAuthnError({
message: `${window.location.hostname} is an invalid domain`,
code: 'ERROR_INVALID_DOMAIN',
cause: error,
});
}
else if (publicKey.rpId !== effectiveDomain) {
// https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)
return new WebAuthnError({
message: `The RP ID "${publicKey.rpId}" is invalid for this domain`,
code: 'ERROR_INVALID_RP_ID',
cause: error,
});
}
}
else if (error.name === 'UnknownError') {
// https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)
// https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)
return new WebAuthnError({
message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',
code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
cause: error,
});
}
return new WebAuthnError({
message: 'a Non-Webauthn related error has occurred',
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
cause: error,
});
}
//# sourceMappingURL=webauthn.errors.js.map
File diff suppressed because one or more lines are too long
+707
View File
@@ -0,0 +1,707 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0;
exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions;
exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions;
exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse;
exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse;
exports.isValidDomain = isValidDomain;
exports.browserSupportsWebAuthn = browserSupportsWebAuthn;
exports.createCredential = createCredential;
exports.getCredential = getCredential;
exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions;
exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions;
const tslib_1 = require("tslib");
const base64url_1 = require("./base64url");
const errors_1 = require("./errors");
const helpers_1 = require("./helpers");
const webauthn_errors_1 = require("./webauthn.errors");
Object.defineProperty(exports, "identifyAuthenticationError", { enumerable: true, get: function () { return webauthn_errors_1.identifyAuthenticationError; } });
Object.defineProperty(exports, "identifyRegistrationError", { enumerable: true, get: function () { return webauthn_errors_1.identifyRegistrationError; } });
Object.defineProperty(exports, "isWebAuthnError", { enumerable: true, get: function () { return webauthn_errors_1.isWebAuthnError; } });
Object.defineProperty(exports, "WebAuthnError", { enumerable: true, get: function () { return webauthn_errors_1.WebAuthnError; } });
/**
* WebAuthn abort service to manage ceremony cancellation.
* Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors.
*
* @experimental This class is experimental and may change in future releases
* @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies}
*/
class WebAuthnAbortService {
/**
* Create an abort signal for a new WebAuthn operation.
* Automatically cancels any existing operation.
*
* @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get()
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal}
*/
createNewAbortSignal() {
// Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()
if (this.controller) {
const abortError = new Error('Cancelling existing WebAuthn API call for new one');
abortError.name = 'AbortError';
this.controller.abort(abortError);
}
const newController = new AbortController();
this.controller = newController;
return newController.signal;
}
/**
* Manually cancel the current WebAuthn operation.
* Useful for cleaning up when user cancels or navigates away.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort}
*/
cancelCeremony() {
if (this.controller) {
const abortError = new Error('Manually cancelling existing WebAuthn API call');
abortError.name = 'AbortError';
this.controller.abort(abortError);
this.controller = undefined;
}
}
}
exports.WebAuthnAbortService = WebAuthnAbortService;
/**
* Singleton instance to ensure only one WebAuthn ceremony is active at a time.
* This prevents "operation already in progress" errors when retrying WebAuthn operations.
*
* @experimental This instance is experimental and may change in future releases
*/
exports.webAuthnAbortService = new WebAuthnAbortService();
/**
* Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers
* as required by the WebAuthn browser API.
* Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback.
*
* @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields
* @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create()
* @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON}
*/
function deserializeCredentialCreationOptions(options) {
if (!options) {
throw new Error('Credential creation options are required');
}
// Check if the native parseCreationOptionsFromJSON method is available
if (typeof PublicKeyCredential !== 'undefined' &&
'parseCreationOptionsFromJSON' in PublicKeyCredential &&
typeof PublicKeyCredential
.parseCreationOptionsFromJSON === 'function') {
// Use the native WebAuthn Level 3 method
return PublicKeyCredential.parseCreationOptionsFromJSON(
/** we assert the options here as typescript still doesn't know about future webauthn types */
options);
}
// Fallback to manual parsing for browsers that don't support the native method
// Destructure to separate fields that need transformation
const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest(options
// Convert challenge from base64url to ArrayBuffer
, ["challenge", "user", "excludeCredentials"]);
// Convert challenge from base64url to ArrayBuffer
const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer;
// Convert user.id from base64url to ArrayBuffer
const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer });
// Build the result object
const result = Object.assign(Object.assign({}, restOptions), { challenge,
user });
// Only add excludeCredentials if it exists
if (excludeCredentials && excludeCredentials.length > 0) {
result.excludeCredentials = new Array(excludeCredentials.length);
for (let i = 0; i < excludeCredentials.length; i++) {
const cred = excludeCredentials[i];
result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key',
// Cast transports to handle future transport types like "cable"
transports: cred.transports });
}
}
return result;
}
/**
* Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers
* as required by the WebAuthn browser API.
* Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback.
*
* @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields
* @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get()
* @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON}
*/
function deserializeCredentialRequestOptions(options) {
if (!options) {
throw new Error('Credential request options are required');
}
// Check if the native parseRequestOptionsFromJSON method is available
if (typeof PublicKeyCredential !== 'undefined' &&
'parseRequestOptionsFromJSON' in PublicKeyCredential &&
typeof PublicKeyCredential
.parseRequestOptionsFromJSON === 'function') {
// Use the native WebAuthn Level 3 method
return PublicKeyCredential.parseRequestOptionsFromJSON(options);
}
// Fallback to manual parsing for browsers that don't support the native method
// Destructure to separate fields that need transformation
const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest(options
// Convert challenge from base64url to ArrayBuffer
, ["challenge", "allowCredentials"]);
// Convert challenge from base64url to ArrayBuffer
const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer;
// Build the result object
const result = Object.assign(Object.assign({}, restOptions), { challenge });
// Only add allowCredentials if it exists
if (allowCredentials && allowCredentials.length > 0) {
result.allowCredentials = new Array(allowCredentials.length);
for (let i = 0; i < allowCredentials.length; i++) {
const cred = allowCredentials[i];
result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key',
// Cast transports to handle future transport types like "cable"
transports: cred.transports });
}
}
return result;
}
/**
* Convert a registration/enrollment credential response to server format.
* Serializes binary fields to base64url for JSON transmission.
* Supports both native WebAuthn Level 3 toJSON and manual fallback.
*
* @param {RegistrationCredential} credential - Credential from navigator.credentials.create()
* @returns {RegistrationResponseJSON} JSON-serializable credential for server
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
*/
function serializeCredentialCreationResponse(credential) {
var _a;
// Check if the credential instance has the toJSON method
if ('toJSON' in credential && typeof credential.toJSON === 'function') {
// Use the native WebAuthn Level 3 method
return credential.toJSON();
}
const credentialWithAttachment = credential;
return {
id: credential.id,
rawId: credential.id,
response: {
attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)),
clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)),
},
type: 'public-key',
clientExtensionResults: credential.getClientExtensionResults(),
// Convert null to undefined and cast to AuthenticatorAttachment type
authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined),
};
}
/**
* Convert an authentication/verification credential response to server format.
* Serializes binary fields to base64url for JSON transmission.
* Supports both native WebAuthn Level 3 toJSON and manual fallback.
*
* @param {AuthenticationCredential} credential - Credential from navigator.credentials.get()
* @returns {AuthenticationResponseJSON} JSON-serializable credential for server
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
*/
function serializeCredentialRequestResponse(credential) {
var _a;
// Check if the credential instance has the toJSON method
if ('toJSON' in credential && typeof credential.toJSON === 'function') {
// Use the native WebAuthn Level 3 method
return credential.toJSON();
}
// Fallback to manual conversion for browsers that don't support toJSON
// Access authenticatorAttachment via type assertion to handle TypeScript version differences
// @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't
const credentialWithAttachment = credential;
const clientExtensionResults = credential.getClientExtensionResults();
const assertionResponse = credential.response;
return {
id: credential.id,
rawId: credential.id, // W3C spec expects rawId to match id for JSON format
response: {
authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)),
clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)),
signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)),
userHandle: assertionResponse.userHandle
? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle))
: undefined,
},
type: 'public-key',
clientExtensionResults,
// Convert null to undefined and cast to AuthenticatorAttachment type
authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined),
};
}
/**
* A simple test to determine if a hostname is a properly-formatted domain name.
* Considers localhost valid for development environments.
*
* A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain
*
* Regex sourced from here:
* https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html
*
* @param {string} hostname - The hostname to validate
* @returns {boolean} True if valid domain or localhost
* @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain}
*/
function isValidDomain(hostname) {
return (
// Consider localhost valid as well since it's okay wrt Secure Contexts
hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname));
}
/**
* Determine if the browser is capable of WebAuthn.
* Checks for necessary Web APIs: PublicKeyCredential and Credential Management.
*
* @returns {boolean} True if browser supports WebAuthn
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility}
*/
function browserSupportsWebAuthn() {
var _a, _b;
return !!((0, helpers_1.isBrowser)() &&
'PublicKeyCredential' in window &&
window.PublicKeyCredential &&
'credentials' in navigator &&
typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' &&
typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function');
}
/**
* Create a WebAuthn credential using the browser's credentials API.
* Wraps navigator.credentials.create() with error handling.
*
* @param {CredentialCreationOptions} options - Options including publicKey parameters
* @returns {Promise<RequestResult<RegistrationCredential, WebAuthnError>>} Created credential or error
* @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create}
*/
async function createCredential(options) {
try {
const response = await navigator.credentials.create(
/** we assert the type here until typescript types are updated */
options);
if (!response) {
return {
data: null,
error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response),
};
}
if (!(response instanceof PublicKeyCredential)) {
return {
data: null,
error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response),
};
}
return { data: response, error: null };
}
catch (err) {
return {
data: null,
error: (0, webauthn_errors_1.identifyRegistrationError)({
error: err,
options,
}),
};
}
}
/**
* Get a WebAuthn credential using the browser's credentials API.
* Wraps navigator.credentials.get() with error handling.
*
* @param {CredentialRequestOptions} options - Options including publicKey parameters
* @returns {Promise<RequestResult<AuthenticationCredential, WebAuthnError>>} Retrieved credential or error
* @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get}
*/
async function getCredential(options) {
try {
const response = await navigator.credentials.get(
/** we assert the type here until typescript types are updated */
options);
if (!response) {
return {
data: null,
error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response),
};
}
if (!(response instanceof PublicKeyCredential)) {
return {
data: null,
error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response),
};
}
return { data: response, error: null };
}
catch (err) {
return {
data: null,
error: (0, webauthn_errors_1.identifyAuthenticationError)({
error: err,
options,
}),
};
}
}
exports.DEFAULT_CREATION_OPTIONS = {
hints: ['security-key'],
authenticatorSelection: {
authenticatorAttachment: 'cross-platform',
requireResidentKey: false,
/** set to preferred because older yubikeys don't have PIN/Biometric */
userVerification: 'preferred',
residentKey: 'discouraged',
},
attestation: 'direct',
};
exports.DEFAULT_REQUEST_OPTIONS = {
/** set to preferred because older yubikeys don't have PIN/Biometric */
userVerification: 'preferred',
hints: ['security-key'],
attestation: 'direct',
};
function deepMerge(...sources) {
const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val);
const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val);
const result = {};
for (const source of sources) {
if (!source)
continue;
for (const key in source) {
const value = source[key];
if (value === undefined)
continue;
if (Array.isArray(value)) {
// preserve array reference, including unions like AuthenticatorTransport[]
result[key] = value;
}
else if (isArrayBufferLike(value)) {
result[key] = value;
}
else if (isObject(value)) {
const existing = result[key];
if (isObject(existing)) {
result[key] = deepMerge(existing, value);
}
else {
result[key] = deepMerge(value);
}
}
else {
result[key] = value;
}
}
}
return result;
}
/**
* Merges WebAuthn credential creation options with overrides.
* Sets sensible defaults for authenticator selection and extensions.
*
* @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server
* @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply
* @param {string} friendlyName - Optional friendly name for the credential
* @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options
* @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria}
*/
function mergeCredentialCreationOptions(baseOptions, overrides) {
return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {});
}
/**
* Merges WebAuthn credential request options with overrides.
* Sets sensible defaults for user verification and hints.
*
* @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server
* @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply
* @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions}
*/
function mergeCredentialRequestOptions(baseOptions, overrides) {
return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {});
}
/**
* WebAuthn API wrapper for Supabase Auth.
* Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials.
*
* @experimental This API is experimental and may change in future releases
* @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API}
*/
class WebAuthnApi {
constructor(client) {
this.client = client;
// Bind all methods so they can be destructured
this.enroll = this._enroll.bind(this);
this.challenge = this._challenge.bind(this);
this.verify = this._verify.bind(this);
this.authenticate = this._authenticate.bind(this);
this.register = this._register.bind(this);
}
/**
* Enroll a new WebAuthn factor.
* Creates an unverified WebAuthn factor that must be verified with a credential.
*
* @experimental This method is experimental and may change in future releases
* @param {Omit<MFAEnrollWebauthnParams, 'factorType'>} params - Enrollment parameters (friendlyName required)
* @returns {Promise<AuthMFAEnrollWebauthnResponse>} Enrolled factor details or error
* @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential}
*/
async _enroll(params) {
return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' }));
}
/**
* Challenge for WebAuthn credential creation or authentication.
* Combines server challenge with browser credential operations.
* Handles both registration (create) and authentication (request) flows.
*
* @experimental This method is experimental and may change in future releases
* @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId
* @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials
* @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation
* @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request
* @returns {Promise<RequestResult>} Challenge response with credential or error
* @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation}
* @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion}
*/
async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) {
var _a;
try {
// Get challenge from server using the client's MFA methods
const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({
factorId,
webauthn,
});
if (!challengeResponse) {
return { data: null, error: challengeError };
}
const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal();
/** webauthn will fail if either of the name/displayname are blank */
if (challengeResponse.webauthn.type === 'create') {
const { user } = challengeResponse.webauthn.credential_options.publicKey;
if (!user.name) {
// Preserve original format: use friendlyName if provided, otherwise fetch fallback
// This maintains backward compatibility with the ${user.id}:${name} format
const nameToUse = friendlyName;
if (!nameToUse) {
// Only fetch user data if friendlyName is not provided (bug fix for null friendlyName)
const currentUser = await this.client.getUser();
const userData = currentUser.data.user;
const fallbackName = ((_a = userData === null || userData === void 0 ? void 0 : userData.user_metadata) === null || _a === void 0 ? void 0 : _a.name) || (userData === null || userData === void 0 ? void 0 : userData.email) || (userData === null || userData === void 0 ? void 0 : userData.id) || 'User';
user.name = `${user.id}:${fallbackName}`;
}
else {
user.name = `${user.id}:${nameToUse}`;
}
}
if (!user.displayName) {
user.displayName = user.name;
}
}
switch (challengeResponse.webauthn.type) {
case 'create': {
const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create);
const { data, error } = await createCredential({
publicKey: options,
signal: abortSignal,
});
if (data) {
return {
data: {
factorId,
challengeId: challengeResponse.id,
webauthn: {
type: challengeResponse.webauthn.type,
credential_response: data,
},
},
error: null,
};
}
return { data: null, error };
}
case 'request': {
const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request);
const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal }));
if (data) {
return {
data: {
factorId,
challengeId: challengeResponse.id,
webauthn: {
type: challengeResponse.webauthn.type,
credential_response: data,
},
},
error: null,
};
}
return { data: null, error };
}
}
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
return {
data: null,
error: new errors_1.AuthUnknownError('Unexpected error in challenge', error),
};
}
}
/**
* Verify a WebAuthn credential with the server.
* Completes the WebAuthn ceremony by sending the credential to the server for verification.
*
* @experimental This method is experimental and may change in future releases
* @param {Object} params - Verification parameters
* @param {string} params.challengeId - ID of the challenge being verified
* @param {string} params.factorId - ID of the WebAuthn factor
* @param {MFAVerifyWebauthnParams<T>['webauthn']} params.webauthn - WebAuthn credential response
* @returns {Promise<AuthMFAVerifyResponse>} Verification result with session or error
* @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion}
* */
async _verify({ challengeId, factorId, webauthn, }) {
return this.client.mfa.verify({
factorId,
challengeId,
webauthn: webauthn,
});
}
/**
* Complete WebAuthn authentication flow.
* Performs challenge and verification in a single operation for existing credentials.
*
* @experimental This method is experimental and may change in future releases
* @param {Object} params - Authentication parameters
* @param {string} params.factorId - ID of the WebAuthn factor to authenticate with
* @param {Object} params.webauthn - WebAuthn configuration
* @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname)
* @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin)
* @param {AbortSignal} params.webauthn.signal - Optional abort signal
* @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get
* @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Authentication result
* @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions}
*/
async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) {
if (!rpId) {
return {
data: null,
error: new errors_1.AuthError('rpId is required for WebAuthn authentication'),
};
}
try {
if (!browserSupportsWebAuthn()) {
return {
data: null,
error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null),
};
}
// Get challenge and credential
const { data: challengeResponse, error: challengeError } = await this.challenge({
factorId,
webauthn: { rpId, rpOrigins },
signal,
}, { request: overrides });
if (!challengeResponse) {
return { data: null, error: challengeError };
}
const { webauthn } = challengeResponse;
// Verify credential
return this._verify({
factorId,
challengeId: challengeResponse.challengeId,
webauthn: {
type: webauthn.type,
rpId,
rpOrigins,
credential_response: webauthn.credential_response,
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
return {
data: null,
error: new errors_1.AuthUnknownError('Unexpected error in authenticate', error),
};
}
}
/**
* Complete WebAuthn registration flow.
* Performs enrollment, challenge, and verification in a single operation for new credentials.
*
* @experimental This method is experimental and may change in future releases
* @param {Object} params - Registration parameters
* @param {string} params.friendlyName - User-friendly name for the credential
* @param {string} params.rpId - Relying Party ID (defaults to current hostname)
* @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin)
* @param {AbortSignal} params.signal - Optional abort signal
* @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create
* @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Registration result
* @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions}
*/
async _register({ friendlyName, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) {
if (!rpId) {
return {
data: null,
error: new errors_1.AuthError('rpId is required for WebAuthn registration'),
};
}
try {
if (!browserSupportsWebAuthn()) {
return {
data: null,
error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null),
};
}
// Enroll factor
const { data: factor, error: enrollError } = await this._enroll({
friendlyName,
});
if (!factor) {
await this.client.mfa
.listFactors()
.then((factors) => {
var _a;
return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' &&
v.friendly_name === friendlyName &&
v.status !== 'unverified');
})
.then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0));
return { data: null, error: enrollError };
}
// Get challenge and create credential
const { data: challengeResponse, error: challengeError } = await this._challenge({
factorId: factor.id,
friendlyName: factor.friendly_name,
webauthn: { rpId, rpOrigins },
signal,
}, {
create: overrides,
});
if (!challengeResponse) {
return { data: null, error: challengeError };
}
return this._verify({
factorId: factor.id,
challengeId: challengeResponse.challengeId,
webauthn: {
rpId,
rpOrigins,
type: challengeResponse.webauthn.type,
credential_response: challengeResponse.webauthn.credential_response,
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
return {
data: null,
error: new errors_1.AuthUnknownError('Unexpected error in register', error),
};
}
}
}
exports.WebAuthnApi = WebAuthnApi;
//# sourceMappingURL=webauthn.js.map
File diff suppressed because one or more lines are too long