yatta/auth
Passwords, sessions, passkeys, OAuth, 2FA, API keys.
56 exported symbols and 367 members, read from src/types/auth.ts.
Construct
createAuth
functioncreateAuth(config: AuthConfig): AuthgetDefaultAuth
functiongetDefaultAuth(): AuthmfaSetupKey
functionChallenge-store key for a user's pending MFA enrolment.
Prefixed so it can never collide with a base64url WebAuthn challenge, and built from the user id so `confirmSetup` — which knows nothing else — can find it. Storing the encrypted seed as the key instead meant the lookup never matched and 2FA could never be turned on.
mfaSetupKey(userId: string): stringAuth
classclass Auth50 members
storepropertystore: AuthStorechallengeStorepropertychallengeStore: AuthChallengeStorerateLimitStorepropertyrateLimitStore: RateLimitStoreauditStorepropertyauditStore: AuthAuditStoreconfigpropertyconfig: AuthConfigcryptopropertycrypto: AuthCryptojwtpropertyjwt: AuthJwtpermissionspropertypermissions: PermissionManagerrateLimiterpropertyrateLimiter: GranularRateLimiterriskpropertyrisk: SecurityRiskEnginemfapropertymfa: AuthMfapasskeypropertypasskey: AuthPasskeyoauthpropertyoauth: AuthOAuthmagicLinkpropertymagicLink: AuthMagicLinkapiKeyspropertyapiKeys: AuthApiKeyspasswordpropertypassword: AuthPasswordSubsystemeventListenerspropertyeventListeners:mailergettermailer: YattaMaileronon(event: string, listener: (payload: any) => void | Promise<void>)emitemit(event: string, payload: Record<string, unknown>, req?: Request)signUpsignUp(input: { email: string; password?: string; metadata?: Record<string, unknown>; req?: Request; }): Promise<AuthResult | { user: PublicUser; emailVerificationRequired: true; }>signInsignIn(input: { email: string; password?: string; mfaCode?: string; recoveryCode?: string; req?: Request; }): Promise<AuthResult | MfaChallenge>signOutsignOut(reqOrToken: Request | { req: Request; } | string): Promise<{ success: boolean; cookies: string[]; }>isSessionLiveisSessionLive(session: AuthSession): booleanWhether a session is still inside its lifetime.
Checked here rather than left to the store. `MemoryAuthStore` filters expired sessions out of its scan, so the default implementation made this look handled — but `AuthStore` is a published interface, and a custom store that returns an expired session makes every caller believe a dead session is live. "The default happens to check" is not a security property. A session with no `expiresAt` is treated as live: some deployments use a shorter access token and never set one, and refusing those would break them loudly for a case that is not a leak.
completeMfacompleteMfa(input: { ticket: string; code?: string; recoveryCode?: string; req?: Request; }): Promise<AuthResult>Finishes a sign-in that stopped at the second factor.
Every flow that can stop — password, passkey, OAuth, magic link — returns `{ mfaRequired: true, ticket }` when the account has 2FA on. Nothing consumed that before, so a 2FA user could not sign in by any route but a password. This is the half that was missing. A signed ticket rather than the bare `userId` the flows used to return. With a bare id, whatever the app built as its second step had no proof the first factor had passed — so anything that accepted a user id and asked the store a question was reachable by anyone who could produce or guess one. The ticket is signed, short-lived, single-use, and only this function can interpret it.
- ticket
- The value from the `mfaRequired` response.
- code
- A 6-digit TOTP code, or a recovery code.
getSessiongetSession(reqOrToken: Request | { req: Request; } | string, options?: { autoRefresh?: boolean; }): Promise<{ user: PublicUser; session: PublicSession; newCookies?: string[]; } | null>getUsergetUser(req: Request): Promise<PublicUser | null>requireUserrequireUser(req: Request): Promise<PublicUser>requireRecentAuthrequireRecentAuth(req: Request, maxAgeSec?: number): Promise<{ user: PublicUser; session: PublicSession; }>reauthenticatereauthenticate(req: Request, password: string): Promise<void>refreshrefresh(refreshToken: string, req?: Request): Promise<AuthResult>sendVerificationEmailsendVerificationEmail(userId: string): Promise<void>verifyEmailverifyEmail(rawToken: string): Promise<PublicUser>cancan(userOrRoles: PublicUser | AuthUser | string[])protectprotect(requirements?: { role?: string; permission?: string; })validateEmailvalidateEmail(email: string): stringvalidatePasswordStrengthvalidatePasswordStrength(pass: string): voidextractClientextractClient(req?: any): { ip: string; userAgent?: string; }toPublicUsertoPublicUser(user: AuthUser): PublicUsertoPublicSessiontoPublicSession(session: AuthSession): PublicSessioncookieNamesgettercookieNames:spendMfaTicketspendMfaTicket(ticket: string): Promise<boolean>Mints the short-lived ticket handed back when 2FA stops a sign-in.
Short-lived on purpose: it authorises nothing on its own, but it is the half of a two-factor check, so a longer life is a wider window for a captured value. Public because every sign-in route needs it — password, passkey, OAuth and magic link all stop here — and four private copies would be four chances to give one of them a different lifetime. Takes an MFA ticket out of circulation, reporting whether it was still there. Uses the store's atomic `consume` where it offers one. Without it this is a read followed by a delete, which two concurrent callers can both pass — and the second session is exactly the one an attacker wants.
issueMfaTicketissueMfaTicket(user: AuthUser): MfaChallengecreateAuthResultcreateAuthResult(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; httpOnly?: boolean; }): stringparseCookiesparseCookies(header: string): Record<string, string>Cookies from a `Cookie:` header.
Built on a null-prototype object, for the same reason `Context.query()` is: a plain `{}` inherits from `Object.prototype`, so a read of a key nobody sent returns the inherited value rather than nothing. The default cookie names are namespaced — `yatta_session`, `yatta_refresh`, `yatta_csrf` — so no inherited key can collide with them and this is not reachable out of the box. But the names are configurable, and `csrfCookieName: "constructor"` or any other Object.prototype member hands back a function where a token belongs. That value is then compared against a header, which is a check that quietly stops checking.
signuppropertysignup:loginpropertylogin:logoutpropertylogout:
AuthApiKeys
classclass AuthApiKeys4 members
createcreate(userId: string, options: { name: string; scopes?: string[]; expiresAt?: Date; }): Promise<{ apiKey: string; record: AuthApiKey; }>verifyverify(rawKey: string, options?: { requireScope?: string; }): Promise<ApiKeyPrincipal | null>listlist(userId: string)revokerevoke(userId: string, id: string)
AuthCrypto
classclass AuthCrypto13 members
shortSecretWarnedpropertyshortSecretWarned:encKeypropertyencKey: BufferjwtKeypropertyjwtKey: BufferoauthKeypropertyoauthKey: BufferrecoveryKeypropertyrecoveryKey: BuffertimingSafeEqualtimingSafeEqual(a: string, b: string): booleanhashhash(value: string): stringhmachmac(value: string, key: Buffer): stringrandomTokenrandomToken(bytes?: ): stringencryptencrypt(plainText: string): stringdecryptdecrypt(cipherPayload: string): stringhashPasswordhashPassword(password: string): Promise<string>verifyPasswordverifyPassword(password: string, hash: string): Promise<boolean>
AuthError
classclass AuthError extends ErrorAuthJwt
classclass AuthJwt2 members
signsign(payload: Omit<JwtClaims, "iat" | "exp" | "jti"> & { expInSec: number; jti?: string; }): stringverifyverify(token: string): JwtClaims | null
AuthMagicLink
classclass AuthMagicLink2 members
requestrequest(email: string, req?: Request): Promise<void>verifyverify(rawToken: string, req?: Request): Promise<AuthResult | MfaChallenge>
AuthMfa
classclass AuthMfa5 members
beginSetupbeginSetup(userId: string, appName?: )verifyCodeverifyCode(secret: string, code: string, user?: AuthUser): boolean | "replayed"Whether a TOTP code is valid for this user right now.
Returns `true`, `false`, or `"replayed"`. `replayed` is distinguished because the situation is not the user's mistake. A code that is genuinely correct but inside a time-step already used is rejected — rightly — but reported as "that code is not valid" it reads as a typo, and the user retypes a code that will never work. It happens on enrolment: the code used to set 2FA up consumes the step, so signing in inside the same 30 seconds is refused.
confirmSetupconfirmSetup(userId: string, code: string): Promise<{ recoveryCodes: string[]; }>disabledisable(req: Request, code?: string): Promise<void>consumeRecoveryCodeconsumeRecoveryCode(userId: string, rawCode: string): Promise<boolean>
AuthOAuth
classclass AuthOAuth6 members
providerspropertyproviders:registerProviderregisterProvider(provider: OAuthProvider)registerDefaultsregisterDefaults()getAuthorizationUrlgetAuthorizationUrl(providerName: string, redirectUri: string): Promise<{ url: string; state: string; codeVerifier?: string; }>sessionUserIdsessionUserId(req: Request | undefined): Promise<string | null>Completes an OAuth sign-in, or links a provider to the caller's own account.
`linkToUserId` has been removed, and deliberately not replaced with `linkToSessionToken`-style indirection of the same shape. Taking a user id from the caller and checking only that it *exists* is account takeover: anyone who can run their own Google sign-in and guess a victim's id passes their identity to `linkIdentity`, and from then on Google signs them in as the victim. To link, pass `req` with the caller's own session cookie. The user is resolved from that session inside this function, so the answer cannot be forged. The user id behind a request's own session, or `null`. Where an operation must act on the caller rather than on a value they supplied. Returning `null` rather than throwing keeps the call sites readable: "no session" and "a session" are two ordinary cases, and only the caller knows which it is. Goes through `getSession` rather than reading the cookie itself, so bearer tokens and the JWT path resolve here too. Reading only the cookie would make linking work in a browser and silently do nothing for a native client. `autoRefresh` is off: this decides who the request is, and a failed refresh should leave that as no answer rather than minting a new session to find out.
handleCallbackhandleCallback(input: { provider: string; code: string; state: string; expectedState: string; redirectUri: string; codeVerifier?: string; req?: Request; }): Promise<AuthResult | MfaChallenge>
AuthPasskey
classclass AuthPasskey8 members
rpConfiggetterrpConfig:generateRegistrationOptionsgenerateRegistrationOptions(userId: string)verifyRegistrationverifyRegistration(userId: string, response: RegistrationResponseJSON, expectedChallenge: string, name?: string)generateAuthenticationOptionsgenerateAuthenticationOptions(userEmail?: string, req?: Request)verifyAuthenticationverifyAuthentication(response: AuthenticationResponseJSON, expectedChallenge: string, req?: Request): Promise<AuthResult | MfaChallenge>listlist(userId: string)renamerename(userId: string, id: string, name: string)removeremove(userId: string, id: string)
AuthPasswordSubsystem
classclass AuthPasswordSubsystem3 members
requestResetrequestReset(email: string, req?: Request): Promise<void>resetreset(rawToken: string, newPassword: string): Promise<void>changechange(userId: string, currentPass: string, newPass: string, currentSessionId?: string): Promise<void>
ForbiddenError
classclass ForbiddenError extends AuthErrorGranularRateLimiter
classclass GranularRateLimiter4 members
isEnabledisEnabled(): booleanassertAllowedassertAllowed(bucket: keyof RateLimitConfig, ip: string, identifier?: string): Promise<void>recordFailurerecordFailure(bucket: keyof RateLimitConfig, ip: string, identifier?: string): Promise<void>recordSuccessrecordSuccess(bucket: keyof RateLimitConfig, ip: string, identifier?: string): Promise<void>
MemoryAuditStore
classclass MemoryAuditStore implements AuthAuditStore3 members
eventspropertyevents: AuthEvent[]recordrecord(event: AuthEvent): Promise<void>listByUserlistByUser(userId: string, limit?: ): Promise<AuthEvent[]>
MemoryAuthStore
classclass MemoryAuthStore implements AuthStore38 members
userspropertyusers:sessionspropertysessions:identitiespropertyidentities:tokenspropertytokens:passkeyspropertypasskeys:apiKeyspropertyapiKeys: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)timingSafeEqualtimingSafeEqual(a: string, b: string): booleanlistSessionsByUserIdlistSessionsByUserId(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"])consumeTokenconsumeToken(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)
MemoryChallengeStore
classclass MemoryChallengeStore implements AuthChallengeStore5 members
challengespropertychallenges:setset(challenge: AuthChallenge): Promise<void>getget(challengeString: string): Promise<AuthChallenge | null>consumeconsume(challengeString: string): Promise<AuthChallenge | null>Reads and removes in one step.
Atomic for this store: the map is synchronous and nothing awaits between the read and the delete, so two concurrent calls cannot both see the entry.
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
classclass PermissionManager4 members
permissionspropertypermissions:initializeinitialize(roleDefs?: RoleDefinitions)resolvePermissionsForRoleresolvePermissionsForRole(role: string, defs: RoleDefinitions, path: Set<string>): Set<string>checkcheck(userRoles: string[], action: string, resource: string, isOwner?: ): boolean
RateLimitError
classclass RateLimitError extends AuthErrorSecurityReauthRequiredError
classclass SecurityReauthRequiredError extends AuthErrorSecurityRiskEngine
classclass SecurityRiskEngine1 member
assessLoginRiskassessLoginRisk(ctx: RiskContext): Promise<{ risk: "low" | "medium" | "high"; reasons: string[]; }>
UnauthorizedError
classclass UnauthorizedError extends AuthErrorTypes
ApiKeyPrincipal
interfaceA verified API key, with its scopes attached as behaviour rather than as data.
`scopes` alone is easy to ignore: a check written once and missed in one route is an authorisation bug that no type checker reports. `requireScope` puts the check in the type, so using the key without considering it is the awkward path.
interface ApiKeyPrincipal5 members
userpropertyuser: PublicUserapiKeypropertyapiKey: AuthApiKeyscopespropertyscopes: string[]hasScopepropertyhasScope: (scope: string) => booleanrequireScopepropertyrequireScope: (scope: string) => void
AuthApiKey
interfaceinterface AuthApiKey9 members
idpropertyid: stringuserIdpropertyuserId: stringnamepropertyname: stringkeyHashpropertykeyHash: stringprefixpropertyprefix: stringscopespropertyscopes: string[]expiresAtpropertyexpiresAt?: DatelastUsedAtpropertylastUsedAt?: DatecreatedAtpropertycreatedAt: Date
AuthAuditStore
interfaceinterface AuthAuditStore2 members
recordrecord(event: AuthEvent): Promise<void>listByUserlistByUser(userId: string, limit?: number): Promise<AuthEvent[]>
AuthChallenge
interfaceinterface AuthChallenge7 members
idpropertyid: stringchallengepropertychallenge: stringThe lookup key, and by convention also the payload.
The store indexes on this field, so it must be the value the caller will look up later. WebAuthn satisfies both at once, because the challenge string *is* the thing being verified.
typepropertytype: "registration" | "authentication"userIdpropertyuserId?: stringdatapropertydata?: stringExtra payload, for a challenge whose key is not its own payload.
MFA enrolment is the case that needs it: the caller to look up later is known only by user id, while the value worth keeping is the TOTP seed. The seed lives here (encrypted) and the key is derived from the user id.
expiresAtpropertyexpiresAt: Dateippropertyip?: string
AuthChallengeStore
interfaceinterface AuthChallengeStore4 members
setset(challenge: AuthChallenge): Promise<void>getget(challengeString: string): Promise<AuthChallenge | null>deletedelete(challengeString: string): Promise<void>consumeconsume(challengeString: string): Promise<AuthChallenge | null>?Reads and removes a challenge in one step.
Optional, and the caller must fall back to `get` + `delete` when it is absent. That fallback is racy across workers — two callers can both pass the `get` — so anything spent on its way in (an MFA ticket, a one-time link) needs this to be a real atomic take rather than a read followed by a hope.
AuthConfig
interfaceinterface AuthConfig14 members
secretpropertysecret: stringstorepropertystore?: AuthStorechallengeStorepropertychallengeStore?: AuthChallengeStoremfapropertymfa?: { challengeTtlSec?: number; }Two-factor settings. Applies to every sign-in route, not just passwords.
rateLimitStorepropertyrateLimitStore?: RateLimitStoreauditStorepropertyauditStore?: AuthAuditStoresessionpropertysession?: SessionConfigpasswordPolicypropertypasswordPolicy?: PasswordPolicyConfigsecuritypropertysecurity?: SecurityConfigrateLimitspropertyrateLimits?: RateLimitConfigcookiespropertycookies?: CookieOptionsemailpropertyemail?: AuthEmailConfigpasskeyspropertypasskeys?: { rpName: string; rpID: string; origin: string; }rolespropertyroles?: RoleDefinitions
AuthEmailConfig
interfaceinterface AuthEmailConfig5 members
frompropertyfrom?: EmailAddressappUrlpropertyappUrl?: stringmailerpropertymailer?: YattaMailerresendCooldownSecpropertyresendCooldownSec?: numbertemplatespropertytemplates?: { verification?: (data: AuthEmailTemplateData) => { subject: string; html: string; text?: string; }; passwordReset?: (data: AuthEmailTemplateData) => { subject: string; html: string; text?: string; }; magicLink?: (data: AuthEmailTemplateData) => { subject: string; html: string; text?: string; }; }
AuthEmailTemplateData
interfaceinterface AuthEmailTemplateData3 members
emailpropertyemail: stringlinkpropertylink: stringtokenpropertytoken: string
AuthEvent
interfaceinterface AuthEvent7 members
idpropertyid: stringuserIdpropertyuserId?: stringtypepropertytype: stringippropertyip?: stringuserAgentpropertyuserAgent?: stringmetadatapropertymetadata?: Record<string, unknown>timestamppropertytimestamp: Date
AuthIdentity
interfaceinterface AuthIdentity7 members
idpropertyid: stringuserIdpropertyuserId: stringproviderpropertyprovider: stringproviderAccountIdpropertyproviderAccountId: stringemailpropertyemail?: stringcreatedAtpropertycreatedAt: DateupdatedAtpropertyupdatedAt: Date
AuthMembership
interfaceinterface AuthMembership5 members
idpropertyid: stringorganizationIdpropertyorganizationId: stringuserIdpropertyuserId: stringrolepropertyrole: stringcreatedAtpropertycreatedAt: Date
AuthOrganization
interfaceinterface AuthOrganization4 members
idpropertyid: stringnamepropertyname: stringslugpropertyslug: stringcreatedAtpropertycreatedAt: Date
AuthPasskeyCredential
interfaceinterface AuthPasskeyCredential8 members
idpropertyid: stringuserIdpropertyuserId: stringnamepropertyname?: stringpublicKeypropertypublicKey: Uint8Arraycounterpropertycounter: numbertransportspropertytransports?: AuthenticatorTransport[]createdAtpropertycreatedAt: DatelastUsedAtpropertylastUsedAt?: Date
AuthResult
interfaceinterface AuthResult5 members
userpropertyuser: PublicUsersessionpropertysession: PublicSessiontokenspropertytokens: TokenPaircookiespropertycookies: string[]toResponsetoResponse(body?: Record<string, unknown>, status?: number): Response
AuthSession
interfaceinterface AuthSession5 members
sessionTokenHashpropertysessionTokenHash: stringrefreshTokenHashpropertyrefreshTokenHash?: stringpreviousRefreshTokenHashpropertypreviousRefreshTokenHash?: stringrotatedAtpropertyrotatedAt?: DaterefreshVersionpropertyrefreshVersion: number
AuthStore
interfaceinterface AuthStore37 members
findUserByIdfindUserById(id: string): Promise<AuthUser | null>findUserByEmailfindUserByEmail(email: string): Promise<AuthUser | null>createUsercreateUser(user: Omit<AuthUser, "createdAt" | "updatedAt">): Promise<AuthUser>updateUserupdateUser(id: string, updates: Partial<AuthUser>): Promise<AuthUser>deleteUserdeleteUser(id: string): Promise<void>createSessioncreateSession(session: AuthSession): Promise<AuthSession>findSessionByIdfindSessionById(id: string): Promise<AuthSession | null>findSessionByTokenHashfindSessionByTokenHash(tokenHash: string): Promise<AuthSession | null>listSessionsByUserIdlistSessionsByUserId(userId: string): Promise<AuthSession[]>updateSessionupdateSession(id: string, updates: Partial<AuthSession>): Promise<AuthSession>deleteSessiondeleteSession(id: string): Promise<void>deleteSessionsByUserIddeleteSessionsByUserId(userId: string): Promise<void>findIdentityfindIdentity(provider: string, providerAccountId: string): Promise<AuthIdentity | null>listIdentitiesByUserIdlistIdentitiesByUserId(userId: string): Promise<AuthIdentity[]>createIdentitycreateIdentity(identity: AuthIdentity): Promise<AuthIdentity>deleteIdentitydeleteIdentity(id: string): Promise<void>createTokencreateToken(token: AuthVerificationToken): Promise<AuthVerificationToken>findTokenByHashfindTokenByHash(tokenHash: string, type: AuthVerificationToken["type"]): Promise<AuthVerificationToken | null>consumeTokenconsumeToken(tokenHash: string, type: AuthVerificationToken["type"]): Promise<AuthVerificationToken | null>deleteTokendeleteToken(id: string): Promise<void>deleteTokensByUserIddeleteTokensByUserId(userId: string, type?: AuthVerificationToken["type"]): Promise<void>savePasskeysavePasskey(cred: AuthPasskeyCredential): Promise<void>findPasskeyByIdfindPasskeyById(id: string): Promise<AuthPasskeyCredential | null>listPasskeysByUserIdlistPasskeysByUserId(userId: string): Promise<AuthPasskeyCredential[]>updatePasskeyupdatePasskey(id: string, updates: Partial<AuthPasskeyCredential>): Promise<void>deletePasskeydeletePasskey(id: string): Promise<void>createApiKeycreateApiKey(key: AuthApiKey): Promise<AuthApiKey>findApiKeyByHashfindApiKeyByHash(keyHash: string): Promise<AuthApiKey | null>listApiKeysByUserIdlistApiKeysByUserId(userId: string): Promise<AuthApiKey[]>updateApiKeyupdateApiKey(id: string, updates: Partial<AuthApiKey>): Promise<void>deleteApiKeydeleteApiKey(id: string): Promise<void>createOrganizationcreateOrganization(org: AuthOrganization): Promise<AuthOrganization>?findOrganizationByIdfindOrganizationById(id: string): Promise<AuthOrganization | null>?findOrganizationBySlugfindOrganizationBySlug(slug: string): Promise<AuthOrganization | null>?createMembershipcreateMembership(membership: AuthMembership): Promise<AuthMembership>?findMembershipfindMembership(orgId: string, userId: string): Promise<AuthMembership | null>?listMembershipsByUserIdlistMembershipsByUserId(userId: string): Promise<AuthMembership[]>?
AuthUser
interfaceinterface AuthUser5 members
passwordHashpropertypasswordHash?: stringencryptedTwoFactorSecretpropertyencryptedTwoFactorSecret?: string | nulltwoFactorRecoveryCodespropertytwoFactorRecoveryCodes?: string[] | nulllastMfaSteppropertylastMfaStep?: numbercredentialVersionpropertycredentialVersion: number
AuthVerificationToken
interfaceinterface AuthVerificationToken5 members
idpropertyid: stringuserIdpropertyuserId: stringtokenHashpropertytokenHash: stringtypepropertytype: "email_verification" | "password_reset" | "magic_link"expiresAtpropertyexpiresAt: Date
CookieOptions
interfaceinterface CookieOptions7 members
sessionCookieNamepropertysessionCookieName?: stringrefreshCookieNamepropertyrefreshCookieName?: stringcsrfCookieNamepropertycsrfCookieName?: stringdomainpropertydomain?: stringpathpropertypath?: stringsecurepropertysecure?: booleansameSitepropertysameSite?: "Lax" | "Strict" | "None"
JwtClaims
interfaceinterface JwtClaims8 members
subpropertysub: stringtypepropertytype: "access" | "refresh" | "mfa"`mfa` is a short-lived, single-use ticket for the second half of a sign-in. It
sidpropertysid?: stringjtipropertyjti: stringverpropertyver?: numberamrpropertyamr?: stringHow the first factor was satisfied. Present on `mfa` tickets.
exppropertyexp: numberiatpropertyiat: number
MfaChallenge
interfaceWhat a sign-in returns when it stops at the second factor.
A `ticket`, not a `userId`. With a bare id, whatever the app built as its second step had no proof the first factor had passed — see .
interface MfaChallenge3 members
mfaRequiredpropertymfaRequired: trueticketpropertyticket: stringShort-lived, single-use, signed. Pass it to `completeMfa`.
expiresInSecpropertyexpiresInSec: numberWhen the ticket stops working. For a countdown in the UI.
OAuthProvider
interfaceinterface OAuthProvider9 members
namepropertyname: stringclientIdpropertyclientId: stringclientSecretpropertyclientSecret: stringauthorizeUrlpropertyauthorizeUrl: stringtokenUrlpropertytokenUrl: stringuserInfoUrlpropertyuserInfoUrl: stringscopespropertyscopes: string[]usePkcepropertyusePkce?: booleanmapProfilepropertymapProfile: (data: Record<string, unknown>) => { id: string; email: string; emailVerified: boolean; name?: string; }
PasswordPolicyConfig
interfaceinterface PasswordPolicyConfig6 members
minLengthpropertyminLength?: numbermaxLengthpropertymaxLength?: numberrequireUppercasepropertyrequireUppercase?: booleanrequireLowercasepropertyrequireLowercase?: booleanrequireNumberspropertyrequireNumbers?: booleanrequireSymbolspropertyrequireSymbols?: boolean
PublicSession
interfaceinterface PublicSession10 members
idpropertyid: stringuserIdpropertyuserId: stringexpiresAtpropertyexpiresAt: DatelastSeenAtpropertylastSeenAt: DatelastAuthenticatedAtpropertylastAuthenticatedAt: DatecreatedAtpropertycreatedAt: DateuserAgentpropertyuserAgent?: stringippropertyip?: stringdeviceIdpropertydeviceId?: stringdeviceNamepropertydeviceName?: string
PublicUser
interfaceinterface PublicUser8 members
idpropertyid: stringemailpropertyemail: stringrolespropertyroles: string[]emailVerifiedpropertyemailVerified: booleantwoFactorEnabledpropertytwoFactorEnabled: booleanmetadatapropertymetadata?: Record<string, unknown>createdAtpropertycreatedAt: DateupdatedAtpropertyupdatedAt: Date
RateLimitConfig
interfaceinterface RateLimitConfig6 members
enabledpropertyenabled?: booleanloginpropertylogin?: { maxAttempts: number; windowSec: number; lockoutSec: number; }signuppropertysignup?: { maxAttempts: number; windowSec: number; lockoutSec: number; }passwordResetpropertypasswordReset?: { maxAttempts: number; windowSec: number; lockoutSec: number; }magicLinkpropertymagicLink?: { maxAttempts: number; windowSec: number; lockoutSec: number; }passkeypropertypasskey?: { maxAttempts: number; windowSec: number; lockoutSec: number; }
RateLimitStore
interfaceinterface RateLimitStore3 members
getget(key: string): Promise<{ hits: number[]; lockoutUntil?: number; } | null>setset(key: string, data: { hits: number[]; lockoutUntil?: number; }, ttlSec: number): Promise<void>deletedelete(key: string): Promise<void>
RiskContext
interfaceinterface RiskContext3 members
userpropertyuser: AuthUserippropertyip?: stringuserAgentpropertyuserAgent?: string
SecurityConfig
interfaceinterface SecurityConfig7 members
trustProxypropertytrustProxy?: booleanTrust `cf-connecting-ip` / `x-real-ip` / `x-forwarded-for` for the client IP.
Only enable when a proxy you control sets them and **strips any incoming copy**. Otherwise a client can send the header itself and rotate apparent IPs to walk straight past the rate limiter.
trustedProxyCountpropertytrustedProxyCount?: numberHow many proxies sit in front of this process and are trusted to append to
Defaults to 1. `x-forwarded-for` reads `client, proxy1, proxy2…`, and the client writes the leftmost entry — so the client IP is found by counting back from the right, past every proxy you trust. One proxy means the second-to-last entry; a CDN plus a load balancer means the third-to-last. Getting this wrong in the permissive direction is a rate-limit bypass, and in the strict direction every client appears to be your proxy. Set it from your topology rather than guessing.
getClientIppropertygetClientIp?: (req: Request) => string | undefinedResolve the peer address of a request.
Bun does not expose it on `Request`; read it from the server instead: `getClientIp: (req) => server.requestIP(req)?.address`. Without this, every client is seen as 127.0.0.1 and all per-IP rate limits become global.
recentAuthWindowSecpropertyrecentAuthWindowSec?: numberallowUnverifiedSessionpropertyallowUnverifiedSession?: booleanpreventAccountEnumerationpropertypreventAccountEnumeration?: booleanencryptionKeypropertyencryptionKey?: string
SessionConfig
interfaceinterface SessionConfig5 members
accessTokenTtlSecpropertyaccessTokenTtlSec?: numberrefreshTokenTtlSecpropertyrefreshTokenTtlSec?: numbersessionTtlSecpropertysessionTtlSec?: numberactivityThrottleSecpropertyactivityThrottleSec?: numberautoRefreshOnCookieAuthpropertyautoRefreshOnCookieAuth?: boolean
TokenPair
interfaceinterface TokenPair3 members
accessTokenpropertyaccessToken: stringrefreshTokenpropertyrefreshToken: stringexpiresInpropertyexpiresIn: number
RoleDefinitions
typetype RoleDefinitions = Record<string, string[] | { can: string[]; inherits?: string[]; }>AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.