API reference

yatta/auth

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

53 exported symbols and 348 members, read from src/types/auth.ts.

Construct

createAuth

function

Creates and initializes a global engine instance.

createAuth(config: AuthConfig): Auth
config
Master authentication settings.

Returns Configured `Auth` instance.

tsts
export const auth = createAuth({  secret: process.env.AUTH_SECRET!,  store: new SQLiteAuthStore(),});

getDefaultAuth

function

Returns the active default instance initialized via .

getDefaultAuth(): Auth

Auth

class

Enterprise Authentication & Security Engine for Bun and web runtimes.

class Auth
tsts
const auth = createAuth({ secret: process.env.AUTH_SECRET! });const { user, tokens, toResponse } = await auth.signUp({  email: "dev@example.com",  password: "SuperSecretPassword123!",});

46 members

  • storeproperty
    store: AuthStore

    Database storage adapter for persistent data.

  • challengeStoreproperty
    challengeStore: AuthChallengeStore

    Storage adapter for WebAuthn challenges.

  • rateLimitStoreproperty
    rateLimitStore: RateLimitStore

    Storage adapter for rate limiting hits and lockouts.

  • auditStoreproperty
    auditStore: AuthAuditStore

    Storage adapter for audit logs.

  • configproperty
    config: AuthConfig

    Resolved configuration.

  • cryptoproperty
    crypto: AuthCrypto

    Cryptography and hashing utility.

  • jwtproperty
    jwt: AuthJwt

    JWT token manager.

  • permissionsproperty
    permissions: PermissionManager

    Role and permission manager.

  • rateLimiterproperty
    rateLimiter: GranularRateLimiter

    Rate limiter subsystem.

  • riskproperty
    risk: SecurityRiskEngine

    Security risk and anomaly engine.

  • mfaproperty
    mfa: AuthMfa

    Multi-Factor Authentication (TOTP & Recovery Codes) subsystem.

  • passkeyproperty
    passkey: AuthPasskey

    FIDO2 / WebAuthn Passkeys subsystem.

  • oauthproperty
    oauth: AuthOAuth

    Third-party OAuth provider subsystem.

  • magicLinkproperty
    magicLink: AuthMagicLink

    Passwordless Magic Links subsystem.

  • apiKeysproperty
    apiKeys: AuthApiKeys

    Developer API Keys subsystem.

  • passwordproperty
    password: AuthPasswordSubsystem

    Password resets and password updates subsystem.

  • eventListenersproperty
    eventListeners:
  • mailergetter
    mailer: YattaMailer

    Resolved mailer instance used for sending transactional emails.

  • on
    on(event: string, listener: (payload: any) => void | Promise<void>)

    Subscribes to an authentication or security event.

    event
    Event name (e.g. `"signup"`, `"login.success"`, `"security.token_replay"`).
    listener
    Callback function invoked with event payload.
  • emit
    emit(event: string, payload: Record<string, unknown>, req?: Request)

    Emits an auth event, writes to the audit store, and notifies active listeners.

    event
    Event identifier.
    payload
    Metadata attached to the event.
    req
    Optional HTTP request for extracting client IP and User-Agent.
  • signUp
    signUp(input: { email: string; password?: string; roles?: string[]; metadata?: Record<string, unknown>; req?: Request; }): Promise<AuthResult | { user: PublicUser; emailVerificationRequired: true; }>

    Registers a new user account with email and optional password, roles, and metadata.

    input
    Signup parameters.
    input.email
    User email address.
    input.password
    Optional plaintext password.
    input.roles
    Optional custom roles (defaults to `["user"]`).
    input.metadata
    Optional profile metadata bag.
    input.req
    Optional HTTP Request for rate limiting and client auditing.

    Returns Complete if unverified sessions are allowed, or `{ user, emailVerificationRequired: true }`.

    tsts
    const result = await auth.signUp({  email: "user@example.com",  password: "MyPassword123!",});
  • signIn
    signIn(input: { email: string; password?: string; mfaCode?: string; recoveryCode?: string; req?: Request; }): Promise<AuthResult | { mfaRequired: true; userId: string; }>

    Authenticates user credentials with brute-force lockout checks and TOTP/recovery verification.

    input
    Login parameters.
    input.email
    Registered user email.
    input.password
    Plaintext password.
    input.mfaCode
    Optional 6-digit TOTP code if 2FA is enabled.
    input.recoveryCode
    Optional backup recovery code if 2FA device is lost.
    input.req
    Optional incoming HTTP Request for rate limiting and anomaly scoring.
    tsts
    const result = await auth.signIn({  email: "user@example.com",  password: "MyPassword123!",});if ("mfaRequired" in result) {  // Prompt user for 6-digit 2FA code}
  • signOut
    signOut(reqOrToken: Request | { req: Request; } | string): Promise<{ success: boolean; cookies: string[]; }>

    Terminates an active user session and returns cleared cookie headers.

    reqOrToken
    Incoming Request (cookies/Authorization header) or raw session token string.

    Returns Status object with cleared cookie strings.

    tsts
    const { cookies } = await auth.signOut(req);return API.withCookies(API.json({ message: "Logged out" }), cookies);
  • getSession
    getSession(reqOrToken: Request | { req: Request; } | string, options?: { autoRefresh?: boolean; }): Promise<{ user: PublicUser; session: AuthSession; newCookies?: string[]; } | null>

    Resolves the active user and session from a Request (via Authorization header or Cookie)

    reqOrToken
    HTTP Request or bearer token string.
    options
    Options including `autoRefresh` behavior.

    Returns Object containing authenticated `user` and `session`, or `null` if unauthenticated.

    tsts
    const authState = await auth.getSession(req);if (authState) {  console.log("Logged in as:", authState.user.email);}
  • getUser
    getUser(req: Request): Promise<PublicUser | null>

    Resolves the authenticated user from an HTTP Request, returning `null` if not logged in.

    req
    Incoming HTTP Request.

    Returns User profile or `null`.

  • requireUser
    requireUser(req: Request): Promise<PublicUser>

    Asserts that a request is authenticated, throwing if not.

    req
    Incoming HTTP Request.

    Returns The authenticated .

  • requireRecentAuth
    requireRecentAuth(req: Request, maxAgeSec?: number): Promise<{ user: PublicUser; session: AuthSession; }>

    Enforces Step-Up Authentication / Recent Authentication for sensitive operations (e.g. billing, password change).

    req
    Incoming HTTP Request.
    maxAgeSec
    Maximum allowable age in seconds since last primary login (default: 600s / 10m).

    Returns The current session and user.

  • refresh
    refresh(refreshToken: string, req?: Request): Promise<AuthResult>

    Refreshes active credentials using a rotating Refresh Token with Token Family replay attack detection.

    refreshToken
    Signed refresh token string.
    req
    Optional HTTP request for client IP/UserAgent auditing.

    Returns Newly generated with rotated tokens.

  • sendVerificationEmail
    sendVerificationEmail(userId: string): Promise<string>

    Generates a 24-hour email verification token and delivers verification instructions via email.

    userId
    Target user ID.

    Returns Raw token string.

  • verifyEmail
    verifyEmail(rawToken: string): Promise<PublicUser>

    Verifies an email token and marks user email as verified.

    rawToken
    Verification token received from email link.

    Returns Updated public user profile.

  • can
    can(userOrRoles: PublicUser | AuthUser | string[])

    Fluent permission checker for evaluating actions and resources against a user's roles.

    userOrRoles
    PublicUser object, AuthUser, or array of role strings.

    Returns Fluent permission evaluation helpers (`.do(perm)` or `.perform(action).on(resource)`).

    tsts
    if (auth.can(user).do("posts:delete")) { ... }if (auth.can(user).perform("edit").on("posts", { isOwner: true })) { ... }
  • protect
    protect(requirements?: { role?: string; permission?: string; })

    Creates an HTTP route middleware requiring authentication and optional roles or permissions.

    requirements
    Optional role or permission restriction.

    Returns Middleware function.

    tsts
    api.use(auth.protect({ role: "admin" }));
  • validateEmail
    validateEmail(email: string): string
  • validatePasswordStrength
    validatePasswordStrength(pass: string): void
  • extractClient
    extractClient(req?: Request | { headers?: Headers | Record<string, string>; }): { ip?: string; userAgent?: string; }
  • toPublicUser
    toPublicUser(user: AuthUser): PublicUser
  • cookieNamesgetter
    cookieNames:
  • 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; }): string
  • parseCookies
    parseCookies(header: string): Record<string, string>
  • signupproperty
    signup:
  • loginproperty
    login:
  • logoutproperty
    logout:
  • sessionproperty
    session:
  • userproperty
    user:

