yatta/auth
Passwords, sessions, passkeys, OAuth, 2FA, API keys.
53 exported symbols and 348 members, read from src/types/auth.ts.
Construct
createAuth
functionCreates and initializes a global engine instance.
createAuth(config: AuthConfig): Auth- config
- Master authentication settings.
Returns Configured `Auth` instance.
export const auth = createAuth({ secret: process.env.AUTH_SECRET!, store: new SQLiteAuthStore(),});getDefaultAuth
functionReturns the active default instance initialized via .
getDefaultAuth(): AuthAuth
classEnterprise Authentication & Security Engine for Bun and web runtimes.
class Authconst auth = createAuth({ secret: process.env.AUTH_SECRET! });const { user, tokens, toResponse } = await auth.signUp({ email: "dev@example.com", password: "SuperSecretPassword123!",});46 members
storepropertystore: AuthStoreDatabase storage adapter for persistent data.
challengeStorepropertychallengeStore: AuthChallengeStoreStorage adapter for WebAuthn challenges.
rateLimitStorepropertyrateLimitStore: RateLimitStoreStorage adapter for rate limiting hits and lockouts.
auditStorepropertyauditStore: AuthAuditStoreStorage adapter for audit logs.
configpropertyconfig: AuthConfigResolved configuration.
cryptopropertycrypto: AuthCryptoCryptography and hashing utility.
jwtpropertyjwt: AuthJwtJWT token manager.
permissionspropertypermissions: PermissionManagerRole and permission manager.
rateLimiterpropertyrateLimiter: GranularRateLimiterRate limiter subsystem.
riskpropertyrisk: SecurityRiskEngineSecurity risk and anomaly engine.
mfapropertymfa: AuthMfaMulti-Factor Authentication (TOTP & Recovery Codes) subsystem.
passkeypropertypasskey: AuthPasskeyFIDO2 / WebAuthn Passkeys subsystem.
oauthpropertyoauth: AuthOAuthThird-party OAuth provider subsystem.
magicLinkpropertymagicLink: AuthMagicLinkPasswordless Magic Links subsystem.
apiKeyspropertyapiKeys: AuthApiKeysDeveloper API Keys subsystem.
passwordpropertypassword: AuthPasswordSubsystemPassword resets and password updates subsystem.
eventListenerspropertyeventListeners:mailergettermailer: YattaMailerResolved mailer instance used for sending transactional emails.
onon(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.
emitemit(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.
signUpsignUp(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!",});signInsignIn(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}signOutsignOut(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);getSessiongetSession(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);}getUsergetUser(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`.
requireUserrequireUser(req: Request): Promise<PublicUser>Asserts that a request is authenticated, throwing if not.
- req
- Incoming HTTP Request.
Returns The authenticated .
requireRecentAuthrequireRecentAuth(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.
refreshrefresh(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.
sendVerificationEmailsendVerificationEmail(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.
verifyEmailverifyEmail(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.
cancan(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 })) { ... }protectprotect(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" }));validateEmailvalidateEmail(email: string): stringvalidatePasswordStrengthvalidatePasswordStrength(pass: string): voidextractClientextractClient(req?: Request | { headers?: Headers | Record<string, string>; }): { ip?: string; userAgent?: string; }toPublicUsertoPublicUser(user: AuthUser): PublicUsercookieNamesgettercookieNames:createAuthResultcreateAuthResult(user: AuthUser, client: { ip?: string; userAgent?: string; }): Promise<AuthResult>buildAuthResultbuildAuthResult(user: AuthUser, session: AuthSession, rawSessionToken: string, refreshJwt: string): AuthResultmakeCookiemakeCookie(name: string, value: string, opts: { maxAge: number; }): stringparseCookiesparseCookies(header: string): Record<string, string>signuppropertysignup:loginpropertylogin:logoutpropertylogout:sessionpropertysession:userpropertyuser:
AuthApiKeys
classManages developer API keys with cryptographic hashing, visible prefixes, and scoping.
class AuthApiKeys4 members
createcreate(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"],});verifyverify(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);}listlist(userId: string)Lists all API keys owned by a user.
revokerevoke(id: string)Revokes and deletes an API key.
AuthCrypto
classHardened cryptographic utility for password hashing, symmetric encryption,
class AuthCrypto8 members
encKeypropertyencKey: BuffertimingSafeEqualtimingSafeEqual(a: string, b: string): booleanConstant-time string equality check to prevent timing attacks.
- a
- First string.
- b
- Second string.
Returns `true` if strings are identically equal in constant time.
hashhash(value: string): stringComputes the SHA-256 hexadecimal hash of an input string.
- value
- Input plaintext.
Returns Hexadecimal digest.
randomTokenrandomToken(bytes?: ): stringGenerates a cryptographically secure random hexadecimal token.
- bytes
- Number of random bytes (default: 32).
Returns Hex-encoded string.
encryptencrypt(plainText: string): stringEncrypts plaintext using authenticated AES-256-GCM.
- plainText
- Sensitive string to encrypt (e.g. TOTP secret).
Returns Formatted ciphertext envelope.
decryptdecrypt(cipherPayload: string): stringDecrypts ciphertext previously encrypted via AES-256-GCM.
- cipherPayload
- Formatted string as `ivHex:tagHex:cipherHex`.
Returns Decrypted plaintext string.
hashPasswordhashPassword(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.
verifyPasswordverifyPassword(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
classBase error class for all Yatta Authentication exceptions.
class AuthError extends ErrorAuthJwt
classHMAC-SHA256 JWT signer and verifier with constant-time signature verification,
class AuthJwt2 members
signsign(payload: Omit<JwtClaims, "iat" | "exp" | "jti"> & { expInSec: number; jti?: string; }): stringSigns a JWT payload with HMAC-SHA256 and Base64URL encoding.
- payload
- Claims without auto-computed `iat` and `exp`.
Returns Signed JWT string (header.payload.signature).
verifyverify(token: string): JwtClaims | nullVerifies and decodes a JWT token. Returns parsed claims or `null` if invalid or expired.
- token
- Raw JWT string.
Returns Parsed or `null`.
AuthMagicLink
classPasswordless sign-in and sign-up using secure, single-use email links.
class AuthMagicLink2 members
requestrequest(email: string, req?: Request): Promise<string>Generates a 15-minute single-use sign-in link and emails it to the user.
- User email address.
- req
- Optional HTTP Request for rate limiting.
Returns Raw token string.
tsts await auth.magicLink.request("user@example.com", req);verifyverify(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
classManages Time-Based One-Time Password (TOTP) two-factor authentication
class AuthMfa6 members
pendingSecretspropertypendingSecrets:beginSetupbeginSetup(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");verifyCodeverifyCode(secret: string, code: string): booleanValidates a 6-digit TOTP code against a secret.
- secret
- Plaintext TOTP secret.
- code
- 6-digit verification code.
Returns `true` if valid.
confirmSetupconfirmSetup(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.
disabledisable(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.
consumeRecoveryCodeconsumeRecoveryCode(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
classHandles OAuth 2.0 authorization flows, PKCE code challenges, and identity linking.
class AuthOAuth5 members
providerspropertyproviders:registerProviderregisterProvider(provider: OAuthProvider)Registers a custom or third-party OAuth provider.
- provider
- OAuth provider configuration.
registerDefaultsregisterDefaults()getAuthorizationUrlgetAuthorizationUrl(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.
handleCallbackhandleCallback(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
classFIDO2 / WebAuthn Passkeys subsystem for biometric and hardware key authentication.
class AuthPasskey8 members
rpConfiggetterrpConfig:generateRegistrationOptionsgenerateRegistrationOptions(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.
verifyRegistrationverifyRegistration(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 }`.
generateAuthenticationOptionsgenerateAuthenticationOptions(userEmail?: string)Generates WebAuthn authentication options to send to `navigator.credentials.get()`.
- userEmail
- Optional user email to restrict credential selection.
Returns Authentication options JSON.
verifyAuthenticationverifyAuthentication(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.
listlist(userId: string)List all passkeys registered by a user.
renamerename(id: string, name: string)Rename a passkey.
removeremove(id: string)Delete a passkey.
AuthPasswordSubsystem
classManages password reset flows, secure password updates, and token generation.
class AuthPasswordSubsystem3 members
requestResetrequestReset(email: string, req?: Request): Promise<string | null>Generates a 1-hour password reset token and sends an email to the user.
- 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);resetreset(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!");changechange(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
classThrown when an authenticated user lacks the necessary roles or permissions (HTTP 403).
class ForbiddenError extends AuthErrorGranularRateLimiter
classGranular sliding-window rate limiter with progressive lockouts.
class GranularRateLimiter4 members
isEnabledisEnabled(): booleanassertAllowedassertAllowed(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).
recordFailurerecordFailure(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.
recordSuccessrecordSuccess(bucket: keyof RateLimitConfig, key: string): Promise<void>Clears failure count on successful authentication.
- bucket
- Rate limit category.
- key
- Unique identifier.
MemoryAuditStore
classclass MemoryAuditStore implements AuthAuditStore3 members
eventspropertyevents: AuthEvent[]recordrecord(event: AuthEvent): Promise<void>listByUserlistByUser(userId: string, limit?: ): Promise<AuthEvent[]>
MemoryAuthStore
classclass MemoryAuthStore implements AuthStore44 members
userspropertyusers:sessionspropertysessions:identitiespropertyidentities:tokenspropertytokens:passkeyspropertypasskeys:apiKeyspropertyapiKeys:orgspropertyorgs:membershipspropertymemberships:findUserByIdfindUserById(id: string)findUserByEmailfindUserByEmail(email: string)createUsercreateUser(data: Omit<AuthUser, "createdAt" | "updatedAt">)updateUserupdateUser(id: string, updates: Partial<AuthUser>)deleteUserdeleteUser(id: string)createSessioncreateSession(session: AuthSession)findSessionByIdfindSessionById(id: string)findSessionByTokenHashfindSessionByTokenHash(tokenHash: string)listSessionsByUserIdlistSessionsByUserId(userId: string)updateSessionupdateSession(id: string, updates: Partial<AuthSession>)deleteSessiondeleteSession(id: string)deleteSessionsByUserIddeleteSessionsByUserId(userId: string)findIdentityfindIdentity(provider: string, providerAccountId: string)listIdentitiesByUserIdlistIdentitiesByUserId(userId: string)createIdentitycreateIdentity(identity: AuthIdentity)deleteIdentitydeleteIdentity(id: string)createTokencreateToken(token: AuthVerificationToken)findTokenByHashfindTokenByHash(tokenHash: string, type: AuthVerificationToken["type"])deleteTokendeleteToken(id: string)deleteTokensByUserIddeleteTokensByUserId(userId: string, type?: AuthVerificationToken["type"])savePasskeysavePasskey(cred: AuthPasskeyCredential)findPasskeyByIdfindPasskeyById(id: string)listPasskeysByUserIdlistPasskeysByUserId(userId: string)updatePasskeyupdatePasskey(id: string, updates: Partial<AuthPasskeyCredential>)deletePasskeydeletePasskey(id: string)createApiKeycreateApiKey(key: AuthApiKey)findApiKeyByHashfindApiKeyByHash(keyHash: string)listApiKeysByUserIdlistApiKeysByUserId(userId: string)updateApiKeyupdateApiKey(id: string, updates: Partial<AuthApiKey>)deleteApiKeydeleteApiKey(id: string)createOrganizationcreateOrganization(org: AuthOrganization)findOrganizationByIdfindOrganizationById(id: string)findOrganizationBySlugfindOrganizationBySlug(slug: string)createMembershipcreateMembership(membership: AuthMembership)findMembershipfindMembership(orgId: string, userId: string)listMembershipsByUserIdlistMembershipsByUserId(userId: string)
MemoryChallengeStore
classclass MemoryChallengeStore implements AuthChallengeStore4 members
challengespropertychallenges:setset(challenge: AuthChallenge): Promise<void>getget(challengeString: string): Promise<AuthChallenge | null>deletedelete(challengeString: string): Promise<void>
MemoryRateLimitStore
classclass MemoryRateLimitStore implements RateLimitStore4 members
storepropertystore:getget(key: string)setset(key: string, data: { hits: number[]; lockoutUntil?: number; }, ttlSec: number)deletedelete(key: string)
PermissionManager
classEvaluates role hierarchies and permissions with wildcard matching (e.g. `"*:*"`, `"posts:*"`).
class PermissionManager5 members
permissionspropertypermissions:initializeinitialize(roleDefs?: RoleDefinitions)detectCyclesdetectCycles(defs: RoleDefinitions)resolvePermissionsForRoleresolvePermissionsForRole(role: string, defs: RoleDefinitions, seen?: ): Set<string>checkcheck(userRoles: string[], action: string, resource: string, isOwner?: ): booleanVerifies 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
classThrown when an IP or user exceeds authentication rate limits or enters account lockout (HTTP 429).
class RateLimitError extends AuthErrorSecurityReauthRequiredError
classThrown when a sensitive operation requires recent user re-authentication / step-up auth (HTTP 403).
class SecurityReauthRequiredError extends AuthErrorSecurityRiskEngine
classEvaluates login context against historical session data to detect suspicious activity.
class SecurityRiskEngine1 member
assessLoginRiskassessLoginRisk(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
classThrown when an unauthenticated request attempts to access a protected resource (HTTP 401).
class UnauthorizedError extends AuthErrorTypes
AuthApiKey
interfaceDeveloper API key used for programmatic service-to-service access.
interface AuthApiKey9 members
idpropertyid: stringUnique API key record ID.
userIdpropertyuserId: stringAssociated user/owner ID.
namepropertyname: stringDescriptive name for the key (e.g. "CI Deployer", "Production Zapier").
keyHashpropertykeyHash: stringCryptographic SHA-256 hash of the full API key secret.
prefixpropertyprefix: stringVisible key prefix shown to developers (e.g. `"yk_live_ab12"`).
scopespropertyscopes: string[]Granted permission scopes (e.g. `["read:users", "write:billing"]`).
expiresAtpropertyexpiresAt?: DateOptional expiration date.
lastUsedAtpropertylastUsedAt?: DateTimestamp of the most recent request authenticated with this key.
createdAtpropertycreatedAt: DateCreation timestamp.
AuthAuditStore
interfaceStorage adapter for recording security audit logs.
interface AuthAuditStore2 members
recordrecord(event: AuthEvent): Promise<void>Record a security event.
listByUserlistByUser(userId: string, limit?: number): Promise<AuthEvent[]>List audit events for a given user.
AuthChallenge
interfaceEphemeral WebAuthn challenge used during registration or login.
interface AuthChallenge6 members
idpropertyid: stringChallenge record ID.
challengepropertychallenge: stringCryptographically random challenge string.
typepropertytype: "registration" | "authentication"Flow type: `"registration"` or `"authentication"`.
userIdpropertyuserId?: stringTarget user ID if known (e.g. during authentication or passkey enrollment).
expiresAtpropertyexpiresAt: DateExpiration timestamp.
ippropertyip?: stringClient IP address that requested the challenge.
AuthChallengeStore
interfaceStorage adapter for storing short-lived WebAuthn registration/authentication challenges.
interface AuthChallengeStore3 members
setset(challenge: AuthChallenge): Promise<void>Store an ephemeral challenge with an expiration timestamp.
getget(challengeString: string): Promise<AuthChallenge | null>Retrieve a challenge by its raw challenge string.
deletedelete(challengeString: string): Promise<void>Delete a challenge once consumed.
AuthConfig
interfaceMaster configuration options passed into .
interface AuthConfig13 members
secretpropertysecret: stringPrimary cryptographic signing and HMAC secret key.
storepropertystore?: AuthStoreDatabase storage adapter for users, sessions, tokens, and credentials. Defaults to in-memory store.
challengeStorepropertychallengeStore?: AuthChallengeStoreStorage adapter for ephemeral WebAuthn challenges. Defaults to in-memory store.
rateLimitStorepropertyrateLimitStore?: RateLimitStoreStorage adapter for rate-limiting hits and lockouts. Defaults to in-memory store.
auditStorepropertyauditStore?: AuthAuditStoreStorage adapter for security audit log events. Defaults to in-memory store.
sessionpropertysession?: SessionConfigSession and token lifetime settings.
passwordPolicypropertypasswordPolicy?: PasswordPolicyConfigPassword complexity rules.
securitypropertysecurity?: SecurityConfigSecurity, proxy, and encryption settings.
rateLimitspropertyrateLimits?: RateLimitConfigRate-limiting and lockout thresholds.
cookiespropertycookies?: CookieOptionsHTTP cookie configuration for session tokens.
emailpropertyemail?: AuthEmailConfigEmail transport and verification email configuration.
passkeyspropertypasskeys?: { rpName: string; rpID: string; origin: string; }WebAuthn / Passkey relying party configuration.
rolespropertyroles?: RoleDefinitionsHierarchical RBAC role and permission definitions.
AuthEmailConfig
interfaceConfiguration for automated system emails (verification, password resets, magic links).
interface AuthEmailConfig5 members
frompropertyfrom?: EmailAddressDefault sender address (e.g. `"noreply@example.com"` or `{ name: "Support", address: "support@example.com" }`).
appUrlpropertyappUrl?: stringRoot application URL used to construct verification and password reset links.
mailerpropertymailer?: YattaMailerMailer instance for sending emails (defaults to globally registered `Mail`).
resendCooldownSecpropertyresendCooldownSec?: numberCooldown time in seconds before allowing another email to be requested. Default: 60.
templatespropertytemplates?: { 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
interfaceData passed into custom email rendering functions.
interface AuthEmailTemplateData3 members
emailpropertyemail: stringRecipient email address.
linkpropertylink: stringOne-click action URL.
tokenpropertytoken: stringRaw security token string.
AuthEvent
interfaceSecurity audit log event.
interface AuthEvent7 members
idpropertyid: stringUnique event identifier.
userIdpropertyuserId?: stringTarget user ID if applicable.
typepropertytype: stringEvent action type (e.g. `"auth:login:success"`, `"auth:mfa:enable"`, `"auth:password:reset"`).
ippropertyip?: stringOriginating client IP address.
userAgentpropertyuserAgent?: stringOriginating client User-Agent string.
metadatapropertymetadata?: Record<string, unknown>Arbitrary event metadata.
timestamppropertytimestamp: DateTimestamp when event occurred.
AuthIdentity
interfaceThird-party OAuth or federated identity linked to a user account.
interface AuthIdentity7 members
idpropertyid: stringUnique identity record ID.
userIdpropertyuserId: stringAssociated local user ID.
providerpropertyprovider: stringOAuth provider identifier (e.g. `"google"`, `"github"`, `"apple"`).
providerAccountIdpropertyproviderAccountId: stringProvider's unique user identifier (e.g. Google sub, GitHub ID).
emailpropertyemail?: stringEmail address returned by the OAuth provider.
createdAtpropertycreatedAt: DateCreation timestamp.
updatedAtpropertyupdatedAt: DateLast update timestamp.
AuthMembership
interfaceUser membership inside an organization.
interface AuthMembership5 members
idpropertyid: stringMembership ID.
organizationIdpropertyorganizationId: stringOrganization ID.
userIdpropertyuserId: stringUser ID.
rolepropertyrole: stringRole within organization (e.g. `"owner"`, `"admin"`, `"member"`).
createdAtpropertycreatedAt: DateMembership start timestamp.
AuthOrganization
interfaceMulti-tenant organization or team account.
interface AuthOrganization4 members
idpropertyid: stringOrganization ID.
namepropertyname: stringDisplay name of the organization.
slugpropertyslug: stringURL-friendly unique slug identifier.
createdAtpropertycreatedAt: DateCreation timestamp.
AuthPasskeyCredential
interfaceFIDO2 / WebAuthn Passkey credential record.
interface AuthPasskeyCredential8 members
idpropertyid: stringBase64URL-encoded credential ID.
userIdpropertyuserId: stringAssociated user ID.
namepropertyname?: stringUser-friendly credential nickname (e.g. "iPhone TouchID", "YubiKey 5").
publicKeypropertypublicKey: Uint8ArrayRaw binary public key bytes.
counterpropertycounter: numberSignature counter used to detect cloned authenticators.
transportspropertytransports?: AuthenticatorTransport[]Transport mechanisms supported by the authenticator (e.g. `["usb", "nfc", "ble", "internal"]`).
createdAtpropertycreatedAt: DateCreation timestamp.
lastUsedAtpropertylastUsedAt?: DateTimestamp when the passkey was last used for authentication.
AuthResult
interfaceResult returned upon successful signup, login, or session refresh.
interface AuthResult5 members
userpropertyuser: PublicUserThe authenticated user profile.
sessionpropertysession: AuthSessionThe created or updated session.
tokenspropertytokens: TokenPairGenerated access and refresh token pair.
cookiespropertycookies: string[]Array of pre-formatted `Set-Cookie` header strings for HTTP response serialization.
toResponsetoResponse(body?: Record<string, unknown>, status?: number): ResponseHelper 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
interfaceActive authentication session record.
interface AuthSession13 members
idpropertyid: stringUnique session identifier (UUID).
userIdpropertyuserId: stringAssociated user ID.
sessionTokenHashpropertysessionTokenHash: stringCryptographic SHA-256 hash of the bearer session token.
refreshTokenHashpropertyrefreshTokenHash?: stringCryptographic SHA-256 hash of the active refresh token.
expiresAtpropertyexpiresAt: DateTimestamp when this session expires.
refreshVersionpropertyrefreshVersion: numberRefresh token rotation counter.
userAgentpropertyuserAgent?: stringClient User-Agent string recorded at login.
ippropertyip?: stringClient IP address recorded at login.
deviceIdpropertydeviceId?: stringClient device identifier if provided.
deviceNamepropertydeviceName?: stringHuman-readable device name (e.g. "MacBook Pro").
lastSeenAtpropertylastSeenAt: DateTimestamp when session was last actively used.
lastAuthenticatedAtpropertylastAuthenticatedAt: DateTimestamp of the most recent primary authentication (used for Step-Up security checks).
createdAtpropertycreatedAt: DateTimestamp when session was created.
AuthStore
interfaceStorage adapter interface defining database interactions required by the Auth engine.
interface AuthStore36 members
findUserByIdfindUserById(id: string): Promise<AuthUser | null>Find a user by their unique ID.
findUserByEmailfindUserByEmail(email: string): Promise<AuthUser | null>Find a user by their email address.
createUsercreateUser(user: Omit<AuthUser, "createdAt" | "updatedAt">): Promise<AuthUser>Create and persist a new user record.
updateUserupdateUser(id: string, updates: Partial<AuthUser>): Promise<AuthUser>Update an existing user record by ID.
deleteUserdeleteUser(id: string): Promise<void>Delete a user record and cascade delete related data.
createSessioncreateSession(session: AuthSession): Promise<AuthSession>Persist a new active session.
findSessionByIdfindSessionById(id: string): Promise<AuthSession | null>Find a session by its unique ID.
findSessionByTokenHashfindSessionByTokenHash(tokenHash: string): Promise<AuthSession | null>Find an active session by its hashed bearer token.
listSessionsByUserIdlistSessionsByUserId(userId: string): Promise<AuthSession[]>List all active sessions belonging to a specific user.
updateSessionupdateSession(id: string, updates: Partial<AuthSession>): Promise<AuthSession>Update an existing session record.
deleteSessiondeleteSession(id: string): Promise<void>Invalidate and delete a session by ID.
deleteSessionsByUserIddeleteSessionsByUserId(userId: string): Promise<void>Invalidate and delete all sessions for a specific user (e.g. on password change).
findIdentityfindIdentity(provider: string, providerAccountId: string): Promise<AuthIdentity | null>Look up a linked third-party OAuth identity.
listIdentitiesByUserIdlistIdentitiesByUserId(userId: string): Promise<AuthIdentity[]>List all third-party identities linked to a user.
createIdentitycreateIdentity(identity: AuthIdentity): Promise<AuthIdentity>Link a third-party OAuth identity to a user account.
deleteIdentitydeleteIdentity(id: string): Promise<void>Unlink a third-party identity by ID.
createTokencreateToken(token: AuthVerificationToken): Promise<AuthVerificationToken>Save an ephemeral verification or reset token.
findTokenByHashfindTokenByHash(tokenHash: string, type: AuthVerificationToken["type"]): Promise<AuthVerificationToken | null>Find an unexpired verification token by its hash and type.
deleteTokendeleteToken(id: string): Promise<void>Invalidate and delete a verification token by ID.
deleteTokensByUserIddeleteTokensByUserId(userId: string, type?: AuthVerificationToken["type"]): Promise<void>Invalidate all verification tokens for a specific user.
savePasskeysavePasskey(cred: AuthPasskeyCredential): Promise<void>Save or update a registered WebAuthn passkey credential.
findPasskeyByIdfindPasskeyById(id: string): Promise<AuthPasskeyCredential | null>Find a passkey credential by its credential ID.
listPasskeysByUserIdlistPasskeysByUserId(userId: string): Promise<AuthPasskeyCredential[]>List all passkeys registered by a user.
updatePasskeyupdatePasskey(id: string, updates: Partial<AuthPasskeyCredential>): Promise<void>Update signature counter and last-used timestamp of a passkey.
deletePasskeydeletePasskey(id: string): Promise<void>Remove a registered passkey by ID.
createApiKeycreateApiKey(key: AuthApiKey): Promise<AuthApiKey>Persist a new developer API key.
findApiKeyByHashfindApiKeyByHash(keyHash: string): Promise<AuthApiKey | null>Find an active API key by its cryptographic hash.
listApiKeysByUserIdlistApiKeysByUserId(userId: string): Promise<AuthApiKey[]>List all developer API keys created by a user.
updateApiKeyupdateApiKey(id: string, updates: Partial<AuthApiKey>): Promise<void>Update metadata, scopes, or last-used timestamp on an API key.
deleteApiKeydeleteApiKey(id: string): Promise<void>Revoke and delete an API key by ID.
createOrganizationcreateOrganization(org: AuthOrganization): Promise<AuthOrganization>?Create an organization.
findOrganizationByIdfindOrganizationById(id: string): Promise<AuthOrganization | null>?Look up an organization by ID.
findOrganizationBySlugfindOrganizationBySlug(slug: string): Promise<AuthOrganization | null>?Look up an organization by slug.
createMembershipcreateMembership(membership: AuthMembership): Promise<AuthMembership>?Add a user to an organization.
findMembershipfindMembership(orgId: string, userId: string): Promise<AuthMembership | null>?Look up a user's membership in an organization.
listMembershipsByUserIdlistMembershipsByUserId(userId: string): Promise<AuthMembership[]>?List all organization memberships for a user.
AuthUser
interfaceComplete internal user record stored in the database.
interface AuthUser4 members
passwordHashpropertypasswordHash?: stringArgon2id hashed password string.
encryptedTwoFactorSecretpropertyencryptedTwoFactorSecret?: stringAES-256-GCM encrypted TOTP secret key.
twoFactorRecoveryCodespropertytwoFactorRecoveryCodes?: string[]Array of SHA-256 hashed one-time backup recovery codes.
credentialVersionpropertycredentialVersion: numberMonotonically increasing version counter incremented on password changes to invalidate old tokens.
AuthVerificationToken
interfaceTime-limited cryptographic verification token (e.g., email confirmation, password reset, magic link).
interface AuthVerificationToken5 members
idpropertyid: stringUnique token record ID.
userIdpropertyuserId: stringAssociated user ID.
tokenHashpropertytokenHash: stringCryptographic SHA-256 hash of the raw secret token.
typepropertytype: "email_verification" | "password_reset" | "magic_link"Purpose of this verification token.
expiresAtpropertyexpiresAt: DateExpiration timestamp after which the token is invalid.
CookieOptions
interfaceCookie options for storing auth tokens in browser clients.
interface CookieOptions7 members
sessionCookieNamepropertysessionCookieName?: stringCookie name for storing the session bearer token. Default: `"yatta_session"`.
refreshCookieNamepropertyrefreshCookieName?: stringCookie name for storing the refresh token. Default: `"yatta_refresh"`.
csrfCookieNamepropertycsrfCookieName?: stringCookie name for anti-CSRF token. Default: `"yatta_csrf"`.
domainpropertydomain?: stringCookie domain scope (e.g. `".example.com"`).
pathpropertypath?: stringURL path scope for cookies. Default: `"/"`.
securepropertysecure?: booleanForce HTTPS-only transmission. Default: true in production.
sameSitepropertysameSite?: "Lax" | "Strict" | "None"SameSite policy to prevent CSRF. Default: `"Lax"`.
JwtClaims
interfaceStandard claims embedded within signed HMAC-SHA256 JWT tokens.
interface JwtClaims9 members
subpropertysub: stringSubject identifier (typically User ID).
typepropertytype: "access" | "refresh"Token category: `"access"` for API requests, `"refresh"` for session renewal.
sidpropertysid: stringAssociated database session ID.
jtipropertyjti: stringUnique JWT identifier (nonce).
verpropertyver?: numberCredential or refresh version for rotation invalidation.
exppropertyexp: numberExpiration timestamp (seconds since Unix epoch).
iatpropertyiat: numberIssued-at timestamp (seconds since Unix epoch).
isspropertyiss?: stringOptional issuer URL.
audpropertyaud?: stringOptional audience string.
OAuthProvider
interfaceConfiguration definition for a third-party OAuth provider.
interface OAuthProvider9 members
namepropertyname: stringUnique provider key (e.g. `"github"`, `"google"`, `"apple"`).
clientIdpropertyclientId: stringOAuth application Client ID.
clientSecretpropertyclientSecret: stringOAuth application Client Secret.
authorizeUrlpropertyauthorizeUrl: stringAuthorization endpoint URL.
tokenUrlpropertytokenUrl: stringToken exchange endpoint URL.
userInfoUrlpropertyuserInfoUrl: stringUser profile info endpoint URL.
scopespropertyscopes: string[]Requested permission scopes.
usePkcepropertyusePkce?: booleanWhether to enforce PKCE with S256 code challenge.
mapProfilepropertymapProfile: (data: Record<string, unknown>) => { id: string; email: string; name?: string; }Function to normalize the provider's user profile into `{ id, email, name? }`.
PasswordPolicyConfig
interfaceConfiguration for password strength and complexity enforcement.
interface PasswordPolicyConfig6 members
minLengthpropertyminLength?: numberMinimum required characters. Default: 12.
maxLengthpropertymaxLength?: numberMaximum allowed characters. Default: 128.
requireUppercasepropertyrequireUppercase?: booleanRequires at least one uppercase letter (A-Z). Default: true.
requireLowercasepropertyrequireLowercase?: booleanRequires at least one lowercase letter (a-z). Default: true.
requireNumberspropertyrequireNumbers?: booleanRequires at least one digit (0-9). Default: true.
requireSymbolspropertyrequireSymbols?: booleanRequires at least one special character symbol. Default: true.
PublicUser
interfaceSanitized public representation of a user. Safe to serialize to client responses.
interface PublicUser8 members
idpropertyid: stringUnique user identifier (UUID).
emailpropertyemail: stringPrimary email address of the user.
rolespropertyroles: string[]Assigned RBAC roles (e.g. `["user"]` or `["admin", "billing"]`).
emailVerifiedpropertyemailVerified: booleanWhether the user has completed email verification.
twoFactorEnabledpropertytwoFactorEnabled: booleanWhether Two-Factor Authentication (TOTP) is enabled.
metadatapropertymetadata?: Record<string, unknown>Arbitrary application-specific metadata (e.g. name, preferences).
createdAtpropertycreatedAt: DateTimestamp when user registered.
updatedAtpropertyupdatedAt: DateTimestamp when user profile was last updated.
RateLimitConfig
interfaceBrute-force rate limiting and account lockout configurations per authentication endpoint.
interface RateLimitConfig6 members
enabledpropertyenabled?: booleanWhether brute-force rate limiting is enabled. Default: true.
loginpropertylogin?: { maxAttempts: number; windowSec: number; lockoutSec: number; }Rate limit policy for login attempts.
signuppropertysignup?: { maxAttempts: number; windowSec: number; lockoutSec: number; }Rate limit policy for signup attempts.
passwordResetpropertypasswordReset?: { maxAttempts: number; windowSec: number; lockoutSec: number; }Rate limit policy for password reset requests.
magicLinkpropertymagicLink?: { maxAttempts: number; windowSec: number; lockoutSec: number; }Rate limit policy for magic link requests.
passkeypropertypasskey?: { maxAttempts: number; windowSec: number; lockoutSec: number; }Rate limit policy for WebAuthn passkey attempts.
RateLimitStore
interfaceStorage adapter for rate limiting attempt counters and lockout timestamps.
interface RateLimitStore3 members
getget(key: string): Promise<{ hits: number[]; lockoutUntil?: number; } | null>Get rate limit state for a key.
setset(key: string, data: { hits: number[]; lockoutUntil?: number; }, ttlSec: number): Promise<void>Set rate limit state with TTL.
deletedelete(key: string): Promise<void>Reset/delete rate limit state.
RiskContext
interfaceContext provided to assess login risk (new IP, unfamiliar user agent).
interface RiskContext3 members
userpropertyuser: AuthUserTarget user trying to log in.
ippropertyip?: stringCurrent client IP.
userAgentpropertyuserAgent?: stringCurrent client User-Agent string.
SecurityConfig
interfaceSecurity flags, proxy trust, and encryption settings.
interface SecurityConfig5 members
trustProxypropertytrustProxy?: boolean | string[]Trust reverse proxy `X-Forwarded-For` headers (boolean or array of trusted proxy IPs).
recentAuthWindowSecpropertyrecentAuthWindowSec?: numberWindow in seconds during which a login is considered "recent" for Step-Up actions. Default: 600 (10 minutes).
allowUnverifiedSessionpropertyallowUnverifiedSession?: booleanAllow active sessions for unverified email accounts. Default: false.
preventAccountEnumerationpropertypreventAccountEnumeration?: booleanPrevent account enumeration by returning identical responses when an email is already registered. Default: true.
encryptionKeypropertyencryptionKey?: string32-byte hexadecimal or base64 key for AES-256-GCM encryption of sensitive data.
SessionConfig
interfaceConfiguration options for sessions and token lifetimes.
interface SessionConfig5 members
accessTokenTtlSecpropertyaccessTokenTtlSec?: numberShort-lived access token validity in seconds. Default: 900 (15 minutes).
refreshTokenTtlSecpropertyrefreshTokenTtlSec?: numberLong-lived refresh token validity in seconds. Default: 2592000 (30 days).
sessionTtlSecpropertysessionTtlSec?: numberDatabase session expiration in seconds. Default: 2592000 (30 days).
activityThrottleSecpropertyactivityThrottleSec?: numberThrottle interval in seconds for updating `lastSeenAt` in the DB. Default: 300 (5 minutes).
autoRefreshOnCookieAuthpropertyautoRefreshOnCookieAuth?: booleanAutomatically rotate refresh cookies on authenticated HTTP requests. Default: false.
TokenPair
interfaceGenerated JWT access & refresh token pair.
interface TokenPair3 members
accessTokenpropertyaccessToken: stringShort-lived signed JWT access token for API authorization.
refreshTokenpropertyrefreshToken: stringLong-lived opaque or signed refresh token for rotating sessions.
expiresInpropertyexpiresIn: numberAccess token lifetime in seconds.
RiskLevel
typeRisk classification level.
type RiskLevel = "low" | "medium" | "high"RoleDefinitions
typeRole and permission mappings for Hierarchical Role-Based Access Control (RBAC).
type RoleDefinitions = Record<string, string[] | { can: string[]; inherits?: string[]; }>const roles: RoleDefinitions = { user: ["profile:read", "profile:write"], admin: { can: ["users:delete", "settings:manage"], inherits: ["user"], },};AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.