auth

37 modules

  • auth/account_queries.ts

    Account and actor database queries.

    Provides CRUD operations for the account and actor tables. For v1, every account has exactly one actor (1:1).

  • auth/account_routes.ts

    Account route specs for cookie-based session management.

    Returns RouteSpec[] — caller applies them to Hono via apply_route_specs.

    Provides: - POST /login — Exchange username + password for signed session cookie - POST /logout — Clear session cookie and revoke auth session - GET /verify — Check if current session is valid - GET /sessions — List auth sessions for current account - POST /sessions/:id/revoke — Revoke a single auth session (account-scoped) - POST /sessions/revoke-all — Revoke all auth sessions for current account - POST /tokens/create — Create an API token - GET /tokens — List API tokens for current account - POST /tokens/:id/revoke — Revoke an API token (account-scoped) - POST /password — Change password (revokes all sessions and API tokens)

    Signup is separate — see signup_routes.ts for invite-gated account creation. Defaults are closed/safe: accounts are created through bootstrap, admin action, or invite.

  • auth/account_schema.ts

    Auth entity types and client-safe schemas.

    Defines the runtime types for the fuz identity system: Account, Actor, Permit, AuthSession, and ApiToken.

    DDL lives in ddl.ts; role system in role_schema.ts. See docs/identity.md for design rationale.

  • auth/admin_routes.ts

    Generic admin route specs — account listing, permit management, session and token revocation.

    All routes require the admin role.

  • auth/api_token_queries.ts

    API token query functions for token CRUD and validation.

  • auth/api_token.ts

    API token generation and hashing utilities.

    Tokens use the format secret_fuz_token_<base64url> and are stored as blake3 hashes. These are pure cryptographic operations with no framework dependency — the bearer auth middleware that validates tokens lives in bearer_auth.ts.

  • auth/app_settings_queries.ts

    App settings database queries.

    Single-row table queries for global app configuration.

  • auth/app_settings_routes.ts

    Admin app settings route specs.

    GET and PATCH routes for managing global app settings (e.g. open signup toggle). All routes require the admin role.

  • auth/app_settings_schema.ts

    App settings types and client-safe schemas.

    Single-row table for global app configuration (e.g. open signup toggle).

  • auth/audit_log_queries.ts

    Audit log database queries.

    Records and retrieves auth mutation events for security monitoring. All write operations should use audit_log_fire_and_forget to ensure audit logging never blocks or breaks auth flows.

    Rollback resilience: audit_log_fire_and_forget writes to background_db (pool-level), not the handler's transaction-scoped db, so audit entries persist even when the request transaction rolls back.

  • auth/audit_log_routes.ts

    Audit log and admin observability route specs.

    All routes require admin role by default. Provides audit event listing, permit history shortcut, and active session overview.

  • auth/audit_log_schema.ts

    Audit log database schema and types.

    Records auth mutations (login, logout, grant, revoke, etc.) for security monitoring and operational visibility.

  • 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).

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

  • auth/bootstrap_account.ts

    Bootstrap flow for creating the first account.

    Uses an atomic bootstrap_lock table to prevent TOCTOU race conditions. Token verification and account creation happen in a single transaction.

  • auth/bootstrap_routes.ts

    Bootstrap route spec for first-time account creation.

    One-shot endpoint: exchanges a bootstrap token + credentials for an account with keeper privileges and a session cookie.

  • auth/daemon_token_middleware.ts

    Daemon token rotation, persistence, and middleware.

    Manages the lifecycle of filesystem-resident daemon tokens: writing to disk, rotation on an interval, and HTTP middleware for authentication.

    Pure token primitives (schema, generation, validation) live in daemon_token.ts. See docs/identity.md for design rationale.

  • auth/daemon_token.ts

    Daemon token primitives — schema, generation, and validation.

    Pure auth operations with no I/O or state management. The middleware, rotation, and persistence logic lives in daemon_token_middleware.ts.

  • auth/ddl.ts

    Auth table DDL — CREATE TABLE, index, and seed statements.

    Consumed by migrations.ts. Separated from account_schema.ts to isolate DDL concerns from runtime types.

  • auth/deps.ts

    Stateless capabilities bundle for fuz_app backends.

    AppDeps is the central dependency injection type — injectable and swappable per environment (production vs test). Does not contain config (static values) or runtime state (mutable refs).

  • auth/invite_queries.ts

    Invite database queries.

    CRUD operations for the invite table — creating invites, finding unclaimed matches, claiming, and cleanup.

  • auth/invite_routes.ts

    Admin invite route specs for invite-based signup.

    All routes require the admin role. Provides CRUD for invites that gate who can sign up.

  • auth/invite_schema.ts

    Invite types and client-safe schemas.

    Defines the runtime types for the invite system: invite creation, matching, and claiming.

  • auth/keyring.ts

    Key ring for cookie signing.

    Encapsulates secret keys and crypto operations. Keys are never exposed - only sign/verify operations are available. This prevents accidental logging or leakage of secrets.

    @example

    const keyring = create_keyring(process.env.SECRET_COOKIE_KEYS); if (!keyring) throw new Error('No keys configured'); const signed = await keyring.sign('user:123:1700000000'); const result = await keyring.verify(signed); // result = { value: 'user:123:1700000000', key_index: 0 }
  • auth/middleware.ts

    Auth middleware stack factory.

    Creates the standard middleware layers (origin, session, request_context, bearer_auth, optional daemon_token) from configuration.

  • auth/migrations.ts

    Auth schema migrations.

    Single v0 migration for the fuz identity system tables. Consumed by run_migrations with namespace 'fuz_auth'.

    Collapsed to a single v0 for the 0.1.0 release — no production databases exist, so the prior v0–v6 development iterations are consolidated. Post-0.1.0, each new migration appends as v1, v2, etc.

    To add a migration, append a new entry to AUTH_MIGRATIONS:

    // v1: add display_name to account { name: 'account_display_name', up: async (db) => { await db.query('ALTER TABLE account ADD COLUMN display_name TEXT'); }, },

    Migrations are forward-only (no down). Use IF NOT EXISTS / IF EXISTS for DDL safety. Named migrations ({name, up}) are preferred for debuggability — the name appears in error messages on failure.

  • auth/password_argon2.ts

    Argon2id password hashing implementation.

    Uses @node-rs/argon2 for native performance with OWASP-recommended parameters. Includes timing attack resistance via verify_dummy.

    Import argon2_password_deps for use as PasswordHashDeps in AppDeps.

  • auth/password.ts

    Password hashing type definitions.

    Defines the PasswordHashDeps injectable interface and PASSWORD_LENGTH_MIN. Concrete Argon2id implementation lives in password_argon2.ts.

  • auth/permit_queries.ts

    Permit database queries.

    Permits are time-bounded, revocable grants of a role to an actor. The system is safe by default — no permit, no capability.

  • auth/request_context.ts

    Request context middleware and permit checking helpers.

    Builds { account, actor, permits } from a session cookie for every authenticated request. Downstream handlers check permits, never flags.

    build_request_context is the shared helper used by session, bearer, and daemon token middleware to resolve account → actor → permits. refresh_permits reloads permits on an existing context.

  • auth/require_keeper.ts

    Keeper credential type guard.

    Two-part check: 1. Credential type must be daemon_token (not session cookie, not API token). 2. Account must hold active keeper permit.

    Both must pass. A session cookie from the bootstrap account still fails check #1.

  • auth/role_schema.ts

    Role system — builtin roles, role options, and extensible role schema factory.

    Defines the authorization policy vocabulary: which roles exist, what capabilities they require (daemon token, web grantability), and a factory for extending with app-defined roles.

  • auth/route_guards.ts

    Auth guard resolver for the route spec system.

    Maps RouteAuth discriminants to auth middleware handlers. Injected into apply_route_specs to decouple the generic HTTP framework (route_spec.ts) from auth-specific middleware.

  • auth/session_cookie.ts

    Generic session management for cookie-based auth.

    Parameterized on identity type via SessionOptions<TIdentity>. Handles signing, expiration, and key rotation. Apps provide encode/decode for their specific identity format.

    Cookie value format: ${encode(identity)}:${expires_at} (signed with HMAC-SHA256).

  • auth/session_lifecycle.ts

    Session lifecycle — creation and cookie management shared across login and bootstrap flows.

  • auth/session_middleware.ts

    Hono session middleware using generic session management.

    Thin wrapper that gets/sets cookies and delegates to session processing.

  • auth/session_queries.ts

    Auth session database queries.

    Server-side sessions keyed by blake3 hash of the session token. The cookie contains the raw token; the database stores only the hash.

  • auth/signup_routes.ts

    Signup route spec for account creation.

    Public endpoint that creates an account. When open_signup is disabled (default), a matching unclaimed invite is required. When enabled, anyone can sign up without an invite. Follows the bootstrap_routes.ts pattern.