AuthApiKeys

class

Manages developer API keys with cryptographic hashing, visible prefixes, and scoping.

4 members

  • create
    create(userId: string, options: { name: string; scopes?: string[]; expiresAt?: Date; }): Promise<{ apiKey: string; record: AuthApiKey; }>

    Generates a new API key with the format `yk_live_<token>`.

    userId
    Owner user ID.
    options
    Configuration including name, allowed scopes, and optional expiration date.

    Returns Object containing the plaintext `apiKey` and the stored `record`.

    tsts
    const { apiKey } = await auth.apiKeys.create(userId, {  name: "Zapier Integration",  scopes: ["read:data", "write:webhooks"],});
  • verify
    verify(rawKey: string): Promise<{ user: PublicUser; apiKey: AuthApiKey; } | null>

    Verifies an incoming developer API key in constant time and updates its lastUsedAt timestamp.

    rawKey
    Plaintext API key starting with `yk_live_`.

    Returns User profile and API key record, or `null` if invalid or expired.

    tsts
    const authResult = await auth.apiKeys.verify(apiKey);if (authResult) {  console.log("Authenticated service account for:", authResult.user.email);}
  • list
    list(userId: string)

    Lists all API keys owned by a user.

  • revoke
    revoke(id: string)

    Revokes and deletes an API key.

AuthCrypto

class

Hardened cryptographic utility for password hashing, symmetric encryption,

8 members

  • encKeyproperty
    encKey: Buffer
  • timingSafeEqual
    timingSafeEqual(a: string, b: string): boolean

    Constant-time string equality check to prevent timing attacks.

    a
    First string.
    b
    Second string.

    Returns `true` if strings are identically equal in constant time.

  • hash
    hash(value: string): string

    Computes the SHA-256 hexadecimal hash of an input string.

    value
    Input plaintext.

    Returns Hexadecimal digest.

  • randomToken
    randomToken(bytes?: ): string

    Generates a cryptographically secure random hexadecimal token.

    bytes
    Number of random bytes (default: 32).

    Returns Hex-encoded string.

  • encrypt
    encrypt(plainText: string): string

    Encrypts plaintext using authenticated AES-256-GCM.

    plainText
    Sensitive string to encrypt (e.g. TOTP secret).

    Returns Formatted ciphertext envelope.

  • decrypt
    decrypt(cipherPayload: string): string

    Decrypts ciphertext previously encrypted via AES-256-GCM.

    cipherPayload
    Formatted string as `ivHex:tagHex:cipherHex`.

    Returns Decrypted plaintext string.

  • hashPassword
    hashPassword(password: string): Promise<string>

    Hashes a password using native Bun Argon2id (or Scrypt fallback in Node).

    password
    Raw plaintext password.

    Returns Securely hashed password string with salt and parameters.

  • verifyPassword
    verifyPassword(password: string, hash: string): Promise<boolean>

    Verifies a plaintext password against a stored Argon2id or Scrypt hash.

    password
    Plaintext candidate password.
    hash
    Stored password hash string.

    Returns Promise resolving to `true` if password matches.

