API reference

yatta/auth

Passwords, sessions, passkeys, OAuth, 2FA, API keys.

56 exported symbols and 367 members, read from src/types/auth.ts.

Construct

createAuth

function
createAuth(config: AuthConfig): Auth

getDefaultAuth

function
getDefaultAuth(): Auth

mfaSetupKey

function

Challenge-store key for a user's pending MFA enrolment.

Prefixed so it can never collide with a base64url WebAuthn challenge, and built from the user id so `confirmSetup` — which knows nothing else — can find it. Storing the encrypted seed as the key instead meant the lookup never matched and 2FA could never be turned on.

mfaSetupKey(userId: string): string

Auth

class
class Auth

50 members

  • storeproperty
    store: AuthStore
  • challengeStoreproperty
    challengeStore: AuthChallengeStore
  • rateLimitStoreproperty
    rateLimitStore: RateLimitStore
  • auditStoreproperty
    auditStore: AuthAuditStore
  • configproperty
    config: AuthConfig
  • cryptoproperty
    crypto: AuthCrypto
  • jwtproperty
    jwt: AuthJwt
  • permissionsproperty
    permissions: PermissionManager
  • rateLimiterproperty
    rateLimiter: GranularRateLimiter
  • riskproperty
    risk: SecurityRiskEngine
  • mfaproperty
    mfa: AuthMfa
  • passkeyproperty
    passkey: AuthPasskey
  • oauthproperty
    oauth: AuthOAuth
  • magicLinkproperty
    magicLink: AuthMagicLink
  • apiKeysproperty
    apiKeys: AuthApiKeys
  • passwordproperty
    password: AuthPasswordSubsystem
  • eventListenersproperty
    eventListeners:
  • mailergetter
    mailer: YattaMailer
  • on
    on(event: string, listener: (payload: any) => void | Promise<void>)
  • emit
    emit(event: string, payload: Record<string, unknown>, req?: Request)
  • signUp
    signUp(input: { email: string; password?: string; metadata?: Record<string, unknown>; req?: Request; }): Promise<AuthResult | { user: PublicUser; emailVerificationRequired: true; }>
  • signIn
    signIn(input: { email: string; password?: string; mfaCode?: string; recoveryCode?: string; req?: Request; }): Promise<AuthResult | MfaChallenge>
  • signOut
    signOut(reqOrToken: Request | { req: Request; } | string): Promise<{ success: boolean; cookies: string[]; }>
  • isSessionLive
    isSessionLive(session: AuthSession): boolean

    Whether a session is still inside its lifetime.

    Checked here rather than left to the store. `MemoryAuthStore` filters expired sessions out of its scan, so the default implementation made this look handled — but `AuthStore` is a published interface, and a custom store that returns an expired session makes every caller believe a dead session is live. "The default happens to check" is not a security property. A session with no `expiresAt` is treated as live: some deployments use a shorter access token and never set one, and refusing those would break them loudly for a case that is not a leak.

  • completeMfa
    completeMfa(input: { ticket: string; code?: string; recoveryCode?: string; req?: Request; }): Promise<AuthResult>

    Finishes a sign-in that stopped at the second factor.

    Every flow that can stop — password, passkey, OAuth, magic link — returns `{ mfaRequired: true, ticket }` when the account has 2FA on. Nothing consumed that before, so a 2FA user could not sign in by any route but a password. This is the half that was missing. A signed ticket rather than the bare `userId` the flows used to return. With a bare id, whatever the app built as its second step had no proof the first factor had passed — so anything that accepted a user id and asked the store a question was reachable by anyone who could produce or guess one. The ticket is signed, short-lived, single-use, and only this function can interpret it.

    ticket
    The value from the `mfaRequired` response.
    code
    A 6-digit TOTP code, or a recovery code.
  • getSession
    getSession(reqOrToken: Request | { req: Request; } | string, options?: { autoRefresh?: boolean; }): Promise<{ user: PublicUser; session: PublicSession; newCookies?: string[]; } | null>
  • getUser
    getUser(req: Request): Promise<PublicUser | null>
  • requireUser
    requireUser(req: Request): Promise<PublicUser>
  • requireRecentAuth
    requireRecentAuth(req: Request, maxAgeSec?: number): Promise<{ user: PublicUser; session: PublicSession; }>
  • reauthenticate
    reauthenticate(req: Request, password: string): Promise<void>
  • refresh
    refresh(refreshToken: string, req?: Request): Promise<AuthResult>
  • sendVerificationEmail
    sendVerificationEmail(userId: string): Promise<void>
  • verifyEmail
    verifyEmail(rawToken: string): Promise<PublicUser>
  • can
    can(userOrRoles: PublicUser | AuthUser | string[])
  • protect
    protect(requirements?: { role?: string; permission?: string; })
  • validateEmail
    validateEmail(email: string): string
  • validatePasswordStrength
    validatePasswordStrength(pass: string): void
  • extractClient
    extractClient(req?: any): { ip: string; userAgent?: string; }
  • toPublicUser
    toPublicUser(user: AuthUser): PublicUser
  • toPublicSession
    toPublicSession(session: AuthSession): PublicSession
  • cookieNamesgetter
    cookieNames:
  • spendMfaTicket
    spendMfaTicket(ticket: string): Promise<boolean>

    Mints the short-lived ticket handed back when 2FA stops a sign-in.

    Short-lived on purpose: it authorises nothing on its own, but it is the half of a two-factor check, so a longer life is a wider window for a captured value. Public because every sign-in route needs it — password, passkey, OAuth and magic link all stop here — and four private copies would be four chances to give one of them a different lifetime. Takes an MFA ticket out of circulation, reporting whether it was still there. Uses the store's atomic `consume` where it offers one. Without it this is a read followed by a delete, which two concurrent callers can both pass — and the second session is exactly the one an attacker wants.

  • issueMfaTicket
    issueMfaTicket(user: AuthUser): MfaChallenge
  • createAuthResult
    createAuthResult(user: AuthUser, client: { ip?: string; userAgent?: string; }): Promise<AuthResult>
  • buildAuthResult
    buildAuthResult(user: AuthUser, session: AuthSession, rawSessionToken: string, refreshJwt: string): AuthResult
  • makeCookie
    makeCookie(name: string, value: string, opts: { maxAge: number; httpOnly?: boolean; }): string
  • parseCookies
    parseCookies(header: string): Record<string, string>

    Cookies from a `Cookie:` header.

    Built on a null-prototype object, for the same reason `Context.query()` is: a plain `{}` inherits from `Object.prototype`, so a read of a key nobody sent returns the inherited value rather than nothing. The default cookie names are namespaced — `yatta_session`, `yatta_refresh`, `yatta_csrf` — so no inherited key can collide with them and this is not reachable out of the box. But the names are configurable, and `csrfCookieName: "constructor"` or any other Object.prototype member hands back a function where a token belongs. That value is then compared against a header, which is a check that quietly stops checking.

  • signupproperty
    signup:
  • loginproperty
    login:
  • logoutproperty
    logout:

