wip:milestone 0 fixes
Some checks failed
CI/CD Pipeline / unit-tests (push) Failing after 1m16s
CI/CD Pipeline / integration-tests (push) Failing after 2m32s
CI/CD Pipeline / lint (push) Successful in 5m22s
CI/CD Pipeline / e2e-tests (push) Has been skipped
CI/CD Pipeline / build (push) Has been skipped

This commit is contained in:
2026-03-15 12:35:42 +02:00
parent 6708cf28a7
commit cffdf8af86
61266 changed files with 4511646 additions and 1938 deletions

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Supabase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,190 @@
<br />
<p align="center">
<a href="https://supabase.io">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/supabase/supabase/master/packages/common/assets/images/supabase-logo-wordmark--dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/supabase/supabase/master/packages/common/assets/images/supabase-logo-wordmark--light.svg">
<img alt="Supabase Logo" width="300" src="https://raw.githubusercontent.com/supabase/supabase/master/packages/common/assets/images/logo-preview.jpg">
</picture>
</a>
<h1 align="center">Supabase Auth JS SDK</h1>
<h3 align="center">An isomorphic JavaScript SDK for the <a href="https://github.com/supabase/auth">Supabase Auth</a> API.</h3>
<p align="center">
<a href="https://supabase.com/docs/guides/auth">Guides</a>
·
<a href="https://supabase.com/docs/reference/javascript/auth-signup">Reference Docs</a>
·
<a href="https://supabase.github.io/supabase-js/auth-js/v2/spec.json">TypeDoc</a>
</p>
</p>
<div align="center">
[![Build](https://github.com/supabase/supabase-js/workflows/CI/badge.svg)](https://github.com/supabase/supabase-js/actions?query=branch%3Amaster)
[![Package](https://img.shields.io/npm/v/@supabase/auth-js)](https://www.npmjs.com/package/@supabase/auth-js)
[![License: MIT](https://img.shields.io/npm/l/@supabase/supabase-js)](#license)
[![pkg.pr.new](https://pkg.pr.new/badge/supabase/auth-js)](https://pkg.pr.new/~/supabase/auth-js)
</div>
## Requirements
- **Node.js 20 or later** (Node.js 18 support dropped as of October 31, 2025)
- For browser support, all modern browsers are supported
> ⚠️ **Node.js 18 Deprecation Notice**
>
> Node.js 18 reached end-of-life on April 30, 2025. As announced in [our deprecation notice](https://github.com/orgs/supabase/discussions/37217), support for Node.js 18 was dropped on October 31, 2025.
## Quick start
Install
```bash
npm install --save @supabase/auth-js
```
Usage
```js
import { AuthClient } from '@supabase/auth-js'
const GOTRUE_URL = 'http://localhost:9999'
const auth = new AuthClient({ url: GOTRUE_URL })
```
- `signUp()`: https://supabase.com/docs/reference/javascript/auth-signup
- `signIn()`: https://supabase.com/docs/reference/javascript/auth-signin
- `signOut()`: https://supabase.com/docs/reference/javascript/auth-signout
### Custom `fetch` implementation
`auth-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers:
```js
import { AuthClient } from '@supabase/auth-js'
const AUTH_URL = 'http://localhost:9999'
const auth = new AuthClient({ url: AUTH_URL, fetch: fetch })
```
## Development
This package is part of the [Supabase JavaScript monorepo](https://github.com/supabase/supabase-js). To work on this package:
### Building
```bash
# Complete build (from monorepo root)
npx nx build auth-js
# Build with watch mode for development
npx nx build auth-js --watch
# Individual build targets
npx nx build:main auth-js # CommonJS build (dist/main/)
npx nx build:module auth-js # ES Modules build (dist/module/)
# Other useful commands
npx nx lint auth-js # Run ESLint
npx nx typecheck auth-js # TypeScript type checking
npx nx docs auth-js # Generate documentation
```
#### Build Outputs
- **CommonJS (`dist/main/`)** - For Node.js environments
- **ES Modules (`dist/module/`)** - For modern bundlers (Webpack, Vite, Rollup)
- **TypeScript definitions (`dist/module/index.d.ts`)** - Type definitions for TypeScript projects
### Testing
The auth-js package has two test suites:
1. **CLI Tests** - Main test suite using Supabase CLI (331 tests)
2. **Docker Tests** - Edge case tests requiring specific GoTrue configurations (11 tests)
#### Prerequisites
- **Supabase CLI** - Required for main test suite ([installation guide](https://supabase.com/docs/guides/cli))
- **Docker** - Required for edge case tests
#### Running Tests
```bash
# Run main test suite with Supabase CLI (recommended)
npx nx test:auth auth-js
# Run Docker-only edge case tests
npx nx test:docker auth-js
# Run both test suites
npx nx test:auth auth-js && npx nx test:docker auth-js
```
#### Main Test Suite (Supabase CLI)
The `test:auth` command automatically:
1. Stops any existing Supabase instance
2. Starts a local Supabase instance via CLI
3. Runs the test suite (excludes `docker-tests/` folder)
4. Cleans up after tests complete
```bash
# Individual commands for manual control
npx nx test:infra auth-js # Start Supabase CLI
npx nx test:suite auth-js # Run tests only
npx nx test:clean-post auth-js # Stop Supabase CLI
```
#### Docker Tests (Edge Cases)
The `test:docker` target runs tests that require specific GoTrue configurations not possible with a single Supabase CLI instance:
- **Signup disabled** - Tests for disabled signup functionality
- **Asymmetric JWT (RS256)** - Tests for RS256 JWT verification
- **Phone OTP / SMS** - Tests requiring Twilio SMS provider
- **Anonymous sign-in disabled** - Tests for disabled anonymous auth
These tests are located in `test/docker-tests/` and use the Docker Compose setup in `infra/docker-compose.yml`.
```bash
# Individual commands for manual control
npx nx test:docker:infra auth-js # Start Docker containers
npx nx test:docker:suite auth-js # Run Docker tests only
npx nx test:docker:clean-post auth-js # Stop Docker containers
```
#### Development Testing
For actively developing and debugging tests:
```bash
# Start Supabase CLI once
npx nx test:infra auth-js
# Run tests multiple times (faster since instance stays up)
npx nx test:suite auth-js
# Clean up when done
npx nx test:clean-post auth-js
```
#### Test Infrastructure
| Suite | Infrastructure | Configuration |
| ------------ | -------------- | --------------------------- |
| CLI Tests | Supabase CLI | `test/supabase/config.toml` |
| Docker Tests | Docker Compose | `infra/docker-compose.yml` |
### Contributing
We welcome contributions! Please see our [Contributing Guide](../../../CONTRIBUTING.md) for details on how to get started.
For major changes or if you're unsure about something, please open an issue first to discuss your proposed changes.

View File

@@ -0,0 +1,4 @@
import GoTrueAdminApi from './GoTrueAdminApi';
declare const AuthAdminApi: typeof GoTrueAdminApi;
export default AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.d.ts.map

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"}

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

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"}

View File

@@ -0,0 +1,4 @@
import GoTrueClient from './GoTrueClient';
declare const AuthClient: typeof GoTrueClient;
export default AuthClient;
//# sourceMappingURL=AuthClient.d.ts.map

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"}

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

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"}

View File

@@ -0,0 +1,227 @@
import { Fetch } from './lib/fetch';
import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams, SignOutScope, GoTrueAdminOAuthApi, GoTrueAdminCustomProvidersApi } 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;
protected url: string;
protected headers: {
[key: string]: string;
};
protected fetch: Fetch;
/**
* Creates an admin API client that can be used to manage users and OAuth clients.
*
* @example
* ```ts
* import { GoTrueAdminApi } from '@supabase/auth-js'
*
* const admin = new GoTrueAdminApi({
* url: 'https://xyzcompany.supabase.co/auth/v1',
* headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` },
* })
* ```
*/
constructor({ url, headers, fetch, }: {
url: string;
headers?: {
[key: string]: string;
};
fetch?: Fetch;
});
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*/
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.
*/
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 email The user's email.
* @param options.password User password. For signup only.
* @param options.data Optional user metadata. For signup only.
* @param options.redirectTo The redirect url which should be appended to the generated link
*/
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.
*/
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.
*/
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.
*/
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)
*/
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.
*/
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;
}
//# sourceMappingURL=GoTrueAdminApi.d.ts.map

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,EAM9B,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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AAE,GAClE;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,EAAE,CAAA;SAAE,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,CAC5C;IAmCD;;;;;;OAMG;IACG,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAiBrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;IACG,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAkBzF;;;;;;;;OAQG;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;CAgBpC"}

View File

@@ -0,0 +1,596 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fetch_1 = require("./lib/fetch");
const helpers_1 = require("./lib/helpers");
const types_1 = require("./lib/types");
const errors_1 = require("./lib/errors");
class GoTrueAdminApi {
/**
* Creates an admin API client that can be used to manage users and OAuth clients.
*
* @example
* ```ts
* import { GoTrueAdminApi } from '@supabase/auth-js'
*
* const admin = new GoTrueAdminApi({
* url: 'https://xyzcompany.supabase.co/auth/v1',
* headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` },
* })
* ```
*/
constructor({ url = '', headers = {}, fetch, }) {
this.url = url;
this.headers = headers;
this.fetch = (0, helpers_1.resolveFetch)(fetch);
this.mfa = {
listFactors: this._listFactors.bind(this),
deleteFactor: this._deleteFactor.bind(this),
};
this.oauth = {
listClients: this._listOAuthClients.bind(this),
createClient: this._createOAuthClient.bind(this),
getClient: this._getOAuthClient.bind(this),
updateClient: this._updateOAuthClient.bind(this),
deleteClient: this._deleteOAuthClient.bind(this),
regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this),
};
this.customProviders = {
listProviders: this._listCustomProviders.bind(this),
createProvider: this._createCustomProvider.bind(this),
getProvider: this._getCustomProvider.bind(this),
updateProvider: this._updateCustomProvider.bind(this),
deleteProvider: this._deleteCustomProvider.bind(this),
};
}
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*/
async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) {
if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) {
throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(', ')}`);
}
try {
await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, {
headers: this.headers,
jwt,
noResolveJson: true,
});
return { data: null, error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async inviteUserByEmail(email, options = {}) {
try {
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, {
body: { email, data: options.data },
headers: this.headers,
redirectTo: options.redirectTo,
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Generates email links and OTPs to be sent via a custom email provider.
* @param email The user's email.
* @param options.password User password. For signup only.
* @param options.data Optional user metadata. For signup only.
* @param options.redirectTo The redirect url which should be appended to the generated link
*/
async generateLink(params) {
try {
const { options } = params, rest = tslib_1.__rest(params, ["options"]);
const body = Object.assign(Object.assign({}, rest), options);
if ('newEmail' in rest) {
// replace newEmail with new_email in request body
body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail;
delete body['newEmail'];
}
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, {
body: body,
headers: this.headers,
xform: fetch_1._generateLinkResponse,
redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return {
data: {
properties: null,
user: null,
},
error,
};
}
throw error;
}
}
// User Admin API
/**
* Creates a new user.
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async createUser(attributes) {
try {
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, {
body: attributes,
headers: this.headers,
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* 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.
*/
async listUsers(params) {
var _a, _b, _c, _d, _e, _f, _g;
try {
const pagination = { nextPage: null, lastPage: 0, total: 0 };
const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, {
headers: this.headers,
noResolveJson: true,
query: {
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
},
xform: fetch_1._noResolveJsonResponse,
});
if (response.error)
throw response.error;
const users = await response.json();
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
if (links.length > 0) {
links.forEach((link) => {
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
pagination[`${rel}Page`] = page;
});
pagination.total = parseInt(total);
}
return { data: Object.assign(Object.assign({}, users), pagination), error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { users: [] }, error };
}
throw error;
}
}
/**
* 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.
*/
async getUserById(uid) {
(0, helpers_1.validateUUID)(uid);
try {
return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, {
headers: this.headers,
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* 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)
*/
async updateUserById(uid, attributes) {
(0, helpers_1.validateUUID)(uid);
try {
return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, {
body: attributes,
headers: this.headers,
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* 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.
*/
async deleteUser(id, shouldSoftDelete = false) {
(0, helpers_1.validateUUID)(id);
try {
return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {
headers: this.headers,
body: {
should_soft_delete: shouldSoftDelete,
},
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async _listFactors(params) {
(0, helpers_1.validateUUID)(params.userId);
try {
const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, {
headers: this.headers,
xform: (factors) => {
return { data: { factors }, error: null };
},
});
return { data, error };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
async _deleteFactor(params) {
(0, helpers_1.validateUUID)(params.userId);
(0, helpers_1.validateUUID)(params.id);
try {
const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, {
headers: this.headers,
});
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _listOAuthClients(params) {
var _a, _b, _c, _d, _e, _f, _g;
try {
const pagination = { nextPage: null, lastPage: 0, total: 0 };
const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, {
headers: this.headers,
noResolveJson: true,
query: {
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
},
xform: fetch_1._noResolveJsonResponse,
});
if (response.error)
throw response.error;
const clients = await response.json();
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
if (links.length > 0) {
links.forEach((link) => {
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
pagination[`${rel}Page`] = page;
});
pagination.total = parseInt(total);
}
return { data: Object.assign(Object.assign({}, clients), pagination), error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { clients: [] }, error };
}
throw error;
}
}
/**
* 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.
*/
async _createOAuthClient(params) {
try {
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, {
body: params,
headers: this.headers,
xform: (client) => {
return { data: client, error: null };
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _getOAuthClient(clientId) {
try {
return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, {
headers: this.headers,
xform: (client) => {
return { data: client, error: null };
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _updateOAuthClient(clientId, params) {
try {
return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, {
body: params,
headers: this.headers,
xform: (client) => {
return { data: client, error: null };
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _deleteOAuthClient(clientId) {
try {
await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, {
headers: this.headers,
noResolveJson: true,
});
return { data: null, error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _regenerateOAuthClientSecret(clientId) {
try {
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, {
headers: this.headers,
xform: (client) => {
return { data: client, error: null };
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _listCustomProviders(params) {
try {
const query = {};
if (params === null || params === void 0 ? void 0 : params.type) {
query.type = params.type;
}
return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/custom-providers`, {
headers: this.headers,
query,
xform: (data) => {
var _a;
return { data: { providers: (_a = data === null || data === void 0 ? void 0 : data.providers) !== null && _a !== void 0 ? _a : [] }, error: null };
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { providers: [] }, error };
}
throw error;
}
}
/**
* 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.
*/
async _createCustomProvider(params) {
try {
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/custom-providers`, {
body: params,
headers: this.headers,
xform: (provider) => {
return { data: provider, error: null };
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _getCustomProvider(identifier) {
try {
return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/custom-providers/${identifier}`, {
headers: this.headers,
xform: (provider) => {
return { data: provider, error: null };
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _updateCustomProvider(identifier, params) {
try {
return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/custom-providers/${identifier}`, {
body: params,
headers: this.headers,
xform: (provider) => {
return { data: provider, error: null };
},
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* Deletes a custom provider.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async _deleteCustomProvider(identifier) {
try {
await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/custom-providers/${identifier}`, {
headers: this.headers,
noResolveJson: true,
});
return { data: null, error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
}
exports.default = GoTrueAdminApi;
//# sourceMappingURL=GoTrueAdminApi.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,783 @@
import GoTrueAdminApi from './GoTrueAdminApi';
import { AuthError } from './lib/errors';
import { Fetch } from './lib/fetch';
import { Deferred } from './lib/helpers';
import type { AuthChangeEvent, AuthFlowType, AuthOtpResponse, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, CallRefreshTokenResult, GoTrueClientOptions, GoTrueMFAApi, InitializeResult, JWK, JwtHeader, JwtPayload, LockFunc, OAuthResponse, AuthOAuthServerApi, ResendParams, Session, SignInAnonymouslyCredentials, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignInWithSSO, SignOut, SignUpWithPasswordCredentials, SSOResponse, Subscription, SupportedStorage, User, UserAttributes, UserIdentity, UserResponse, VerifyOtpParams, Web3Credentials } from './lib/types';
export default class GoTrueClient {
private static nextInstanceID;
private instanceID;
/**
* Namespace for the GoTrue admin methods.
* These methods should only be used in a trusted server-side environment.
*/
admin: GoTrueAdminApi;
/**
* Namespace for the MFA methods.
*/
mfa: GoTrueMFAApi;
/**
* Namespace for the OAuth 2.1 authorization server methods.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
* Used to implement the authorization code flow on the consent page.
*/
oauth: AuthOAuthServerApi;
/**
* The storage key used to identify the values saved in localStorage
*/
protected storageKey: string;
protected flowType: AuthFlowType;
/**
* The JWKS used for verifying asymmetric JWTs
*/
protected get jwks(): {
keys: JWK[];
};
protected set jwks(value: {
keys: JWK[];
});
protected get jwks_cached_at(): number;
protected set jwks_cached_at(value: number);
protected autoRefreshToken: boolean;
protected persistSession: boolean;
protected storage: SupportedStorage;
/**
* @experimental
*/
protected userStorage: SupportedStorage | null;
protected memoryStorage: {
[key: string]: string;
} | null;
protected stateChangeEmitters: Map<string | symbol, Subscription>;
protected autoRefreshTicker: ReturnType<typeof setInterval> | null;
protected autoRefreshTickTimeout: ReturnType<typeof setTimeout> | null;
protected visibilityChangedCallback: (() => Promise<any>) | null;
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null;
/**
* Keeps track of the async client initialization.
* When null or not yet resolved the auth state is `unknown`
* Once resolved the auth state is known and it's safe to call any further client methods.
* Keep extra care to never reject or throw uncaught errors
*/
protected initializePromise: Promise<InitializeResult> | null;
protected detectSessionInUrl: boolean | ((url: URL, params: {
[parameter: string]: string;
}) => boolean);
protected url: string;
protected headers: {
[key: string]: string;
};
protected hasCustomAuthorizationHeader: boolean;
protected suppressGetSessionWarning: boolean;
protected fetch: Fetch;
protected lock: LockFunc;
protected lockAcquired: boolean;
protected pendingInLock: Promise<any>[];
protected throwOnError: boolean;
protected lockAcquireTimeout: number;
/**
* Used to broadcast state change events to other tabs listening.
*/
protected broadcastChannel: BroadcastChannel | null;
protected logDebugMessages: boolean;
protected logger: (message: string, ...args: any[]) => void;
/**
* Create a new client for use in the browser.
*
* @example
* ```ts
* import { GoTrueClient } from '@supabase/auth-js'
*
* const auth = new GoTrueClient({
* url: 'https://xyzcompany.supabase.co/auth/v1',
* headers: { apikey: 'public-anon-key' },
* storageKey: 'supabase-auth',
* })
* ```
*/
constructor(options: GoTrueClientOptions);
/**
* Returns whether error throwing mode is enabled for this client.
*/
isThrowOnErrorEnabled(): boolean;
/**
* Centralizes return handling with optional error throwing. When `throwOnError` is enabled
* and the provided result contains a non-nullish error, the error is thrown instead of
* being returned. This ensures consistent behavior across all public API methods.
*/
private _returnResult;
private _logPrefix;
private _debug;
/**
* Initializes the client session either from the url or from storage.
* This method is automatically called when instantiating the client, but should also be called
* manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
*/
initialize(): Promise<InitializeResult>;
/**
* IMPORTANT:
* 1. Never throw in this method, as it is called from the constructor
* 2. Never return a session from this method as it would be cached over
* the whole lifetime of the client
*/
private _initialize;
/**
* Creates a new anonymous user.
*
* @returns A session where the is_anonymous claim in the access token JWT set to true
*/
signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>;
/**
* Creates a new user.
*
* Be aware that if a user account exists in the system you may get back an
* error message that attempts to hide this information from the user.
* This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*
* @category Auth
*
* @remarks
* - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers).
* - **Confirm email** determines if users need to confirm their email address after signing up.
* - If **Confirm email** is enabled, a `user` is returned but `session` is null.
* - If **Confirm email** is disabled, both a `user` and a `session` are returned.
* - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration).
* - If signUp() is called for an existing confirmed user:
* - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned.
* - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned.
* - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser).
*
* @example Sign up with an email and password
* ```js
* const { data, error } = await supabase.auth.signUp({
* email: 'example@email.com',
* password: 'example-password',
* })
* ```
*
* @exampleResponse Sign up with an email and password
* ```json
* // Some fields may be null if "confirm email" is enabled.
* {
* "data": {
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_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"
* },
* "session": {
* "access_token": "<ACCESS_TOKEN>",
* "token_type": "bearer",
* "expires_in": 3600,
* "expires_at": 1700000000,
* "refresh_token": "<REFRESH_TOKEN>",
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_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"
* }
* }
* },
* "error": null
* }
* ```
*
* @example Sign up with a phone number and password (SMS)
* ```js
* const { data, error } = await supabase.auth.signUp({
* phone: '123456789',
* password: 'example-password',
* options: {
* channel: 'sms'
* }
* })
* ```
*
* @exampleDescription Sign up with a phone number and password (whatsapp)
* The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.
*
* @example Sign up with a phone number and password (whatsapp)
* ```js
* const { data, error } = await supabase.auth.signUp({
* phone: '123456789',
* password: 'example-password',
* options: {
* channel: 'whatsapp'
* }
* })
* ```
*
* @example Sign up with additional user metadata
* ```js
* const { data, error } = await supabase.auth.signUp(
* {
* email: 'example@email.com',
* password: 'example-password',
* options: {
* data: {
* first_name: 'John',
* age: 27,
* }
* }
* }
* )
* ```
*
* @exampleDescription Sign up with a redirect URL
* - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.
*
* @example Sign up with a redirect URL
* ```js
* const { data, error } = await supabase.auth.signUp(
* {
* email: 'example@email.com',
* password: 'example-password',
* options: {
* emailRedirectTo: 'https://example.com/welcome'
* }
* }
* )
* ```
*/
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;
/**
* Log in an existing user with an email and password or phone and password.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or that the
* email/phone and password combination is wrong or that the account can only
* be accessed via social login.
*/
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>;
/**
* Log in an existing user via a third-party provider.
* This method supports the PKCE flow.
*/
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
*/
exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse>;
/**
* Signs in a user by verifying a message signed by the user's private key.
* Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards,
* both of which derive from the EIP-4361 standard
* With slight variation on Solana's side.
* @reference https://eips.ethereum.org/EIPS/eip-4361
*/
signInWithWeb3(credentials: Web3Credentials): Promise<{
data: {
session: Session;
user: User;
};
error: null;
} | {
data: {
session: null;
user: null;
};
error: AuthError;
}>;
private signInWithEthereum;
private signInWithSolana;
private _exchangeCodeForSession;
/**
* Allows signing in with an OIDC ID token. The authentication provider used
* should be enabled and configured.
*/
signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
/**
* Log in a user using magiclink or a one-time password (OTP).
*
* If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
* If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
* If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or, that the account
* can only be accessed via social login.
*
* Do note that you will need to configure a Whatsapp sender on Twilio
* if you are using phone sign in with the 'whatsapp' channel. The whatsapp
* channel is not supported on other providers
* at this time.
* This method supports PKCE when an email is passed.
*/
signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>;
/**
* Log in a user given a User supplied OTP or TokenHash received through mobile or email.
*/
verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>;
/**
* Attempts a single-sign on using an enterprise Identity Provider. A
* successful SSO attempt will redirect the current page to the identity
* provider authorization page. The redirect URL is implementation and SSO
* protocol specific.
*
* You can use it by providing a SSO domain. Typically you can extract this
* domain by asking users for their email address. If this domain is
* registered on the Auth instance the redirect will use that organization's
* currently active SSO Identity Provider for the login.
*
* If you have built an organization-specific login page, you can use the
* organization's SSO Identity Provider UUID directly instead.
*/
signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>;
/**
* Sends a reauthentication OTP to the user's email or phone number.
* Requires the user to be signed-in.
*/
reauthenticate(): Promise<AuthResponse>;
private _reauthenticate;
/**
* Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
*/
resend(credentials: ResendParams): Promise<AuthOtpResponse>;
/**
* Returns the session, refreshing it if necessary.
*
* The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
*
* **IMPORTANT:** This method loads values directly from the storage attached
* to the client. If that storage is based on request cookies for example,
* the values in it may not be authentic and therefore it's strongly advised
* against using this method and its results in such circumstances. A warning
* will be emitted if this is detected. Use {@link #getUser()} instead.
*/
getSession(): Promise<{
data: {
session: Session;
};
error: null;
} | {
data: {
session: null;
};
error: AuthError;
} | {
data: {
session: null;
};
error: null;
}>;
/**
* Acquires a global lock based on the storage key.
*/
private _acquireLock;
/**
* Use instead of {@link #getSession} inside the library. It is
* semantically usually what you want, as getting a session involves some
* processing afterwards that requires only one client operating on the
* session at once across multiple tabs or processes.
*/
private _useSession;
/**
* NEVER USE DIRECTLY!
*
* Always use {@link #_useSession}.
*/
private __loadSession;
/**
* Gets the current user details if there is an existing session. This method
* performs a network request to the Supabase Auth server, so the returned
* value is authentic and can be used to base authorization rules on.
*
* @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.
*/
getUser(jwt?: string): Promise<UserResponse>;
private _getUser;
/**
* Updates user data for a logged in user.
*/
updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
protected _updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
/**
* Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
* If the refresh token or access token in the current session is invalid, an error will be thrown.
* @param currentSession The current session that minimally contains an access token and refresh token.
*/
setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
protected _setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Returns a new session, regardless of expiry status.
* Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
* If the current session's refresh token is invalid, an error will be thrown.
* @param currentSession The current session. If passed in, it must contain a refresh token.
*/
refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
protected _refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Gets the session data from a URL string
*/
private _getSessionFromURL;
/**
* Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
*
* If `detectSessionInUrl` is a function, it will be called with the URL and params to determine
* if the URL should be processed as a Supabase auth callback. This allows users to exclude
* URLs from other OAuth providers (e.g., Facebook Login) that also return access_token in the fragment.
*/
private _isImplicitGrantCallback;
/**
* Checks if the current URL and backing storage contain parameters given by a PKCE flow
*/
private _isPKCECallback;
/**
* Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event.
*
* For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.
* There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
*
* If using `others` scope, no `SIGNED_OUT` event is fired!
*/
signOut(options?: SignOut): Promise<{
error: AuthError | null;
}>;
protected _signOut({ scope }?: SignOut): Promise<{
error: AuthError | null;
}>;
/**
* Receive a notification every time an auth event happens.
* Safe to use without an async function as callback.
*
* @param callback A callback function to be invoked when an auth event happens.
*/
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void): {
data: {
subscription: Subscription;
};
};
/**
* Avoid using an async function inside `onAuthStateChange` as you might end
* up with a deadlock. The callback function runs inside an exclusive lock,
* so calling other Supabase Client APIs that also try to acquire the
* exclusive lock, might cause a deadlock. This behavior is observable across
* tabs. In the next major library version, this behavior will not be supported.
*
* Receive a notification every time an auth event happens.
*
* @param callback A callback function to be invoked when an auth event happens.
* @deprecated Due to the possibility of deadlocks with async functions as callbacks, use the version without an async function.
*/
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => Promise<void>): {
data: {
subscription: Subscription;
};
};
private _emitInitialSession;
/**
* Sends a password reset request to an email address. This method supports the PKCE flow.
*
* @param email The email address of the user.
* @param options.redirectTo The URL to send the user to after they click the password reset link.
* @param options.captchaToken Verification token received when the user completes the captcha on the site.
*/
resetPasswordForEmail(email: string, options?: {
redirectTo?: string;
captchaToken?: string;
}): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Gets all the identities linked to a user.
*/
getUserIdentities(): Promise<{
data: {
identities: UserIdentity[];
};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Links an oauth identity to an existing user.
* This method supports the PKCE flow.
*/
linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Links an OIDC identity to an existing user.
*/
linkIdentity(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
private linkIdentityOAuth;
private linkIdentityIdToken;
/**
* Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
*/
unlinkIdentity(identity: UserIdentity): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Generates a new JWT.
* @param refreshToken A valid refresh token that was returned on login.
*/
private _refreshAccessToken;
private _isValidSession;
private _handleProviderSignIn;
/**
* Recovers the session from LocalStorage and refreshes the token
* Note: this method is async to accommodate for AsyncStorage e.g. in React native.
*/
private _recoverAndRefresh;
private _callRefreshToken;
private _notifyAllSubscribers;
/**
* set currentSession and currentUser
* process to _startAutoRefreshToken if possible
*/
private _saveSession;
private _removeSession;
/**
* Removes any registered visibilitychange callback.
*
* {@see #startAutoRefresh}
* {@see #stopAutoRefresh}
*/
private _removeVisibilityChangedCallback;
/**
* This is the private implementation of {@link #startAutoRefresh}. Use this
* within the library.
*/
private _startAutoRefresh;
/**
* This is the private implementation of {@link #stopAutoRefresh}. Use this
* within the library.
*/
private _stopAutoRefresh;
/**
* Starts an auto-refresh process in the background. The session is checked
* every few seconds. Close to the time of expiration a process is started to
* refresh the session. If refreshing fails it will be retried for as long as
* necessary.
*
* If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
* to call this function, it will be called for you.
*
* On browsers the refresh process works only when the tab/window is in the
* foreground to conserve resources as well as prevent race conditions and
* flooding auth with requests. If you call this method any managed
* visibility change callback will be removed and you must manage visibility
* changes on your own.
*
* On non-browser platforms the refresh process works *continuously* in the
* background, which may not be desirable. You should hook into your
* platform's foreground indication mechanism and call these methods
* appropriately to conserve resources.
*
* {@see #stopAutoRefresh}
*/
startAutoRefresh(): Promise<void>;
/**
* Stops an active auto refresh process running in the background (if any).
*
* If you call this method any managed visibility change callback will be
* removed and you must manage visibility changes on your own.
*
* See {@link #startAutoRefresh} for more details.
*/
stopAutoRefresh(): Promise<void>;
/**
* Runs the auto refresh token tick.
*/
private _autoRefreshTokenTick;
/**
* Registers callbacks on the browser / platform, which in-turn run
* algorithms when the browser window/tab are in foreground. On non-browser
* platforms it assumes always foreground.
*/
private _handleVisibilityChange;
/**
* Callback registered with `window.addEventListener('visibilitychange')`.
*/
private _onVisibilityChanged;
/**
* Generates the relevant login URL for a third-party provider.
* @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param options.scopes A space-separated list of scopes granted to the OAuth application.
* @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
*/
private _getUrlForProvider;
private _unenroll;
/**
* {@see GoTrueMFAApi#enroll}
*/
private _enroll;
/**
* {@see GoTrueMFAApi#verify}
*/
private _verify;
/**
* {@see GoTrueMFAApi#challenge}
*/
private _challenge;
/**
* {@see GoTrueMFAApi#challengeAndVerify}
*/
private _challengeAndVerify;
/**
* {@see GoTrueMFAApi#listFactors}
*/
private _listFactors;
/**
* {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
*/
private _getAuthenticatorAssuranceLevel;
/**
* Retrieves details about an OAuth authorization request.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*
* Returns authorization details including client info, scopes, and user information.
* If the response includes only a redirect_url field, it means consent was already given - the caller
* should handle the redirect manually if needed.
*/
private _getAuthorizationDetails;
/**
* Approves an OAuth authorization request.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
private _approveAuthorization;
/**
* Denies an OAuth authorization request.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
private _denyAuthorization;
/**
* Lists all OAuth grants that the authenticated user has authorized.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
private _listOAuthGrants;
/**
* Revokes a user's OAuth grant for a specific client.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
private _revokeOAuthGrant;
private fetchJwk;
/**
* Extracts the JWT claims present in the access token by first verifying the
* JWT against the server's JSON Web Key Set endpoint
* `/.well-known/jwks.json` which is often cached, resulting in significantly
* faster responses. Prefer this method over {@link #getUser} which always
* sends a request to the Auth server for each JWT.
*
* If the project is not using an asymmetric JWT signing key (like ECC or
* RSA) it always sends a request to the Auth server (similar to {@link
* #getUser}) to verify the JWT.
*
* @param jwt An optional specific JWT you wish to verify, not the one you
* can obtain from {@link #getSession}.
* @param options Various additional options that allow you to customize the
* behavior of this method.
*/
getClaims(jwt?: string, options?: {
/**
* @deprecated Please use options.jwks instead.
*/
keys?: JWK[];
/** If set to `true` the `exp` claim will not be validated against the current time. */
allowExpired?: boolean;
/** If set, this JSON Web Key Set is going to have precedence over the cached value available on the server. */
jwks?: {
keys: JWK[];
};
}): Promise<{
data: {
claims: JwtPayload;
header: JwtHeader;
signature: Uint8Array;
};
error: null;
} | {
data: null;
error: AuthError;
} | {
data: null;
error: null;
}>;
}
//# sourceMappingURL=GoTrueClient.d.ts.map

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

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

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"}

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

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"}

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

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"}

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

View File

@@ -0,0 +1,26 @@
/** 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;
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

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,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"}

View File

@@ -0,0 +1,31 @@
"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.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;
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

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;AAE9E,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"}

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

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"}

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=error-codes.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"error-codes.js","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,243 @@
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 #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);
}
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;
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;
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;
/**
* 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[]);
}
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

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,CAA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,qBAAqB,CAEtF;AAED;;;;;;;;;GASG;AACH,qBAAa,mBAAoB,SAAQ,eAAe;gBAC1C,OAAO,EAAE,MAAM;CAG5B"}

View File

@@ -0,0 +1,289 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = 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.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;
}
}
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 {
name: this.name,
message: this.message,
status: this.status,
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 {
name: this.name,
message: this.message,
status: this.status,
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';
}
/**
* 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;
}
}
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

View File

@@ -0,0 +1 @@
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":";;;AAmCA,kCAEC;AAuBD,wCAEC;AA+DD,8DAEC;AAgED,4EAIC;AAwDD,gFAIC;AAkBD,8DAEC;AA8BD,0DAEC;AAhTD;;;;;;;;;GASG;AACH,MAAa,SAAU,SAAQ,KAAK;IAclC,YAAY,OAAe,EAAE,MAAe,EAAE,IAAa;QACzD,KAAK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,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;CACF;AAXD,sDAWC;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"}

View File

@@ -0,0 +1,34 @@
import { AuthResponse, AuthResponsePassword, SSOResponse, GenerateLinkResponse, UserResponse } from './types';
export type Fetch = typeof fetch;
export interface FetchOptions {
headers?: {
[key: string]: string;
};
noResolveJson?: boolean;
}
export interface FetchParameters {
signal?: AbortSignal;
}
export type RequestMethodType = 'GET' | 'POST' | 'PUT' | '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: any): AuthResponse;
export declare function _sessionResponsePassword(data: any): AuthResponsePassword;
export declare function _userResponse(data: any): UserResponse;
export declare function _ssoResponse(data: any): SSOResponse;
export declare function _generateLinkResponse(data: any): GenerateLinkResponse;
export declare function _noResolveJsonResponse(data: any): Response;
export {};
//# sourceMappingURL=fetch.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib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;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAmBrE;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,GAAG,GAAG,QAAQ,CAE1D"}

View File

@@ -0,0 +1,184 @@
"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) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
const NETWORK_ERROR_CODES = [502, 503, 504];
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) {
console.error(e);
// fetch failed, likely due to a network or CORS error
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);
}
}
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
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

View File

@@ -0,0 +1,91 @@
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'): RsaHashedImportParams | EcKeyImportParams;
export declare function validateUUID(str: string): 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 {};
//# sourceMappingURL=helpers.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAE5C,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAE3C;AAED,eAAO,MAAM,SAAS,eAAyE,CAAA;AAO/F;;GAEG;AACH,eAAO,MAAM,oBAAoB,eAmChC,CAAA;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM;;EAsBlD;AAED,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,GAAI,cAAc,KAAK,KAAG,KAKlD,CAAA;AAED,eAAO,MAAM,sBAAsB,GAAI,eAAe,OAAO,KAAG,aAAa,IAAI,QAShF,CAAA;AAGD,eAAO,MAAM,YAAY,GACvB,SAAS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D,wBAAgB,oBAAoB,WAcnC;AAaD,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,mBAc3D;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,gBAAgB,EACzB,UAAU,EAAE,MAAM,EAClB,kBAAkB,UAAQ,qBAW3B;AAKD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,eAiBzD;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,QAQtC;AAED,wBAAgB,YAAY,CAC1B,GAAG,EAAE,OAAO,GAAG,OAAO,GAAG,OAAO,GAC/B,qBAAqB,GAAG,iBAAiB,CAgB3C;AAID,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,QAIvC;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"}

View File

@@ -0,0 +1,395 @@
"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.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) {
return value;
}
};
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 += '/PASSWORD_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 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

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

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"}

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

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"}

View File

@@ -0,0 +1,107 @@
/**
* @experimental
*/
export declare const internals: {
/**
* @experimental
*/
debug: boolean;
};
/**
* An error thrown when a lock cannot be acquired after some amount of time.
*
* Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.
*
* @example
* ```ts
* import { LockAcquireTimeoutError } from '@supabase/auth-js'
*
* class CustomLockError extends LockAcquireTimeoutError {
* constructor() {
* super('Lock timed out')
* }
* }
* ```
*/
export declare abstract class LockAcquireTimeoutError extends Error {
readonly isAcquireTimeout = true;
constructor(message: string);
}
/**
* Error thrown when the browser Navigator Lock API fails to acquire a lock.
*
* @example
* ```ts
* import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js'
*
* throw new NavigatorLockAcquireTimeoutError('Lock timed out')
* ```
*/
export declare class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
/**
* Error thrown when the process-level lock helper cannot acquire a lock.
*
* @example
* ```ts
* import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js'
*
* throw new ProcessLockAcquireTimeoutError('Lock timed out')
* ```
*/
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.
* @example
* ```ts
* await navigatorLock('sync-user', 1000, async () => {
* await refreshSession()
* })
* ```
*/
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.
* @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

View File

@@ -0,0 +1 @@
{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB;;OAEG;;CAOJ,CAAA;AAED;;;;;;;;;;;;;;;GAeG;AACH,8BAAsB,uBAAwB,SAAQ,KAAK;IACzD,SAAgB,gBAAgB,QAAO;gBAE3B,OAAO,EAAE,MAAM;CAG5B;AAED;;;;;;;;;GASG;AACH,qBAAa,gCAAiC,SAAQ,uBAAuB;CAAG;AAChF;;;;;;;;;GASG;AACH,qBAAa,8BAA+B,SAAQ,uBAAuB;CAAG;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;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,CAiKZ;AAID;;;;;;;;;;;;;;;;;;;GAmBG;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"}

View File

@@ -0,0 +1,314 @@
"use strict";
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");
/**
* @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.
*
* Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.
*
* @example
* ```ts
* import { LockAcquireTimeoutError } from '@supabase/auth-js'
*
* class CustomLockError extends LockAcquireTimeoutError {
* constructor() {
* super('Lock timed out')
* }
* }
* ```
*/
class LockAcquireTimeoutError extends Error {
constructor(message) {
super(message);
this.isAcquireTimeout = true;
}
}
exports.LockAcquireTimeoutError = LockAcquireTimeoutError;
/**
* Error thrown when the browser Navigator Lock API fails to acquire a lock.
*
* @example
* ```ts
* import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js'
*
* throw new NavigatorLockAcquireTimeoutError('Lock timed out')
* ```
*/
class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError;
/**
* Error thrown when the process-level lock helper cannot acquire a lock.
*
* @example
* ```ts
* import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js'
*
* throw new ProcessLockAcquireTimeoutError('Lock timed out')
* ```
*/
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.
* @example
* ```ts
* await navigatorLock('sync-user', 1000, async () => {
* await refreshSession()
* })
* ```
*/
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();
if (acquireTimeout > 0) {
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) {
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');
return await fn();
}
}
});
}
catch (e) {
if ((e === null || e === void 0 ? void 0 : e.name) === 'AbortError' && acquireTimeout > 0) {
// 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();
}
}));
}
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.
* @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 && e.isAcquireTimeout) {
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 && e.isAcquireTimeout) {
// 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

View File

@@ -0,0 +1,5 @@
/**
* https://mathiasbynens.be/notes/globalthis
*/
export declare function polyfillGlobalThis(): void;
//# sourceMappingURL=polyfills.d.ts.map

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"}

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

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

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

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":";;;AAkLA,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;AAspBtE,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,UAAU,CAAU,CAAA;AAmiBvC,QAAA,eAAe,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAA"}

View File

@@ -0,0 +1,2 @@
export declare const version = "2.99.1";
//# sourceMappingURL=version.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"}

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.99.1';
//# sourceMappingURL=version.js.map

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,QAAQ,CAAA"}

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;
//# sourceM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O,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"}

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

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,EACN,cA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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"}

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

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,OAAO,EAAE,MA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AAa,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"}

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

View File

@@ -0,0 +1 @@
{"version":3,"file":"solana.js","sourceRoot":"","sources":["../../../../src/lib/web3/solana.ts"],"names":[],"mappings":";AAAA,2HAA2H"}

View File

@@ -0,0 +1,276 @@
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;
/**
* 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

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,sBAA6B,CAAA;AAE9D;;;GAGG;AACH,MAAM,MAAM,+BAA+B,GAAG,sCAAsC,CAAA;AAEpF;;;GAGG;AACH,MAAM,MAAM,8BAA8B,GAAG,qCAAqC,CAAA;AAElF;;;;;;;;GAQG;AACH,wBAAgB,oCAAoC,CAClD,OAAO,EAAE,+BAA+B,GACvC,wCAAwC,CA0D1C;AAED;;;;;;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ationOptions 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';
/**
* 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';
/**
* 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';
//# sourceMappingURL=webauthn.dom.d.ts.map

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;IAC/B;;;OAGG;IACH,IAAI,EAAE,iCAAiC,CAAA;IACvC;;;OAGG;IACH,SAAS,EAAE,eAAe,CAAA;IAC1B;;;OAGG;IACH,gBAAgB,EAAE,6BAA6B,EAAE,CAAA;IACjD;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,iCAAiC,EAAE,CAAA;IACxD;;;OAGG;IACH,sBAAsB,CAAC,EAAE,8BAA8B,CAAA;IACvD;;;OAG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AG,UAAU,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA;AAEzD;;;;;;;GAOG;AACH,MAAM,MAAM,uBAAuB,GAAG,gBAAgB,GAAG,UAAU,CAAA"}

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

View File

@@ -0,0 +1 @@
{"version":3,"file":"webauthn.dom.js","sourceRoot":"","sources":["../../../src/lib/webauthn.dom.ts"],"names":[],"mappings":";AAAA,oGAAoG"}

View File

@@ -0,0 +1,80 @@
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;
});
}
/**
* 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

View File

@@ -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;CAMF;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"}

View File

@@ -0,0 +1,265 @@
"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;
}
}
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

View File

@@ -0,0 +1,706 @@
"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.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

View File

@@ -0,0 +1,4 @@
import GoTrueAdminApi from './GoTrueAdminApi';
declare const AuthAdminApi: typeof GoTrueAdminApi;
export default AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.d.ts.map

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"}

View File

@@ -0,0 +1,4 @@
import GoTrueAdminApi from './GoTrueAdminApi';
const AuthAdminApi = GoTrueAdminApi;
export default AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AuthAdminApi.js","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,MAAM,YAAY,GAAG,cAAc,CAAA;AAEnC,eAAe,YAAY,CAAA"}

View File

@@ -0,0 +1,4 @@
import GoTrueClient from './GoTrueClient';
declare const AuthClient: typeof GoTrueClient;
export default AuthClient;
//# sourceMappingURL=AuthClient.d.ts.map

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"}

View File

@@ -0,0 +1,4 @@
import GoTrueClient from './GoTrueClient';
const AuthClient = GoTrueClient;
export default AuthClient;
//# sourceMappingURL=AuthClient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AuthClient.js","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,MAAM,UAAU,GAAG,YAAY,CAAA;AAE/B,eAAe,UAAU,CAAA"}

View File

@@ -0,0 +1,227 @@
import { Fetch } from './lib/fetch';
import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams, SignOutScope, GoTrueAdminOAuthApi, GoTrueAdminCustomProvidersApi } 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;
protected url: string;
protected headers: {
[key: string]: string;
};
protected fetch: Fetch;
/**
* Creates an admin API client that can be used to manage users and OAuth clients.
*
* @example
* ```ts
* import { GoTrueAdminApi } from '@supabase/auth-js'
*
* const admin = new GoTrueAdminApi({
* url: 'https://xyzcompany.supabase.co/auth/v1',
* headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` },
* })
* ```
*/
constructor({ url, headers, fetch, }: {
url: string;
headers?: {
[key: string]: string;
};
fetch?: Fetch;
});
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*/
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.
*/
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 email The user's email.
* @param options.password User password. For signup only.
* @param options.data Optional user metadata. For signup only.
* @param options.redirectTo The redirect url which should be appended to the generated link
*/
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.
*/
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.
*/
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.
*/
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)
*/
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.
*/
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;
}
//# sourceMappingURL=GoTrueAdminApi.d.ts.map

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,EAM9B,MAAM,aAAa,CAAA;AACpB,OAAO,EAA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GAClB,OAAO,CACN;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,IAAI,EAAE,CAAC;YAAC,GAAG,EAAE,MAAM,CAAA;SAAE,GAAG,UAAU,CAAC;QAAC,KAAK,EAAE,IAAI,CAAA;KAAE,GAClE;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,EAAE,CAAA;SAAE,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,CAC5C;IAmCD;;;;;;OAMG;IACG,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAiBrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;IACG,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAkBzF;;;;;;;;OAQG;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;CAgBpC"}

View File

@@ -0,0 +1,593 @@
import { __rest } from "tslib";
import { _generateLinkResponse, _noResolveJsonResponse, _request, _userResponse, } from './lib/fetch';
import { resolveFetch, validateUUID } from './lib/helpers';
import { SIGN_OUT_SCOPES, } from './lib/types';
import { isAuthError } from './lib/errors';
export default class GoTrueAdminApi {
/**
* Creates an admin API client that can be used to manage users and OAuth clients.
*
* @example
* ```ts
* import { GoTrueAdminApi } from '@supabase/auth-js'
*
* const admin = new GoTrueAdminApi({
* url: 'https://xyzcompany.supabase.co/auth/v1',
* headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` },
* })
* ```
*/
constructor({ url = '', headers = {}, fetch, }) {
this.url = url;
this.headers = headers;
this.fetch = resolveFetch(fetch);
this.mfa = {
listFactors: this._listFactors.bind(this),
deleteFactor: this._deleteFactor.bind(this),
};
this.oauth = {
listClients: this._listOAuthClients.bind(this),
createClient: this._createOAuthClient.bind(this),
getClient: this._getOAuthClient.bind(this),
updateClient: this._updateOAuthClient.bind(this),
deleteClient: this._deleteOAuthClient.bind(this),
regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this),
};
this.customProviders = {
listProviders: this._listCustomProviders.bind(this),
createProvider: this._createCustomProvider.bind(this),
getProvider: this._getCustomProvider.bind(this),
updateProvider: this._updateCustomProvider.bind(this),
deleteProvider: this._deleteCustomProvider.bind(this),
};
}
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*/
async signOut(jwt, scope = SIGN_OUT_SCOPES[0]) {
if (SIGN_OUT_SCOPES.indexOf(scope) < 0) {
throw new Error(`@supabase/auth-js: Parameter scope must be one of ${SIGN_OUT_SCOPES.join(', ')}`);
}
try {
await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, {
headers: this.headers,
jwt,
noResolveJson: true,
});
return { data: null, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async inviteUserByEmail(email, options = {}) {
try {
return await _request(this.fetch, 'POST', `${this.url}/invite`, {
body: { email, data: options.data },
headers: this.headers,
redirectTo: options.redirectTo,
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Generates email links and OTPs to be sent via a custom email provider.
* @param email The user's email.
* @param options.password User password. For signup only.
* @param options.data Optional user metadata. For signup only.
* @param options.redirectTo The redirect url which should be appended to the generated link
*/
async generateLink(params) {
try {
const { options } = params, rest = __rest(params, ["options"]);
const body = Object.assign(Object.assign({}, rest), options);
if ('newEmail' in rest) {
// replace newEmail with new_email in request body
body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail;
delete body['newEmail'];
}
return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, {
body: body,
headers: this.headers,
xform: _generateLinkResponse,
redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo,
});
}
catch (error) {
if (isAuthError(error)) {
return {
data: {
properties: null,
user: null,
},
error,
};
}
throw error;
}
}
// User Admin API
/**
* Creates a new user.
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async createUser(attributes) {
try {
return await _request(this.fetch, 'POST', `${this.url}/admin/users`, {
body: attributes,
headers: this.headers,
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* 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.
*/
async listUsers(params) {
var _a, _b, _c, _d, _e, _f, _g;
try {
const pagination = { nextPage: null, lastPage: 0, total: 0 };
const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, {
headers: this.headers,
noResolveJson: true,
query: {
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
},
xform: _noResolveJsonResponse,
});
if (response.error)
throw response.error;
const users = await response.json();
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
if (links.length > 0) {
links.forEach((link) => {
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
pagination[`${rel}Page`] = page;
});
pagination.total = parseInt(total);
}
return { data: Object.assign(Object.assign({}, users), pagination), error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: { users: [] }, error };
}
throw error;
}
}
/**
* 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.
*/
async getUserById(uid) {
validateUUID(uid);
try {
return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, {
headers: this.headers,
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* 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)
*/
async updateUserById(uid, attributes) {
validateUUID(uid);
try {
return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, {
body: attributes,
headers: this.headers,
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* 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.
*/
async deleteUser(id, shouldSoftDelete = false) {
validateUUID(id);
try {
return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {
headers: this.headers,
body: {
should_soft_delete: shouldSoftDelete,
},
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async _listFactors(params) {
validateUUID(params.userId);
try {
const { data, error } = await _request(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, {
headers: this.headers,
xform: (factors) => {
return { data: { factors }, error: null };
},
});
return { data, error };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
async _deleteFactor(params) {
validateUUID(params.userId);
validateUUID(params.id);
try {
const data = await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, {
headers: this.headers,
});
return { data, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _listOAuthClients(params) {
var _a, _b, _c, _d, _e, _f, _g;
try {
const pagination = { nextPage: null, lastPage: 0, total: 0 };
const response = await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, {
headers: this.headers,
noResolveJson: true,
query: {
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
},
xform: _noResolveJsonResponse,
});
if (response.error)
throw response.error;
const clients = await response.json();
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
if (links.length > 0) {
links.forEach((link) => {
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
pagination[`${rel}Page`] = page;
});
pagination.total = parseInt(total);
}
return { data: Object.assign(Object.assign({}, clients), pagination), error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: { clients: [] }, error };
}
throw error;
}
}
/**
* 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.
*/
async _createOAuthClient(params) {
try {
return await _request(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, {
body: params,
headers: this.headers,
xform: (client) => {
return { data: client, error: null };
},
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _getOAuthClient(clientId) {
try {
return await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, {
headers: this.headers,
xform: (client) => {
return { data: client, error: null };
},
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _updateOAuthClient(clientId, params) {
try {
return await _request(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, {
body: params,
headers: this.headers,
xform: (client) => {
return { data: client, error: null };
},
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _deleteOAuthClient(clientId) {
try {
await _request(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, {
headers: this.headers,
noResolveJson: true,
});
return { data: null, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _regenerateOAuthClientSecret(clientId) {
try {
return await _request(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, {
headers: this.headers,
xform: (client) => {
return { data: client, error: null };
},
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _listCustomProviders(params) {
try {
const query = {};
if (params === null || params === void 0 ? void 0 : params.type) {
query.type = params.type;
}
return await _request(this.fetch, 'GET', `${this.url}/admin/custom-providers`, {
headers: this.headers,
query,
xform: (data) => {
var _a;
return { data: { providers: (_a = data === null || data === void 0 ? void 0 : data.providers) !== null && _a !== void 0 ? _a : [] }, error: null };
},
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { providers: [] }, error };
}
throw error;
}
}
/**
* 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.
*/
async _createCustomProvider(params) {
try {
return await _request(this.fetch, 'POST', `${this.url}/admin/custom-providers`, {
body: params,
headers: this.headers,
xform: (provider) => {
return { data: provider, error: null };
},
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _getCustomProvider(identifier) {
try {
return await _request(this.fetch, 'GET', `${this.url}/admin/custom-providers/${identifier}`, {
headers: this.headers,
xform: (provider) => {
return { data: provider, error: null };
},
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* 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.
*/
async _updateCustomProvider(identifier, params) {
try {
return await _request(this.fetch, 'PUT', `${this.url}/admin/custom-providers/${identifier}`, {
body: params,
headers: this.headers,
xform: (provider) => {
return { data: provider, error: null };
},
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* Deletes a custom provider.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async _deleteCustomProvider(identifier) {
try {
await _request(this.fetch, 'DELETE', `${this.url}/admin/custom-providers/${identifier}`, {
headers: this.headers,
noResolveJson: true,
});
return { data: null, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
}
//# sourceMappingURL=GoTrueAdminApi.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,783 @@
import GoTrueAdminApi from './GoTrueAdminApi';
import { AuthError } from './lib/errors';
import { Fetch } from './lib/fetch';
import { Deferred } from './lib/helpers';
import type { AuthChangeEvent, AuthFlowType, AuthOtpResponse, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, CallRefreshTokenResult, GoTrueClientOptions, GoTrueMFAApi, InitializeResult, JWK, JwtHeader, JwtPayload, LockFunc, OAuthResponse, AuthOAuthServerApi, ResendParams, Session, SignInAnonymouslyCredentials, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignInWithSSO, SignOut, SignUpWithPasswordCredentials, SSOResponse, Subscription, SupportedStorage, User, UserAttributes, UserIdentity, UserResponse, VerifyOtpParams, Web3Credentials } from './lib/types';
export default class GoTrueClient {
private static nextInstanceID;
private instanceID;
/**
* Namespace for the GoTrue admin methods.
* These methods should only be used in a trusted server-side environment.
*/
admin: GoTrueAdminApi;
/**
* Namespace for the MFA methods.
*/
mfa: GoTrueMFAApi;
/**
* Namespace for the OAuth 2.1 authorization server methods.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
* Used to implement the authorization code flow on the consent page.
*/
oauth: AuthOAuthServerApi;
/**
* The storage key used to identify the values saved in localStorage
*/
protected storageKey: string;
protected flowType: AuthFlowType;
/**
* The JWKS used for verifying asymmetric JWTs
*/
protected get jwks(): {
keys: JWK[];
};
protected set jwks(value: {
keys: JWK[];
});
protected get jwks_cached_at(): number;
protected set jwks_cached_at(value: number);
protected autoRefreshToken: boolean;
protected persistSession: boolean;
protected storage: SupportedStorage;
/**
* @experimental
*/
protected userStorage: SupportedStorage | null;
protected memoryStorage: {
[key: string]: string;
} | null;
protected stateChangeEmitters: Map<string | symbol, Subscription>;
protected autoRefreshTicker: ReturnType<typeof setInterval> | null;
protected autoRefreshTickTimeout: ReturnType<typeof setTimeout> | null;
protected visibilityChangedCallback: (() => Promise<any>) | null;
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null;
/**
* Keeps track of the async client initialization.
* When null or not yet resolved the auth state is `unknown`
* Once resolved the auth state is known and it's safe to call any further client methods.
* Keep extra care to never reject or throw uncaught errors
*/
protected initializePromise: Promise<InitializeResult> | null;
protected detectSessionInUrl: boolean | ((url: URL, params: {
[parameter: string]: string;
}) => boolean);
protected url: string;
protected headers: {
[key: string]: string;
};
protected hasCustomAuthorizationHeader: boolean;
protected suppressGetSessionWarning: boolean;
protected fetch: Fetch;
protected lock: LockFunc;
protected lockAcquired: boolean;
protected pendingInLock: Promise<any>[];
protected throwOnError: boolean;
protected lockAcquireTimeout: number;
/**
* Used to broadcast state change events to other tabs listening.
*/
protected broadcastChannel: BroadcastChannel | null;
protected logDebugMessages: boolean;
protected logger: (message: string, ...args: any[]) => void;
/**
* Create a new client for use in the browser.
*
* @example
* ```ts
* import { GoTrueClient } from '@supabase/auth-js'
*
* const auth = new GoTrueClient({
* url: 'https://xyzcompany.supabase.co/auth/v1',
* headers: { apikey: 'public-anon-key' },
* storageKey: 'supabase-auth',
* })
* ```
*/
constructor(options: GoTrueClientOptions);
/**
* Returns whether error throwing mode is enabled for this client.
*/
isThrowOnErrorEnabled(): boolean;
/**
* Centralizes return handling with optional error throwing. When `throwOnError` is enabled
* and the provided result contains a non-nullish error, the error is thrown instead of
* being returned. This ensures consistent behavior across all public API methods.
*/
private _returnResult;
private _logPrefix;
private _debug;
/**
* Initializes the client session either from the url or from storage.
* This method is automatically called when instantiating the client, but should also be called
* manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
*/
initialize(): Promise<InitializeResult>;
/**
* IMPORTANT:
* 1. Never throw in this method, as it is called from the constructor
* 2. Never return a session from this method as it would be cached over
* the whole lifetime of the client
*/
private _initialize;
/**
* Creates a new anonymous user.
*
* @returns A session where the is_anonymous claim in the access token JWT set to true
*/
signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>;
/**
* Creates a new user.
*
* Be aware that if a user account exists in the system you may get back an
* error message that attempts to hide this information from the user.
* This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*
* @category Auth
*
* @remarks
* - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers).
* - **Confirm email** determines if users need to confirm their email address after signing up.
* - If **Confirm email** is enabled, a `user` is returned but `session` is null.
* - If **Confirm email** is disabled, both a `user` and a `session` are returned.
* - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration).
* - If signUp() is called for an existing confirmed user:
* - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned.
* - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned.
* - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser).
*
* @example Sign up with an email and password
* ```js
* const { data, error } = await supabase.auth.signUp({
* email: 'example@email.com',
* password: 'example-password',
* })
* ```
*
* @exampleResponse Sign up with an email and password
* ```json
* // Some fields may be null if "confirm email" is enabled.
* {
* "data": {
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_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"
* },
* "session": {
* "access_token": "<ACCESS_TOKEN>",
* "token_type": "bearer",
* "expires_in": 3600,
* "expires_at": 1700000000,
* "refresh_token": "<REFRESH_TOKEN>",
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_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"
* }
* }
* },
* "error": null
* }
* ```
*
* @example Sign up with a phone number and password (SMS)
* ```js
* const { data, error } = await supabase.auth.signUp({
* phone: '123456789',
* password: 'example-password',
* options: {
* channel: 'sms'
* }
* })
* ```
*
* @exampleDescription Sign up with a phone number and password (whatsapp)
* The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.
*
* @example Sign up with a phone number and password (whatsapp)
* ```js
* const { data, error } = await supabase.auth.signUp({
* phone: '123456789',
* password: 'example-password',
* options: {
* channel: 'whatsapp'
* }
* })
* ```
*
* @example Sign up with additional user metadata
* ```js
* const { data, error } = await supabase.auth.signUp(
* {
* email: 'example@email.com',
* password: 'example-password',
* options: {
* data: {
* first_name: 'John',
* age: 27,
* }
* }
* }
* )
* ```
*
* @exampleDescription Sign up with a redirect URL
* - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.
*
* @example Sign up with a redirect URL
* ```js
* const { data, error } = await supabase.auth.signUp(
* {
* email: 'example@email.com',
* password: 'example-password',
* options: {
* emailRedirectTo: 'https://example.com/welcome'
* }
* }
* )
* ```
*/
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;
/**
* Log in an existing user with an email and password or phone and password.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or that the
* email/phone and password combination is wrong or that the account can only
* be accessed via social login.
*/
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>;
/**
* Log in an existing user via a third-party provider.
* This method supports the PKCE flow.
*/
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
*/
exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse>;
/**
* Signs in a user by verifying a message signed by the user's private key.
* Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards,
* both of which derive from the EIP-4361 standard
* With slight variation on Solana's side.
* @reference https://eips.ethereum.org/EIPS/eip-4361
*/
signInWithWeb3(credentials: Web3Credentials): Promise<{
data: {
session: Session;
user: User;
};
error: null;
} | {
data: {
session: null;
user: null;
};
error: AuthError;
}>;
private signInWithEthereum;
private signInWithSolana;
private _exchangeCodeForSession;
/**
* Allows signing in with an OIDC ID token. The authentication provider used
* should be enabled and configured.
*/
signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
/**
* Log in a user using magiclink or a one-time password (OTP).
*
* If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
* If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
* If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or, that the account
* can only be accessed via social login.
*
* Do note that you will need to configure a Whatsapp sender on Twilio
* if you are using phone sign in with the 'whatsapp' channel. The whatsapp
* channel is not supported on other providers
* at this time.
* This method supports PKCE when an email is passed.
*/
signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>;
/**
* Log in a user given a User supplied OTP or TokenHash received through mobile or email.
*/
verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>;
/**
* Attempts a single-sign on using an enterprise Identity Provider. A
* successful SSO attempt will redirect the current page to the identity
* provider authorization page. The redirect URL is implementation and SSO
* protocol specific.
*
* You can use it by providing a SSO domain. Typically you can extract this
* domain by asking users for their email address. If this domain is
* registered on the Auth instance the redirect will use that organization's
* currently active SSO Identity Provider for the login.
*
* If you have built an organization-specific login page, you can use the
* organization's SSO Identity Provider UUID directly instead.
*/
signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>;
/**
* Sends a reauthentication OTP to the user's email or phone number.
* Requires the user to be signed-in.
*/
reauthenticate(): Promise<AuthResponse>;
private _reauthenticate;
/**
* Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
*/
resend(credentials: ResendParams): Promise<AuthOtpResponse>;
/**
* Returns the session, refreshing it if necessary.
*
* The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
*
* **IMPORTANT:** This method loads values directly from the storage attached
* to the client. If that storage is based on request cookies for example,
* the values in it may not be authentic and therefore it's strongly advised
* against using this method and its results in such circumstances. A warning
* will be emitted if this is detected. Use {@link #getUser()} instead.
*/
getSession(): Promise<{
data: {
session: Session;
};
error: null;
} | {
data: {
session: null;
};
error: AuthError;
} | {
data: {
session: null;
};
error: null;
}>;
/**
* Acquires a global lock based on the storage key.
*/
private _acquireLock;
/**
* Use instead of {@link #getSession} inside the library. It is
* semantically usually what you want, as getting a session involves some
* processing afterwards that requires only one client operating on the
* session at once across multiple tabs or processes.
*/
private _useSession;
/**
* NEVER USE DIRECTLY!
*
* Always use {@link #_useSession}.
*/
private __loadSession;
/**
* Gets the current user details if there is an existing session. This method
* performs a network request to the Supabase Auth server, so the returned
* value is authentic and can be used to base authorization rules on.
*
* @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.
*/
getUser(jwt?: string): Promise<UserResponse>;
private _getUser;
/**
* Updates user data for a logged in user.
*/
updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
protected _updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
/**
* Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
* If the refresh token or access token in the current session is invalid, an error will be thrown.
* @param currentSession The current session that minimally contains an access token and refresh token.
*/
setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
protected _setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Returns a new session, regardless of expiry status.
* Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
* If the current session's refresh token is invalid, an error will be thrown.
* @param currentSession The current session. If passed in, it must contain a refresh token.
*/
refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
protected _refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Gets the session data from a URL string
*/
private _getSessionFromURL;
/**
* Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
*
* If `detectSessionInUrl` is a function, it will be called with the URL and params to determine
* if the URL should be processed as a Supabase auth callback. This allows users to exclude
* URLs from other OAuth providers (e.g., Facebook Login) that also return access_token in the fragment.
*/
private _isImplicitGrantCallback;
/**
* Checks if the current URL and backing storage contain parameters given by a PKCE flow
*/
private _isPKCECallback;
/**
* Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event.
*
* For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.
* There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
*
* If using `others` scope, no `SIGNED_OUT` event is fired!
*/
signOut(options?: SignOut): Promise<{
error: AuthError | null;
}>;
protected _signOut({ scope }?: SignOut): Promise<{
error: AuthError | null;
}>;
/**
* Receive a notification every time an auth event happens.
* Safe to use without an async function as callback.
*
* @param callback A callback function to be invoked when an auth event happens.
*/
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void): {
data: {
subscription: Subscription;
};
};
/**
* Avoid using an async function inside `onAuthStateChange` as you might end
* up with a deadlock. The callback function runs inside an exclusive lock,
* so calling other Supabase Client APIs that also try to acquire the
* exclusive lock, might cause a deadlock. This behavior is observable across
* tabs. In the next major library version, this behavior will not be supported.
*
* Receive a notification every time an auth event happens.
*
* @param callback A callback function to be invoked when an auth event happens.
* @deprecated Due to the possibility of deadlocks with async functions as callbacks, use the version without an async function.
*/
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => Promise<void>): {
data: {
subscription: Subscription;
};
};
private _emitInitialSession;
/**
* Sends a password reset request to an email address. This method supports the PKCE flow.
*
* @param email The email address of the user.
* @param options.redirectTo The URL to send the user to after they click the password reset link.
* @param options.captchaToken Verification token received when the user completes the captcha on the site.
*/
resetPasswordForEmail(email: string, options?: {
redirectTo?: string;
captchaToken?: string;
}): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Gets all the identities linked to a user.
*/
getUserIdentities(): Promise<{
data: {
identities: UserIdentity[];
};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Links an oauth identity to an existing user.
* This method supports the PKCE flow.
*/
linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Links an OIDC identity to an existing user.
*/
linkIdentity(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
private linkIdentityOAuth;
private linkIdentityIdToken;
/**
* Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
*/
unlinkIdentity(identity: UserIdentity): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Generates a new JWT.
* @param refreshToken A valid refresh token that was returned on login.
*/
private _refreshAccessToken;
private _isValidSession;
private _handleProviderSignIn;
/**
* Recovers the session from LocalStorage and refreshes the token
* Note: this method is async to accommodate for AsyncStorage e.g. in React native.
*/
private _recoverAndRefresh;
private _callRefreshToken;
private _notifyAllSubscribers;
/**
* set currentSession and currentUser
* process to _startAutoRefreshToken if possible
*/
private _saveSession;
private _removeSession;
/**
* Removes any registered visibilitychange callback.
*
* {@see #startAutoRefresh}
* {@see #stopAutoRefresh}
*/
private _removeVisibilityChangedCallback;
/**
* This is the private implementation of {@link #startAutoRefresh}. Use this
* within the library.
*/
private _startAutoRefresh;
/**
* This is the private implementation of {@link #stopAutoRefresh}. Use this
* within the library.
*/
private _stopAutoRefresh;
/**
* Starts an auto-refresh process in the background. The session is checked
* every few seconds. Close to the time of expiration a process is started to
* refresh the session. If refreshing fails it will be retried for as long as
* necessary.
*
* If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
* to call this function, it will be called for you.
*
* On browsers the refresh process works only when the tab/window is in the
* foreground to conserve resources as well as prevent race conditions and
* flooding auth with requests. If you call this method any managed
* visibility change callback will be removed and you must manage visibility
* changes on your own.
*
* On non-browser platforms the refresh process works *continuously* in the
* background, which may not be desirable. You should hook into your
* platform's foreground indication mechanism and call these methods
* appropriately to conserve resources.
*
* {@see #stopAutoRefresh}
*/
startAutoRefresh(): Promise<void>;
/**
* Stops an active auto refresh process running in the background (if any).
*
* If you call this method any managed visibility change callback will be
* removed and you must manage visibility changes on your own.
*
* See {@link #startAutoRefresh} for more details.
*/
stopAutoRefresh(): Promise<void>;
/**
* Runs the auto refresh token tick.
*/
private _autoRefreshTokenTick;
/**
* Registers callbacks on the browser / platform, which in-turn run
* algorithms when the browser window/tab are in foreground. On non-browser
* platforms it assumes always foreground.
*/
private _handleVisibilityChange;
/**
* Callback registered with `window.addEventListener('visibilitychange')`.
*/
private _onVisibilityChanged;
/**
* Generates the relevant login URL for a third-party provider.
* @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param options.scopes A space-separated list of scopes granted to the OAuth application.
* @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
*/
private _getUrlForProvider;
private _unenroll;
/**
* {@see GoTrueMFAApi#enroll}
*/
private _enroll;
/**
* {@see GoTrueMFAApi#verify}
*/
private _verify;
/**
* {@see GoTrueMFAApi#challenge}
*/
private _challenge;
/**
* {@see GoTrueMFAApi#challengeAndVerify}
*/
private _challengeAndVerify;
/**
* {@see GoTrueMFAApi#listFactors}
*/
private _listFactors;
/**
* {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
*/
private _getAuthenticatorAssuranceLevel;
/**
* Retrieves details about an OAuth authorization request.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*
* Returns authorization details including client info, scopes, and user information.
* If the response includes only a redirect_url field, it means consent was already given - the caller
* should handle the redirect manually if needed.
*/
private _getAuthorizationDetails;
/**
* Approves an OAuth authorization request.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
private _approveAuthorization;
/**
* Denies an OAuth authorization request.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
private _denyAuthorization;
/**
* Lists all OAuth grants that the authenticated user has authorized.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
private _listOAuthGrants;
/**
* Revokes a user's OAuth grant for a specific client.
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
*/
private _revokeOAuthGrant;
private fetchJwk;
/**
* Extracts the JWT claims present in the access token by first verifying the
* JWT against the server's JSON Web Key Set endpoint
* `/.well-known/jwks.json` which is often cached, resulting in significantly
* faster responses. Prefer this method over {@link #getUser} which always
* sends a request to the Auth server for each JWT.
*
* If the project is not using an asymmetric JWT signing key (like ECC or
* RSA) it always sends a request to the Auth server (similar to {@link
* #getUser}) to verify the JWT.
*
* @param jwt An optional specific JWT you wish to verify, not the one you
* can obtain from {@link #getSession}.
* @param options Various additional options that allow you to customize the
* behavior of this method.
*/
getClaims(jwt?: string, options?: {
/**
* @deprecated Please use options.jwks instead.
*/
keys?: JWK[];
/** If set to `true` the `exp` claim will not be validated against the current time. */
allowExpired?: boolean;
/** If set, this JSON Web Key Set is going to have precedence over the cached value available on the server. */
jwks?: {
keys: JWK[];
};
}): Promise<{
data: {
claims: JwtPayload;
header: JwtHeader;
signature: Uint8Array;
};
error: null;
} | {
data: null;
error: AuthError;
} | {
data: null;
error: null;
}>;
}
//# sourceMappingURL=GoTrueClient.d.ts.map

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More