AuthError

class

Base error class for all Yatta Authentication exceptions.

class AuthError extends Error

AuthJwt

class

HMAC-SHA256 JWT signer and verifier with constant-time signature verification,

class AuthJwt

2 members

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

    Signs a JWT payload with HMAC-SHA256 and Base64URL encoding.

    payload
    Claims without auto-computed `iat` and `exp`.

    Returns Signed JWT string (header.payload.signature).

  • verify
    verify(token: string): JwtClaims | null

    Verifies and decodes a JWT token. Returns parsed claims or `null` if invalid or expired.

    token
    Raw JWT string.

    Returns Parsed or `null`.

class

Passwordless sign-in and sign-up using secure, single-use email links.

2 members

  • request
    request(email: string, req?: Request): Promise<string>

    Generates a 15-minute single-use sign-in link and emails it to the user.

    email
    User email address.
    req
    Optional HTTP Request for rate limiting.

    Returns Raw token string.

    tsts
    await auth.magicLink.request("user@example.com", req);
  • verify
    verify(rawToken: string, req?: Request): Promise<AuthResult>

    Validates and consumes a magic link token, establishing an active user session.

    rawToken
    Token string received from email link.
    req
    Optional HTTP Request for client auditing.

    Returns Authenticated .

AuthMfa

class

Manages Time-Based One-Time Password (TOTP) two-factor authentication

class AuthMfa

6 members

  • pendingSecretsproperty
    pendingSecrets:
  • beginSetup
    beginSetup(userId: string, appName?: )

    Begins 2FA enrollment by generating an uncommitted TOTP secret and QR code URI.

    userId
    Target user ID.
    appName
    Display application name in authenticator apps (e.g. Google Authenticator).

    Returns Secret and otpauth:// URI.

    tsts
    const { secret, uri } = auth.mfa.beginSetup(user.id, "MyApp");
  • verifyCode
    verifyCode(secret: string, code: string): boolean

    Validates a 6-digit TOTP code against a secret.

    secret
    Plaintext TOTP secret.
    code
    6-digit verification code.

    Returns `true` if valid.

  • confirmSetup
    confirmSetup(userId: string, code: string): Promise<{ recoveryCodes: string[]; }>

    Confirms TOTP setup by verifying the first code, encrypts secret at rest with AES-256-GCM,

    userId
    Target user ID.
    code
    6-digit verification code from authenticator app.

    Returns Array of 10 backup recovery codes.

  • disable
    disable(userId: string, req: Request): Promise<void>

    Disables 2FA on a user account. Requires recent step-up authentication.

    userId
    Target user ID.
    req
    Incoming HTTP Request.
  • consumeRecoveryCode
    consumeRecoveryCode(userId: string, rawCode: string): Promise<boolean>

    Validates and burns a single-use backup recovery code.

    userId
    Target user ID.
    rawCode
    Recovery code entered by user.

    Returns `true` if code was valid and consumed.

AuthOAuth

class

Handles OAuth 2.0 authorization flows, PKCE code challenges, and identity linking.

class AuthOAuth

5 members

  • providersproperty
    providers:
  • registerProvider
    registerProvider(provider: OAuthProvider)

    Registers a custom or third-party OAuth provider.

    provider
    OAuth provider configuration.
  • registerDefaults
    registerDefaults()
  • getAuthorizationUrl
    getAuthorizationUrl(providerName: string, redirectUri: string): Promise<{ url: string; state: string; codeVerifier?: string; }>

    Generates the OAuth redirect URL with anti-CSRF HMAC state and PKCE verifier.

    providerName
    Registered provider name (e.g. `"github"`, `"google"`).
    redirectUri
    Callback redirect URI.

    Returns URL to redirect user to, state token, and optional PKCE code verifier.

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

    Handles OAuth callback exchange, validates state & PKCE, links identity to user,

    input
    Callback parameters.

    Returns Completed .

AuthPasskey

class

FIDO2 / WebAuthn Passkeys subsystem for biometric and hardware key authentication.

8 members

  • rpConfiggetter
    rpConfig:
  • generateRegistrationOptions
    generateRegistrationOptions(userId: string)

    Generates WebAuthn registration options to send to the browser's `navigator.credentials.create()`.

    userId
    Authenticated user enrolling a passkey.

    Returns Registration options JSON.

  • verifyRegistration
    verifyRegistration(userId: string, response: RegistrationResponseJSON, expectedChallenge: string, name?: string)

    Verifies WebAuthn registration response from client and stores the public key.

    userId
    Authenticated user ID.
    response
    Browser credential response.
    expectedChallenge
    The challenge previously issued.
    name
    Optional friendly label (e.g. "MacBook TouchID").

    Returns `{ verified: true }`.

  • generateAuthenticationOptions
    generateAuthenticationOptions(userEmail?: string)

    Generates WebAuthn authentication options to send to `navigator.credentials.get()`.

    userEmail
    Optional user email to restrict credential selection.

    Returns Authentication options JSON.

  • verifyAuthentication
    verifyAuthentication(response: AuthenticationResponseJSON, expectedChallenge: string, req?: Request): Promise<AuthResult>

    Verifies a WebAuthn authentication assertion and issues an active login session.

    response
    Browser credential authentication result.
    expectedChallenge
    The authentication challenge issued.
    req
    Optional HTTP Request for client auditing.

    Returns Complete with session tokens.

  • list
    list(userId: string)

    List all passkeys registered by a user.

  • rename
    rename(id: string, name: string)

    Rename a passkey.

  • remove
    remove(id: string)

    Delete a passkey.

AuthPasswordSubsystem

class

Manages password reset flows, secure password updates, and token generation.

