/** * The security section of the generated OpenAPI document, derived from the * middleware each route carries (stacksjs/stacks#3576). * * Without it every endpoint read as unauthenticated: generated clients sent no * credentials and API reference pages told readers nothing about auth. * * - `auth` documents the bearer token, with the login cookie as the * alternative a browser uses. * - `api` documents the API key header (`config.auth.apiKeys.header`). * - `abilities:,` and `api:,` add the abilities or key scopes as `x-required-scopes` (an * http bearer scheme carries no scopes in OpenAPI 3.0). * - A route with no authenticating middleware is marked `security: []`. * - Protected operations gain the 401 / 403 / 429 answers they can give, * unless the action declares its own. * * An app maps its own middleware to schemes in `config/security.ts`: * * ```ts * api: { * openapi: { * securitySchemes: { apiKeyAuth: { type: 'apiKey', in: 'header', name: 'X-Api-Key' } }, * middleware: { 'api-key': 'apiKeyAuth', 'internal': null }, * }, * } * ``` * * A mapping names one scheme, several alternatives (an array), or `null` for * middleware that authenticates nothing. */ /** An OpenAPI 3.0 security scheme object. */ export interface SecuritySchemeObject { type: 'http' | 'apiKey' | 'oauth2' | 'openIdConnect' | 'mutualTLS' scheme?: string bearerFormat?: string in?: 'header' | 'query' | 'cookie' name?: string description?: string [extension: string]: unknown } /** `config/security.ts` `api.openapi`. */ export interface OpenApiSecurityConfig { /** Schemes added to (or replacing) the framework's own. */ securitySchemes?: Record /** Middleware name to scheme name(s); `null` authenticates nothing. */ middleware?: Record } /** What a route's middleware says about its operation. */ export interface OperationSecurity { /** The operation's `security` array: alternatives, each an AND of schemes. */ security: Array> /** Token abilities the operation requires. */ scopes: string[] /** It needs credentials: answer 401 without them. */ authenticated: boolean /** It checks what the caller may do: answer 403. */ authorized: boolean /** It is rate limited: answer 429. */ throttled: boolean } /** The framework's schemes; `cookieName` is the login cookie, `apiKeyHeader` the `api` middleware's header. */ export function defaultSecuritySchemes(cookieName = 'auth-token', apiKeyHeader = 'X-Api-Key'): Record { return { apiKeyAuth: { type: 'apiKey', in: 'header', name: apiKeyHeader, description: 'An API key (`config.auth.apiKeys`). Also accepted as `Authorization: Bearer `.', }, bearerAuth: { type: 'http', scheme: 'bearer', description: 'A personal access token or a session token, sent as `Authorization: Bearer `.', }, cookieAuth: { type: 'apiKey', in: 'cookie', name: cookieName, description: 'The login cookie a browser holds after signing in.', }, } } const DEFAULT_MIDDLEWARE_SCHEMES: Record = { auth: ['bearerAuth', 'cookieAuth'], api: ['apiKeyAuth'], } /** Middleware that decides what an authenticated caller may do. */ const AUTHORIZING = new Set(['abilities', 'ability', 'can', 'permission', 'role', 'team', 'teampermission']) const THROTTLING = new Set(['throttle']) interface ParsedReference { name: string params: string[] } function parseReference(reference: string): ParsedReference | undefined { const trimmed = reference.trim() // `!auth` removes inherited middleware; it adds no requirement. if (!trimmed || trimmed.startsWith('!')) return undefined const colon = trimmed.indexOf(':') const name = (colon === -1 ? trimmed : trimmed.slice(0, colon)).toLowerCase() const params = colon === -1 ? [] : trimmed.slice(colon + 1).split(',').map(param => param.trim()).filter(Boolean) return { name, params } } /** The security an operation needs, from its route's middleware. */ export function operationSecurity(middleware: readonly string[] | undefined, config: OpenApiSecurityConfig = {}): OperationSecurity { const mapping: Record = { ...DEFAULT_MIDDLEWARE_SCHEMES } for (const [name, schemes] of Object.entries(config.middleware ?? {})) mapping[name.toLowerCase()] = schemes === null ? null : Array.isArray(schemes) ? schemes : [schemes] // Each authenticating middleware is one requirement; its schemes are the // ways to meet it. Two of them must both be met. const requirements: string[][] = [] const scopes: string[] = [] let authorized = false let throttled = false for (const reference of middleware ?? []) { const parsed = parseReference(reference) if (!parsed) continue const schemes = mapping[parsed.name] if (schemes && schemes.length > 0) requirements.push(schemes) if (AUTHORIZING.has(parsed.name)) authorized = true // `abilities:a,b` (token abilities) and `api:a,b` (API key scopes). if (parsed.name === 'abilities' || parsed.name === 'ability' || parsed.name === 'api') { scopes.push(...parsed.params) if (parsed.name === 'api' && parsed.params.length > 0) authorized = true } if (THROTTLING.has(parsed.name)) throttled = true } let security: Array> = [{}] for (const alternatives of requirements) { const next: Array> = [] for (const combination of security) { for (const scheme of alternatives) next.push({ ...combination, [scheme]: [] }) } security = next } return { security: requirements.length === 0 ? [] : security, scopes: [...new Set(scopes)], authenticated: requirements.length > 0, authorized, throttled, } } /** The 401 / 403 / 429 answers a protected operation can give, as OpenAPI responses. */ export function securityResponses(security: OperationSecurity): Record { const responses: Record = {} if (security.authenticated) responses['401'] = { description: 'Unauthenticated: the request carried no valid credentials.' } if (security.authorized || security.scopes.length > 0) responses['403'] = { description: 'Forbidden: the credentials are valid but do not allow this.' } if (security.throttled) responses['429'] = { description: 'Too many requests: retry after the `Retry-After` header.' } return responses }