AuthHandler

View as MarkdownOpen in Claude

AuthHandler provides a unified authentication layer supporting Bearer tokens, API keys, and HTTP Basic Auth. All credential comparisons use constant-time algorithms to prevent timing attacks. It can be used as Hono middleware or as a standalone request validator.

import { AuthHandler } from '@signalwire/sdk';
const auth = new AuthHandler({
bearerToken: 'my-secret-token',
apiKey: 'my-api-key',
});

Constructor

config
AuthConfigRequired

Authentication configuration object with the following optional fields:

config.bearerToken
string

Bearer token matched against the Authorization: Bearer <token> header.

config.apiKey
string

API key matched against the X-Api-Key header (or the custom header named by config.apiKeyHeader).

config.apiKeyHeader
stringDefaults to 'X-Api-Key'

Custom header name to use for API key lookup instead of the default X-Api-Key. Lookup is case-insensitive.

config.basicAuth
[string, string]

Basic auth credentials as a [username, password] tuple.

config.customValidator
(request: { headers, method, url }) => boolean | Promise<boolean>

Custom validator function. Return true to allow the request.

config.allowUnauthenticated
boolean

When explicitly set to false, deny requests if no auth methods are configured. By default, unauthenticated access is allowed when no methods are set.

Methods

Example

import { AuthHandler } from '@signalwire/sdk';
const auth = new AuthHandler({
bearerToken: process.env.AUTH_TOKEN,
basicAuth: ['admin', 'secret'],
apiKey: process.env.API_KEY,
});
// Check which methods are configured
console.log('Bearer:', auth.hasBearerAuth()); // true
console.log('API Key:', auth.hasApiKeyAuth()); // true
console.log('Basic:', auth.hasBasicAuth()); // true
// Validate incoming request headers
const isValid = await auth.validate({
authorization: 'Bearer my-secret-token',
});
console.log('Valid:', isValid);