3 members

  • requestReset
    requestReset(email: string, req?: Request): Promise<string | null>

    Generates a 1-hour password reset token and sends an email to the user.

    email
    User email address.
    req
    Optional HTTP request for client IP rate limiting.

    Returns Raw token string (or null if user does not exist).

    tsts
    await auth.password.requestReset("user@example.com", req);
  • reset
    reset(rawToken: string, newPassword: string): Promise<void>

    Consumes a password reset token and sets a new password for the user.

    rawToken
    Token string received from reset email link.
    newPassword
    New plaintext password meeting complexity policy.
    tsts
    await auth.password.reset(token, "NewStrongPassword123!");
  • change
    change(userId: string, currentPass: string, newPass: string): Promise<void>

    Updates an authenticated user's password after verifying their current password.

    userId
    The authenticated user ID.
    currentPass
    Existing plaintext password.
    newPass
    New plaintext password.
    tsts
    await auth.password.change(userId, "OldPassword123!", "NewPassword123!");

ForbiddenError

class

Thrown when an authenticated user lacks the necessary roles or permissions (HTTP 403).

GranularRateLimiter

class

Granular sliding-window rate limiter with progressive lockouts.

4 members

  • isEnabled
    isEnabled(): boolean
  • assertAllowed
    assertAllowed(bucket: keyof RateLimitConfig, key: string): Promise<void>

    Asserts that an action is allowed, throwing if locked out.

    bucket
    The rate limit category (e.g. `"login"`, `"signup"`).
    key
    Unique identifier (e.g. IP address or email).
  • recordFailure
    recordFailure(bucket: keyof RateLimitConfig, key: string): Promise<void>

    Records a failed attempt and activates a lockout if threshold is exceeded.

    bucket
    Rate limit category.
    key
    Unique identifier.
  • recordSuccess
    recordSuccess(bucket: keyof RateLimitConfig, key: string): Promise<void>

    Clears failure count on successful authentication.

    bucket
    Rate limit category.
    key
    Unique identifier.

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

44 members

  • usersproperty
    users:
  • sessionsproperty
    sessions:
  • identitiesproperty
    identities:
  • tokensproperty
    tokens:
  • passkeysproperty
    passkeys:
  • apiKeysproperty
    apiKeys:
  • orgsproperty
    orgs:
  • membershipsproperty
    memberships:
  • 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)
  • 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"])
  • 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)
  • createOrganization
    createOrganization(org: AuthOrganization)
  • findOrganizationById
    findOrganizationById(id: string)
  • findOrganizationBySlug
    findOrganizationBySlug(slug: string)
  • createMembership
    createMembership(membership: AuthMembership)
  • findMembership
    findMembership(orgId: string, userId: string)
  • listMembershipsByUserId
    listMembershipsByUserId(userId: string)

MemoryChallengeStore

class

4 members

  • challengesproperty
    challenges:
  • set
    set(challenge: AuthChallenge): Promise<void>
  • get
    get(challengeString: string): Promise<AuthChallenge | null>
  • 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

Evaluates role hierarchies and permissions with wildcard matching (e.g. `"*:*"`, `"posts:*"`).

5 members

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

    Verifies whether a set of user roles has permission to perform an action on a resource.

    userRoles
    Roles assigned to the user.
    action
    The requested operation (e.g. `"read"`, `"delete"`, `"publish"`).
    resource
    The resource domain (e.g. `"posts"`, `"billing"`, `"users"`).
    isOwner
    Whether the user owns the target resource (satisfies `:own` permissions).

    Returns `true` if authorized.

    tsts
    const allowed = auth.permissions.check(["editor"], "publish", "articles");

RateLimitError

class

Thrown when an IP or user exceeds authentication rate limits or enters account lockout (HTTP 429).

SecurityReauthRequiredError

class

Thrown when a sensitive operation requires recent user re-authentication / step-up auth (HTTP 403).

SecurityRiskEngine

class

Evaluates login context against historical session data to detect suspicious activity.

1 member

  • assessLoginRisk
    assessLoginRisk(ctx: RiskContext): Promise<{ risk: RiskLevel; reasons: string[]; }>

    Analyzes IP and browser characteristics against past user sessions.

    ctx
    Risk evaluation context.

    Returns Risk evaluation with level and list of warning reasons.

UnauthorizedError

class

Thrown when an unauthenticated request attempts to access a protected resource (HTTP 401).

Types

AuthApiKey

interface

Developer API key used for programmatic service-to-service access.

interface AuthApiKey

9 members

  • idproperty
    id: string

    Unique API key record ID.

  • userIdproperty
    userId: string

    Associated user/owner ID.

  • nameproperty
    name: string

    Descriptive name for the key (e.g. "CI Deployer", "Production Zapier").

  • keyHashproperty
    keyHash: string

    Cryptographic SHA-256 hash of the full API key secret.

  • prefixproperty
    prefix: string

    Visible key prefix shown to developers (e.g. `"yk_live_ab12"`).

  • scopesproperty
    scopes: string[]

    Granted permission scopes (e.g. `["read:users", "write:billing"]`).

  • expiresAtproperty
    expiresAt?: Date

    Optional expiration date.

  • lastUsedAtproperty
    lastUsedAt?: Date

    Timestamp of the most recent request authenticated with this key.

  • createdAtproperty
    createdAt: Date

    Creation timestamp.

AuthAuditStore

interface

Storage adapter for recording security audit logs.

interface AuthAuditStore

2 members

  • record
    record(event: AuthEvent): Promise<void>

    Record a security event.

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

    List audit events for a given user.

AuthChallenge

interface

Ephemeral WebAuthn challenge used during registration or login.

interface AuthChallenge

6 members

  • idproperty
    id: string

    Challenge record ID.

  • challengeproperty
    challenge: string

    Cryptographically random challenge string.

  • typeproperty
    type: "registration" | "authentication"

    Flow type: `"registration"` or `"authentication"`.

  • userIdproperty
    userId?: string

    Target user ID if known (e.g. during authentication or passkey enrollment).

  • expiresAtproperty
    expiresAt: Date

    Expiration timestamp.

  • ipproperty
    ip?: string

    Client IP address that requested the challenge.