AuthApiKeys

class

4 members

  • create
    create(userId: string, options: { name: string; scopes?: string[]; expiresAt?: Date; }): Promise<{ apiKey: string; record: AuthApiKey; }>
  • verify
    verify(rawKey: string, options?: { requireScope?: string; }): Promise<ApiKeyPrincipal | null>
  • list
    list(userId: string)
  • revoke
    revoke(userId: string, id: string)

AuthCrypto

class

13 members

  • shortSecretWarnedproperty
    shortSecretWarned:
  • encKeyproperty
    encKey: Buffer
  • jwtKeyproperty
    jwtKey: Buffer
  • oauthKeyproperty
    oauthKey: Buffer
  • recoveryKeyproperty
    recoveryKey: Buffer
  • timingSafeEqual
    timingSafeEqual(a: string, b: string): boolean
  • hash
    hash(value: string): string
  • hmac
    hmac(value: string, key: Buffer): string
  • randomToken
    randomToken(bytes?: ): string
  • encrypt
    encrypt(plainText: string): string
  • decrypt
    decrypt(cipherPayload: string): string
  • hashPassword
    hashPassword(password: string): Promise<string>
  • verifyPassword
    verifyPassword(password: string, hash: string): Promise<boolean>

AuthError

class
class AuthError extends Error

AuthJwt

class
class AuthJwt

2 members

  • sign
    sign(payload: Omit<JwtClaims, "iat" | "exp" | "jti"> & { expInSec: number; jti?: string; }): string
  • verify
    verify(token: string): JwtClaims | null
class

2 members

  • request
    request(email: string, req?: Request): Promise<void>
  • verify
    verify(rawToken: string, req?: Request): Promise<AuthResult | MfaChallenge>

AuthMfa

class
class AuthMfa

