auth/bearer_auth.ts view source
(deps: QueryDeps, 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 malformed, invalid, expired, or empty tokens — calls next() without
setting account identity, letting downstream auth enforcement (the RPC
dispatcher's pre-authorization / 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.
Discards bearer tokens when an Origin or Referer header is present —
next() with no identity, as for a bad token — so browsers must use cookie
auth, reducing attack surface.
A token that fails the is_api_token_shaped precheck soft-fails before
the database is touched.
Auth scheme matching is case-insensitive per RFC 7235.
On success, sets the api_token arm of ResolvedAuth (RESOLVED_AUTH_KEY):
the account, the token id, its scope, and its deadline. The last leg of the
chain, it skips when an earlier one (the daemon token or a session cookie)
already resolved the request — before reading the header, so a token sent
beside a winning credential is never looked up and its last_used_at /
last_used_ip never move. Acting-actor resolution + RequestContext
construction are deferred to the dispatcher's authorization phase.
There is deliberately no rate limit on this path, and no 429 — every
failure soft-fails to "no credential". An API token is 32 bytes of CSPRNG
output resolved by a blake3 hash lookup, so guessing is bounded by entropy,
not by throttling; a limiter here would buy nothing measurable while costing
availability (the check/record has to precede the async lookup to close its
own TOCTOU window, so concurrent requests bearing a *valid* token race each
other into a 429). The Rust spine never had one here; this is the converged
shape. See docs/security.md §Why bearer auth is not rate limited.
deps
query dependencies (pool-level db for middleware)
log
the logger instance
Loggerreturns
MiddlewareHandler mutates
Hono context— sets `RESOLVED_AUTH_KEY` on success