AuthChallengeStore

interface

Storage adapter for storing short-lived WebAuthn registration/authentication challenges.

3 members

  • set
    set(challenge: AuthChallenge): Promise<void>

    Store an ephemeral challenge with an expiration timestamp.

  • get
    get(challengeString: string): Promise<AuthChallenge | null>

    Retrieve a challenge by its raw challenge string.

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

    Delete a challenge once consumed.

AuthConfig

interface

Master configuration options passed into .

interface AuthConfig

13 members

  • secretproperty
    secret: string

    Primary cryptographic signing and HMAC secret key.

  • storeproperty
    store?: AuthStore

    Database storage adapter for users, sessions, tokens, and credentials. Defaults to in-memory store.

  • challengeStoreproperty
    challengeStore?: AuthChallengeStore

    Storage adapter for ephemeral WebAuthn challenges. Defaults to in-memory store.

  • rateLimitStoreproperty
    rateLimitStore?: RateLimitStore

    Storage adapter for rate-limiting hits and lockouts. Defaults to in-memory store.

  • auditStoreproperty
    auditStore?: AuthAuditStore

    Storage adapter for security audit log events. Defaults to in-memory store.

  • sessionproperty
    session?: SessionConfig

    Session and token lifetime settings.

  • passwordPolicyproperty
    passwordPolicy?: PasswordPolicyConfig

    Password complexity rules.

  • securityproperty
    security?: SecurityConfig

    Security, proxy, and encryption settings.

  • rateLimitsproperty
    rateLimits?: RateLimitConfig

    Rate-limiting and lockout thresholds.

  • cookiesproperty
    cookies?: CookieOptions

    HTTP cookie configuration for session tokens.

  • emailproperty
    email?: AuthEmailConfig

    Email transport and verification email configuration.

  • passkeysproperty
    passkeys?: { rpName: string; rpID: string; origin: string; }

    WebAuthn / Passkey relying party configuration.

  • rolesproperty
    roles?: RoleDefinitions

    Hierarchical RBAC role and permission definitions.

AuthEmailConfig

interface

Configuration for automated system emails (verification, password resets, magic links).

interface AuthEmailConfig

5 members

  • fromproperty
    from?: EmailAddress

    Default sender address (e.g. `"noreply@example.com"` or `{ name: "Support", address: "support@example.com" }`).

  • appUrlproperty
    appUrl?: string

    Root application URL used to construct verification and password reset links.

  • mailerproperty
    mailer?: YattaMailer

    Mailer instance for sending emails (defaults to globally registered `Mail`).

  • resendCooldownSecproperty
    resendCooldownSec?: number

    Cooldown time in seconds before allowing another email to be requested. Default: 60.

  • 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; }; }

    Custom template functions for rendered emails.

AuthEmailTemplateData

interface

Data passed into custom email rendering functions.

3 members

  • emailproperty
    email: string

    Recipient email address.

  • linkproperty
    link: string

    One-click action URL.

  • tokenproperty
    token: string

    Raw security token string.

AuthEvent

interface

Security audit log event.

interface AuthEvent

7 members

  • idproperty
    id: string

    Unique event identifier.

  • userIdproperty
    userId?: string

    Target user ID if applicable.

  • typeproperty
    type: string

    Event action type (e.g. `"auth:login:success"`, `"auth:mfa:enable"`, `"auth:password:reset"`).

  • ipproperty
    ip?: string

    Originating client IP address.

  • userAgentproperty
    userAgent?: string

    Originating client User-Agent string.

  • metadataproperty
    metadata?: Record<string, unknown>

    Arbitrary event metadata.

  • timestampproperty
    timestamp: Date

    Timestamp when event occurred.

AuthIdentity

interface

Third-party OAuth or federated identity linked to a user account.

interface AuthIdentity

7 members

  • idproperty
    id: string

    Unique identity record ID.

  • userIdproperty
    userId: string

    Associated local user ID.

  • providerproperty
    provider: string

    OAuth provider identifier (e.g. `"google"`, `"github"`, `"apple"`).

  • providerAccountIdproperty
    providerAccountId: string

    Provider's unique user identifier (e.g. Google sub, GitHub ID).

  • emailproperty
    email?: string

    Email address returned by the OAuth provider.

  • createdAtproperty
    createdAt: Date

    Creation timestamp.

  • updatedAtproperty
    updatedAt: Date

    Last update timestamp.

AuthMembership

interface

User membership inside an organization.

interface AuthMembership

5 members

  • idproperty
    id: string

    Membership ID.

  • organizationIdproperty
    organizationId: string

    Organization ID.

  • userIdproperty
    userId: string

    User ID.

  • roleproperty
    role: string

    Role within organization (e.g. `"owner"`, `"admin"`, `"member"`).

  • createdAtproperty
    createdAt: Date

    Membership start timestamp.

AuthOrganization

interface

Multi-tenant organization or team account.

4 members

  • idproperty
    id: string

    Organization ID.

  • nameproperty
    name: string

    Display name of the organization.

  • slugproperty
    slug: string

    URL-friendly unique slug identifier.

  • createdAtproperty
    createdAt: Date

    Creation timestamp.

AuthPasskeyCredential

interface

FIDO2 / WebAuthn Passkey credential record.

8 members

  • idproperty
    id: string

    Base64URL-encoded credential ID.

  • userIdproperty
    userId: string

    Associated user ID.

  • nameproperty
    name?: string

    User-friendly credential nickname (e.g. "iPhone TouchID", "YubiKey 5").

  • publicKeyproperty
    publicKey: Uint8Array

    Raw binary public key bytes.

  • counterproperty
    counter: number

    Signature counter used to detect cloned authenticators.

  • transportsproperty
    transports?: AuthenticatorTransport[]

    Transport mechanisms supported by the authenticator (e.g. `["usb", "nfc", "ble", "internal"]`).

  • createdAtproperty
    createdAt: Date

    Creation timestamp.

  • lastUsedAtproperty
    lastUsedAt?: Date

    Timestamp when the passkey was last used for authentication.