5 members

  • beginSetup
    beginSetup(userId: string, appName?: )
  • verifyCode
    verifyCode(secret: string, code: string, user?: AuthUser): boolean | "replayed"

    Whether a TOTP code is valid for this user right now.

    Returns `true`, `false`, or `"replayed"`. `replayed` is distinguished because the situation is not the user's mistake. A code that is genuinely correct but inside a time-step already used is rejected — rightly — but reported as "that code is not valid" it reads as a typo, and the user retypes a code that will never work. It happens on enrolment: the code used to set 2FA up consumes the step, so signing in inside the same 30 seconds is refused.

  • confirmSetup
    confirmSetup(userId: string, code: string): Promise<{ recoveryCodes: string[]; }>
  • disable
    disable(req: Request, code?: string): Promise<void>
  • consumeRecoveryCode
    consumeRecoveryCode(userId: string, rawCode: string): Promise<boolean>

AuthOAuth

class
class AuthOAuth

6 members

  • providersproperty
    providers:
  • registerProvider
    registerProvider(provider: OAuthProvider)
  • registerDefaults
    registerDefaults()
  • getAuthorizationUrl
    getAuthorizationUrl(providerName: string, redirectUri: string): Promise<{ url: string; state: string; codeVerifier?: string; }>
  • sessionUserId
    sessionUserId(req: Request | undefined): Promise<string | null>

    Completes an OAuth sign-in, or links a provider to the caller's own account.

    `linkToUserId` has been removed, and deliberately not replaced with `linkToSessionToken`-style indirection of the same shape. Taking a user id from the caller and checking only that it *exists* is account takeover: anyone who can run their own Google sign-in and guess a victim's id passes their identity to `linkIdentity`, and from then on Google signs them in as the victim. To link, pass `req` with the caller's own session cookie. The user is resolved from that session inside this function, so the answer cannot be forged. The user id behind a request's own session, or `null`. Where an operation must act on the caller rather than on a value they supplied. Returning `null` rather than throwing keeps the call sites readable: "no session" and "a session" are two ordinary cases, and only the caller knows which it is. Goes through `getSession` rather than reading the cookie itself, so bearer tokens and the JWT path resolve here too. Reading only the cookie would make linking work in a browser and silently do nothing for a native client. `autoRefresh` is off: this decides who the request is, and a failed refresh should leave that as no answer rather than minting a new session to find out.

  • handleCallback
    handleCallback(input: { provider: string; code: string; state: string; expectedState: string; redirectUri: string; codeVerifier?: string; req?: Request; }): Promise<AuthResult | MfaChallenge>

AuthPasskey

class

8 members

  • rpConfiggetter
    rpConfig:
  • generateRegistrationOptions
    generateRegistrationOptions(userId: string)
  • verifyRegistration
    verifyRegistration(userId: string, response: RegistrationResponseJSON, expectedChallenge: string, name?: string)
  • generateAuthenticationOptions
    generateAuthenticationOptions(userEmail?: string, req?: Request)
  • verifyAuthentication
    verifyAuthentication(response: AuthenticationResponseJSON, expectedChallenge: string, req?: Request): Promise<AuthResult | MfaChallenge>
  • list
    list(userId: string)
  • rename
    rename(userId: string, id: string, name: string)
  • remove
    remove(userId: string, id: string)

AuthPasswordSubsystem

class

3 members

  • requestReset
    requestReset(email: string, req?: Request): Promise<void>
  • reset
    reset(rawToken: string, newPassword: string): Promise<void>
  • change
    change(userId: string, currentPass: string, newPass: string, currentSessionId?: string): Promise<void>

ForbiddenError

class

GranularRateLimiter

class

4 members

  • isEnabled
    isEnabled(): boolean
  • assertAllowed
    assertAllowed(bucket: keyof RateLimitConfig, ip: string, identifier?: string): Promise<void>
  • recordFailure
    recordFailure(bucket: keyof RateLimitConfig, ip: string, identifier?: string): Promise<void>
  • recordSuccess
    recordSuccess(bucket: keyof RateLimitConfig, ip: string, identifier?: string): Promise<void>

MemoryAuditStore

class

3 members

  • eventsproperty
    events: AuthEvent[]
  • record
    record(event: AuthEvent): Promise<void>
  • listByUser
    listByUser(userId: string, limit?: ): Promise<AuthEvent[]>

MemoryAuthStore

class
class MemoryAuthStore implements AuthStore

