Api Key Exposure in Adonisjs (Typescript)
Api Key Exposure in Adonisjs with Typescript — how this specific combination creates or exposes the vulnerability
AdonisJS is a Node.js web framework commonly used with TypeScript to build HTTP APIs. When API keys are handled in AdonisJS controllers or services written in TypeScript, exposure risks arise from insecure defaults, misconfigured middleware, or accidental leakage in responses. Because AdonisJS relies on IoC containers and environment-based configuration, keys stored in .env files can be exposed if the application serves configuration files or if error responses include stack traces that reveal file paths and environment variables.
In TypeScript projects, developers often define configuration interfaces that map environment variables to typed settings. If these configurations are imported into routes or controllers and inadvertently serialized into HTTP responses (for example via debug endpoints or unrestricted JSON serialization), API keys can be exposed to unauthenticated clients. AdonisJS’s support for Hooks and Middleware means that if authentication middleware is omitted or incorrectly ordered, keys may be accessible to public endpoints without proper checks.
Another common exposure pattern occurs when AdonisJS applications proxy requests to external services. If the server-side request logic in TypeScript does not strip sensitive headers before logging or error handling, API keys may appear in logs or SSRF-induced outbound requests. Because AdonisJS supports first-class HTTP clients, developers must explicitly redact or avoid attaching sensitive keys to client configurations that could be triggered by unauthenticated endpoints.
The risk is compounded when OpenAPI specs are generated from TypeScript route definitions without scrubbing security-sensitive parameters. If an API spec inadvertently documents endpoints that accept or return raw API keys, and runtime error messages reveal internal paths or configuration keys, an attacker can combine specification introspection with uncontrolled error output to discover valid keys. This aligns with BFLA/Privilege Escalation and Data Exposure checks, where excessive data exposure through error messages or misconfigured routes leads to key leakage.
Typescript-Specific Remediation in Adonisjs — concrete code fixes
To mitigate API key exposure in AdonisJS with TypeScript, apply strict separation between configuration and runtime behavior, and ensure that typed interfaces do not propagate sensitive values into serializable outputs. Use environment-based configuration files and avoid exposing configuration objects through controllers or debug routes.
Secure configuration and import patterns
Define API keys in .env and reference them via typed configuration without exporting raw values. Prefer runtime retrieval over static exports that could be serialized.
// .env
API_KEY=sk_live_abc123
// config/api.ts
import { schema } from '@ioc:Adonis/Core/Validator'
export default {
apiKey: () => {
const key = process.env.API_KEY
if (!key) {
throw new Error('API_KEY is missing from environment')
}
return key
},
}
In controllers, avoid returning configuration objects directly. Instead, use explicit DTOs that omit sensitive fields and validate outputs.
// controllers/UsersController.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { ApiKeyConfig } from 'App/Config/api'
export default class UsersController {
public async show({ response }: HttpContextContract) {
// Do not expose API key in response
return response.send({ ok: true })
}
}
Middleware and route protection
Ensure that routes requiring keys are guarded by authentication middleware. In TypeScript, type-safe middleware can validate context before allowing access to sensitive operations.
// middleware/ensureApiKey.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
export default async function ensureApiKey({ request, response, next }: HttpContextContract) {
const provided = request.header('x-api-key')
const expected = process.env.API_KEY
if (!expected || provided !== expected) {
return response.unauthorized({ error: 'Unauthorized' })
}
await next()
}
// start/routes.ts
import Route from '@ioc:Adonis/Core/Route'
import ensureApiKey from 'App/Middleware/ensure_api_key'
Route.get('/admin', 'AdminController.index').middleware([ensureApiKey])
Safe logging and error handling
Prevent key leakage in logs by sanitizing request and error data. Use typed logging utilities that redact sensitive headers.
// app/Helpers/logger.ts
export function safeLog(method: string, url: string, headers: Record) {
const safeHeaders = { ...headers }
if (safeHeaders['x-api-key']) {
safeHeaders['x-api-key'] = '[REDACTED]'
}
console.log({ method, url, headers: safeHeaders })
}
OpenAPI spec hygiene
When generating specs from TypeScript route definitions, ensure that parameters and responses involving keys are marked as sensitive and excluded from public documentation. Use serialization decorators or manual filtering to avoid leaking schema details that could aid attackers.