AuthResult

interface

Result returned upon successful signup, login, or session refresh.

interface AuthResult

5 members

  • userproperty
    user: PublicUser

    The authenticated user profile.

  • sessionproperty
    session: AuthSession

    The created or updated session.

  • tokensproperty
    tokens: TokenPair

    Generated access and refresh token pair.

  • cookiesproperty
    cookies: string[]

    Array of pre-formatted `Set-Cookie` header strings for HTTP response serialization.

  • toResponse
    toResponse(body?: Record<string, unknown>, status?: number): Response

    Helper method to serialize this AuthResult into an HTTP `Response` with proper `Set-Cookie` headers.

    body
    Optional JSON body properties to merge into the response.
    status
    HTTP response status code (default: 200).

    Returns Formatted web-standard `Response`.

AuthSession

interface

Active authentication session record.

interface AuthSession

13 members

  • idproperty
    id: string

    Unique session identifier (UUID).

  • userIdproperty
    userId: string

    Associated user ID.

  • sessionTokenHashproperty
    sessionTokenHash: string

    Cryptographic SHA-256 hash of the bearer session token.

  • refreshTokenHashproperty
    refreshTokenHash?: string

    Cryptographic SHA-256 hash of the active refresh token.

  • expiresAtproperty
    expiresAt: Date

    Timestamp when this session expires.

  • refreshVersionproperty
    refreshVersion: number

    Refresh token rotation counter.

  • userAgentproperty
    userAgent?: string

    Client User-Agent string recorded at login.

  • ipproperty
    ip?: string

    Client IP address recorded at login.

  • deviceIdproperty
    deviceId?: string

    Client device identifier if provided.

  • deviceNameproperty
    deviceName?: string

    Human-readable device name (e.g. "MacBook Pro").

  • lastSeenAtproperty
    lastSeenAt: Date

    Timestamp when session was last actively used.

  • lastAuthenticatedAtproperty
    lastAuthenticatedAt: Date

    Timestamp of the most recent primary authentication (used for Step-Up security checks).

  • createdAtproperty
    createdAt: Date

    Timestamp when session was created.

AuthStore

interface

Storage adapter interface defining database interactions required by the Auth engine.

interface AuthStore

36 members

  • findUserById
    findUserById(id: string): Promise<AuthUser | null>

    Find a user by their unique ID.

  • findUserByEmail
    findUserByEmail(email: string): Promise<AuthUser | null>

    Find a user by their email address.

  • createUser
    createUser(user: Omit<AuthUser, "createdAt" | "updatedAt">): Promise<AuthUser>

    Create and persist a new user record.

  • updateUser
    updateUser(id: string, updates: Partial<AuthUser>): Promise<AuthUser>

    Update an existing user record by ID.

  • deleteUser
    deleteUser(id: string): Promise<void>

    Delete a user record and cascade delete related data.

  • createSession
    createSession(session: AuthSession): Promise<AuthSession>

    Persist a new active session.

  • findSessionById
    findSessionById(id: string): Promise<AuthSession | null>

    Find a session by its unique ID.

  • findSessionByTokenHash
    findSessionByTokenHash(tokenHash: string): Promise<AuthSession | null>

    Find an active session by its hashed bearer token.

  • listSessionsByUserId
    listSessionsByUserId(userId: string): Promise<AuthSession[]>

    List all active sessions belonging to a specific user.

  • updateSession
    updateSession(id: string, updates: Partial<AuthSession>): Promise<AuthSession>

    Update an existing session record.

  • deleteSession
    deleteSession(id: string): Promise<void>

    Invalidate and delete a session by ID.

  • deleteSessionsByUserId
    deleteSessionsByUserId(userId: string): Promise<void>

    Invalidate and delete all sessions for a specific user (e.g. on password change).

  • findIdentity
    findIdentity(provider: string, providerAccountId: string): Promise<AuthIdentity | null>

    Look up a linked third-party OAuth identity.

  • listIdentitiesByUserId
    listIdentitiesByUserId(userId: string): Promise<AuthIdentity[]>

    List all third-party identities linked to a user.

  • createIdentity
    createIdentity(identity: AuthIdentity): Promise<AuthIdentity>

    Link a third-party OAuth identity to a user account.

  • deleteIdentity
    deleteIdentity(id: string): Promise<void>

    Unlink a third-party identity by ID.

  • createToken
    createToken(token: AuthVerificationToken): Promise<AuthVerificationToken>

    Save an ephemeral verification or reset token.

  • findTokenByHash
    findTokenByHash(tokenHash: string, type: AuthVerificationToken["type"]): Promise<AuthVerificationToken | null>

    Find an unexpired verification token by its hash and type.

  • deleteToken
    deleteToken(id: string): Promise<void>

    Invalidate and delete a verification token by ID.

  • deleteTokensByUserId
    deleteTokensByUserId(userId: string, type?: AuthVerificationToken["type"]): Promise<void>

    Invalidate all verification tokens for a specific user.

  • savePasskey
    savePasskey(cred: AuthPasskeyCredential): Promise<void>

    Save or update a registered WebAuthn passkey credential.

  • findPasskeyById
    findPasskeyById(id: string): Promise<AuthPasskeyCredential | null>

    Find a passkey credential by its credential ID.

  • listPasskeysByUserId
    listPasskeysByUserId(userId: string): Promise<AuthPasskeyCredential[]>

    List all passkeys registered by a user.

  • updatePasskey
    updatePasskey(id: string, updates: Partial<AuthPasskeyCredential>): Promise<void>

    Update signature counter and last-used timestamp of a passkey.

  • deletePasskey
    deletePasskey(id: string): Promise<void>

    Remove a registered passkey by ID.

  • createApiKey
    createApiKey(key: AuthApiKey): Promise<AuthApiKey>

    Persist a new developer API key.

  • findApiKeyByHash
    findApiKeyByHash(keyHash: string): Promise<AuthApiKey | null>

    Find an active API key by its cryptographic hash.

  • listApiKeysByUserId
    listApiKeysByUserId(userId: string): Promise<AuthApiKey[]>

    List all developer API keys created by a user.

  • updateApiKey
    updateApiKey(id: string, updates: Partial<AuthApiKey>): Promise<void>

    Update metadata, scopes, or last-used timestamp on an API key.

  • deleteApiKey
    deleteApiKey(id: string): Promise<void>

    Revoke and delete an API key by ID.

  • createOrganization
    createOrganization(org: AuthOrganization): Promise<AuthOrganization>?

    Create an organization.

  • findOrganizationById
    findOrganizationById(id: string): Promise<AuthOrganization | null>?

    Look up an organization by ID.

  • findOrganizationBySlug
    findOrganizationBySlug(slug: string): Promise<AuthOrganization | null>?

    Look up an organization by slug.

  • createMembership
    createMembership(membership: AuthMembership): Promise<AuthMembership>?

    Add a user to an organization.

  • findMembership
    findMembership(orgId: string, userId: string): Promise<AuthMembership | null>?

    Look up a user's membership in an organization.

  • listMembershipsByUserId
    listMembershipsByUserId(userId: string): Promise<AuthMembership[]>?

    List all organization memberships for a user.

