Stacks Authentication & Authorization
The @stacksjs/auth package provides comprehensive authentication and authorization for Stacks applications, built on @stacksjs/ts-auth.
Key Paths
- Core package source:
storage/framework/core/auth/src/
- Configuration:
config/auth.ts
- Security config:
config/security.ts
- Hashing config:
config/hashing.ts
- Application gates:
app/Gates.ts
- Application middleware:
app/Middleware/
- Middleware aliases:
app/Middleware.ts
- Auth types:
storage/framework/core/types/src/auth.ts
Source Files
auth/src/
├── index.ts # All re-exports
├── authentication.ts # Auth class - core auth logic
├── authenticator.ts # 2FA and personal access client
├── client.ts # Client re-exports
├── middleware.ts # Auth middleware handler
├── rate-limiter.ts # RateLimiter class (5 attempts, 15min lockout)
├── passkey.ts # WebAuthn/Passkey support
├── password/reset.ts # Password reset flow
├── register.ts # User registration
├── user.ts # Auth user helpers
├── tokens.ts # Token CRUD, scopes, refresh tokens, OAuth clients
├── gate.ts # Authorization gates & policies
├── policy.ts # BasePolicy class + discovery
├── authorizable.ts # User authorization mixin
├── rbac.ts # Full RBAC system
├── email-verification.ts # Email verification flow
└── session-auth.ts # Session-based SPA auth
Auth Class (authentication.ts) — Static Methods
Login & Authentication
Auth.attempt(credentials: AuthCredentials): Promise<boolean> — validate credentials without creating token
Auth.validate(credentials: AuthCredentials): Promise<boolean> — alias for attempt
Auth.login(credentials: AuthCredentials, options?: TokenCreateOptions): Promise<{ user, token } | null> — login and create token
Auth.loginUsingId(userId: number, options?: TokenCreateOptions): Promise<{ user, token } | null> — login by user ID
Auth.logout(): Promise<void> — revoke current token
Auth.once(credentials: AuthCredentials): Promise<boolean> — one-time auth without token
Auth.requestToken(credentials, clientId, clientSecret): Promise<{ token } | null> — OAuth token request
User State
Auth.user(): Promise<UserModel | undefined> — get authenticated user from bearer token
Auth.check(): Promise<boolean> — is user authenticated?
Auth.guest(): Promise<boolean> — is user a guest?
Auth.id(): Promise<number | undefined> — get authenticated user ID
Auth.setUser(user: UserModel): void — manually set user
Token Creation
Auth.createTokenForUser(user, options?: TokenCreateOptions): Promise<NewAccessToken>
Auth.createToken(user, name?, abilities?): Promise<AuthToken>
Token Validation
Auth.validateToken(token: string): Promise<boolean> — validate bearer token
Auth.getUserFromToken(token: string): Promise<UserModel | undefined>
Auth.currentAccessToken(): Promise<PersonalAccessToken | undefined>
Token Abilities (Scopes)
Auth.tokenCan(ability: string): Promise<boolean>
Auth.tokenCant(ability: string): Promise<boolean>
Auth.tokenAbilities(): Promise<string[]>
Auth.tokenCanAll(abilities: string[]): Promise<boolean>
Auth.tokenCanAny(abilities: string[]): Promise<boolean>
Token Management
Auth.tokens(userId?: number): Promise<PersonalAccessToken[]>
Auth.revokeToken(token: string): Promise<void>
Auth.revokeTokenById(tokenId: number): Promise<void>
Auth.revokeAllTokens(userId?: number): Promise<void>
Auth.revokeOtherTokens(userId?: number): Promise<void>
Auth.pruneExpiredTokens(): Promise<number>
Auth.pruneRevokedTokens(): Promise<number>
Auth.rotateToken(oldToken: string): Promise<AuthToken | null>
Auth.findToken(tokenId: number): Promise<PersonalAccessToken | null>
Utility
Auth.guard(name?: string): typeof Auth — select guard (returns self)
Auth.viaRemember(): boolean — always false currently
Auth.clearState(): void — clear cached user/token
Token System (tokens.ts)
Access Tokens
tokens(userId: number): Promise<AccessToken[]>
findToken(plainTextToken: string): Promise<AccessToken | null>
currentAccessToken(): Promise<AccessToken | null>
createToken(userId, name?, scopes?, options?): Promise<PersonalAccessTokenResult>
- Options:
{ expiresInMinutes?, withRefreshToken?, refreshExpiresInDays? }
Refresh Tokens
refreshToken(refreshTokenPlain, options?): Promise<RefreshTokenResult>
validateRefreshToken(refreshTokenPlain): Promise<boolean>
revokeRefreshToken(refreshTokenPlain): Promise<void>
revokeAllRefreshTokens(userId): Promise<void>
deleteExpiredRefreshTokens(): Promise<number>
deleteRevokedRefreshTokens(daysOld?): Promise<number>
Token Revocation
revokeToken(plainTextToken): Promise<void>
revokeTokenById(tokenId): Promise<void>
revokeAllTokens(userId): Promise<void>
revokeOtherTokens(userId): Promise<void>
deleteExpiredTokens(): Promise<number>
deleteRevokedTokens(daysOld?): Promise<number>
Token Scopes
tokenCan(scope): Promise<boolean>
tokenCant(scope): Promise<boolean>
tokenCanAll(scopes): Promise<boolean>
tokenCanAny(scopes): Promise<boolean>
tokenAbilities(): Promise<string[]>
parseScopes(scopes: string | string[] | null | undefined): TokenScopes
OAuth Clients
clients(userId): Promise<OAuthClient[]>
findClient(clientId): Promise<OAuthClient | null>
createClient(options: CreateClientOptions): Promise<CreateClientResult>
revokeClient(clientId): Promise<void>
Two-Factor Authentication (authenticator.ts)
generateTwoFactorSecret(): string
generateTwoFactorToken(secret: Secret): Promise<Token>
verifyTwoFactorCode(token: Token, secret: Secret): Promise<boolean>
generateTwoFactorUri(user?, service?, secret?): string
createPersonalAccessClient(): Promise<Result<string, never>>
Re-exported from @stacksjs/ts-auth
generateTOTP, verifyTOTP, generateTOTPSecret, totpKeyUri
Authorization Gates (gate.ts)
Gate Functions
define<T>(ability: string, callback: GateCallback<T>): void
policy(model: string | { name }, policyClass: new () => Policy): void
before(callback): void — run before any gate check
after(callback): void — run after any gate check
allows(ability, user, ...args): Promise<boolean>
denies(ability, user, ...args): Promise<boolean>
can(ability, user, ...args): Promise<boolean>
cannot(ability, user, ...args): Promise<boolean>
any(abilities[], user, ...args): Promise<boolean>
all(abilities[], user, ...args): Promise<boolean>
none(abilities[], user, ...args): Promise<boolean>
authorize(ability, user, ...args): Promise<AuthorizationResponse> — throws on deny
inspect(ability, user, ...args): Promise<AuthorizationResponse> — never throws
has(ability): boolean
hasPolicy(model): boolean
abilities(): string[]
getPolicyFor<T>(model: T): Policy<T> | null
flush(): void — clear all gates
Gate Facade — Gate.define(), Gate.can(), etc
AuthorizationResponse Class
static allow(message?): AuthorizationResponse
static deny(message?, code?): AuthorizationResponse
allowed(): boolean, denied(): boolean
authorize(): void — throws AuthorizationException if denied
Policy Interface
Methods: before?, viewAny?, view?, create?, update?, delete?, restore?, forceDelete?
BasePolicy Abstract Class
Protected helpers: allow(message?), deny(message?, code?), denyIf(condition), denyUnless(condition), allowIf(condition)
RBAC System (rbac.ts)
Role Management
Rbac.createRole(name, guardName?, description?): Promise<RoleRecord>
Rbac.findRole(name, guardName?): Promise<RoleRecord | null>
Rbac.deleteRole(name, guardName?): Promise<void>
Rbac.getAllRoles(guardName?): Promise<RoleRecord[]>
Permission Management
Rbac.createPermission(name, guardName?, description?): Promise<PermissionRecord>
Rbac.findPermission(name, guardName?): Promise<PermissionRecord | null>
Rbac.deletePermission(name, guardName?): Promise<void>
Rbac.getAllPermissions(guardName?): Promise<PermissionRecord[]>
User-Role Operations
Rbac.getUserRoles(user): Promise<RoleRecord[]>
Rbac.assignRole(user, roleName, guardName?): Promise<void>
Rbac.removeRole(user, roleName, guardName?): Promise<void>
Rbac.removeAllRoles(user): Promise<void>
Rbac.syncRoles(user, roleNames[], guardName?): Promise<void> - replaces assignments for that guard and preserves roles from other guards
Rbac.hasRole(user, roleName, guardName?): Promise<boolean>
Rbac.hasAnyRole(user, roleNames[], guardName?): Promise<boolean>
Rbac.hasAllRoles(user, roleNames[], guardName?): Promise<boolean>
User-Permission Operations
Rbac.getUserPermissions(user): Promise<PermissionRecord[]>
Rbac.givePermission(user, permissionName, guardName?): Promise<void>
Rbac.revokePermission(user, permissionName, guardName?): Promise<void>
Rbac.revokeAllPermissions(user): Promise<void>
Rbac.syncPermissions(user, permissionNames[], guardName?): Promise<void>
Rbac.hasPermission(user, permissionName, guardName?): Promise<boolean>
Rbac.hasAnyPermission(user, permissionNames[], guardName?): Promise<boolean>
Rbac.hasAllPermissions(user, permissionNames[], guardName?): Promise<boolean>
Role-Permission Operations
Rbac.getRolePermissions(roleId): Promise<PermissionRecord[]>
Rbac.givePermissionToRole(roleName, permissionName, guardName?): Promise<void>
Rbac.revokePermissionFromRole(roleName, permissionName, guardName?): Promise<void>
Rbac.syncRolePermissions(roleName, permissionNames[], guardName?): Promise<void>
withRbac Mixin
withRbac(user) — adds hasRole(), hasPermission(), assignRole(), givePermission(), etc. to any user object
RBAC Types
interface RoleRecord { id, name, guard_name, description?, created_at?, updated_at? }
interface PermissionRecord { id, name, guard_name, description?, created_at?, updated_at? }
interface RbacStore { findRoleByName, createRole, deleteRole, getAllRoles, findPermissionByName, createPermission, ... }
Session Auth (session-auth.ts)
SessionAuth.login(email, password): Promise<{ user, sessionId }>
SessionAuth.logout(sessionId): void
SessionAuth.user(sessionId): Promise<UserModel | undefined>
SessionAuth.check(sessionId): boolean
SessionAuth.refresh(sessionId, ttlMs?): boolean
Internal: in-memory Map with 10k session limit, 5-minute eviction interval, timing-safe password comparison with dummy bcrypt hash.
Email Verification (email-verification.ts)
EmailVerification.isVerified(user): boolean
EmailVerification.send(user): Promise<void>
EmailVerification.verify(userId, token): Promise<EmailVerificationResult>
EmailVerification.resend(user): Promise<EmailVerificationResult>
Password Reset (password/reset.ts)
const actions = passwordResets(email)
await actions.sendEmail()
const valid = await actions.verifyToken(token)
const result = await actions.resetPassword(token, newPassword)
Registration (register.ts)
register(credentials: NewUser): Promise<{ token: AuthToken }>
User Helpers (user.ts)
authUser(): Promise<UserModel | undefined>
check(): Promise<boolean>
id(): Promise<number | undefined>
email(): Promise<string | undefined>
name(): Promise<string | undefined>
isAuthenticated(): Promise<boolean>
logout(): Promise<void>
refresh(): Promise<void>
Passkey/WebAuthn (passkey.ts)
getUserPasskeys(userId): Promise<PasskeyAttribute[]>
getUserPasskey(userId, passkeyId): Promise<PasskeyAttribute | undefined>
setCurrentRegistrationOptions(user, verified): Promise<void>
Re-exported from @stacksjs/ts-auth
generateRegistrationOptions, generateAuthenticationOptions
verifyRegistrationResponse, verifyAuthenticationResponse
startRegistration, startAuthentication (browser)
browserSupportsWebAuthn, browserSupportsWebAuthnAutofill
platformAuthenticatorIsAvailable
Auth Middleware (middleware.ts)
export const authMiddlewareHandler = {
name: 'auth',
handle: authMiddleware, // validates bearer token, throws 401
}
Rate Limiter (rate-limiter.ts)
class RateLimiter {
static MAX_ATTEMPTS = 5
static LOCKOUT_DURATION = 15 * 60 * 1000 // 15 minutes
static MAX_STORE_SIZE = 10_000
static EVICTION_INTERVAL = 5 * 60 * 1000 // 5 minutes
static isRateLimited(email): boolean
static recordFailedAttempt(email): void
static resetAttempts(email): void
static validateAttempt(email): void // throws HttpError 429
}
Authorizable Mixin (authorizable.ts)
const authUser = withAuthorization(user)
await authUser.can('edit-post', post)
await authUser.cannot('delete-post', post)
await authUser.canAny(['edit', 'delete'], post)
await authUser.canAll(['edit', 'publish'], post)
await authUser.authorize('edit-post', post) // throws if denied
Configuration
config/auth.ts
{
default: 'api',
guards: { api: { driver: 'token', provider: 'users' } },
providers: { users: { driver: 'database', table: 'users' } },
username: 'email', // AUTH_USERNAME_FIELD env
password: 'password', // AUTH_PASSWORD_FIELD env
tokenExpiry: 30, // days, AUTH_TOKEN_EXPIRY env
tokenRotation: 7, // days, AUTH_TOKEN_ROTATION env
defaultAbilities: ['*'],
defaultTokenName: 'auth-token',
passwordReset: { expire: 60, throttle: 60 }
}
config/hashing.ts
{
driver: 'bcrypt', // 'bcrypt' | 'argon2'
bcrypt: { rounds: 12 },
argon2: { memory: 65536, time: 3 }
}
config/security.ts
{
firewall: {
enabled: true,
countryCodes: [],
ipAddresses: { allowlist: [], blocklist: [] },
rateLimitPerMinute: 500,
useIpReputationLists: true,
useKnownBadInputsRuleSet: true
}
}
Middleware Aliases (app/Middleware.ts)
Auth-relevant aliases: auth, guest, verified (EnsureEmailIsVerified),
abilities, can, role, permission, team, signed, throttle. The
environment aliases are env, env:local, env:development / env:dev,
env:staging, env:production / env:prod — with a COLON, not a dot; an
earlier version of this list wrote env.local and those never existed. See
stacks-middleware for the full set and for the !alias and alias:params
forms.
Application Gates (app/Gates.ts)
import { defineGates } from '@stacksjs/auth'
export default defineGates({
gates: {
'access-admin': user => user?.email?.endsWith('@stacksjs.org') ?? false,
'edit-settings': user => !!user,
'view-dashboard': user => !!user,
},
policies: {
Post: 'PostPolicy',
},
})
Registered at boot by initializeAuthorization(), from
injectGlobalAutoImports() — the one place every entry point comes through, so
HTTP, buddy seed, a scheduled job and a console command all get the same
gates.
Both halves of policies are checked: the key names a model the ORM exposes,
the value a policy file under app/Policies/ or the framework defaults. An
explicit mapping WINS over the <Model>Policy naming convention, which is the
reason to write one.
Gate.define(...) still works for a gate registered at runtime; defineGates
is the declarative form and the one the ability-name completions come from.
Default API Routes
POST /login → LoginAction (validates email + password)
POST /register → RegisterAction
POST /auth/refresh → RefreshTokenAction
POST /auth/token → CreateTokenAction
GET /auth/tokens → ListTokensAction (auth middleware)
DELETE /auth/tokens/{id} → RevokeTokenAction (auth middleware)
GET /me → GetMeAction (auth middleware)
POST /logout → LogoutAction (auth middleware)
User Model Traits
// User model uses:
traits: {
useAuth: { usePasskey: true },
useUuid: true,
useTimestamps: true,
useSocials: ['github'],
}
Gotchas
- Auth depends on
@stacksjs/ts-auth for TOTP and passkey functions
- Password hashing defaults to bcrypt with 12 rounds (config/hashing.ts)
- Rate limiter uses in-memory Map, resets on server restart — not shared across workers
- Session auth also uses in-memory Map with 10k limit — for SPA cookie auth
- Token format is
tokenId|plainText — the | separates the encrypted ID from the plain token
- The
parseToken() helper splits on | to extract both parts
- Bearer tokens come from the
Authorization: Bearer <token> header
Auth.user() internally calls getBearerToken() → parseToken() → getTokenFromId() → validates hash
- RBAC has an internal cache (
userRoles, userPermissions, rolePermissions) — call Rbac.flushCache() after direct DB changes
syncRoles() and syncPermissions() are guard-scoped replacements: they preserve assignments belonging to other guards
- Gate
before callbacks can short-circuit — return true to allow, null to continue checking
- An ability with no gate and no policy method denies. That is the right default, and it means a gate that was never registered is indistinguishable from one that says no — which is how
initializeAuthorization() went unnoticed while nothing called it
allows() and friends take Ability, which is open (GateName | PolicyAbility | (string & {})). A /can/:ability route passes an ability straight through, so narrowing it would reject correct code; the union is for completions
withRbac() and withAuthorization() return new objects with methods mixed in
- The
RbacStore interface must be implemented and set via Rbac.setStore() for RBAC to work
- Password reset tokens expire after 60 minutes by default
- Default token abilities are
['*'] — wildcard access
- Token expiry defaults to 30 days
- Session auth uses timing-safe bcrypt comparison even for failed lookups (dummy hash prevents timing attacks)
Build
cd storage/framework/core/auth && bun build.ts
1---2name: stacks-auth-53description: Use when implementing authentication, authorization, passkeys, TOTP/2FA, RBAC, gates, policies, session auth, token management, email verification, password resets, or rate limiting in a Stacks application. Covers the @stacksjs/auth package, config/auth.ts, app/Gates.ts, and app/Middleware/.4license: MIT5compatibility: Bun >= 1.3.0, TypeScript6allowed-tools: Read Edit Write Bash Grep Glob7metadata:8 source: https://skillmd.com/skills/stacksjs/stacks-auth-59---1011# Stacks Authentication & Authorization1213The `@stacksjs/auth` package provides comprehensive authentication and authorization for Stacks applications, built on `@stacksjs/ts-auth`.1415## Key Paths1617- Core package source: `storage/framework/core/auth/src/`18- Configuration: `config/auth.ts`19- Security config: `config/security.ts`20- Hashing config: `config/hashing.ts`21- Application gates: `app/Gates.ts`22- Application middleware: `app/Middleware/`23- Middleware aliases: `app/Middleware.ts`24- Auth types: `storage/framework/core/types/src/auth.ts`2526## Source Files2728```29auth/src/30├── index.ts # All re-exports31├── authentication.ts # Auth class - core auth logic32├── authenticator.ts # 2FA and personal access client33├── client.ts # Client re-exports34├── middleware.ts # Auth middleware handler35├── rate-limiter.ts # RateLimiter class (5 attempts, 15min lockout)36├── passkey.ts # WebAuthn/Passkey support37├── password/reset.ts # Password reset flow38├── register.ts # User registration39├── user.ts # Auth user helpers40├── tokens.ts # Token CRUD, scopes, refresh tokens, OAuth clients41├── gate.ts # Authorization gates & policies42├── policy.ts # BasePolicy class + discovery43├── authorizable.ts # User authorization mixin44├── rbac.ts # Full RBAC system45├── email-verification.ts # Email verification flow46└── session-auth.ts # Session-based SPA auth47```4849## Auth Class (authentication.ts) — Static Methods5051### Login & Authentication52- `Auth.attempt(credentials: AuthCredentials): Promise<boolean>` — validate credentials without creating token53- `Auth.validate(credentials: AuthCredentials): Promise<boolean>` — alias for attempt54- `Auth.login(credentials: AuthCredentials, options?: TokenCreateOptions): Promise<{ user, token } | null>` — login and create token55- `Auth.loginUsingId(userId: number, options?: TokenCreateOptions): Promise<{ user, token } | null>` — login by user ID56- `Auth.logout(): Promise<void>` — revoke current token57- `Auth.once(credentials: AuthCredentials): Promise<boolean>` — one-time auth without token58- `Auth.requestToken(credentials, clientId, clientSecret): Promise<{ token } | null>` — OAuth token request5960### User State61- `Auth.user(): Promise<UserModel | undefined>` — get authenticated user from bearer token62- `Auth.check(): Promise<boolean>` — is user authenticated?63- `Auth.guest(): Promise<boolean>` — is user a guest?64- `Auth.id(): Promise<number | undefined>` — get authenticated user ID65- `Auth.setUser(user: UserModel): void` — manually set user6667### Token Creation68- `Auth.createTokenForUser(user, options?: TokenCreateOptions): Promise<NewAccessToken>`69- `Auth.createToken(user, name?, abilities?): Promise<AuthToken>`7071### Token Validation72- `Auth.validateToken(token: string): Promise<boolean>` — validate bearer token73- `Auth.getUserFromToken(token: string): Promise<UserModel | undefined>`74- `Auth.currentAccessToken(): Promise<PersonalAccessToken | undefined>`7576### Token Abilities (Scopes)77- `Auth.tokenCan(ability: string): Promise<boolean>`78- `Auth.tokenCant(ability: string): Promise<boolean>`79- `Auth.tokenAbilities(): Promise<string[]>`80- `Auth.tokenCanAll(abilities: string[]): Promise<boolean>`81- `Auth.tokenCanAny(abilities: string[]): Promise<boolean>`8283### Token Management84- `Auth.tokens(userId?: number): Promise<PersonalAccessToken[]>`85- `Auth.revokeToken(token: string): Promise<void>`86- `Auth.revokeTokenById(tokenId: number): Promise<void>`87- `Auth.revokeAllTokens(userId?: number): Promise<void>`88- `Auth.revokeOtherTokens(userId?: number): Promise<void>`89- `Auth.pruneExpiredTokens(): Promise<number>`90- `Auth.pruneRevokedTokens(): Promise<number>`91- `Auth.rotateToken(oldToken: string): Promise<AuthToken | null>`92- `Auth.findToken(tokenId: number): Promise<PersonalAccessToken | null>`9394### Utility95- `Auth.guard(name?: string): typeof Auth` — select guard (returns self)96- `Auth.viaRemember(): boolean` — always false currently97- `Auth.clearState(): void` — clear cached user/token9899## Token System (tokens.ts)100101### Access Tokens102- `tokens(userId: number): Promise<AccessToken[]>`103- `findToken(plainTextToken: string): Promise<AccessToken | null>`104- `currentAccessToken(): Promise<AccessToken | null>`105- `createToken(userId, name?, scopes?, options?): Promise<PersonalAccessTokenResult>`106 - Options: `{ expiresInMinutes?, withRefreshToken?, refreshExpiresInDays? }`107108### Refresh Tokens109- `refreshToken(refreshTokenPlain, options?): Promise<RefreshTokenResult>`110- `validateRefreshToken(refreshTokenPlain): Promise<boolean>`111- `revokeRefreshToken(refreshTokenPlain): Promise<void>`112- `revokeAllRefreshTokens(userId): Promise<void>`113- `deleteExpiredRefreshTokens(): Promise<number>`114- `deleteRevokedRefreshTokens(daysOld?): Promise<number>`115116### Token Revocation117- `revokeToken(plainTextToken): Promise<void>`118- `revokeTokenById(tokenId): Promise<void>`119- `revokeAllTokens(userId): Promise<void>`120- `revokeOtherTokens(userId): Promise<void>`121- `deleteExpiredTokens(): Promise<number>`122- `deleteRevokedTokens(daysOld?): Promise<number>`123124### Token Scopes125- `tokenCan(scope): Promise<boolean>`126- `tokenCant(scope): Promise<boolean>`127- `tokenCanAll(scopes): Promise<boolean>`128- `tokenCanAny(scopes): Promise<boolean>`129- `tokenAbilities(): Promise<string[]>`130- `parseScopes(scopes: string | string[] | null | undefined): TokenScopes`131132### OAuth Clients133- `clients(userId): Promise<OAuthClient[]>`134- `findClient(clientId): Promise<OAuthClient | null>`135- `createClient(options: CreateClientOptions): Promise<CreateClientResult>`136- `revokeClient(clientId): Promise<void>`137138## Two-Factor Authentication (authenticator.ts)139140- `generateTwoFactorSecret(): string`141- `generateTwoFactorToken(secret: Secret): Promise<Token>`142- `verifyTwoFactorCode(token: Token, secret: Secret): Promise<boolean>`143- `generateTwoFactorUri(user?, service?, secret?): string`144- `createPersonalAccessClient(): Promise<Result<string, never>>`145146### Re-exported from @stacksjs/ts-auth147- `generateTOTP`, `verifyTOTP`, `generateTOTPSecret`, `totpKeyUri`148149## Authorization Gates (gate.ts)150151### Gate Functions152- `define<T>(ability: string, callback: GateCallback<T>): void`153- `policy(model: string | { name }, policyClass: new () => Policy): void`154- `before(callback): void` — run before any gate check155- `after(callback): void` — run after any gate check156- `allows(ability, user, ...args): Promise<boolean>`157- `denies(ability, user, ...args): Promise<boolean>`158- `can(ability, user, ...args): Promise<boolean>`159- `cannot(ability, user, ...args): Promise<boolean>`160- `any(abilities[], user, ...args): Promise<boolean>`161- `all(abilities[], user, ...args): Promise<boolean>`162- `none(abilities[], user, ...args): Promise<boolean>`163- `authorize(ability, user, ...args): Promise<AuthorizationResponse>` — throws on deny164- `inspect(ability, user, ...args): Promise<AuthorizationResponse>` — never throws165- `has(ability): boolean`166- `hasPolicy(model): boolean`167- `abilities(): string[]`168- `getPolicyFor<T>(model: T): Policy<T> | null`169- `flush(): void` — clear all gates170171### Gate Facade — `Gate.define()`, `Gate.can()`, etc172173### AuthorizationResponse Class174- `static allow(message?): AuthorizationResponse`175- `static deny(message?, code?): AuthorizationResponse`176- `allowed(): boolean`, `denied(): boolean`177- `authorize(): void` — throws AuthorizationException if denied178179### Policy Interface180Methods: `before?`, `viewAny?`, `view?`, `create?`, `update?`, `delete?`, `restore?`, `forceDelete?`181182### BasePolicy Abstract Class183Protected helpers: `allow(message?)`, `deny(message?, code?)`, `denyIf(condition)`, `denyUnless(condition)`, `allowIf(condition)`184185## RBAC System (rbac.ts)186187### Role Management188- `Rbac.createRole(name, guardName?, description?): Promise<RoleRecord>`189- `Rbac.findRole(name, guardName?): Promise<RoleRecord | null>`190- `Rbac.deleteRole(name, guardName?): Promise<void>`191- `Rbac.getAllRoles(guardName?): Promise<RoleRecord[]>`192193### Permission Management194- `Rbac.createPermission(name, guardName?, description?): Promise<PermissionRecord>`195- `Rbac.findPermission(name, guardName?): Promise<PermissionRecord | null>`196- `Rbac.deletePermission(name, guardName?): Promise<void>`197- `Rbac.getAllPermissions(guardName?): Promise<PermissionRecord[]>`198199### User-Role Operations200- `Rbac.getUserRoles(user): Promise<RoleRecord[]>`201- `Rbac.assignRole(user, roleName, guardName?): Promise<void>`202- `Rbac.removeRole(user, roleName, guardName?): Promise<void>`203- `Rbac.removeAllRoles(user): Promise<void>`204- `Rbac.syncRoles(user, roleNames[], guardName?): Promise<void>` - replaces assignments for that guard and preserves roles from other guards205- `Rbac.hasRole(user, roleName, guardName?): Promise<boolean>`206- `Rbac.hasAnyRole(user, roleNames[], guardName?): Promise<boolean>`207- `Rbac.hasAllRoles(user, roleNames[], guardName?): Promise<boolean>`208209### User-Permission Operations210- `Rbac.getUserPermissions(user): Promise<PermissionRecord[]>`211- `Rbac.givePermission(user, permissionName, guardName?): Promise<void>`212- `Rbac.revokePermission(user, permissionName, guardName?): Promise<void>`213- `Rbac.revokeAllPermissions(user): Promise<void>`214- `Rbac.syncPermissions(user, permissionNames[], guardName?): Promise<void>`215- `Rbac.hasPermission(user, permissionName, guardName?): Promise<boolean>`216- `Rbac.hasAnyPermission(user, permissionNames[], guardName?): Promise<boolean>`217- `Rbac.hasAllPermissions(user, permissionNames[], guardName?): Promise<boolean>`218219### Role-Permission Operations220- `Rbac.getRolePermissions(roleId): Promise<PermissionRecord[]>`221- `Rbac.givePermissionToRole(roleName, permissionName, guardName?): Promise<void>`222- `Rbac.revokePermissionFromRole(roleName, permissionName, guardName?): Promise<void>`223- `Rbac.syncRolePermissions(roleName, permissionNames[], guardName?): Promise<void>`224225### withRbac Mixin226`withRbac(user)` — adds `hasRole()`, `hasPermission()`, `assignRole()`, `givePermission()`, etc. to any user object227228### RBAC Types229```typescript230interface RoleRecord { id, name, guard_name, description?, created_at?, updated_at? }231interface PermissionRecord { id, name, guard_name, description?, created_at?, updated_at? }232interface RbacStore { findRoleByName, createRole, deleteRole, getAllRoles, findPermissionByName, createPermission, ... }233```234235## Session Auth (session-auth.ts)236237- `SessionAuth.login(email, password): Promise<{ user, sessionId }>`238- `SessionAuth.logout(sessionId): void`239- `SessionAuth.user(sessionId): Promise<UserModel | undefined>`240- `SessionAuth.check(sessionId): boolean`241- `SessionAuth.refresh(sessionId, ttlMs?): boolean`242243Internal: in-memory Map with 10k session limit, 5-minute eviction interval, timing-safe password comparison with dummy bcrypt hash.244245## Email Verification (email-verification.ts)246247- `EmailVerification.isVerified(user): boolean`248- `EmailVerification.send(user): Promise<void>`249- `EmailVerification.verify(userId, token): Promise<EmailVerificationResult>`250- `EmailVerification.resend(user): Promise<EmailVerificationResult>`251252## Password Reset (password/reset.ts)253254```typescript255const actions = passwordResets(email)256await actions.sendEmail()257const valid = await actions.verifyToken(token)258const result = await actions.resetPassword(token, newPassword)259```260261## Registration (register.ts)262263- `register(credentials: NewUser): Promise<{ token: AuthToken }>`264265## User Helpers (user.ts)266267- `authUser(): Promise<UserModel | undefined>`268- `check(): Promise<boolean>`269- `id(): Promise<number | undefined>`270- `email(): Promise<string | undefined>`271- `name(): Promise<string | undefined>`272- `isAuthenticated(): Promise<boolean>`273- `logout(): Promise<void>`274- `refresh(): Promise<void>`275276## Passkey/WebAuthn (passkey.ts)277278- `getUserPasskeys(userId): Promise<PasskeyAttribute[]>`279- `getUserPasskey(userId, passkeyId): Promise<PasskeyAttribute | undefined>`280- `setCurrentRegistrationOptions(user, verified): Promise<void>`281282### Re-exported from @stacksjs/ts-auth283- `generateRegistrationOptions`, `generateAuthenticationOptions`284- `verifyRegistrationResponse`, `verifyAuthenticationResponse`285- `startRegistration`, `startAuthentication` (browser)286- `browserSupportsWebAuthn`, `browserSupportsWebAuthnAutofill`287- `platformAuthenticatorIsAvailable`288289## Auth Middleware (middleware.ts)290291```typescript292export const authMiddlewareHandler = {293 name: 'auth',294 handle: authMiddleware, // validates bearer token, throws 401295}296```297298## Rate Limiter (rate-limiter.ts)299300```typescript301class RateLimiter {302 static MAX_ATTEMPTS = 5303 static LOCKOUT_DURATION = 15 * 60 * 1000 // 15 minutes304 static MAX_STORE_SIZE = 10_000305 static EVICTION_INTERVAL = 5 * 60 * 1000 // 5 minutes306307 static isRateLimited(email): boolean308 static recordFailedAttempt(email): void309 static resetAttempts(email): void310 static validateAttempt(email): void // throws HttpError 429311}312```313314## Authorizable Mixin (authorizable.ts)315316```typescript317const authUser = withAuthorization(user)318await authUser.can('edit-post', post)319await authUser.cannot('delete-post', post)320await authUser.canAny(['edit', 'delete'], post)321await authUser.canAll(['edit', 'publish'], post)322await authUser.authorize('edit-post', post) // throws if denied323```324325## Configuration326327### config/auth.ts328```typescript329{330 default: 'api',331 guards: { api: { driver: 'token', provider: 'users' } },332 providers: { users: { driver: 'database', table: 'users' } },333 username: 'email', // AUTH_USERNAME_FIELD env334 password: 'password', // AUTH_PASSWORD_FIELD env335 tokenExpiry: 30, // days, AUTH_TOKEN_EXPIRY env336 tokenRotation: 7, // days, AUTH_TOKEN_ROTATION env337 defaultAbilities: ['*'],338 defaultTokenName: 'auth-token',339 passwordReset: { expire: 60, throttle: 60 }340}341```342343### config/hashing.ts344```typescript345{346 driver: 'bcrypt', // 'bcrypt' | 'argon2'347 bcrypt: { rounds: 12 },348 argon2: { memory: 65536, time: 3 }349}350```351352### config/security.ts353```typescript354{355 firewall: {356 enabled: true,357 countryCodes: [],358 ipAddresses: { allowlist: [], blocklist: [] },359 rateLimitPerMinute: 500,360 useIpReputationLists: true,361 useKnownBadInputsRuleSet: true362 }363}364```365366## Middleware Aliases (app/Middleware.ts)367368Auth-relevant aliases: `auth`, `guest`, `verified` (EnsureEmailIsVerified),369`abilities`, `can`, `role`, `permission`, `team`, `signed`, `throttle`. The370environment aliases are `env`, `env:local`, `env:development` / `env:dev`,371`env:staging`, `env:production` / `env:prod` — with a COLON, not a dot; an372earlier version of this list wrote `env.local` and those never existed. See373`stacks-middleware` for the full set and for the `!alias` and `alias:params`374forms.375376## Application Gates (app/Gates.ts)377378```typescript379import { defineGates } from '@stacksjs/auth'380381export default defineGates({382 gates: {383 'access-admin': user => user?.email?.endsWith('@stacksjs.org') ?? false,384 'edit-settings': user => !!user,385 'view-dashboard': user => !!user,386 },387 policies: {388 Post: 'PostPolicy',389 },390})391```392393Registered at boot by `initializeAuthorization()`, from394`injectGlobalAutoImports()` — the one place every entry point comes through, so395HTTP, `buddy seed`, a scheduled job and a console command all get the same396gates.397398Both halves of `policies` are checked: the key names a model the ORM exposes,399the value a policy file under `app/Policies/` or the framework defaults. An400explicit mapping WINS over the `<Model>Policy` naming convention, which is the401reason to write one.402403`Gate.define(...)` still works for a gate registered at runtime; `defineGates`404is the declarative form and the one the ability-name completions come from.405406## Default API Routes407408- `POST /login` → LoginAction (validates email + password)409- `POST /register` → RegisterAction410- `POST /auth/refresh` → RefreshTokenAction411- `POST /auth/token` → CreateTokenAction412- `GET /auth/tokens` → ListTokensAction (auth middleware)413- `DELETE /auth/tokens/{id}` → RevokeTokenAction (auth middleware)414- `GET /me` → GetMeAction (auth middleware)415- `POST /logout` → LogoutAction (auth middleware)416417## User Model Traits418419```typescript420// User model uses:421traits: {422 useAuth: { usePasskey: true },423 useUuid: true,424 useTimestamps: true,425 useSocials: ['github'],426}427```428429## Gotchas430431- Auth depends on `@stacksjs/ts-auth` for TOTP and passkey functions432- Password hashing defaults to bcrypt with 12 rounds (config/hashing.ts)433- Rate limiter uses in-memory Map, resets on server restart — not shared across workers434- Session auth also uses in-memory Map with 10k limit — for SPA cookie auth435- Token format is `tokenId|plainText` — the `|` separates the encrypted ID from the plain token436- The `parseToken()` helper splits on `|` to extract both parts437- Bearer tokens come from the `Authorization: Bearer <token>` header438- `Auth.user()` internally calls `getBearerToken()` → `parseToken()` → `getTokenFromId()` → validates hash439- RBAC has an internal cache (`userRoles`, `userPermissions`, `rolePermissions`) — call `Rbac.flushCache()` after direct DB changes440- `syncRoles()` and `syncPermissions()` are guard-scoped replacements: they preserve assignments belonging to other guards441- Gate `before` callbacks can short-circuit — return `true` to allow, `null` to continue checking442- An ability with no gate and no policy method **denies**. That is the right default, and it means a gate that was never registered is indistinguishable from one that says no — which is how `initializeAuthorization()` went unnoticed while nothing called it443- `allows()` and friends take `Ability`, which is open (`GateName | PolicyAbility | (string & {})`). A `/can/:ability` route passes an ability straight through, so narrowing it would reject correct code; the union is for completions444- `withRbac()` and `withAuthorization()` return new objects with methods mixed in445- The `RbacStore` interface must be implemented and set via `Rbac.setStore()` for RBAC to work446- Password reset tokens expire after 60 minutes by default447- Default token abilities are `['*']` — wildcard access448- Token expiry defaults to 30 days449- Session auth uses timing-safe bcrypt comparison even for failed lookups (dummy hash prevents timing attacks)450451## Build452453```bash454cd storage/framework/core/auth && bun build.ts455```