38 members

  • usersproperty
    users:
  • sessionsproperty
    sessions:
  • identitiesproperty
    identities:
  • tokensproperty
    tokens:
  • passkeysproperty
    passkeys:
  • apiKeysproperty
    apiKeys:
  • findUserById
    findUserById(id: string)
  • findUserByEmail
    findUserByEmail(email: string)
  • createUser
    createUser(data: Omit<AuthUser, "createdAt" | "updatedAt">)
  • updateUser
    updateUser(id: string, updates: Partial<AuthUser>)
  • deleteUser
    deleteUser(id: string)
  • createSession
    createSession(session: AuthSession)
  • findSessionById
    findSessionById(id: string)
  • findSessionByTokenHash
    findSessionByTokenHash(tokenHash: string)
  • timingSafeEqual
    timingSafeEqual(a: string, b: string): boolean
  • listSessionsByUserId
    listSessionsByUserId(userId: string)
  • updateSession
    updateSession(id: string, updates: Partial<AuthSession>)
  • deleteSession
    deleteSession(id: string)
  • deleteSessionsByUserId
    deleteSessionsByUserId(userId: string)
  • findIdentity
    findIdentity(provider: string, providerAccountId: string)
  • listIdentitiesByUserId
    listIdentitiesByUserId(userId: string)
  • createIdentity
    createIdentity(identity: AuthIdentity)
  • deleteIdentity
    deleteIdentity(id: string)
  • createToken
    createToken(token: AuthVerificationToken)
  • findTokenByHash
    findTokenByHash(tokenHash: string, type: AuthVerificationToken["type"])
  • consumeToken
    consumeToken(tokenHash: string, type: AuthVerificationToken["type"])
  • deleteToken
    deleteToken(id: string)
  • deleteTokensByUserId
    deleteTokensByUserId(userId: string, type?: AuthVerificationToken["type"])
  • savePasskey
    savePasskey(cred: AuthPasskeyCredential)
  • findPasskeyById
    findPasskeyById(id: string)
  • listPasskeysByUserId
    listPasskeysByUserId(userId: string)
  • updatePasskey
    updatePasskey(id: string, updates: Partial<AuthPasskeyCredential>)
  • deletePasskey
    deletePasskey(id: string)
  • createApiKey
    createApiKey(key: AuthApiKey)
  • findApiKeyByHash
    findApiKeyByHash(keyHash: string)
  • listApiKeysByUserId
    listApiKeysByUserId(userId: string)
  • updateApiKey
    updateApiKey(id: string, updates: Partial<AuthApiKey>)
  • deleteApiKey
    deleteApiKey(id: string)

MemoryChallengeStore

class

5 members

  • challengesproperty
    challenges:
  • set
    set(challenge: AuthChallenge): Promise<void>
  • get
    get(challengeString: string): Promise<AuthChallenge | null>
  • consume
    consume(challengeString: string): Promise<AuthChallenge | null>

    Reads and removes in one step.

    Atomic for this store: the map is synchronous and nothing awaits between the read and the delete, so two concurrent calls cannot both see the entry.

  • delete
    delete(challengeString: string): Promise<void>

MemoryRateLimitStore

class

4 members

  • storeproperty
    store:
  • get
    get(key: string)
  • set
    set(key: string, data: { hits: number[]; lockoutUntil?: number; }, ttlSec: number)
  • delete
    delete(key: string)

PermissionManager

class

4 members

  • permissionsproperty
    permissions:
  • initialize
    initialize(roleDefs?: RoleDefinitions)
  • resolvePermissionsForRole
    resolvePermissionsForRole(role: string, defs: RoleDefinitions, path: Set<string>): Set<string>
  • check
    check(userRoles: string[], action: string, resource: string, isOwner?: ): boolean

RateLimitError

class

SecurityReauthRequiredError

class

SecurityRiskEngine

class

1 member

  • assessLoginRisk
    assessLoginRisk(ctx: RiskContext): Promise<{ risk: "low" | "medium" | "high"; reasons: string[]; }>

UnauthorizedError

class

Types

ApiKeyPrincipal

interface

A verified API key, with its scopes attached as behaviour rather than as data.

`scopes` alone is easy to ignore: a check written once and missed in one route is an authorisation bug that no type checker reports. `requireScope` puts the check in the type, so using the key without considering it is the awkward path.

interface ApiKeyPrincipal

5 members

  • userproperty
    user: PublicUser
  • apiKeyproperty
    apiKey: AuthApiKey
  • scopesproperty
    scopes: string[]
  • hasScopeproperty
    hasScope: (scope: string) => boolean
  • requireScopeproperty
    requireScope: (scope: string) => void