AuthUser

interface

Complete internal user record stored in the database.

interface AuthUser

4 members

  • passwordHashproperty
    passwordHash?: string

    Argon2id hashed password string.

  • encryptedTwoFactorSecretproperty
    encryptedTwoFactorSecret?: string

    AES-256-GCM encrypted TOTP secret key.

  • twoFactorRecoveryCodesproperty
    twoFactorRecoveryCodes?: string[]

    Array of SHA-256 hashed one-time backup recovery codes.

  • credentialVersionproperty
    credentialVersion: number

    Monotonically increasing version counter incremented on password changes to invalidate old tokens.

AuthVerificationToken

interface

Time-limited cryptographic verification token (e.g., email confirmation, password reset, magic link).

5 members

  • idproperty
    id: string

    Unique token record ID.

  • userIdproperty
    userId: string

    Associated user ID.

  • tokenHashproperty
    tokenHash: string

    Cryptographic SHA-256 hash of the raw secret token.

  • typeproperty
    type: "email_verification" | "password_reset" | "magic_link"

    Purpose of this verification token.

  • expiresAtproperty
    expiresAt: Date

    Expiration timestamp after which the token is invalid.

CookieOptions

interface

Cookie options for storing auth tokens in browser clients.

interface CookieOptions

7 members

  • sessionCookieNameproperty
    sessionCookieName?: string

    Cookie name for storing the session bearer token. Default: `"yatta_session"`.

  • refreshCookieNameproperty
    refreshCookieName?: string

    Cookie name for storing the refresh token. Default: `"yatta_refresh"`.

  • csrfCookieNameproperty
    csrfCookieName?: string

    Cookie name for anti-CSRF token. Default: `"yatta_csrf"`.

  • domainproperty
    domain?: string

    Cookie domain scope (e.g. `".example.com"`).

  • pathproperty
    path?: string

    URL path scope for cookies. Default: `"/"`.

  • secureproperty
    secure?: boolean

    Force HTTPS-only transmission. Default: true in production.

  • sameSiteproperty
    sameSite?: "Lax" | "Strict" | "None"

    SameSite policy to prevent CSRF. Default: `"Lax"`.

JwtClaims

interface

Standard claims embedded within signed HMAC-SHA256 JWT tokens.

interface JwtClaims

9 members

  • subproperty
    sub: string

    Subject identifier (typically User ID).

  • typeproperty
    type: "access" | "refresh"

    Token category: `"access"` for API requests, `"refresh"` for session renewal.

  • sidproperty
    sid: string

    Associated database session ID.

  • jtiproperty
    jti: string

    Unique JWT identifier (nonce).

  • verproperty
    ver?: number

    Credential or refresh version for rotation invalidation.

  • expproperty
    exp: number

    Expiration timestamp (seconds since Unix epoch).

  • iatproperty
    iat: number

    Issued-at timestamp (seconds since Unix epoch).

  • issproperty
    iss?: string

    Optional issuer URL.

  • audproperty
    aud?: string

    Optional audience string.

OAuthProvider

interface

Configuration definition for a third-party OAuth provider.

interface OAuthProvider

9 members

  • nameproperty
    name: string

    Unique provider key (e.g. `"github"`, `"google"`, `"apple"`).

  • clientIdproperty
    clientId: string

    OAuth application Client ID.

  • clientSecretproperty
    clientSecret: string

    OAuth application Client Secret.

  • authorizeUrlproperty
    authorizeUrl: string

    Authorization endpoint URL.

  • tokenUrlproperty
    tokenUrl: string

    Token exchange endpoint URL.

  • userInfoUrlproperty
    userInfoUrl: string

    User profile info endpoint URL.

  • scopesproperty
    scopes: string[]

    Requested permission scopes.

  • usePkceproperty
    usePkce?: boolean

    Whether to enforce PKCE with S256 code challenge.

  • mapProfileproperty
    mapProfile: (data: Record<string, unknown>) => { id: string; email: string; name?: string; }

    Function to normalize the provider's user profile into `{ id, email, name? }`.

PasswordPolicyConfig

interface

Configuration for password strength and complexity enforcement.

