/** * Identity: people, sessions and the token every other product sends. * * The identity server is at `/v1/identity` (`/auth/v1` in the old vocabulary). A session is an * access token (a short-lived JWT that row-level security reads) plus a refresh token that buys * the next one. This module keeps the session, stores it where the caller said to (the browser's * localStorage by default), renews it before it expires, and tells every listener when it * changes, which is how live learns to re-authorise its topics. * * The routes and fields it sends are the vocabulary's own (`/session?via=password` and * `profile_data`, or `/token?grant_type=password` and `data`); a person and a session it hands * back carry BOTH names for each renamed field (`person` and `user`, `profile_data` and * `user_metadata`, `server_data` and `app_metadata`), whichever the server sent, so code written * against either reads them. */ import { type Fetch, type Vocabulary } from './http.js'; /** One person's account, as the identity server describes it. */ export interface Person { id: string; aud: string; role?: string; email?: string; phone?: string; email_confirmed_at?: string | null; phone_confirmed_at?: string | null; confirmed_at?: string | null; last_sign_in_at?: string | null; /** What the person may change about themselves (`changePerson({ profile_data })`). */ profile_data: Record; /** What only the server key may set (`operator.createUser({ server_data })`). */ server_data: Record; /** @deprecated Since 0.4.0: `server_data`, the same value. */ app_metadata: Record; /** @deprecated Since 0.4.0: `profile_data`, the same value. */ user_metadata: Record; identities?: Record[]; created_at: string; updated_at?: string; is_anonymous?: boolean; [field: string]: unknown; } /** @deprecated Since 0.4.0: `Person`. */ export type User = Person; export interface Session { access_token: string; refresh_token: string; token_type: string; expires_in: number; /** Seconds since the epoch. */ expires_at: number; person: Person; /** @deprecated Since 0.4.0: `person`, the same object. */ user: Person; provider_token?: string | null; provider_refresh_token?: string | null; } export declare class AuthError extends Error { readonly status: number; readonly code: string | undefined; constructor(message: string, status: number, code?: string); } export type AuthEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED' | 'PASSWORD_RECOVERY'; export type AuthResult = { data: T; error: null; } | { data: { [K in keyof T]: null; }; error: AuthError; }; /** A result naming one person, under the new name and the old. */ export interface PersonData { person: Person | null; /** @deprecated Since 0.4.0: `person`, the same object. */ user: Person | null; } /** A result naming a person and a session. */ export interface SessionData extends PersonData { session: Session | null; } /** Where a session is kept between page loads. `localStorage` fits; so does anything async. */ export interface SessionStorage { getItem(key: string): string | null | Promise; setItem(key: string, value: string): void | Promise; removeItem(key: string): void | Promise; } export interface AuthOptions { /** Keep the session between page loads. Default: true in a browser, false elsewhere. */ persistSession?: boolean; /** Refresh the access token before it expires. Default: true. */ autoRefreshToken?: boolean; /** Finish a sign-in from the URL a redirect landed on. Default: true in a browser. */ detectSessionInUrl?: boolean; /** `pkce` (the default) or `implicit`, for magic links and OAuth redirects. */ flowType?: 'pkce' | 'implicit'; storage?: SessionStorage; storageKey?: string; /** * Told what the session did and why: each refresh and its outcome, a session adopted from * storage because another tab or process refreshed it first, and every sign-out with its * cause. For a log that has to explain an unexpected sign-out after the fact. No token is * ever passed to it. */ debug?: (...parts: unknown[]) => void; } type Listener = (event: AuthEvent, session: Session | null) => void; /** The identity server's routes, old then new. */ declare const ROUTES: { readonly signup: readonly ["signup", "register"]; readonly token: readonly ["token", "session"]; readonly logout: readonly ["logout", "sign-off"]; readonly user: readonly ["user", "person"]; readonly recover: readonly ["recover", "reset"]; readonly verify: readonly ["verify", "confirm"]; readonly otp: readonly ["otp", "code"]; readonly authorize: readonly ["authorize", "provider/start"]; readonly sso: readonly ["sso", "sso/start"]; readonly people: readonly ["admin/users", "operator/people"]; }; type Route = keyof typeof ROUTES; /** * A person as the server sent it, carrying each renamed field under both names, whichever it * was sent under (an old server sends only the old ones, a new one both). */ export declare function toPerson(body: unknown): Person; export declare class AuthClient { private readonly url; private readonly key; private readonly fetch; private readonly headers; private readonly storage; private readonly storageKey; private readonly persist; private readonly autoRefresh; private readonly flowType; private readonly listeners; private session; private refreshing; private timer; /** Set by stopAutoRefresh and cleared by startAutoRefresh; a sign-in does not re-arm it. */ private paused; private readonly debug; /** A bearer the caller fixed in `global.headers`, used by `currentPerson()` when nobody is signed in. */ private readonly fixedBearer; private readonly ready; /** The operator half: managing other people's accounts. Needs the server key. */ readonly operator: AuthAdmin; /** @deprecated Since 0.4.0: `operator`, the same object. Removed in 0.5.0. */ readonly admin: AuthAdmin; /** @internal Which names the wire speaks. */ readonly vocabulary: Vocabulary; /** @deprecated Since 0.4.0: use `register()`, the same function. Removed in 0.5.0. */ signUp: AuthClient['register']; /** @deprecated Since 0.4.0: use `passwordSignIn()`, the same function. Removed in 0.5.0. */ signInWithPassword: AuthClient['passwordSignIn']; /** @deprecated Since 0.4.0: use `codeSignIn()`, the same function. Removed in 0.5.0. */ signInWithOtp: AuthClient['codeSignIn']; /** @deprecated Since 0.4.0: use `providerSignIn()`, the same function. Removed in 0.5.0. */ signInWithOAuth: AuthClient['providerSignIn']; /** @deprecated Since 0.4.0: use `ssoSignIn()`, the same function. Removed in 0.5.0. */ signInWithSSO: AuthClient['ssoSignIn']; /** @deprecated Since 0.4.0: use `guestSignIn()`, the same function. Removed in 0.5.0. */ signInAnonymously: AuthClient['guestSignIn']; /** @deprecated Since 0.4.0: use `confirmCode()`, the same function. Removed in 0.5.0. */ verifyOtp: AuthClient['confirmCode']; /** @deprecated Since 0.4.0: use `finishProviderSignIn()`, the same function. Removed in 0.5.0. */ exchangeCodeForSession: AuthClient['finishProviderSignIn']; /** @deprecated Since 0.4.0: use `signOff()`, the same function. Removed in 0.5.0. */ signOut: AuthClient['signOff']; /** @deprecated Since 0.4.0: use `currentSession()`, the same function. Removed in 0.5.0. */ getSession: AuthClient['currentSession']; /** @deprecated Since 0.4.0: use `currentPerson()`, the same function. Removed in 0.5.0. */ getUser: AuthClient['currentPerson']; /** @deprecated Since 0.4.0: use `renew()`, the same function. Removed in 0.5.0. */ refreshSession: AuthClient['renew']; /** @deprecated Since 0.4.0: use `onSessionChange()`, the same function. Removed in 0.5.0. */ onAuthStateChange: AuthClient['onSessionChange']; /** @deprecated Since 0.4.0: use `sendReset()`, the same function. Removed in 0.5.0. */ resetPasswordForEmail: AuthClient['sendReset']; /** @deprecated Since 0.4.0: use `changePerson()`, the same function. Removed in 0.5.0. */ updateUser: AuthClient['changePerson']; constructor(url: string, key: string, fetchImpl: Fetch, headers: Record, ref: string, options?: AuthOptions, vocabulary?: Vocabulary); /** @internal A route's path in this client's vocabulary, with `rest` after it. */ route(name: Route, rest?: string): string; /** The query that asks the token route for `grant`: `grant_type=` (old) or `via=` (new). */ private grant; /** * @internal A person's data fields under this vocabulary's names: `profile_data` and * `server_data`, or the old `oldProfile` (`data` or `user_metadata`) and `app_metadata`. * Absent ones are left out. */ fields(oldProfile: 'data' | 'user_metadata', profile: unknown, server?: unknown): Record; /** @internal */ call(path: string, init?: { method?: string; body?: unknown; token?: string; query?: Record; }): Promise<{ body: Record; error: AuthError | null; }>; /** The session as storage holds it now, or null. Unreadable or shapeless contents are cleared. */ private readStored; /** * Adopts what storage holds when it is not what this client holds. Storage can be shared: two * tabs, two origins reading one cookie, two app instances reading one file. Whoever refreshes * first rotates the refresh token, and a client still holding the old one would present a * spent token and be signed out, taking the shared store with it. So storage is read before * the session is used or refreshed, on every getSession. */ private syncFromStorage; private initialize; /** * Finishes a redirect: `?code=` (PKCE) or `#access_token=` (implicit). * * In PKCE mode only the code exchange establishes a session, since it needs the verifier * this storage holds for a sign-in it started. A fragment is ignored there: anyone can mint * one for their OWN account and link a victim to it, which would silently replace the * victim's session with the attacker's (login CSRF). */ private fromUrl; private save; private emit; private schedule; /** One refresh at a time: two callers asking together share the one request. */ private refresh; private signedIn; /** The token to send as `Authorization`: the session's, or the project key when signed out. */ getAccessToken(): Promise; /** The current session, renewed first if it has expired. Read locally, not verified. */ currentSession(): Promise>; /** The signed-in person, as the identity server says it is now. Use this, not the session, to decide. */ currentPerson(jwt?: string): Promise>; /** Adopt a session obtained elsewhere (a server, another tab). */ setSession(tokens: { access_token: string; refresh_token: string; }): Promise>; /** Renew now, with the stored refresh token or the one given. */ renew(current?: { refresh_token: string; }): Promise>; /** Called with every change of session. Returns the handle that stops it. */ onSessionChange(listener: Listener): { data: { subscription: { unsubscribe: () => void; }; }; }; /** A new account. `options.profile_data` (`options.data` before 0.4.0) is the person's own data. */ register(credentials: { email?: string; phone?: string; password: string; options?: { profile_data?: Record; /** @deprecated Since 0.4.0: `profile_data`. */ data?: Record; emailRedirectTo?: string; captchaToken?: string; }; }): Promise>; passwordSignIn(credentials: { email?: string; phone?: string; password: string; }): Promise>; /** * An account with no email or password, which can be upgraded later with `changePerson`. The * person's data goes in `options.profile_data`, as `register` takes it; `options.data` and a * bare `data` are still read, since 0.3.x and earlier took it there. */ guestSignIn(credentials?: { options?: { profile_data?: Record; /** @deprecated Since 0.4.0: `profile_data`. */ data?: Record; }; /** @deprecated Since 0.3.2: `options.profile_data`. */ data?: Record; }): Promise>; /** Sends a magic link or a one-time code. The session arrives by `confirmCode` or the redirect. */ codeSignIn(credentials: { email?: string; phone?: string; options?: { emailRedirectTo?: string; shouldCreateUser?: boolean; profile_data?: Record; /** @deprecated Since 0.4.0: `profile_data`. */ data?: Record; channel?: 'sms' | 'whatsapp'; }; }): Promise>; /** Confirms a one-time code, or a link's token hash, which signs in. */ confirmCode(params: { email?: string; phone?: string; token?: string; token_hash?: string; type: 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email' | 'sms' | 'phone_change'; }): Promise>; /** * The URL that signs in with a provider (GitHub, Google, …). In a browser it navigates * there unless `skipBrowserRedirect`; elsewhere it only returns it. */ providerSignIn(credentials: { provider: string; options?: { redirectTo?: string; scopes?: string; queryParams?: Record; skipBrowserRedirect?: boolean; }; }): Promise>; /** * Signs in with an ID token the provider handed the app directly (Google One Tap, Sign in * with Apple), with no redirect. */ signInWithIdToken(credentials: { provider: string; token: string; access_token?: string; nonce?: string; options?: { captchaToken?: string; }; }): Promise>; /** * The URL that signs in through a SAML identity provider, named by its id or by the email * domain it is registered for. In a browser it navigates there unless * `skipBrowserRedirect`; elsewhere it only returns it. The session arrives by the redirect. */ ssoSignIn(params: ({ providerId: string; } | { domain: string; }) & { options?: { redirectTo?: string; captchaToken?: string; skipBrowserRedirect?: boolean; }; }): Promise>; /** Finishes a PKCE sign-in (a provider's, a link's, SSO's) with the `code` the redirect carried. */ finishProviderSignIn(code: string): Promise>; private startPkce; /** Ends the session here (`local`), everywhere (`global`) or everywhere else (`others`). */ signOff(options?: { scope?: 'global' | 'local' | 'others'; }): Promise<{ error: AuthError | null; }>; /** Mails a password reset link to `email`. */ sendReset(email: string, options?: { redirectTo?: string; captchaToken?: string; }): Promise<{ data: Record; error: AuthError | null; }>; /** Changes the signed-in person's email, phone, password or `profile_data`. */ changePerson(attributes: { email?: string; phone?: string; password?: string; nonce?: string; profile_data?: Record; /** @deprecated Since 0.4.0: `profile_data`. */ data?: Record; }, options?: { emailRedirectTo?: string; }): Promise>; /** Re-sends a confirmation or change email, or a code. */ resend(params: { type: 'signup' | 'email_change' | 'sms' | 'phone_change'; email?: string; phone?: string; options?: { emailRedirectTo?: string; }; }): Promise<{ error: AuthError | null; }>; /** * Stops refreshing the token until `startAutoRefresh`. For scripts that want to exit cleanly, * and for an app going to sleep, which should not refresh into a network that is not back. */ stopAutoRefresh(): void; /** Resumes refreshing: at once if the token is due, otherwise when it will be. */ startAutoRefresh(): Promise; } /** What `admin.generateLink` returns beside the user: the link, and the parts it is made of. */ export interface GenerateLinkProperties { action_link: string; email_otp: string; hashed_token: string; redirect_to: string; verification_type: string; } /** Account management with the server key. Never ship that key to a browser. */ export declare class AuthAdmin { private readonly auth; constructor(auth: AuthClient); /** * A new account. `profile_data` is the person's own data, `server_data` what only the server * key sets (`user_metadata` and `app_metadata` before 0.4.0). */ createUser(attributes: { email?: string; phone?: string; password?: string; email_confirm?: boolean; phone_confirm?: boolean; profile_data?: Record; server_data?: Record; /** @deprecated Since 0.4.0: `profile_data`. */ user_metadata?: Record; /** @deprecated Since 0.4.0: `server_data`. */ app_metadata?: Record; ban_duration?: string; }): Promise>; /** A page of accounts, as `people` (and `users`, its 0.3.x name). */ listUsers(params?: { page?: number; perPage?: number; }): Promise>; getUserById(id: string): Promise>; /** Changes any of `createUser`'s attributes, under either name. */ updateUserById(id: string, attributes: Record): Promise>; /** `shouldSoftDelete` keeps the row and scrubs it, so foreign keys to it still hold. */ deleteUser(id: string, shouldSoftDelete?: boolean): Promise>; inviteUserByEmail(email: string, options?: { profile_data?: Record; /** @deprecated Since 0.4.0: `profile_data`. */ data?: Record; redirectTo?: string; }): Promise>; /** A sign-in, invite or recovery link, returned instead of emailed. */ generateLink(params: { type: 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change_current' | 'email_change_new'; email: string; password?: string; newEmail?: string; options?: { profile_data?: Record; /** @deprecated Since 0.4.0: `profile_data`. */ data?: Record; redirectTo?: string; }; }): Promise>; /** Attributes with the person's data fields under the vocabulary's names, the new one winning when both are given. */ private speak; } export {};