AuthApiKey

interface
interface AuthApiKey

9 members

  • idproperty
    id: string
  • userIdproperty
    userId: string
  • nameproperty
    name: string
  • keyHashproperty
    keyHash: string
  • prefixproperty
    prefix: string
  • scopesproperty
    scopes: string[]
  • expiresAtproperty
    expiresAt?: Date
  • lastUsedAtproperty
    lastUsedAt?: Date
  • createdAtproperty
    createdAt: Date

AuthAuditStore

interface
interface AuthAuditStore

2 members

  • record
    record(event: AuthEvent): Promise<void>
  • listByUser
    listByUser(userId: string, limit?: number): Promise<AuthEvent[]>

AuthChallenge

interface
interface AuthChallenge

7 members

  • idproperty
    id: string
  • challengeproperty
    challenge: string

    The lookup key, and by convention also the payload.

    The store indexes on this field, so it must be the value the caller will look up later. WebAuthn satisfies both at once, because the challenge string *is* the thing being verified.

  • typeproperty
    type: "registration" | "authentication"
  • userIdproperty
    userId?: string
  • dataproperty
    data?: string

    Extra payload, for a challenge whose key is not its own payload.

    MFA enrolment is the case that needs it: the caller to look up later is known only by user id, while the value worth keeping is the TOTP seed. The seed lives here (encrypted) and the key is derived from the user id.

  • expiresAtproperty
    expiresAt: Date
  • ipproperty
    ip?: string

AuthChallengeStore

interface

4 members

  • set
    set(challenge: AuthChallenge): Promise<void>
  • get
    get(challengeString: string): Promise<AuthChallenge | null>
  • delete
    delete(challengeString: string): Promise<void>
  • consume
    consume(challengeString: string): Promise<AuthChallenge | null>?

    Reads and removes a challenge in one step.

    Optional, and the caller must fall back to `get` + `delete` when it is absent. That fallback is racy across workers — two callers can both pass the `get` — so anything spent on its way in (an MFA ticket, a one-time link) needs this to be a real atomic take rather than a read followed by a hope.

AuthConfig

interface
interface AuthConfig

14 members

  • secretproperty
    secret: string
  • storeproperty
    store?: AuthStore
  • challengeStoreproperty
    challengeStore?: AuthChallengeStore
  • mfaproperty
    mfa?: { challengeTtlSec?: number; }

    Two-factor settings. Applies to every sign-in route, not just passwords.

  • rateLimitStoreproperty
    rateLimitStore?: RateLimitStore
  • auditStoreproperty
    auditStore?: AuthAuditStore
  • sessionproperty
    session?: SessionConfig
  • passwordPolicyproperty
    passwordPolicy?: PasswordPolicyConfig
  • securityproperty
    security?: SecurityConfig
  • rateLimitsproperty
    rateLimits?: RateLimitConfig
  • cookiesproperty
    cookies?: CookieOptions
  • emailproperty
    email?: AuthEmailConfig
  • passkeysproperty
    passkeys?: { rpName: string; rpID: string; origin: string; }
  • rolesproperty
    roles?: RoleDefinitions

AuthEmailConfig

interface
interface AuthEmailConfig

5 members

  • fromproperty
    from?: EmailAddress
  • appUrlproperty
    appUrl?: string
  • mailerproperty
    mailer?: YattaMailer
  • resendCooldownSecproperty
    resendCooldownSec?: number
  • templatesproperty
    templates?: { verification?: (data: AuthEmailTemplateData) => { subject: string; html: string; text?: string; }; passwordReset?: (data: AuthEmailTemplateData) => { subject: string; html: string; text?: string; }; magicLink?: (data: AuthEmailTemplateData) => { subject: string; html: string; text?: string; }; }

AuthEmailTemplateData

interface

3 members

  • emailproperty
    email: string
  • linkproperty
    link: string
  • tokenproperty
    token: string

AuthEvent

interface
interface AuthEvent

7 members

  • idproperty
    id: string
  • userIdproperty
    userId?: string
  • typeproperty
    type: string
  • ipproperty
    ip?: string
  • userAgentproperty
    userAgent?: string
  • metadataproperty
    metadata?: Record<string, unknown>
  • timestampproperty
    timestamp: Date

AuthIdentity

interface
interface AuthIdentity