6 members

  • minLengthproperty
    minLength?: number

    Minimum required characters. Default: 12.

  • maxLengthproperty
    maxLength?: number

    Maximum allowed characters. Default: 128.

  • requireUppercaseproperty
    requireUppercase?: boolean

    Requires at least one uppercase letter (A-Z). Default: true.

  • requireLowercaseproperty
    requireLowercase?: boolean

    Requires at least one lowercase letter (a-z). Default: true.

  • requireNumbersproperty
    requireNumbers?: boolean

    Requires at least one digit (0-9). Default: true.

  • requireSymbolsproperty
    requireSymbols?: boolean

    Requires at least one special character symbol. Default: true.

PublicUser

interface

Sanitized public representation of a user. Safe to serialize to client responses.

interface PublicUser

8 members

  • idproperty
    id: string

    Unique user identifier (UUID).

  • emailproperty
    email: string

    Primary email address of the user.

  • rolesproperty
    roles: string[]

    Assigned RBAC roles (e.g. `["user"]` or `["admin", "billing"]`).

  • emailVerifiedproperty
    emailVerified: boolean

    Whether the user has completed email verification.

  • twoFactorEnabledproperty
    twoFactorEnabled: boolean

    Whether Two-Factor Authentication (TOTP) is enabled.

  • metadataproperty
    metadata?: Record<string, unknown>

    Arbitrary application-specific metadata (e.g. name, preferences).

  • createdAtproperty
    createdAt: Date

    Timestamp when user registered.

  • updatedAtproperty
    updatedAt: Date

    Timestamp when user profile was last updated.

RateLimitConfig

interface

Brute-force rate limiting and account lockout configurations per authentication endpoint.

interface RateLimitConfig

6 members

  • enabledproperty
    enabled?: boolean

    Whether brute-force rate limiting is enabled. Default: true.

  • loginproperty
    login?: { maxAttempts: number; windowSec: number; lockoutSec: number; }

    Rate limit policy for login attempts.

  • signupproperty
    signup?: { maxAttempts: number; windowSec: number; lockoutSec: number; }

    Rate limit policy for signup attempts.

  • passwordResetproperty
    passwordReset?: { maxAttempts: number; windowSec: number; lockoutSec: number; }

    Rate limit policy for password reset requests.

  • magicLinkproperty
    magicLink?: { maxAttempts: number; windowSec: number; lockoutSec: number; }

    Rate limit policy for magic link requests.

  • passkeyproperty
    passkey?: { maxAttempts: number; windowSec: number; lockoutSec: number; }

    Rate limit policy for WebAuthn passkey attempts.

RateLimitStore

interface

Storage adapter for rate limiting attempt counters and lockout timestamps.

interface RateLimitStore

3 members

  • get
    get(key: string): Promise<{ hits: number[]; lockoutUntil?: number; } | null>

    Get rate limit state for a key.

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

    Set rate limit state with TTL.

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

    Reset/delete rate limit state.

RiskContext

interface

Context provided to assess login risk (new IP, unfamiliar user agent).

interface RiskContext

3 members

  • userproperty
    user: AuthUser

    Target user trying to log in.

  • ipproperty
    ip?: string

    Current client IP.

  • userAgentproperty
    userAgent?: string

    Current client User-Agent string.

SecurityConfig

interface

Security flags, proxy trust, and encryption settings.

interface SecurityConfig

5 members

  • trustProxyproperty
    trustProxy?: boolean | string[]

    Trust reverse proxy `X-Forwarded-For` headers (boolean or array of trusted proxy IPs).

  • recentAuthWindowSecproperty
    recentAuthWindowSec?: number

    Window in seconds during which a login is considered "recent" for Step-Up actions. Default: 600 (10 minutes).

  • allowUnverifiedSessionproperty
    allowUnverifiedSession?: boolean

    Allow active sessions for unverified email accounts. Default: false.

  • preventAccountEnumerationproperty
    preventAccountEnumeration?: boolean

    Prevent account enumeration by returning identical responses when an email is already registered. Default: true.

  • encryptionKeyproperty
    encryptionKey?: string

    32-byte hexadecimal or base64 key for AES-256-GCM encryption of sensitive data.

SessionConfig

interface

Configuration options for sessions and token lifetimes.

interface SessionConfig

5 members

  • accessTokenTtlSecproperty
    accessTokenTtlSec?: number

    Short-lived access token validity in seconds. Default: 900 (15 minutes).

  • refreshTokenTtlSecproperty
    refreshTokenTtlSec?: number

    Long-lived refresh token validity in seconds. Default: 2592000 (30 days).

  • sessionTtlSecproperty
    sessionTtlSec?: number

    Database session expiration in seconds. Default: 2592000 (30 days).

  • activityThrottleSecproperty
    activityThrottleSec?: number

    Throttle interval in seconds for updating `lastSeenAt` in the DB. Default: 300 (5 minutes).

  • autoRefreshOnCookieAuthproperty
    autoRefreshOnCookieAuth?: boolean

    Automatically rotate refresh cookies on authenticated HTTP requests. Default: false.

TokenPair

interface

Generated JWT access & refresh token pair.

interface TokenPair

3 members

  • accessTokenproperty
    accessToken: string

    Short-lived signed JWT access token for API authorization.

  • refreshTokenproperty
    refreshToken: string

    Long-lived opaque or signed refresh token for rotating sessions.

  • expiresInproperty
    expiresIn: number

    Access token lifetime in seconds.

RiskLevel

type

Risk classification level.

type RiskLevel = "low" | "medium" | "high"

RoleDefinitions

type

Role and permission mappings for Hierarchical Role-Based Access Control (RBAC).

type RoleDefinitions = Record<string, string[] | { can: string[]; inherits?: string[]; }>
tsts
const roles: RoleDefinitions = {  user: ["profile:read", "profile:write"],  admin: {    can: ["users:delete", "settings:manage"],    inherits: ["user"],  },};
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.