/** * Authorization Gate System * * Laravel-like authorization gates for fine-grained access control. * Supports both inline gates and policy classes. */ import type { AuthenticatedUser } from '@stacksjs/types' import type { AuthUser } from './user' /** * The user a gate, a policy or an RBAC helper is handed (stacksjs/stacks#3314). * * The same object arrives under two types. The router's request carries the * User row (`AuthUser`, what `User.find` returns), so `request.can()` and an * action typed with the router's request pass that. An action typed with * `RequestInstance` from `@stacksjs/types` gets `request.user()` as * `AuthenticatedUser`, the app's User columns without the model's methods, * since that package cannot depend on the ORM. Both have `id` and `email`. */ export type GateUser = AuthUser | AuthenticatedUser type UserModel = GateUser /** * Gate callback function type */ export type GateCallback = (_user: UserModel | null, ..._args: T[]) => boolean | Promise | AuthorizationResponse /** * Augmentation target: the ability names this application's own gates define. * * Derived from `app/Gates.ts` itself by * `storage/framework/types/gates.d.ts`, so it cannot drift from the file it * describes - the gates are the declaration. * * @example * ```ts * declare module '@stacksjs/auth' { * interface AppGates { * 'access-admin': true * } * } * ``` */ // eslint-disable-next-line ts/no-empty-object-type -- augmentation target; empty by design export interface AppGates {} /** An ability name defined by one of the application's gates. */ export type GateName = keyof AppGates extends never ? string : keyof AppGates & string /** * The abilities `BasePolicy` resolves. A policy may add its own methods, which * is why `Ability` below stays open. */ export type PolicyAbility = 'viewAny' | 'view' | 'create' | 'update' | 'delete' | 'restore' | 'forceDelete' /** * Any ability that can be checked. * * Deliberately open. An ability is legitimately dynamic - a `/can/:ability` * route passes one straight through, which is the reason * `RESERVED_POLICY_MEMBERS` exists at all - so narrowing this to the declared * set would reject correct code and break the fail-closed tests that check * what an UNKNOWN ability does. The union is here for the editor: the gates * and policy abilities are offered, and anything else still compiles. */ // eslint-disable-next-line ts/ban-types -- `string & {}` keeps literal completions alive export type Ability = GateName | PolicyAbility | (string & {}) /** * The arguments an ability takes after the user. * * A gate the application declares contributes its own parameter list, so * `Gate.allows('update-post', user, post)` is checked against how the gate was * written. Anything else - a policy ability, or a name computed at runtime - * keeps `any[]`, which is what it was for every ability before. */ export type AbilityArgs = A extends keyof AppGates ? (AppGates[A] extends readonly unknown[] ? AppGates[A] : any[]) : any[] /** * Augmentation target: the policy classes under `app/Policies/`, and the * framework defaults behind it, by filename. * * Filled by `storage/framework/types/registries.d.ts`, which reads the same * name map `findPolicyFile` resolves through. */ // eslint-disable-next-line ts/no-empty-object-type -- augmentation target; empty by design export interface PolicyClasses {} /** A policy class name, as narrow as the application has made it. */ export type PolicyName = keyof PolicyClasses extends never ? string : keyof PolicyClasses & string /** * Augmentation target: the models a policy may be registered for. * * Derived from the models barrel, so it is the models that exist rather than a * list somebody maintains alongside them. */ // eslint-disable-next-line ts/no-empty-object-type -- augmentation target; empty by design export interface PolicyModels {} /** A model name a policy may be registered for. */ export type PolicyModelName = keyof PolicyModels extends never ? string : keyof PolicyModels & string /** Runs before every check. `true` allows, `false` denies, `null` continues. */ export type GateBeforeCallback = (_user: UserModel | null, _ability: string, _args: unknown[]) => boolean | null | Promise /** Runs after every check. A boolean overrides the result; anything else keeps it. */ export type GateAfterCallback = (_user: UserModel | null, _ability: string, _result: boolean, _args: unknown[]) => boolean | void | Promise /** * How `app/Gates.ts` maps a model to the policy that authorizes it. * * Every key optional: a mapping is written only for the models whose policy * does not follow the `Policy` convention. */ export type PolicyMapping = { readonly [K in PolicyModelName]?: PolicyName | { policy: PolicyName, model?: PolicyModelName } } /** The shape of `app/Gates.ts`. */ export interface GatesDefinition { /** Ability name to the check that answers it. */ gates: Readonly> /** Model name to the policy class that authorizes it. */ policies?: PolicyMapping /** Callbacks that run before every check. */ before?: readonly GateBeforeCallback[] /** Callbacks that run after every check. */ after?: readonly GateAfterCallback[] } /** * Every key of a policy map that is not a model, required to hold something no * policy name can be. * * Applied to the PARAMETER rather than to the type parameter's constraint: a * constraint that reads `T['policies']` is a self-reference and TypeScript * refuses it, while the parameter may name `T` freely because inference has * already run against the `T &` half. */ type OnlyKnownModels = { [K in keyof TPolicies]: K extends PolicyModelName ? TPolicies[K] : { 'this is not a model in this application': never } } /** * Define the application's gates, policy mappings and before/after callbacks. * * The `define*` helper for `app/Gates.ts`. Both halves of `policies` are * checked - the key names a model that exists, the value names a policy file * that exists - where the type used to be * `Record` on both sides, so a mapping to * a policy that is not there registered nothing and denied every check on that * model with no error anywhere. * * The `const` type parameter keeps the ability names, which is what * `storage/framework/types/gates.d.ts` reads back to fill `AppGates`. * * The second half of the constraint is what rejects a key that is not a model, * and it is not redundant with `PolicyMapping`. Excess-property checking is a * freshness rule on the object literal and stops applying as soon as inference * has a matching property to work with: `{ Psot: 'PostPolicy' }` alone was * caught, and the same typo beside one correct entry was not. Requiring every * key outside the model list to hold something no policy name can be makes the * check structural. * * @example * ```ts * // app/Gates.ts * import { defineGates } from '@stacksjs/auth' * * export default defineGates({ * gates: { * 'access-admin': user => user?.email?.endsWith('@stacksjs.com') ?? false, * }, * policies: { * Post: 'PostPolicy', * }, * }) * ``` */ export function defineGates( definition: T & { policies?: OnlyKnownModels }, ): T { return definition } /** * Policy method type. The return type intentionally allows `null` so that * a policy's `before()` hook (which returns `null` to delegate to the * underlying ability check) is index-compatible with the catch-all * `[key: string]: PolicyMethod | undefined` signature on `Policy`. */ export type PolicyMethod = (_user: UserModel | null, _model?: T, ..._args: any[]) => boolean | null | Promise | AuthorizationResponse /** * Method names that live on `BasePolicy.prototype` (or `Object`) and must * NEVER be resolvable as an ability. Without this guard, `policyInstance[ability]` * (unrestricted bracket access) would resolve inherited helpers like `allow` * / `allowIf` / `before` when the ability string is caller-influenced (e.g. a * generic `/can/:ability` route), and calling `allow()` returns an * unconditional ALLOW — a fail-open authorization bypass. See the auth * correctness sweep (stacksjs/stacks#1985). */ const RESERVED_POLICY_MEMBERS: ReadonlySet = new Set([ 'before', 'allow', 'deny', 'denyIf', 'denyUnless', 'allowIf', 'constructor', ]) /** * Authorization response for detailed allow/deny */ export class AuthorizationResponse { public readonly isAllowed: boolean public readonly message?: string public readonly code?: string constructor( allowed: boolean, message?: string, code?: string, ) { this.isAllowed = allowed this.message = message this.code = code WeakSet.prototype.add.call(state.responses, this) } static allow(message?: string): AuthorizationResponse { return new AuthorizationResponse(true, message) } static deny(message?: string, code?: string): AuthorizationResponse { return new AuthorizationResponse(false, message || 'This action is unauthorized.', code) } allowed(): boolean { return this.isAllowed } denied(): boolean { return !this.isAllowed } authorize(): void { if (!this.isAllowed) { throw new AuthorizationException(this.message || 'This action is unauthorized.', this.code) } } } /** * Authorization exception */ export class AuthorizationException extends Error { constructor( message: string = 'This action is unauthorized.', public readonly code?: string, public readonly status: number = 403, ) { super(message) this.name = 'AuthorizationException' } } /** * Policy class interface */ export interface Policy { /** Called before any other policy method */ before?(user: UserModel | null, ability: string): boolean | null | Promise /** View any records */ viewAny?(user: UserModel | null): boolean | Promise | AuthorizationResponse /** View a specific record */ view?(user: UserModel | null, model: T): boolean | Promise | AuthorizationResponse /** Create new records */ create?(user: UserModel | null): boolean | Promise | AuthorizationResponse /** Update a specific record */ update?(user: UserModel | null, model: T): boolean | Promise | AuthorizationResponse /** Delete a specific record */ delete?(user: UserModel | null, model: T): boolean | Promise | AuthorizationResponse /** Restore a soft-deleted record */ restore?(user: UserModel | null, model: T): boolean | Promise | AuthorizationResponse /** Permanently delete a record */ forceDelete?(user: UserModel | null, model: T): boolean | Promise | AuthorizationResponse /** Any custom ability methods */ [key: string]: PolicyMethod | undefined } /** * Gate registry state */ interface GateState { gates: Map policies: Map Policy> beforeCallbacks: GateBeforeCallback[] afterCallbacks: GateAfterCallback[] } interface GateProcessState extends GateState { version: 1 responses: WeakSet } // Each independently bundled Action has its own module instance. Registrations // and native response identities belong to this JavaScript process, not a request. const GATE_PROCESS_STATE = Symbol.for('@stacksjs/auth:gate-process-state') function ownValue(object: object, key: PropertyKey): unknown { const descriptor = Object.getOwnPropertyDescriptor(object, key) return descriptor && 'value' in descriptor ? descriptor.value : undefined } function callbackArray(value: unknown): boolean { if (!Array.isArray(value)) return false for (let index = 0; index < value.length; index++) { if (typeof ownValue(value, String(index)) !== 'function') return false } return true } function processGateState(): GateProcessState { const descriptor = Object.getOwnPropertyDescriptor(globalThis, GATE_PROCESS_STATE) if (!descriptor) { const created: GateProcessState = { version: 1, gates: new Map(), policies: new Map(), beforeCallbacks: [], afterCallbacks: [], responses: new WeakSet(), } Object.defineProperty(globalThis, GATE_PROCESS_STATE, { value: created }) return created } const candidate: unknown = 'value' in descriptor ? descriptor.value : undefined if (candidate && typeof candidate === 'object' && ownValue(candidate, 'version') === 1) { const gates = ownValue(candidate, 'gates'), policies = ownValue(candidate, 'policies') const responses = ownValue(candidate, 'responses') try { // Intrinsic brand checks reject duck objects and wrapped collections. Map.prototype.has.call(gates, '') Map.prototype.has.call(policies, '') WeakSet.prototype.has.call(responses, candidate) if (callbackArray(ownValue(candidate, 'beforeCallbacks')) && callbackArray(ownValue(candidate, 'afterCallbacks'))) return candidate as GateProcessState } catch { /* An incompatible process owner must fail closed. */ } } throw new TypeError('[gate] Incompatible shared Gate process state') } const state = processGateState() /** * Define a new authorization gate * * @example * define('edit-settings', (user) => user?.isAdmin) * define('update-post', (user, post) => user?.id === post.userId) */ export function define(ability: Ability, callback: GateCallback): void { state.gates.set(ability, callback) } /** * Register a policy for a model * * @example * policy('Post', PostPolicy) * policy(Post, PostPolicy) */ export function policy(model: PolicyModelName | { name: PolicyModelName }, policyClass: new () => Policy): void { const modelName = typeof model === 'string' ? model : model.name state.policies.set(modelName, policyClass) } /** * Register a callback to run before all gate checks * * @example * before((user, _ability) => { * if (user?.isSuperAdmin) return true // Super admins can do anything * return null // Continue to normal checks * }) */ export function before(callback: GateBeforeCallback): void { state.beforeCallbacks.push(callback) } /** * Register a callback to run after all gate checks */ export function after(callback: GateAfterCallback): void { state.afterCallbacks.push(callback) } /** * Check if the user is allowed to perform an ability * * @example * if (await allows('edit-settings', user)) { ... } * if (await allows('update', user, post)) { ... } */ export async function allows(ability: A, user: UserModel | null, ...args: AbilityArgs): Promise { return check(ability, user, ...args) } /** * Check if the user is denied from performing an ability * * @example * if (await denies('delete', user, post)) { ... } */ export async function denies(ability: A, user: UserModel | null, ...args: AbilityArgs): Promise { return !(await check(ability, user, ...args)) } /** * Check if the user can perform an ability (alias for allows) */ export async function can(ability: A, user: UserModel | null, ...args: AbilityArgs): Promise { return check(ability, user, ...args) } /** * Check if the user cannot perform an ability (alias for denies) */ export async function cannot(ability: A, user: UserModel | null, ...args: AbilityArgs): Promise { return !(await check(ability, user, ...args)) } /** * Check if the user can perform any of the given abilities * * @example * if (await any(['update', 'delete'], user, post)) { ... } */ /* * `any` / `all` / `none` keep `any[]`: one argument list is checked against * SEVERAL abilities, which may each declare different parameters, so there is * no single tuple that is correct for the call. The single-ability functions * above are where the declaration can be enforced. */ export async function any(abilities: readonly Ability[], user: UserModel | null, ...args: any[]): Promise { for (const ability of abilities) { if (await check(ability, user, ...args)) { return true } } return false } /** * Check if the user can perform all of the given abilities * * @example * if (await all(['view', 'update'], user, post)) { ... } */ export async function all(abilities: readonly Ability[], user: UserModel | null, ...args: any[]): Promise { for (const ability of abilities) { if (!(await check(ability, user, ...args))) { return false } } return true } /** * Check if the user can perform none of the given abilities */ export async function none(abilities: readonly Ability[], user: UserModel | null, ...args: any[]): Promise { return !(await any(abilities, user, ...args)) } /** * Authorize an ability or throw an exception * * @example * await authorize('update', user, post) // Throws if not allowed */ export async function authorize(ability: A, user: UserModel | null, ...args: AbilityArgs): Promise { const result = await inspect(ability, user, ...args) if (!result.isAllowed) { throw new AuthorizationException(result.message, result.code) } return result } /** * Get detailed inspection result for an ability check */ export async function inspect(ability: A, user: UserModel | null, ...args: AbilityArgs): Promise { let response: AuthorizationResponse | null = null // Run before callbacks. An explicit true/false is an override that // short-circuits policy/gate resolution — but it still passes through the // after callbacks below (Laravel parity). for (const callback of state.beforeCallbacks) { const beforeResult = await callback(user, ability, args) if (beforeResult === true) { response = AuthorizationResponse.allow() break } if (beforeResult === false) { response = AuthorizationResponse.deny() break } // null means continue checking } if (!response) response = await resolveAbility(ability, user, args) // Run after callbacks for EVERY resolution path — policy, inline gate, and // the default deny — not just inline gates as before. A global // `Gate.after()` override / lockdown kill-switch was previously bypassed // for any policy-resolved ability (the common case for model // authorization: view/update/delete). stacksjs/stacks#1985. for (const callback of state.afterCallbacks) { const afterResult = await callback(user, ability, response.isAllowed, args) if (typeof afterResult === 'boolean') { return afterResult ? AuthorizationResponse.allow() : AuthorizationResponse.deny() } } return response } /** * Resolve an ability through the policy -> inline-gate -> default-deny chain, * WITHOUT running the before/after callbacks. `inspect()` owns those so they * apply uniformly to every path. */ async function resolveAbility(ability: string, user: UserModel | null, args: any[]): Promise { // Check for policy first (if model is passed) const model = args[0] if (model && typeof model === 'object') { const policyClass = state.policies.get(model.constructor?.name) if (policyClass) { const response = await runPolicy(policyClass, ability, user, args) if (response) return response } } // Check inline gate const gate = state.gates.get(ability) if (gate) { return normalizeResponse(await gate(user, ...args)) } // No gate or policy found - deny by default return AuthorizationResponse.deny(`No gate or policy defined for ability: ${ability}`) } /** * Run one policy class for one ability. * * Shared by the instance-keyed path (`resolveAbility`, which finds the policy * through `args[0].constructor.name`) and the name-keyed one (`inspectFor`), so * neither can drift from the other on the part that matters: the * RESERVED_POLICY_MEMBERS guard. Without it, `policyInstance[ability]` resolves * inherited helpers like `allow` / `allowIf`, and `allow()` returns an * unconditional ALLOW - a fail-open bypass whenever the ability string is * caller-influenced (stacksjs/stacks#1985). * * Returns null when this policy has no own method for the ability, so the * caller decides what that means: `resolveAbility` falls through to an inline * gate, and `inspectFor` denies, having nowhere else to look. */ async function runPolicy( policyClass: new () => any, ability: string, user: UserModel | null, args: any[], ): Promise { const policyInstance = new policyClass() if (policyInstance.before) { const beforeResult = await policyInstance.before(user, ability) if (beforeResult === true) return AuthorizationResponse.allow() if (beforeResult === false) return AuthorizationResponse.deny() } const method = RESERVED_POLICY_MEMBERS.has(ability) ? undefined : policyInstance[ability] as PolicyMethod | undefined if (typeof method !== 'function') return null const result = await method.call(policyInstance, user, ...args) // null is "no opinion", and the policy resolution path for this ability is // already exhausted, so it means no. return normalizeResponse(result ?? false) } /** * Check an ability against the policy registered for a model NAME, answering * three states: no policy (null), allowed, denied. * * The vocabulary in `policy.ts` was unreachable from the code that wanted it. * Resolution keys on `args[0].constructor.name`, so it needs a model INSTANCE, * and the generated API and the dashboard actions both hold rows the query * builder returned - plain objects, whose constructor is `Object`. There was no * path from a model name to its policy, which is why 0 of the 750 default * actions consult one (stacksjs/stacks#2883). * * The three-way answer is the point. `allows()` DENIES when nothing is * registered, which is right for a named gate and catastrophic for a generated * route: it would refuse every one of the 107 models that has no policy. A * caller must be able to tell "nobody has an opinion" from "the answer is no", * and null makes that impossible to read as fail-open by accident. * * The global before/after callbacks run when a policy IS registered, so a * `Gate.after()` lockdown still applies. They do not run otherwise: with no * policy there is no decision to override, and inventing one would turn this * back into a deny for every unpoliced model. * * @example * const verdict = await Gate.inspectFor('Order', 'delete', user, row) * if (verdict && !verdict.isAllowed) * return response.json({ message: verdict.message }, 403) */ export async function inspectFor( model: string | { name: string }, ability: Ability, user: UserModel | null, ...args: any[] ): Promise { const modelName = typeof model === 'string' ? model : model.name const policyClass = state.policies.get(modelName) if (!policyClass) return null let response: AuthorizationResponse | null = null for (const callback of state.beforeCallbacks) { const beforeResult = await callback(user, ability, args) if (beforeResult === true) { response = AuthorizationResponse.allow() break } if (beforeResult === false) { response = AuthorizationResponse.deny() break } } // A policy with no own method for this ability has not permitted it. There // is no inline-gate fallback here: the caller named a model, so an ability // the model's policy does not implement is one nothing has allowed. response ??= await runPolicy(policyClass, ability, user, args) ?? AuthorizationResponse.deny(`${modelName}'s policy defines no ${String(ability)} ability`) for (const callback of state.afterCallbacks) { const afterResult = await callback(user, ability, response.isAllowed, args) if (typeof afterResult === 'boolean') return afterResult ? AuthorizationResponse.allow() : AuthorizationResponse.deny() } return response } /** * {@link inspectFor} as a boolean, reading "no policy registered" as allowed. * * The convenience form for a caller with nothing of its own to add: no policy * means this layer is not the one saying no. Anything that needs to tell that * apart from a permission - to log it, or to skip work - uses `inspectFor`. */ export async function allowsFor( model: string | { name: string }, ability: Ability, user: UserModel | null, ...args: any[] ): Promise { const response = await inspectFor(model, ability, user, ...args) return response ? response.isAllowed : true } /** * Core check implementation */ async function check(ability: string, user: UserModel | null, ...args: any[]): Promise { const response = await inspect(ability, user, ...args) return response.isAllowed } /** * Normalize a gate/policy result to AuthorizationResponse. * * Strictly accepts only boolean or AuthorizationResponse. The previous * `result ? allow() : deny()` form interpreted ANY truthy value as * "allow" — a policy that accidentally returned `await User.find(id)` * (a user object) would be treated as authorization granted, even * though the policy author meant "fetched the user as a side effect, * not deciding on permission". Failing loudly catches the bug. */ function normalizeResponse(result: boolean | AuthorizationResponse): AuthorizationResponse { if (result && typeof result === 'object' && WeakSet.prototype.has.call(state.responses, result)) { // Identity comes only from a native constructor, including another bundle. // Reject altered/accessor fields without reading or invoking their getters. const allowed = Object.getOwnPropertyDescriptor(result, 'isAllowed') const message = Object.getOwnPropertyDescriptor(result, 'message') const code = Object.getOwnPropertyDescriptor(result, 'code') if (allowed && 'value' in allowed && typeof allowed.value === 'boolean' && message && 'value' in message && (message.value === undefined || typeof message.value === 'string') && code && 'value' in code && (code.value === undefined || typeof code.value === 'string')) return result } if (typeof result !== 'boolean') { throw new TypeError( `[gate] Policy must return boolean or AuthorizationResponse; got ${typeof result}. ` + 'If you returned a model/value by mistake, return `true`/`false` instead.', ) } return result ? AuthorizationResponse.allow() : AuthorizationResponse.deny() } /** * Get a policy instance for a model */ export function getPolicyFor(model: T): Policy | null { if (!model || typeof model !== 'object') { return null } const modelName = model.constructor?.name const policyClass = state.policies.get(modelName) if (policyClass) { return new policyClass() as Policy } return null } /** * Check if a gate is defined */ export function has(ability: Ability): boolean { return state.gates.has(ability) } /** * Check if a policy is registered for a model */ export function hasPolicy(model: string | { name: string }): boolean { const modelName = typeof model === 'string' ? model : model.name return state.policies.has(modelName) } /** * Get all defined gate names */ export function abilities(): string[] { return Array.from(state.gates.keys()) } /** * Clear all gates and policies (useful for testing) */ export function flush(): void { state.gates.clear() state.policies.clear() state.beforeCallbacks = [] state.afterCallbacks = [] } /** * Gate facade for convenient access */ export const Gate = { define, policy, before, after, allows, allowsFor, denies, can, cannot, any, all, none, authorize, inspect, inspectFor, has, hasPolicy, abilities, getPolicyFor, flush, AuthorizationResponse, AuthorizationException, } export default Gate