7 members

  • idproperty
    id: string
  • userIdproperty
    userId: string
  • providerproperty
    provider: string
  • providerAccountIdproperty
    providerAccountId: string
  • emailproperty
    email?: string
  • createdAtproperty
    createdAt: Date
  • updatedAtproperty
    updatedAt: Date

AuthMembership

interface
interface AuthMembership

5 members

  • idproperty
    id: string
  • organizationIdproperty
    organizationId: string
  • userIdproperty
    userId: string
  • roleproperty
    role: string
  • createdAtproperty
    createdAt: Date

AuthOrganization

interface

4 members

  • idproperty
    id: string
  • nameproperty
    name: string
  • slugproperty
    slug: string
  • createdAtproperty
    createdAt: Date

AuthPasskeyCredential

interface

8 members

  • idproperty
    id: string
  • userIdproperty
    userId: string
  • nameproperty
    name?: string
  • publicKeyproperty
    publicKey: Uint8Array
  • counterproperty
    counter: number
  • transportsproperty
    transports?: AuthenticatorTransport[]
  • createdAtproperty
    createdAt: Date
  • lastUsedAtproperty
    lastUsedAt?: Date

AuthResult

interface
interface AuthResult

5 members

  • userproperty
    user: PublicUser
  • sessionproperty
    session: PublicSession
  • tokensproperty
    tokens: TokenPair
  • cookiesproperty
    cookies: string[]
  • toResponse
    toResponse(body?: Record<string, unknown>, status?: number): Response

AuthSession

interface
interface AuthSession

5 members

  • sessionTokenHashproperty
    sessionTokenHash: string
  • refreshTokenHashproperty
    refreshTokenHash?: string
  • previousRefreshTokenHashproperty
    previousRefreshTokenHash?: string
  • rotatedAtproperty
    rotatedAt?: Date
  • refreshVersionproperty
    refreshVersion: number

AuthStore

interface
interface AuthStore

37 members

  • findUserById
    findUserById(id: string): Promise<AuthUser | null>
  • findUserByEmail
    findUserByEmail(email: string): Promise<AuthUser | null>
  • createUser
    createUser(user: Omit<AuthUser, "createdAt" | "updatedAt">): Promise<AuthUser>
  • updateUser
    updateUser(id: string, updates: Partial<AuthUser>): Promise<AuthUser>
  • deleteUser
    deleteUser(id: string): Promise<void>
  • createSession
    createSession(session: AuthSession): Promise<AuthSession>
  • findSessionById
    findSessionById(id: string): Promise<AuthSession | null>
  • findSessionByTokenHash
    findSessionByTokenHash(tokenHash: string): Promise<AuthSession | null>
  • listSessionsByUserId
    listSessionsByUserId(userId: string): Promise<AuthSession[]>
  • updateSession
    updateSession(id: string, updates: Partial<AuthSession>): Promise<AuthSession>
  • deleteSession
    deleteSession(id: string): Promise<void>
  • deleteSessionsByUserId
    deleteSessionsByUserId(userId: string): Promise<void>
  • findIdentity
    findIdentity(provider: string, providerAccountId: string): Promise<AuthIdentity | null>
  • listIdentitiesByUserId
    listIdentitiesByUserId(userId: string): Promise<AuthIdentity[]>
  • createIdentity
    createIdentity(identity: AuthIdentity): Promise<AuthIdentity>
  • deleteIdentity
    deleteIdentity(id: string): Promise<void>
  • createToken
    createToken(token: AuthVerificationToken): Promise<AuthVerificationToken>
  • findTokenByHash
    findTokenByHash(tokenHash: string, type: AuthVerificationToken["type"]): Promise<AuthVerificationToken | null>
  • consumeToken
    consumeToken(tokenHash: string, type: AuthVerificationToken["type"]): Promise<AuthVerificationToken | null>
  • deleteToken
    deleteToken(id: string): Promise<void>
  • deleteTokensByUserId
    deleteTokensByUserId(userId: string, type?: AuthVerificationToken["type"]): Promise<void>
  • savePasskey
    savePasskey(cred: AuthPasskeyCredential): Promise<void>
  • findPasskeyById
    findPasskeyById(id: string): Promise<AuthPasskeyCredential | null>
  • listPasskeysByUserId
    listPasskeysByUserId(userId: string): Promise<AuthPasskeyCredential[]>
  • updatePasskey
    updatePasskey(id: string, updates: Partial<AuthPasskeyCredential>): Promise<void>
  • deletePasskey
    deletePasskey(id: string): Promise<void>
  • createApiKey
    createApiKey(key: AuthApiKey): Promise<AuthApiKey>
  • findApiKeyByHash
    findApiKeyByHash(keyHash: string): Promise<AuthApiKey | null>
  • listApiKeysByUserId
    listApiKeysByUserId(userId: string): Promise<AuthApiKey[]>
  • updateApiKey
    updateApiKey(id: string, updates: Partial<AuthApiKey>): Promise<void>
  • deleteApiKey
    deleteApiKey(id: string): Promise<void>
  • createOrganization
    createOrganization(org: AuthOrganization): Promise<AuthOrganization>?
  • findOrganizationById
    findOrganizationById(id: string): Promise<AuthOrganization | null>?
  • findOrganizationBySlug
    findOrganizationBySlug(slug: string): Promise<AuthOrganization | null>?
  • createMembership
    createMembership(membership: AuthMembership): Promise<AuthMembership>?
  • findMembership
    findMembership(orgId: string, userId: string): Promise<AuthMembership | null>?
  • listMembershipsByUserId
    listMembershipsByUserId(userId: string): Promise<AuthMembership[]>?

