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.

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

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.

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

1import { AuthHandler } from '@signalwire/sdk';
2
3const auth = new AuthHandler({
4 bearerToken: process.env.AUTH_TOKEN,
5 basicAuth: ['admin', 'secret'],
6 apiKey: process.env.API_KEY,
7});
8
9// Check which methods are configured
10console.log('Bearer:', auth.hasBearerAuth()); // true
11console.log('API Key:', auth.hasApiKeyAuth()); // true
12console.log('Basic:', auth.hasBasicAuth()); // true
13
14// Validate incoming request headers
15const isValid = await auth.validate({
16 authorization: 'Bearer my-secret-token',
17});
18console.log('Valid:', isValid);