auth/bearer_auth.ts

Bearer auth middleware for API token authentication.

Bearer tokens are rejected when Origin or Referer headers are present — browsers must use cookie auth. This reduces attack surface: a stolen token cannot be replayed from a browser context (the browser adds Origin automatically). The discard is silent on the wire (anti-enumeration); in DEV only, the middleware adds an `X-Fuz-Auth-Debug: bearer_discarded_browser_context` response header so tests/tooling can tell "token discarded for browser context" apart from "no credential supplied" without weakening production.

Token generation and hashing utilities live in auth/api_token.ts.

view source

Declarations
#

create_bearer_auth_middleware
#

auth/bearer_auth.ts view source

(deps: QueryDeps, ip_rate_limiter: RateLimiter | null, log: Logger): MiddlewareHandler import {create_bearer_auth_middleware} from '@fuzdev/fuz_app/auth/bearer_auth.js';

Create middleware that authenticates via bearer token.

Soft-fails for invalid, expired, or empty tokens — calls next() without setting account identity, letting downstream auth enforcement (the RPC dispatcher's pre-validation / post-authorization auth gates or require_auth) return a consistent JSON-RPC or route-level error. This avoids leaking token-specific diagnostics (invalid_token, account_not_found) that could aid enumeration attacks, and ensures public actions are not blocked by bad credentials.

Rejects bearer tokens when an Origin or Referer header is present — browsers must use cookie auth to reduce attack surface. Auth scheme matching is case-insensitive per RFC 7235. On success, sets c.var.auth_account_id, CREDENTIAL_TYPE_KEY = 'api_token', and AUTH_API_TOKEN_ID_KEY. Skips when an account is already authenticated (e.g. by session middleware). Acting-actor resolution + RequestContext construction are deferred to the dispatcher's authorization phase.

Rate limiting (429) is the only hard-fail — it's a throttling concern independent of auth identity.

deps

query dependencies (pool-level db for middleware)

ip_rate_limiter

per-IP rate limiter for bearer token attempts (null to disable)

type RateLimiter | null

log

the logger instance

type Logger

returns

MiddlewareHandler

mutates

  • Hono — context - sets `ACCOUNT_ID_KEY`, `CREDENTIAL_TYPE_KEY`, and `AUTH_API_TOKEN_ID_KEY` on success

Depends on
#

Imported by
#