AuthUser

interface
interface AuthUser

5 members

  • passwordHashproperty
    passwordHash?: string
  • encryptedTwoFactorSecretproperty
    encryptedTwoFactorSecret?: string | null
  • twoFactorRecoveryCodesproperty
    twoFactorRecoveryCodes?: string[] | null
  • lastMfaStepproperty
    lastMfaStep?: number
  • credentialVersionproperty
    credentialVersion: number

AuthVerificationToken

interface

5 members

  • idproperty
    id: string
  • userIdproperty
    userId: string
  • tokenHashproperty
    tokenHash: string
  • typeproperty
    type: "email_verification" | "password_reset" | "magic_link"
  • expiresAtproperty
    expiresAt: Date

CookieOptions

interface
interface CookieOptions

7 members

  • sessionCookieNameproperty
    sessionCookieName?: string
  • refreshCookieNameproperty
    refreshCookieName?: string
  • csrfCookieNameproperty
    csrfCookieName?: string
  • domainproperty
    domain?: string
  • pathproperty
    path?: string
  • secureproperty
    secure?: boolean
  • sameSiteproperty
    sameSite?: "Lax" | "Strict" | "None"

JwtClaims

interface
interface JwtClaims

8 members

  • subproperty
    sub: string
  • typeproperty
    type: "access" | "refresh" | "mfa"

    `mfa` is a short-lived, single-use ticket for the second half of a sign-in. It

  • sidproperty
    sid?: string
  • jtiproperty
    jti: string
  • verproperty
    ver?: number
  • amrproperty
    amr?: string

    How the first factor was satisfied. Present on `mfa` tickets.

  • expproperty
    exp: number
  • iatproperty
    iat: number

MfaChallenge

interface

What a sign-in returns when it stops at the second factor.

A `ticket`, not a `userId`. With a bare id, whatever the app built as its second step had no proof the first factor had passed — see .

interface MfaChallenge

3 members

  • mfaRequiredproperty
    mfaRequired: true
  • ticketproperty
    ticket: string

    Short-lived, single-use, signed. Pass it to `completeMfa`.

  • expiresInSecproperty
    expiresInSec: number

    When the ticket stops working. For a countdown in the UI.

OAuthProvider

interface
interface OAuthProvider

9 members

  • nameproperty
    name: string
  • clientIdproperty
    clientId: string
  • clientSecretproperty
    clientSecret: string
  • authorizeUrlproperty
    authorizeUrl: string
  • tokenUrlproperty
    tokenUrl: string
  • userInfoUrlproperty
    userInfoUrl: string
  • scopesproperty
    scopes: string[]
  • usePkceproperty
    usePkce?: boolean
  • mapProfileproperty
    mapProfile: (data: Record<string, unknown>) => { id: string; email: string; emailVerified: boolean; name?: string; }

PasswordPolicyConfig

interface

6 members

  • minLengthproperty
    minLength?: number
  • maxLengthproperty
    maxLength?: number
  • requireUppercaseproperty
    requireUppercase?: boolean
  • requireLowercaseproperty
    requireLowercase?: boolean
  • requireNumbersproperty
    requireNumbers?: boolean
  • requireSymbolsproperty
    requireSymbols?: boolean

PublicSession

interface
interface PublicSession

10 members

  • idproperty
    id: string
  • userIdproperty
    userId: string
  • expiresAtproperty
    expiresAt: Date
  • lastSeenAtproperty
    lastSeenAt: Date
  • lastAuthenticatedAtproperty
    lastAuthenticatedAt: Date
  • createdAtproperty
    createdAt: Date
  • userAgentproperty
    userAgent?: string
  • ipproperty
    ip?: string
  • deviceIdproperty
    deviceId?: string
  • deviceNameproperty
    deviceName?: string

PublicUser

interface
interface PublicUser

8 members

  • idproperty
    id: string
  • emailproperty
    email: string
  • rolesproperty
    roles: string[]
  • emailVerifiedproperty
    emailVerified: boolean
  • twoFactorEnabledproperty
    twoFactorEnabled: boolean
  • metadataproperty
    metadata?: Record<string, unknown>
  • createdAtproperty
    createdAt: Date
  • updatedAtproperty
    updatedAt: Date

RateLimitConfig

interface
interface RateLimitConfig

6 members

  • enabledproperty
    enabled?: boolean
  • loginproperty
    login?: { maxAttempts: number; windowSec: number; lockoutSec: number; }
  • signupproperty
    signup?: { maxAttempts: number; windowSec: number; lockoutSec: number; }
  • passwordResetproperty
    passwordReset?: { maxAttempts: number; windowSec: number; lockoutSec: number; }
  • magicLinkproperty
    magicLink?: { maxAttempts: number; windowSec: number; lockoutSec: number; }
  • passkeyproperty
    passkey?: { maxAttempts: number; windowSec: number; lockoutSec: number; }

RateLimitStore

interface
interface RateLimitStore

3 members

  • get
    get(key: string): Promise<{ hits: number[]; lockoutUntil?: number; } | null>
  • set
    set(key: string, data: { hits: number[]; lockoutUntil?: number; }, ttlSec: number): Promise<void>
  • delete
    delete(key: string): Promise<void>

RiskContext

interface
interface RiskContext

3 members

  • userproperty
    user: AuthUser
  • ipproperty
    ip?: string
  • userAgentproperty
    userAgent?: string

SecurityConfig

interface
interface SecurityConfig

7 members

  • trustProxyproperty
    trustProxy?: boolean

    Trust `cf-connecting-ip` / `x-real-ip` / `x-forwarded-for` for the client IP.

    Only enable when a proxy you control sets them and **strips any incoming copy**. Otherwise a client can send the header itself and rotate apparent IPs to walk straight past the rate limiter.

  • trustedProxyCountproperty
    trustedProxyCount?: number

    How many proxies sit in front of this process and are trusted to append to

    Defaults to 1. `x-forwarded-for` reads `client, proxy1, proxy2…`, and the client writes the leftmost entry — so the client IP is found by counting back from the right, past every proxy you trust. One proxy means the second-to-last entry; a CDN plus a load balancer means the third-to-last. Getting this wrong in the permissive direction is a rate-limit bypass, and in the strict direction every client appears to be your proxy. Set it from your topology rather than guessing.

  • getClientIpproperty
    getClientIp?: (req: Request) => string | undefined

    Resolve the peer address of a request.

    Bun does not expose it on `Request`; read it from the server instead: `getClientIp: (req) => server.requestIP(req)?.address`. Without this, every client is seen as 127.0.0.1 and all per-IP rate limits become global.

  • recentAuthWindowSecproperty
    recentAuthWindowSec?: number
  • allowUnverifiedSessionproperty
    allowUnverifiedSession?: boolean
  • preventAccountEnumerationproperty
    preventAccountEnumeration?: boolean
  • encryptionKeyproperty
    encryptionKey?: string

SessionConfig

interface
interface SessionConfig

5 members

  • accessTokenTtlSecproperty
    accessTokenTtlSec?: number
  • refreshTokenTtlSecproperty
    refreshTokenTtlSec?: number
  • sessionTtlSecproperty
    sessionTtlSec?: number
  • activityThrottleSecproperty
    activityThrottleSec?: number
  • autoRefreshOnCookieAuthproperty
    autoRefreshOnCookieAuth?: boolean

TokenPair

interface
interface TokenPair

3 members

  • accessTokenproperty
    accessToken: string
  • refreshTokenproperty
    refreshToken: string
  • expiresInproperty
    expiresIn: number

RoleDefinitions

type
type RoleDefinitions = Record<string, string[] | { can: string[]; inherits?: string[]; }>
Tip
Most of the types above are inferred. You rarely import AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.