api #

fullstack app library

151 modules ยท 709 declarations

Modules
#

Account
#

auth/account_schema.ts view source

Account

Account โ€” authentication identity. You log in as an account.

id

type string

username

email

type Email | null

email_verified

type boolean

password_hash

type string

created_at

type string

created_by

type string | null

updated_at

type string

updated_by

type string | null

ACCOUNT_EMAIL_INDEX
#

auth/ddl.ts view source

"\nCREATE UNIQUE INDEX IF NOT EXISTS idx_account_email ON account (LOWER(email)) WHERE email IS NOT NULL"

ACCOUNT_SCHEMA
#

auth/ddl.ts view source

"\nCREATE TABLE IF NOT EXISTS account (\n id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n username TEXT UNIQUE NOT NULL,\n email TEXT,\n email_verified BOOLEAN NOT NULL DEFAULT false,\n password_hash TEXT NOT NULL,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n created_by UUID,\n updated_at TIMESTAMPTZ ...

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.

ACCOUNT_USERNAME_CI_INDEX
#

auth/ddl.ts view source

"\nCREATE UNIQUE INDEX IF NOT EXISTS idx_account_username_ci ON account (LOWER(username))"

AccountRouteOptions
#

auth/account_routes.ts view source

AccountRouteOptions

Per-factory configuration for account route specs.

inheritance

login_account_rate_limiter

Rate limiter for login attempts, keyed by submitted username. Pass null to disable.

type RateLimiter | null

max_sessions

Max active sessions per account. Evicts oldest on login. Default 5, null disables.

type number | null

max_tokens

Max API tokens per account. Evicts oldest on creation. Default 10, null disables.

type number | null

AccountSessions
#

AccountSessionsState
#

ui/account_sessions_state.svelte.ts view source

inheritance

extends:

sessions

type Array<AuthSession>

active_count

readonly

fetch

type (): Promise<void>

returns Promise<void>

revoke

type (id: string): Promise<void>

id
type string
returns Promise<void>

revoke_all

type (): Promise<void>

returns Promise<void>

AccountStatusOptions
#

auth/account_routes.ts view source

AccountStatusOptions

Options for the account status route spec.

path

Override the default path (/api/account/status).

type string

bootstrap_status

Runtime bootstrap status โ€” when available, 401 responses include bootstrap_available.

type {available: boolean}

ActionAuth
#

actions/action_spec.ts view source

ZodUnion<readonly [ZodLiteral<"public">, ZodLiteral<"authenticated">, ZodLiteral<"keeper">, ZodObject<{ role: ZodString; }, $strict>]>

ActionEventOptions
#

ActionEventPhase
#

actions/action_spec.ts view source

ZodEnum<{ send_request: "send_request"; receive_request: "receive_request"; send_response: "send_response"; receive_response: "receive_response"; send_error: "send_error"; receive_error: "receive_error"; send: "send"; receive: "receive"; execute: "execute"; }>

ActionInitiator
#

ActionKind
#

ActionRegistry
#

actions/action_registry.ts view source

Utility class to manage and query action specifications. Provides helper methods to get actions by various criteria.

specs

type Array<ActionSpecUnion>

readonly

constructor

type new (specs: ({ method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<unknown, unknown, $ZodTypeInternals<...>>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async: true; } | { ...; } | { ...; })[]): ActionRegistry

specs
type ({ method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<unknown, unknown, $ZodTypeInternals<...>>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async:...

ActionRouteOptions
#

actions/action_bridge.ts view source

ActionRouteOptions

Options for deriving a RouteSpec from an ActionSpec.

path

type string

handler

params

URL path parameter schema. Use z.strictObject() with string fields matching :param segments.

type z.ZodObject

query

URL query parameter schema. Use z.strictObject() with string fields.

type z.ZodObject

http_method

Override the default HTTP method (default: side_effects โ†’ POST, else GET).

auth

Override the default auth mapping (default: 'public' โ†’ none, 'authenticated' โ†’ authenticated, 'keeper' โ†’ keeper, {role} โ†’ role).

errors

Handler-specific error schemas (HTTP status code โ†’ Zod schema). Transport-specific โ€” not on ActionSpec.

ActionSideEffects
#

ActionSpec
#

actions/action_spec.ts view source

ZodObject<{ method: ZodString; kind: ZodEnum<{ request_response: "request_response"; remote_notification: "remote_notification"; local_call: "local_call"; }>; initiator: ZodEnum<...>; ... 5 more ...; description: ZodString; }, $strict>

ActionSpecUnion
#

actions/action_spec.ts view source

ZodUnion<readonly [ZodObject<{ method: ZodString; initiator: ZodEnum<{ frontend: "frontend"; backend: "backend"; both: "both"; }>; side_effects: ZodUnion<readonly [ZodLiteral<true>, ZodNull]>; ... 5 more ...; async: ZodDefault<...>; }, $strict>, ZodObject<...>, ZodObject<...>]>

Actor
#

auth/account_schema.ts view source

Actor

Actor โ€” the entity that acts. Owns cells, holds permits, appears in audit trails.

id

type string

account_id

type string

name

type string

created_at

type string

updated_at

type string | null

updated_by

type string | null

ACTOR_INDEX
#

ACTOR_SCHEMA
#

auth/ddl.ts view source

"\nCREATE TABLE IF NOT EXISTS actor (\n id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n account_id UUID NOT NULL REFERENCES account(id) ON DELETE CASCADE,\n name TEXT NOT NULL,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n updated_at TIMESTAMPTZ,\n updated_by UUID REFERENCES actor(id) ON DELETE SET NULL\...

ActorSummaryJson
#

ADMIN_ONLY_FIELD_BLOCKLIST
#

AdminAccountEntryJson
#

auth/account_schema.ts view source

ZodObject<{ account: ZodObject<{ id: ZodString; username: ZodString; email: ZodNullable<ZodEmail>; email_verified: ZodBoolean; created_at: ZodString; updated_at: ZodString; updated_by: ZodNullable<...>; }, $strict>; actor: ZodNullable<...>; permits: ZodArray<...>; }, $strict>

Zod schema for an admin account listing entry (account + actor + permits).

AdminAccountJson
#

auth/account_schema.ts view source

ZodObject<{ id: ZodString; username: ZodString; email: ZodNullable<ZodEmail>; email_verified: ZodBoolean; created_at: ZodString; updated_at: ZodString; updated_by: ZodNullable<...>; }, $strict>

Zod schema for admin-facing account data โ€” extends SessionAccountJson with audit fields.

AdminAccounts
#

AdminAccountsState
#

ui/admin_accounts_state.svelte.ts view source

inheritance

extends:

accounts

type Array<AdminAccountEntryJson>

grantable_roles

type Array<string>

granting_keys

type SvelteSet<string>

readonly

revoking_ids

type SvelteSet<string>

readonly

account_count

readonly

fetch

type (): Promise<void>

returns Promise<void>

grant_permit

type (account_id: string, role: string): Promise<void>

account_id
type string
role
type string
returns Promise<void>

revoke_permit

type (account_id: string, permit_id: string): Promise<void>

account_id
type string
permit_id
type string
returns Promise<void>

AdminAuditLog
#

AdminInvites
#

AdminInvitesState
#

ui/admin_invites_state.svelte.ts view source

inheritance

extends:

invites

type Array<InviteWithUsernamesJson>

creating

deleting_ids

type SvelteSet<string>

readonly

invite_count

readonly

unclaimed_count

readonly

fetch

type (): Promise<void>

returns Promise<void>

create_invite

type (email?: string | undefined, username?: string | undefined): Promise<boolean>

email?
type string | undefined
optional
username?
type string | undefined
optional
returns Promise<boolean>

delete_invite

type (id: string): Promise<void>

id
type string
returns Promise<void>

AdminOverview
#

AdminPermitHistory
#

AdminRouteOptions
#

auth/admin_routes.ts view source

AdminRouteOptions

Options for admin route specs.

roles

Role schema result from create_role_schema(). Defaults to builtin roles only. Pass the full result to enable extended app-defined roles in the admin UI. Both Role and role_options come from the same call โ€” passing them together via this field ensures they stay in sync.

AdminSessionJson
#

auth/audit_log_schema.ts view source

ZodObject<{ id: ZodString; account_id: ZodString; created_at: ZodString; expires_at: ZodString; last_seen_at: ZodString; username: ZodString; }, $strict>

Zod schema for admin session listing (session + username).

AdminSessions
#

AdminSessionsState
#

ui/admin_sessions_state.svelte.ts view source

inheritance

extends:

sessions

type Array<AdminSessionJson>

revoking_account_ids

type SvelteSet<string>

readonly

revoking_token_account_ids

type SvelteSet<string>

readonly

active_count

readonly

fetch

type (): Promise<void>

returns Promise<void>

revoke_all_for_account

type (account_id: string): Promise<void>

account_id
type string
returns Promise<void>

revoke_all_tokens_for_account

type (account_id: string): Promise<void>

account_id
type string
returns Promise<void>

AdminSettings
#

AdminSurface
#

AdversarialHeaderCase
#

testing/adversarial_headers.ts view source

AdversarialHeaderCase

A header-level attack case for middleware stack testing.

name

type string

headers

type Record<string, string>

expected_status

type number

expected_error

type string

expected_error_schema

Zod schema to validate error response body against. Defaults to ApiError when expected_error is set.

type z.ZodType

validate_expectation

Whether the request should reach token validation or be short-circuited by earlier middleware.

type 'called' | 'not_called'

AdversarialTestOptions
#

testing/attack_surface.ts view source

AdversarialTestOptions

Options for adversarial test runners (auth enforcement and input validation).

build

Build the app surface bundle (surface + route specs + middleware specs).

type () => AppSurfaceSpec

roles

All roles in the app (e.g. ['admin', 'keeper']).

type Array<string>

Alignment
#

API_TOKEN_INDEX
#

API_TOKEN_PREFIX
#

API_TOKEN_SCHEMA
#

auth/ddl.ts view source

"\nCREATE TABLE IF NOT EXISTS api_token (\n id TEXT PRIMARY KEY,\n account_id UUID NOT NULL REFERENCES account(id) ON DELETE CASCADE,\n name TEXT NOT NULL,\n token_hash TEXT NOT NULL,\n expires_at TIMESTAMPTZ,\n last_used_at TIMESTAMPTZ,\n last_used_ip TEXT,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n)"

ApiError
#

ApiToken
#

auth/account_schema.ts view source

ApiToken

API token for CLI/programmatic access.

id

type string

account_id

type string

name

type string

token_hash

type string

expires_at

type string | null

last_used_at

type string | null

last_used_ip

type string | null

created_at

type string

ApiTokenQueryDeps
#

APP_SETTINGS_SCHEMA
#

auth/ddl.ts view source

"\nCREATE TABLE IF NOT EXISTS app_settings (\n id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),\n open_signup BOOLEAN NOT NULL DEFAULT false,\n updated_at TIMESTAMPTZ,\n updated_by UUID\n)"

APP_SETTINGS_SEED
#

AppBackend
#

server/app_backend.ts view source

AppBackend

Result of create_app_backend() โ€” database metadata + deps bundle.

This is the initialized backend, not the HTTP server. Pass it to create_app_server() to assemble the Hono app.

deps

type AppDeps

db_type

type DbType

db_name

type string

migration_results

Migration results from create_app_backend (auth migrations only).

type ReadonlyArray<MigrationResult>
readonly

close

Close the database connection. Bound to the actual driver.

type () => Promise<void>

AppDeps
#

auth/deps.ts view source

AppDeps

Stateless capabilities bundle for fuz_app backends.

Injectable and swappable per environment (production vs test). Does not contain config (static values) or runtime state (mutable refs).

stat

Get file/directory stats, or null if path doesn't exist.

type (path: string) => Promise<StatResult | null>

read_file

Read a file as text.

type (path: string) => Promise<string>

delete_file

Delete a file.

type (path: string) => Promise<void>

keyring

HMAC-SHA256 cookie signing keyring.

type Keyring

password

Password hashing operations. Use argon2_password_deps in production.

db

Database instance.

type Db

log

Structured logger instance.

type Logger

on_audit_event

Called after each audit log INSERT succeeds. Use to broadcast audit events via SSE. Flows automatically to all route factories that receive deps or RouteFactoryDeps. Defaults to a noop when not wired to SSE.

type (event: AuditLogEvent) => void

apply_middleware_specs
#

http/route_spec.ts view source

(app: Hono<BlankEnv, BlankSchema, "/">, specs: MiddlewareSpec[]): void

Apply named middleware specs to a Hono app.

app

the Hono app

type Hono<BlankEnv, BlankSchema, "/">

specs

middleware specs to apply

type MiddlewareSpec[]

returns

void

apply_route_specs
#

http/route_spec.ts view source

(app: Hono<BlankEnv, BlankSchema, "/">, specs: RouteSpec[], resolve_auth_guards: AuthGuardResolver, log: Logger, db: Db): void

Apply route specs to a Hono app.

For each spec: resolves auth to guards via the provided resolver, adds input validation middleware (for routes with non-null input schemas), wraps handler with DEV-only output and error validation, and registers the route.

Each handler receives a RouteContext with: - db: transaction-scoped (for non-GET) or pool-level (for GET) - background_db: always pool-level - pending_effects: fire-and-forget effect queue

app

the Hono app

type Hono<BlankEnv, BlankSchema, "/">

specs

route specs to apply

type RouteSpec[]

resolve_auth_guards

maps RouteAuth to middleware โ€” use fuz_auth_guard_resolver from auth/route_guards.ts

log

the logger instance

type Logger

db

database instance for transaction wrapping and RouteContext

type Db

returns

void

AppServer
#

server/app_server.ts view source

AppServer

Result of create_app_server().

app

type Hono

surface_spec

Surface spec โ€” serializable surface + raw specs that produced it.

bootstrap_status

app_settings

Global app settings (mutable ref โ€” mutated by settings admin route).

migration_results

Combined migration results โ€” auth migrations from create_app_backend plus consumer migrations.

type ReadonlyArray<MigrationResult>

audit_sse

Factory-managed audit log SSE. null when audit_log_sse option is not set.

type AuditLogSse | null

close

Close the database connection. Propagated from AppBackend.

type () => Promise<void>

AppServerContext
#

server/app_server.ts view source

AppServerContext

Context passed to create_route_specs.

deps

type AppDeps

backend

bootstrap_status

session_options

type SessionOptions<string>

ip_rate_limiter

Shared IP rate limiter (from options). null when not configured.

type RateLimiter | null

login_account_rate_limiter

Per-account login rate limiter (from options). null when not configured.

type RateLimiter | null

signup_account_rate_limiter

Per-account signup rate limiter (from options). null when not configured.

type RateLimiter | null

app_settings

Global app settings (mutable ref โ€” mutated by settings admin route).

audit_sse

Factory-managed audit log SSE. null when audit_log_sse option is not set.

type AuditLogSse | null

AppServerOptions
#

server/app_server.ts view source

AppServerOptions

Configuration for create_app_server().

Requires a pre-initialized AppBackend from create_app_backend(). Two explicit steps: init backend then assemble server.

backend

Pre-initialized backend from create_app_backend().

session_options

Session options for cookie-based auth.

type SessionOptions<string>

allowed_origins

Parsed allowed origin patterns.

type Array<RegExp>

proxy

Trusted proxy options.

type { trusted_proxies: Array<string>; get_connection_ip: (c: Context) => string | undefined; }

ip_rate_limiter

Shared IP rate limiter for login, bootstrap, and bearer auth. Omit or undefined to use a default limiter (5 attempts per 15 minutes). Pass null to explicitly disable rate limiting. Also available on AppServerContext for route factory callbacks.

type RateLimiter | null

login_account_rate_limiter

Per-account rate limiter for login attempts. Omit or undefined to use a default limiter (10 attempts per 30 minutes). Pass null to explicitly disable rate limiting. Also available on AppServerContext for route factory callbacks.

type RateLimiter | null

signup_account_rate_limiter

Per-account rate limiter for signup attempts, keyed by submitted username. Omit or undefined to use a default limiter (10 attempts per 30 minutes). Pass null to explicitly disable rate limiting. Also available on AppServerContext for route factory callbacks.

type RateLimiter | null

bearer_ip_rate_limiter

Rate limiter for bearer token auth attempts (per-IP). Omit or undefined to use a default limiter (5 attempts per 15 minutes). Pass null to explicitly disable rate limiting.

type RateLimiter | null

max_body_size

Maximum allowed request body size in bytes. Omit or undefined to use the default (1 MiB). Pass null to explicitly disable body size limiting.

type number | null

daemon_token_state

Daemon token state for keeper auth. Omit to disable.

bootstrap

Bootstrap options. Omit to skip bootstrap status check and routes.

type { token_path: string | null; /** Route prefix for bootstrap routes. Default `'/api/account'`. */ route_prefix?: string; /** * Called after successful bootstrap (account + session created). * Use for app-specific post-bootstrap work like generating API tokens. */ on_bootstrap?: (result: BootstrapAccountSuccess, c: Context) => Promise<void>; }

surface_route

Set to false to disable the auto-created surface route (GET /api/surface). Default: auto-created (authenticated).

type false

migration_namespaces

Consumer migration namespaces โ€” run after auth migrations during init.

type Array<MigrationNamespace>

create_route_specs

Build route specs from the initialized backend. Called after all middleware is ready.

type (context: AppServerContext) => Array<RouteSpec>

transform_middleware

Optional: transform middleware specs before applying.

type (specs: Array<MiddlewareSpec>) => Array<MiddlewareSpec>

audit_log_sse

Enable factory-managed audit log SSE.

When truthy, creates an AuditLogSse instance internally, wires on_audit_event on the backend deps (composing with any existing callback), and auto-includes AUDIT_LOG_EVENT_SPECS in the surface. The result is exposed on AppServerContext (for route factories) and AppServer (for the caller).

Pass true for defaults (admin role), or {role: 'custom'} for a custom role. Omit to wire audit SSE manually.

type true | {role?: string}

event_specs

SSE event specs for surface generation. Defaults to [] (no SSE events).

type Array<SseEventSpec>

env_schema

Env schema for surface generation. Pass z.object({}) when there are no env vars beyond BaseServerEnv.

type z.ZodObject

post_route_middleware

Middleware applied after routes, before static serving. Included in surface.

type Array<MiddlewareSpec>

static_serving

Static file serving. Omit if not serving static files.

type { serve_static: ServeStaticFactory; spa_fallback?: string; }

await_pending_effects

Await all pending fire-and-forget effects before returning the response. Use in tests so audit log assertions don't need polling. Default false (production: true fire-and-forget).

type boolean

on_effect_error

Called when a pending effect rejects. Use for monitoring, metrics, or alerting in production. Only called when await_pending_effects is false (production mode).

type (error: unknown, context: EffectErrorContext) => void

env_values

Env values for startup summary logging.

type Record<string, unknown>

AppSettings
#

AppSettingsJson
#

auth/app_settings_schema.ts view source

ZodObject<{ open_signup: ZodBoolean; updated_at: ZodNullable<ZodString>; updated_by: ZodNullable<ZodString>; }, $strict>

Zod schema for client-safe app settings data.

AppSettingsRouteOptions
#

AppSettingsState
#

ui/app_settings_state.svelte.ts view source

inheritance

extends:

settings

type AppSettingsWithUsernameJson | null

updating

fetch

type (): Promise<void>

returns Promise<void>

update_open_signup

type (value: boolean): Promise<void>

value
type boolean
returns Promise<void>

AppSettingsWithUsernameJson
#

auth/app_settings_schema.ts view source

ZodObject<{ open_signup: ZodBoolean; updated_at: ZodNullable<ZodString>; updated_by: ZodNullable<ZodString>; updated_by_username: ZodNullable<...>; }, $strict>

Zod schema for admin app settings with resolved updater username.

AppShell
#

ui/AppShell.svelte view source

children

type Snippet

sidebar

type Snippet

sidebar_width?

type number
optional

sidebar_state?

optional

keyboard_shortcut?

type string | false
optional

show_toggle?

type boolean
optional

toggle_button?

type Snippet<[{title: string; show_sidebar: boolean; toggle: () => void}]>
optional

AppSurface
#

http/surface.ts view source

AppSurface

Generated attack surface โ€” JSON-serializable.

middleware

type Array<AppSurfaceMiddleware>

routes

type Array<AppSurfaceRoute>

env

type Array<AppSurfaceEnv>

events

type Array<AppSurfaceEvent>

diagnostics

type Array<AppSurfaceDiagnostic>

AppSurfaceDiagnostic
#

http/surface.ts view source

AppSurfaceDiagnostic

Assembly-time diagnostic collected during surface generation or server assembly.

level

type 'warning' | 'info'

category

type string

message

type string

source

type string

AppSurfaceEnv
#

http/surface.ts view source

AppSurfaceEnv

An env var in the generated attack surface (JSON-serializable).

name

type string

description

type string

sensitivity

Sensitivity level from .meta({sensitivity}). null when not sensitive.

type Sensitivity | null

has_default

type boolean

optional

type boolean

AppSurfaceEvent
#

http/surface.ts view source

AppSurfaceEvent

An SSE event in the generated attack surface (JSON-serializable).

method

type string

description

type string

channel

type string | null

params_schema

type unknown

AppSurfaceMiddleware
#

http/surface.ts view source

AppSurfaceMiddleware

A middleware in the generated attack surface (JSON-serializable).

name

type string

path

type string

error_schemas

JSON Schema representations of error responses, keyed by HTTP status code. null when none.

type Record<string, unknown> | null

AppSurfaceRoute
#

http/surface.ts view source

AppSurfaceRoute

A route in the generated attack surface (JSON-serializable).

method

type string

path

type string

auth

applicable_middleware

type Array<string>

description

type string

is_mutation

Whether this route mutates state (POST, PUT, DELETE, PATCH).

type boolean

transaction

Whether this route's handler runs inside a database transaction.

type boolean

rate_limit_key

Rate limit key type declared on the route spec. null when not rate-limited.

type RateLimitKey | null

params_schema

JSON Schema representation of the URL path params schema. null when no params.

type unknown

query_schema

JSON Schema representation of the URL query params schema. null when no query schema.

type unknown

input_schema

JSON Schema representation of the request body schema. null for no-body routes.

type unknown

output_schema

JSON Schema representation of the success response schema.

type unknown

error_schemas

JSON Schema representations of error responses, keyed by HTTP status code. null when none.

type Record<string, unknown> | null

AppSurfaceSpec
#

http/surface.ts view source

AppSurfaceSpec

The surface bundled with the source specs that produced it.

AppSurface is JSON-serializable (snapshots, UI, startup logging). AppSurfaceSpec is runtime-only (tests, introspection, attack surface assertions).

surface

route_specs

type Array<RouteSpec>

middleware_specs

type Array<MiddlewareSpec>

argon2_password_deps
#

assert_404_schemas_use_specific_errors
#

testing/surface_invariants.ts view source

(surface: AppSurface): void

Routes declaring 404 error schemas should use specific z.literal() or z.enum() error codes, not generic z.string().

A generic 404 schema (ApiError with z.string()) means the error code is unconstrained โ€” the handler could return any string, making client error handling fragile. Routes with params (:id) are the primary 404 producers; their error schemas should use specific constants like ERROR_ACCOUNT_NOT_FOUND.

Only flags routes that have params_schema (param-driven resource lookup) โ€” routes declaring 404 for other reasons (e.g., bootstrap not configured) may legitimately use generic schemas.

surface

returns

void

assert_descriptions_present
#

assert_error_code_status_consistency
#

testing/surface_invariants.ts view source

(surface: AppSurface): void

The same z.literal() error code should not appear at different HTTP status codes across routes.

Extracts const values from error schema error properties (which correspond to z.literal() in the Zod source). Flags when the same literal appears at different status codes โ€” e.g., ERROR_INVALID_CREDENTIALS at both 401 and 403 would be a bug.

Only checks schemas with const values (literal schemas). Generic z.string() schemas (which produce {type: 'string'} in JSON Schema) are ignored.

surface

returns

void

assert_error_coverage
#

testing/error_coverage.ts view source

(collector: ErrorCoverageCollector, route_specs: RouteSpec[], options?: ErrorCoverageOptions | undefined): void

Assert error coverage meets a minimum threshold.

Computes the ratio of exercised error statuses to total declared error statuses. When min_coverage is 0 (default), logs coverage info without failing. When > 0, fails if coverage is below the threshold.

collector

the coverage collector with recorded observations

route_specs

route specs to check coverage against

type RouteSpec[]

options?

threshold and exclusion configuration

type ErrorCoverageOptions | undefined
optional

returns

void

assert_error_schema_tightness
#

testing/surface_invariants.ts view source

(surface: AppSurface, options?: ErrorSchemaTightnessOptions | undefined): void

Assert that all error schemas meet a minimum specificity threshold.

Calls audit_error_schema_tightness and fails on any entry below the configured threshold. Use allowlist and ignore_statuses to exclude known exceptions during progressive tightening.

surface

the app surface to check

options?

threshold and exclusion configuration

type ErrorSchemaTightnessOptions | undefined
optional

returns

void

assert_error_schema_valid
#

testing/assertions.ts view source

(lookup: Map<string, Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>>>, route: AppSurfaceRoute, status: number, body: unknown): void

Assert that an error schema exists for a route+status and validate the body against it.

Protected routes should always have auto-derived error schemas (401 for authenticated, 403 for role-restricted). A missing schema indicates a gap in error schema derivation.

lookup

map from "METHOD /path" to merged error schemas

type Map<string, Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>>>

route

the surface route to validate against

status

expected HTTP status code

type number

body

the parsed response body to validate

type unknown

returns

void

assert_error_schemas_structurally_valid
#

testing/surface_invariants.ts view source

(surface: AppSurface): void

Every route's declared error schemas must have an error field at the top level (conforming to the ApiError base shape {error: string}).

Catches typos in error schema definitions and ensures consumers can always read .error from error responses.

surface

returns

void

assert_full_middleware_stack
#

assert_input_routes_declare_400
#

assert_keeper_routes_under_prefix
#

testing/surface_invariants.ts view source

(surface: AppSurface, prefixes?: string[]): void

Keeper-protected routes must be under expected path prefixes.

Catches keeper routes accidentally placed outside the API namespace (e.g., a keeper route at /health or /admin/ instead of /api/...).

surface

prefixes

type string[]
default DEFAULT_KEEPER_ROUTE_PREFIXES

returns

void

assert_middleware_errors_propagated
#

assert_mutation_routes_use_post
#

testing/surface_invariants.ts view source

(surface: AppSurface): void

Routes with non-null input schemas should use POST (or other mutation methods), not GET.

GET routes with request bodies are technically allowed by HTTP but semantically suspicious โ€” they bypass browser security assumptions about GET being idempotent. Query-string-driven filtering (audit log, list endpoints) should use params schemas or query string parsing, not input schemas.

surface

returns

void

assert_no_duplicate_routes
#

assert_no_error_info_leakage
#

testing/integration_helpers.ts view source

(body: Record<string, unknown>, context: string): void

Assert that an error response contains no leaky field values.

Checks both field names and string values for patterns indicating stack traces, SQL, or internal paths.

body

parsed error response JSON

type Record<string, unknown>

context

description for error messages

type string

returns

void

assert_no_sensitive_fields_in_json
#

testing/integration_helpers.ts view source

(body: unknown, blocklist: readonly string[], context: string): void

Assert that a parsed JSON body contains no fields from the given blocklist.

body

parsed response JSON

type unknown

blocklist

field names to check for

type readonly string[]

context

description for error messages

type string

returns

void

assert_no_unexpected_public_mutations
#

testing/surface_invariants.ts view source

(surface: AppSurface, allowlist?: string[]): void

Public mutation routes (auth: none + is_mutation) must be in the allowlist.

Catches accidentally unprotected POST/PUT/DELETE routes. Routes like login and bootstrap are public mutations by design โ€” they go in the allowlist.

surface

allowlist

type string[]
default []

returns

void

assert_non_admin_schemas_no_admin_fields
#

testing/data_exposure.ts view source

(surface: AppSurface, admin_only_fields?: readonly string[]): void

Assert that non-admin route output schemas don't contain admin-only fields.

surface

the app surface to check

admin_only_fields

field names that are admin-only

type readonly string[]
default ADMIN_ONLY_FIELD_BLOCKLIST

returns

void

assert_only_expected_public_routes
#

testing/assertions.ts view source

(surface: AppSurface, expected_public: string[]): void

Bidirectional check: no unexpected public routes, no missing expected ones.

surface

the app surface to check

expected_public

format: ['GET /health', 'POST /api/account/login']

type string[]

returns

void

assert_output_schemas_no_sensitive_fields
#

testing/data_exposure.ts view source

(surface: AppSurface, sensitive_fields?: readonly string[]): void

Assert that no output schema in the surface contains sensitive field names.

surface

the app surface to check

sensitive_fields

field names to flag

type readonly string[]
default SENSITIVE_FIELD_BLOCKLIST

returns

void

assert_params_routes_declare_400
#

assert_protected_routes_declare_401
#

assert_query_routes_declare_400
#

assert_rate_limit_retry_after_header
#

testing/integration_helpers.ts view source

(response: Response, body: { retry_after: number; }): void

Assert that a 429 response includes a valid Retry-After header matching the JSON body's retry_after field.

response

the 429 response

type Response

body

parsed JSON body with retry_after field

type { retry_after: number; }

returns

void

assert_response_matches_spec
#

testing/integration_helpers.ts view source

(route_specs: RouteSpec[], method: string, path: string, response: Response): Promise<void>

Validate a response body against the route spec's declared schemas.

For 2xx responses, validates against spec.output. For error responses, validates against the merged error schema for that status code. Throws with details on mismatch.

route_specs

route specs for schema lookup

type RouteSpec[]

method

HTTP method of the request

type string

path

path of the request

type string

response

the Response to validate

type Response

returns

Promise<void>

assert_role_routes_declare_403
#

assert_row
#

db/assert_row.ts view source

<T>(row: T | undefined, context?: string | undefined): T

Assert that a row is present, throwing a descriptive error if missing.

Use after INSERT ... RETURNING queries where the database guarantees a row is returned on success. Replaces bare row! non-null assertions with an explicit runtime check.

row

the row from query_one (T | undefined) or rows[0] (T | undefined)

type T | undefined

context?

optional context for the error message (e.g. table or operation name)

type string | undefined
optional

returns

T

the row, guaranteed non-undefined

assert_sensitive_routes_rate_limited
#

testing/surface_invariants.ts view source

(surface: AppSurface, sensitive_patterns?: (string | RegExp)[]): void

Sensitive routes must declare rate limiting (rate_limit_key is non-null) or have 429 in their error schemas.

Matches routes against sensitive patterns and flags any that lack rate limit declarations. Catches forgotten rate limiting on credential-handling routes.

surface

sensitive_patterns

type (string | RegExp)[]
default DEFAULT_SENSITIVE_PATTERNS

returns

void

assert_surface_deterministic
#

testing/assertions.ts view source

(build_surface: () => AppSurface): void

Verify surface generation is deterministic (build twice, compare).

build_surface

function that builds the surface

type () => AppSurface

returns

void

assert_surface_invariants
#

assert_surface_matches_snapshot
#

testing/assertions.ts view source

(surface: AppSurface, snapshot_path: string): void

Compare live surface against a committed snapshot JSON file.

surface

the live surface to check

snapshot_path

absolute path to the committed JSON snapshot

type string

returns

void

assert_surface_security_policy
#

testing/surface_invariants.ts view source

(surface: AppSurface, options?: SurfaceSecurityPolicyOptions): void

Run security policy invariants. Configurable with sensible defaults.

Checks: - Sensitive routes are rate-limited - No unexpected public mutation routes - Input schemas use mutation methods (not GET) - Keeper routes under expected prefixes

surface

options

default {}

returns

void

assert_valid_sql_identifier
#

db/sql_identifier.ts view source

(name: string): string

Assert that a string is a valid SQL identifier.

Use this before interpolating table or column names into DDL queries where parameterized placeholders ($1) are not supported.

name

the identifier to validate

type string

returns

string

the validated identifier

throws

  • if - the identifier contains invalid characters

audit_error_schema_tightness
#

testing/surface_invariants.ts view source

(surface: AppSurface): ErrorSchemaAuditEntry[]

Audit error schema tightness across all routes in a surface.

Reports which route x status code combinations use generic ApiError (z.string()) vs specific z.literal() or z.enum() error codes. Use the output to prioritize progressive tightening of error schemas.

surface

the app surface to audit

returns

ErrorSchemaAuditEntry[]

audit entries for every route x status combination

AUDIT_EVENT_TYPES
#

auth/audit_log_schema.ts view source

readonly ["login", "logout", "bootstrap", "signup", "password_change", "session_revoke", "session_revoke_all", "token_create", "token_revoke", "token_revoke_all", "permit_grant", "permit_revoke", "invite_create", "invite_delete", "app_settings_update"]

All tracked auth event types.

AUDIT_LOG_DEFAULT_LIMIT
#

AUDIT_LOG_EVENT_SPECS
#

audit_log_fire_and_forget
#

auth/audit_log_queries.ts view source

<T extends AuditEventType>(route: Pick<RouteContext, "background_db" | "pending_effects">, input: AuditLogInput<T>, log: Logger, on_event: (event: AuditLogEvent) => void): Promise<...>

Log an audit event without blocking the caller.

Errors are logged to console โ€” audit logging never breaks auth flows. Uses background_db so audit entries persist even if the request transaction rolls back. Write failures and on_event callback failures are logged separately so the error message indicates which phase failed.

route

background_db and pending_effects from the route context

type Pick<RouteContext, "background_db" | "pending_effects">

input

the audit event to record

type AuditLogInput<T>

log

the logger instance

type Logger

on_event

callback invoked with the inserted row after a successful write

type (event: AuditLogEvent) => void

returns

Promise<void>

the settled promise (callers may ignore it โ€” fire-and-forget semantics preserved)

AUDIT_LOG_INDEXES
#

AUDIT_LOG_SCHEMA
#

auth/audit_log_schema.ts view source

"\nCREATE TABLE IF NOT EXISTS audit_log (\n id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n seq SERIAL NOT NULL,\n event_type TEXT NOT NULL,\n outcome TEXT NOT NULL DEFAULT 'success',\n actor_id UUID REFERENCES actor(id) ON DELETE SET NULL,\n account_id UUID REFERENCES account(id) ON DELETE SET NULL,\n targe...

AUDIT_METADATA_SCHEMAS
#

auth/audit_log_schema.ts view source

{ login: ZodNullable<ZodObject<{ username: ZodString; }, $loose>>; logout: ZodNull; bootstrap: ZodNullable<ZodObject<{ error: ZodString; }, $loose>>; ... 11 more ...; app_settings_update: ZodObject<...>; }

Per-event-type metadata Zod schemas.

Uses z.looseObject so consumers can add extra fields (e.g. visiones self_service) while known fields are validated. Events with outcome-dependent metadata use a union with z.null().

AuditCompletenessTestOptions
#

testing/audit_completeness.ts view source

AuditCompletenessTestOptions

session_options

Session config for cookie-based auth.

type SessionOptions<string>

create_route_specs

Route spec factory โ€” same one used in production.

type (ctx: AppServerContext) => Array<RouteSpec>

app_options

Optional overrides for AppServerOptions.

type Partial< Omit<AppServerOptions, 'backend' | 'session_options' | 'create_route_specs'> >

db_factories

Database factories to run tests against. Default: pglite only.

type Array<DbFactory>

AuditEventType
#

auth/audit_log_schema.ts view source

ZodEnum<{ login: "login"; logout: "logout"; bootstrap: "bootstrap"; signup: "signup"; password_change: "password_change"; session_revoke: "session_revoke"; session_revoke_all: "session_revoke_all"; ... 7 more ...; app_settings_update: "app_settings_update"; }>

Zod schema for audit event types.

AuditLogEvent
#

auth/audit_log_schema.ts view source

AuditLogEvent

Audit log row from the database.

id

type string

seq

type number

event_type

outcome

actor_id

type string | null

account_id

type string | null

target_account_id

type string | null

ip

type string | null

created_at

type string

metadata

type Record<string, unknown> | null

AuditLogEventJson
#

auth/audit_log_schema.ts view source

ZodObject<{ id: ZodString; seq: ZodNumber; event_type: ZodEnum<{ login: "login"; logout: "logout"; bootstrap: "bootstrap"; signup: "signup"; password_change: "password_change"; session_revoke: "session_revoke"; ... 8 more ...; app_settings_update: "app_settings_update"; }>; ... 6 more ...; metadata: ZodNullable<...>...

Zod schema for client-safe audit log event.

AuditLogEventWithUsernamesJson
#

auth/audit_log_schema.ts view source

ZodObject<{ id: ZodString; seq: ZodNumber; event_type: ZodEnum<{ login: "login"; logout: "logout"; bootstrap: "bootstrap"; signup: "signup"; password_change: "password_change"; session_revoke: "session_revoke"; ... 8 more ...; app_settings_update: "app_settings_update"; }>; ... 8 more ...; target_username: ZodNullab...

Zod schema for audit log events with resolved usernames.

AuditLogFetchOptions
#

AuditLogInput
#

auth/audit_log_schema.ts view source

AuditLogInput<T>

Input for creating an audit log entry.

generics

T

constraint AuditEventType

event_type

type T

outcome

actor_id

type string | null

account_id

type string | null

target_account_id

type string | null

ip

type string | null

metadata

type (AuditMetadataMap[T] & Record<string, unknown>) | null

AuditLogListOptions
#

auth/audit_log_schema.ts view source

AuditLogListOptions

Options for listing audit log entries.

limit

type number

offset

type number

event_type

event_type_in

type Array<AuditEventType>

account_id

type string

outcome

since_seq

When set, only return events with seq greater than this value. Enables SSE reconnection gap fill.

type number

AuditLogRouteOptions
#

auth/audit_log_routes.ts view source

AuditLogRouteOptions

Options for audit log route specs.

required_role

Role required to access audit routes. Default 'admin'.

type string

stream

When provided, includes an SSE route at /audit-log/stream for realtime audit events. The subscribe function receives the stream, channels, and the subscriber's account_id as an identity key โ€” enabling close_by_identity() for auth revocation.

type { subscribe: ( stream: SseStream<SseNotification>, channels?: Array<string>, identity?: string, ) => () => void; log: Logger; }

AuditLogSse
#

realtime/sse_auth_guard.ts view source

AuditLogSse

Convenience factory result for audit log SSE.

Satisfies AuditLogRouteOptions['stream'] and provides the combined on_audit_event callback (broadcast + guard).

subscribe

Subscribe function โ€” pass as part of stream option to create_audit_log_route_specs.

type ( stream: SseStream<SseNotification>, channels?: Array<string>, identity?: string, ) => () => void

log

Logger โ€” pass as part of stream option to create_audit_log_route_specs.

type Logger

on_audit_event

Combined broadcast + guard callback. Pass as on_audit_event on CreateAppBackendOptions.

type (event: AuditLogEvent) => void

registry

The underlying registry โ€” exposed for subscriber count monitoring.

type SubscriberRegistry<SseNotification>

AuditLogState
#

ui/audit_log_state.svelte.ts view source

inheritance

extends:

events

type Array<AuditLogEventWithUsernamesJson>

permit_history_events

type Array<PermitHistoryEventJson>

count

readonly

connected

Whether the SSE stream is currently connected.

constructor

type new (stream_url?: string): AuditLogState

stream_url
type string
default '/api/admin/audit-log/stream'

fetch

type (options?: AuditLogFetchOptions | undefined): Promise<void>

options?
type AuditLogFetchOptions | undefined
optional
returns Promise<void>

fetch_permit_history

type (limit?: number | undefined, offset?: number | undefined): Promise<void>

limit?
type number | undefined
optional
offset?
type number | undefined
optional
returns Promise<void>

subscribe

Connect to the SSE stream for realtime audit events.

New events are prepended to events. EventSource auto-reconnects on transient errors; since_seq fills gaps on reconnection.

type (): () => void

returns () => void

cleanup function that closes the connection

disconnect

Close the SSE connection.

type (): void

returns void

AuditMetadataMap
#

AuditOutcome
#

AUTH_DROP_TABLES
#

testing/db.ts view source

readonly ["app_settings", "invite", "audit_log", "api_token", "auth_session", "permit", "actor", "account", "bootstrap_lock"]

All auth tables in drop order (children first for FK safety).

The full set created by AUTH_MIGRATIONS โ€” use for clean-slate test DB initialization. AUTH_TRUNCATE_TABLES is the subset for between-test data cleanup (excludes audit_log).

When adding tables to AUTH_MIGRATIONS, add them here too.

AUTH_INTEGRATION_TRUNCATE_TABLES
#

testing/db.ts view source

string[]

Auth tables including audit_log โ€” for integration tests that exercise the full middleware stack (login, admin, rate limiting).

Separate from AUTH_TRUNCATE_TABLES because unit-level DB tests that don't touch audit logging don't need to truncate it.

AUTH_MIGRATION_NAMESPACE
#

AUTH_MIGRATION_NS
#

AUTH_MIGRATIONS
#

auth/migrations.ts view source

Migration[]

Auth schema migrations in order.

- v0: Full auth schema โ€” account (with email_verified), actor, permit, auth_session, api_token, audit_log (with seq), bootstrap_lock, invite, app_settings, plus all indexes and seeds.

AUTH_SESSION_EXTEND_THRESHOLD_MS
#

AUTH_SESSION_INDEXES
#

AUTH_SESSION_LIFETIME_MS
#

AUTH_SESSION_SCHEMA
#

auth/ddl.ts view source

"\nCREATE TABLE IF NOT EXISTS auth_session (\n id TEXT PRIMARY KEY,\n account_id UUID NOT NULL REFERENCES account(id) ON DELETE CASCADE,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n expires_at TIMESTAMPTZ NOT NULL,\n last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n)"

auth_state_context
#

ui/auth_state.svelte.ts view source

{ get: (error_message?: string | undefined) => AuthState; get_maybe: () => AuthState | undefined; set: (value: AuthState) => AuthState; }

Svelte context for AuthState. Use auth_state_context.set(state) in the provider and auth_state_context.get() to access.

AUTH_TRUNCATE_TABLES
#

testing/db.ts view source

string[]

Auth table names in truncation order (children first for FK safety).

Consumer projects can spread this into their own list and append app-specific tables.

AuthGuardResolver
#

AuthMiddlewareOptions
#

auth/middleware.ts view source

AuthMiddlewareOptions

Per-factory configuration for the standard auth middleware stack.

allowed_origins

type Array<RegExp>

session_options

type SessionOptions<string>

path

Path pattern for middleware (default: '/api/*').

type string

daemon_token_state

Daemon token state for keeper auth. Omit to disable daemon token middleware.

bearer_ip_rate_limiter

Rate limiter for bearer token auth attempts (per-IP). Pass null to disable.

type RateLimiter | null

AuthSession
#

auth/account_schema.ts view source

AuthSession

Server-side auth session, keyed by blake3 hash of session token.

id

type string

account_id

type string

created_at

type string

expires_at

type string

last_seen_at

type string

AuthSessionJson
#

auth/account_schema.ts view source

ZodObject<{ id: ZodString; account_id: ZodString; created_at: ZodString; expires_at: ZodString; last_seen_at: ZodString; }, $strict>

Zod schema for AuthSession โ€” id is the blake3 hash, safe for client.

AuthSessionRouteOptions
#

auth/account_routes.ts view source

AuthSessionRouteOptions

Shared options for route factories that create sessions and rate-limit by IP.

Extended by AccountRouteOptions and SignupRouteOptions. Consumers can destructure these from AppServerContext once and spread into multiple factories.

session_options

type SessionOptions<string>

ip_rate_limiter

Rate limiter for auth attempts, keyed by client IP. Pass null to disable.

type RateLimiter | null

AuthState
#

ui/auth_state.svelte.ts view source

verifying

verified

verify_error

type string | null

account

type SessionAccount | null

permits

type Array<Permit>

active_permits

type Array<Permit>

readonly

roles

type Array<string>

readonly

needs_bootstrap

True when bootstrap is available (no accounts exist yet).

check_session

Check auth state and bootstrap availability.

Fetches GET /api/account/status โ€” returns account info (200) or 401 with optional bootstrap_available flag. Called on init, and after login/bootstrap to refresh state.

type (): Promise<void>

returns Promise<void>

login

Log in with username and password.

type (username: string, password: string): Promise<boolean>

username
type string
password
type string
returns Promise<boolean>

true if login succeeded, false otherwise

bootstrap

Bootstrap the first keeper account.

type (token: string, username: string, password: string): Promise<boolean>

token
type string
username
type string
password
type string
returns Promise<boolean>

true if bootstrap succeeded, false otherwise

signup

Sign up with an invite.

type (username: string, password: string, email?: string | undefined): Promise<boolean>

username
type string
password
type string
email?
type string | undefined
optional
returns Promise<boolean>

true if signup succeeded, false otherwise

logout

Log out by clearing the session cookie.

type (): Promise<void>

returns Promise<void>

AuthTestApps
#

testing/auth_apps.ts view source

AuthTestApps

Pre-built Hono apps for each auth level, shared across adversarial test suites.

public

type Hono

authed

type Hono

keeper

type Hono

by_role

type Map<string, Hono>

BaseServerEnv
#

server/env.ts view source

ZodObject<{ NODE_ENV: ZodEnum<{ development: "development"; production: "production"; }>; PORT: ZodDefault<ZodCoercedNumber<unknown>>; HOST: ZodDefault<ZodString>; ... 9 more ...; SMTP_PASSWORD: ZodOptional<...>; }, $strict>

Base Zod schema for server environment variables.

Provides the common fields used by fuz apps: server config, database, auth, security, public URLs, and SMTP.

Apps can use directly or extend with app-specific fields via .extend().

BearerAuthMocks
#

testing/middleware.ts view source

BearerAuthMocks

Mocks bundle returned by create_bearer_auth_mocks.

mock_validate

type ReturnType<typeof vi.fn>

mock_find_by_id

type ReturnType<typeof vi.fn>

mock_find_by_account

type ReturnType<typeof vi.fn>

mock_find_active_for_actor

type ReturnType<typeof vi.fn>

BearerAuthTestCase
#

testing/middleware.ts view source

BearerAuthTestCase

A full test case for the table-driven bearer auth runner.

inheritance

validate_expectation

Whether the request should reach token validation or be short-circuited.

type 'called' | 'not_called'

assert_context_set

If true, assert REQUEST_CONTEXT_KEY and CREDENTIAL_TYPE_KEY were set to api_token values.

type boolean

assert_context_preserved

If true, assert the pre-existing session context and credential type are preserved.

type boolean

assert_mocks

Optional callback for custom spy assertions on the mocks bundle.

type (mocks: BearerAuthMocks) => void

BearerAuthTestOptions
#

testing/middleware.ts view source

BearerAuthTestOptions

Mock configuration for bearer auth middleware test setup.

name

Test description.

type string

headers

Request headers.

type Record<string, string>

pre_context

Pre-set request context (simulates session already resolved).

mock_validate_result

What query_validate_api_token() returns.

type unknown

mock_find_by_id_result

What query_account_by_id() returns.

type unknown

mock_find_by_account_result

What query_actor_by_account() returns.

type unknown

mock_permits_result

What query_permit_find_active_for_actor() returns.

type unknown

expected_status

Expected HTTP status, or 'next' if the middleware should call next().

type number | 'next'

expected_error

Expected error field in JSON response body.

type string

expected_error_schema

Zod schema to validate error response body against. Defaults to ApiError when expected_error is set.

type z.ZodType

bootstrap_account
#

auth/bootstrap_account.ts view source

(deps: BootstrapAccountDeps, provided_token: string, input: BootstrapAccountInput): Promise<BootstrapAccountResult>

Bootstrap the first account with keeper and admin privileges.

Uses an atomic bootstrap_lock UPDATE to prevent concurrent bootstrap attempts (TOCTOU). The full flow runs in a single transaction:

1. Read and verify the bootstrap token (before transaction) 2. Hash the password (CPU-intensive, before transaction) 3. Acquire the bootstrap lock atomically (inside transaction) 4. Create account + actor 5. Grant keeper and admin permits (no expiry, granted_by = null) 6. Delete the token file (after commit, reported via token_file_deleted)

deps

database, token path, filesystem callbacks, and password hashing

provided_token

the bootstrap token from the user

type string

input

username and password

returns

Promise<BootstrapAccountResult>

the created account, actor, and permits โ€” or a bootstrap failure

BOOTSTRAP_LOCK_SCHEMA
#

auth/ddl.ts view source

"\nCREATE TABLE IF NOT EXISTS bootstrap_lock (\n id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),\n bootstrapped BOOLEAN NOT NULL DEFAULT false\n)"

BOOTSTRAP_LOCK_SEED
#

auth/ddl.ts view source

"\nINSERT INTO bootstrap_lock (id, bootstrapped)\n SELECT 1, EXISTS(SELECT 1 FROM account)\n ON CONFLICT DO NOTHING"

Seed the bootstrap_lock table, setting bootstrapped based on whether accounts exist.

bootstrap_test_account
#

testing/app_server.ts view source

(options: BootstrapTestAccountOptions): Promise<{ account: { id: string; username: string; }; actor: { id: string; }; api_token: string; session_cookie: string; }>

Bootstrap a test account with credentials.

Creates an account with actor, grants roles, creates an API token, creates a session, and signs a session cookie. Shared by create_test_app_server and TestApp.create_account.

options

returns

Promise<{ account: { id: string; username: string; }; actor: { id: string; }; api_token: string; session_cookie: string; }>

BootstrapAccountDeps
#

auth/bootstrap_account.ts view source

BootstrapAccountDeps

Dependencies for bootstrap_account.

db

type Db

token_path

Path to the bootstrap token file on disk.

type string

read_file

Read a file's contents as a string.

type (path: string) => Promise<string>

delete_file

Delete a file.

type (path: string) => Promise<void>

password

Only hashing is needed โ€” verification happens separately during login.

type Pick<PasswordHashDeps, 'hash_password'>

log

Structured logger instance.

type Logger

BootstrapAccountFailure
#

BootstrapAccountInput
#

BootstrapAccountResult
#

BootstrapAccountSuccess
#

auth/bootstrap_account.ts view source

BootstrapAccountSuccess

Successful bootstrap result with the created entities.

ok

type true

account

type Account

actor

type Actor

permits

type {keeper: Permit; admin: Permit}

token_file_deleted

Whether the bootstrap token file was successfully deleted after account creation.

type boolean

BootstrapForm
#

BootstrapRouteOptions
#

auth/bootstrap_routes.ts view source

BootstrapRouteOptions

Per-factory configuration for bootstrap route specs.

bootstrap_status is runtime state (a mutable ref), not a dep or options value โ€” it is passed through so the route handler can flip it on success.

session_options

type SessionOptions<string>

bootstrap_status

Shared mutable reference โ€” flipped to false after successful bootstrap.

on_bootstrap

Called after successful bootstrap (account + session created). Use for app-specific post-bootstrap work like generating API tokens.

type (result: BootstrapAccountSuccess, c: Context) => Promise<void>

ip_rate_limiter

Rate limiter for bootstrap attempts (per-IP). Pass null to disable.

type RateLimiter | null

BootstrapStatus
#

BootstrapTestAccountOptions
#

build_request_context
#

auth/request_context.ts view source

(deps: QueryDeps, account_id: string): Promise<RequestContext | null>

Build a full RequestContext from an account id.

Shared helper used by session, bearer, and daemon token middleware, as well as WebSocket upgrade handlers. Does the account โ†’ actor โ†’ permits lookup pipeline and returns the composed context, or null if the account or actor is not found.

deps

query dependencies

account_id

the account to build context for

type string

returns

Promise<RequestContext | null>

a request context, or null if account/actor not found

BUILTIN_ROLE_OPTIONS
#

BUILTIN_ROLES
#

BuiltinRole
#

CardinalPosition
#

check_bootstrap_status
#

auth/bootstrap_routes.ts view source

(deps: CheckBootstrapStatusDeps, options: { token_path: string | null; }): Promise<BootstrapStatus>

Check bootstrap availability at startup.

Bootstrap is available when: 1. A token path is configured 2. The token file exists on disk 3. The bootstrap_lock table shows bootstrapped = false

deps

filesystem and database access for the check

options

static configuration including token_path

type { token_path: string | null; }

returns

Promise<BootstrapStatus>

an object with available (boolean) and token_path (string | null)

check_error_response_fields
#

testing/integration_helpers.ts view source

(body: Record<string, unknown>): string[]

Assert that an error response body contains no unexpected fields.

Error schemas use z.looseObject (intentional โ€” multiple producers), but test responses should be checked for fields that could leak information. Flags any field not in the known-safe set.

body

parsed error response JSON

type Record<string, unknown>

returns

string[]

array of unexpected field names (empty = clean)

CheckBootstrapStatusDeps
#

auth/bootstrap_routes.ts view source

CheckBootstrapStatusDeps

Dependencies for checking bootstrap status at startup.

stat

type (path: string) => Promise<StatResult | null>

db

type Db

log

type Logger

clear_session_cookie
#

ClientApiTokenJson
#

auth/account_schema.ts view source

ZodObject<{ id: ZodString; account_id: ZodString; name: ZodString; expires_at: ZodNullable<ZodString>; last_used_at: ZodNullable<ZodString>; last_used_ip: ZodNullable<...>; created_at: ZodString; }, $strict>

Zod schema for client-safe API token listing (excludes token_hash).

CliLogger
#

cli/logger.ts view source

CliLogger

error

Logs an error via Logger (gets Logger's error prefix).

type (...args: Array<unknown>) => void

warn

Logs a warning via Logger (gets Logger's warn prefix).

type (...args: Array<unknown>) => void

info

Logs info via Logger (gets Logger's label prefix).

type (...args: Array<unknown>) => void

debug

Logs debug via Logger (gets Logger's debug prefix).

type (...args: Array<unknown>) => void

raw

Logs raw output via Logger (no prefix, no level filtering).

type (...args: Array<unknown>) => void

success

Logs a success message with [done] prefix at info level.

type (msg: string) => void

skip

Logs a skip message with [skip] prefix at info level.

type (msg: string) => void

step

Logs a step message with ==> prefix at info level.

type (msg: string) => void

header

Logs a header with === title === decoration at info level.

type (title: string) => void

dim

Logs a dimmed message at info level.

type (msg: string) => void

logger

The underlying Logger instance.

type Logger

collect_json_keys_recursive
#

testing/integration_helpers.ts view source

(value: unknown): Set<string>

Recursively collect all key names from a parsed JSON value.

Walks objects and arrays to find every property name at any nesting depth.

value

parsed JSON value

type unknown

returns

Set<string>

set of all key names found

collect_json_schema_property_names
#

testing/data_exposure.ts view source

(schema: unknown): Set<string>

Recursively collect all property names from a JSON Schema.

Walks properties, items, allOf/anyOf/oneOf, and additionalProperties to find every declared field name at any depth.

schema

JSON Schema object

type unknown

returns

Set<string>

set of all property names found

collect_middleware_errors
#

http/surface.ts view source

(middleware: MiddlewareSpec[], route_path: string): Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>> | null

Collect error schemas from all middleware that applies to a route path.

middleware

the middleware specs

type MiddlewareSpec[]

route_path

the route path to match against

type string

returns

Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>> | null

merged middleware error schemas, or null if none

colors
#

cli/util.ts view source

{ readonly green: "" | "\u001B[32m"; readonly yellow: "" | "\u001B[33m"; readonly blue: "" | "\u001B[34m"; readonly red: "" | "\u001B[31m"; readonly cyan: "" | "\u001B[36m"; readonly dim: "" | "\u001B[2m"; readonly bold: "" | "\u001B[1m"; readonly reset: "" | "\u001B[0m"; }

ColumnInfo
#

http/db_routes.ts view source

ColumnInfo

Column metadata from information_schema.

column_name

type string

data_type

type string

is_nullable

type string

ColumnLayout
#

CommandDeps
#

runtime/deps.ts view source

CommandDeps

Command execution.

run_command

Run a command and return the result.

type (cmd: string, args: Array<string>) => Promise<CommandResult>

CommandMeta
#

cli/help.ts view source

CommandMeta<TCategory>

Command metadata for help generation.

generics

TCategory

constraint string
default string

schema

type z.ZodType

summary

type string

usage

type string

category

type TCategory

CommandResult
#

runtime/deps.ts view source

CommandResult

Result of executing a command.

success

type boolean

code

type number

stdout

type string

stderr

type string

confirm
#

cli/util.ts view source

(runtime: TerminalDeps, message: string): Promise<boolean>

Prompt for yes/no confirmation.

runtime

runtime with stdout_write and stdin_read capabilities

message

message to display

type string

returns

Promise<boolean>

true if user confirms, false otherwise

ConfirmButton
#

ui/ConfirmButton.svelte view source

onconfirm

type (popover: Popover) => void

popover_button_attrs?

type SvelteHTMLElements['button'] | undefined
optional

hide_on_confirm?

type boolean | undefined
optional

popover_content?

Unlike on PopoverButton this is optional and has a confirm arg

type Snippet<[popover: Popover, confirm: () => void]> | undefined
optional

popover_button_content?

Content for the popover button

type Snippet<[popover: Popover, confirm: () => void]> | undefined
optional

children?

Unlike on PopoverButton this has a confirm arg

type Snippet<[popover: Popover, confirm: () => void]> | undefined
optional

create_account_route_specs
#

auth/account_routes.ts view source

(deps: RouteFactoryDeps, options: AccountRouteOptions): RouteSpec[]

Create account route specs for session-based auth.

All session/token revocation is account-scoped to prevent cross-account attacks.

deps

stateless capabilities (keyring, password, log)

options

per-factory configuration (session_options, ip_rate_limiter, login_account_rate_limiter)

returns

RouteSpec[]

route specs (not yet applied to Hono)

create_account_status_route_spec
#

auth/account_routes.ts view source

(options?: AccountStatusOptions | undefined): RouteSpec

Create the account status route spec.

Handles both authenticated and unauthenticated requests: - Authenticated: returns {account} with 200 - Unauthenticated: returns 401 with optional bootstrap_available flag

This eliminates the need for a separate /health fetch on page load โ€” the frontend gets both session state and bootstrap availability in one request.

options?

optional configuration (bootstrap_status for bootstrap detection)

type AccountStatusOptions | undefined
optional

returns

RouteSpec

a single account status route spec

create_admin_account_route_specs
#

auth/admin_routes.ts view source

(deps: Pick<RouteFactoryDeps, "log" | "on_audit_event">, options?: AdminRouteOptions | undefined): RouteSpec[]

Create admin route specs for account listing and permit management.

deps

stateless capabilities (log)

type Pick<RouteFactoryDeps, "log" | "on_audit_event">

options?

optional options with role schema for validation

type AdminRouteOptions | undefined
optional

returns

RouteSpec[]

route specs for admin account management

create_app_backend
#

server/app_backend.ts view source

(options: CreateAppBackendOptions): Promise<AppBackend>

Initialize the backend: database + auth migrations + deps.

Calls create_db โ†’ run_migrations (auth namespace) and bundles the result with the provided keyring and password deps.

options

keyring, password deps, and optional database URL

returns

Promise<AppBackend>

app backend with deps, database metadata, and migration results

create_app_server
#

server/app_server.ts view source

(options: AppServerOptions): Promise<AppServer>

Create a fully assembled Hono app with auth, middleware, and routes.

Handles the full lifecycle: consumer migrations โ†’ proxy middleware โ†’ auth middleware โ†’ bootstrap status โ†’ route specs โ†’ surface generation โ†’ Hono app assembly โ†’ static serving.

options

server configuration

returns

Promise<AppServer>

assembled Hono app, backend, surface build, and bootstrap status

create_app_settings_route_specs
#

auth/app_settings_routes.ts view source

(deps: Pick<RouteFactoryDeps, "log" | "on_audit_event">, options: AppSettingsRouteOptions): RouteSpec[]

Create admin app settings route specs.

deps

stateless capabilities (log, on_audit_event)

type Pick<RouteFactoryDeps, "log" | "on_audit_event">

options

per-factory configuration

returns

RouteSpec[]

route specs for app settings management

create_app_surface_spec
#

create_audit_log_route_specs
#

auth/audit_log_routes.ts view source

(options?: AuditLogRouteOptions | undefined): RouteSpec[]

Create audit log and admin observability route specs.

options?

optional options with role override

type AuditLogRouteOptions | undefined
optional

returns

RouteSpec[]

route specs for audit log and admin session management

create_audit_log_sse
#

create_auth_middleware_specs
#

auth/middleware.ts view source

(deps: AppDeps, options: AuthMiddlewareOptions): Promise<MiddlewareSpec[]>

Create the auth middleware stack.

Returns [origin, session, request_context, bearer_auth] middleware specs for the given path pattern. When daemon_token_state is provided, appends a 5th daemon_token layer. Apps can append extra entries for non-standard paths (e.g., tx's /tx binary endpoint).

deps

stateless capabilities (keyring, db)

type AppDeps

options

middleware configuration (allowed_origins, session_options, path, daemon_token_state)

returns

Promise<MiddlewareSpec[]>

the middleware spec array

create_auth_test_apps
#

testing/auth_apps.ts view source

(route_specs: RouteSpec[], roles: string[]): AuthTestApps

Create one Hono test app per auth level.

route_specs

the route specs to register

type RouteSpec[]

roles

all roles in the app

type string[]

returns

AuthTestApps

apps keyed by auth level

create_banner
#

create_bearer_auth_middleware
#

auth/bearer_auth.ts view source

(deps: QueryDeps, ip_rate_limiter: RateLimiter | null, log: Logger): MiddlewareHandler

Create middleware that authenticates via bearer token.

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, builds the request context ({ account, actor, permits }) and sets it on the Hono context. Skips if a request context is already set (e.g. by session middleware).

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

create_bearer_auth_mocks
#

create_bearer_auth_test_app
#

testing/middleware.ts view source

(tc: BearerAuthTestOptions, ip_rate_limiter?: RateLimiter | null): { app: Hono<BlankEnv, BlankSchema, "/">; mocks: BearerAuthMocks; }

Create a Hono app wired with create_bearer_auth_middleware using mocked deps.

The route handler at /api/test returns the resolved context in the response body, enabling assertions on REQUEST_CONTEXT_KEY and CREDENTIAL_TYPE_KEY.

tc

the test config providing mock behavior

ip_rate_limiter

optional rate limiter (null to disable)

type RateLimiter | null
default null

returns

{ app: Hono<BlankEnv, BlankSchema, "/">; mocks: BearerAuthMocks; }

the app and mocks bundle

create_bootstrap_route_specs
#

auth/bootstrap_routes.ts view source

(deps: RouteFactoryDeps, options: BootstrapRouteOptions): RouteSpec[]

Create bootstrap route specs for first-time account creation.

deps

stateless capabilities including filesystem access

options

per-factory configuration (session, token path, bootstrap status)

returns

RouteSpec[]

route specs (not yet applied to Hono)

create_cli_logger
#

cli/logger.ts view source

(logger: Logger): CliLogger

Creates a CLI logger wrapping a Logger with semantic output methods.

logger

the Logger instance to wrap

type Logger

returns

CliLogger

a CliLogger with CLI semantic methods mapped to Logger levels

create_daemon_token_middleware
#

auth/daemon_token_middleware.ts view source

(state: DaemonTokenState, deps: QueryDeps): MiddlewareHandler

Create middleware that authenticates via daemon token.

Checks the X-Daemon-Token header. Behavior: - No header: pass through (don't touch existing context) - Header present + valid: build RequestContext from keeper account, set credential_type: 'daemon_token' (overrides any existing session/bearer context) - Header present + invalid: return 401 (fail-closed, no downgrade) - Header present + valid but keeper_account_id is null: return 503

state

the daemon token runtime state

deps

query dependencies (pool-level db for middleware)

returns

MiddlewareHandler

create_database
#

dev/setup.ts view source

(deps: CommandDeps, db_name: string, options?: CreateDatabaseOptions | undefined): Promise<CommandResult>

Create a PostgreSQL database if createdb is available.

deps

command execution capability

db_name

database name to create

type string

options?

logger

type CreateDatabaseOptions | undefined
optional

returns

Promise<CommandResult>

the command result

create_db
#

db/create_db.ts view source

(database_url: string): Promise<CreateDbResult>

Create a database connection based on a URL.

Returns the Db instance, a typed close callback, driver type, and display name. The close callback is bound to the actual driver โ€” callers never need to know which driver is in use.

For direct driver construction without URL routing, import create_pg_db from db_pg.ts or create_pglite_db from db_pglite.ts.

database_url

connection URL (postgres://, postgresql://, file://, or memory://)

type string

returns

Promise<CreateDbResult>

database instance, close callback, type, and display name

create_db_route_specs
#

http/db_routes.ts view source

(options: DbRouteOptions): RouteSpec[]

Create the db API route specs.

options

route configuration (db_type, db_name, extra_stats)

returns

RouteSpec[]

route specs for database administration

create_deno_runtime
#

runtime/deno.ts view source

(args: readonly string[]): RuntimeDeps

Create a runtime backed by Deno APIs.

Returns an object satisfying all *Deps interfaces from deps.ts. Pass to shared functions that accept EnvDeps, FsReadDeps, etc.

args

CLI arguments (typically Deno.args)

type readonly string[]

returns

RuntimeDeps

runtime implementation using Deno APIs

create_describe_db
#

testing/db.ts view source

(factories: DbFactory | DbFactory[], truncate_tables: string[]): (name: string, fn: (get_db: () => Db) => void) => void

Create a describe_db function bound to specific factories and truncate tables.

Returns a 2-arg (name, fn) function that runs the test suite against each factory. Each factory gets its own describe block with a shared database instance, automatic beforeEach truncation, and afterAll cleanup. Skipped factories use describe.skip.

factories

one or more database factories to run suites against

type DbFactory | DbFactory[]

truncate_tables

tables to truncate between tests (children first for FK safety)

type string[]

returns

(name: string, fn: (get_db: () => Db) => void) => void

a describe_db function for use in test files

create_expired_test_cookie
#

create_extract_global_flags
#

cli/args.ts view source

<T extends Record<string, unknown>>(schema: ZodType<T, unknown, $ZodTypeInternals<T, unknown>>, fallback: T): (unparsed: ParsedArgs) => { flags: T; remaining: ParsedArgs; }

Create a project-specific global flag extractor.

Returns a function that separates global flags from command-specific args. The schema defines which flags are global (with aliases via .meta({aliases})), and the fallback provides defaults when parsing fails.

schema

Zod schema for global flags

type ZodType<T, unknown, $ZodTypeInternals<T, unknown>>

fallback

default values when parsing fails

type T

returns

(unparsed: ParsedArgs) => { flags: T; remaining: ParsedArgs; }

extractor function (unparsed) => {flags, remaining}

create_health_route_spec
#

http/common_routes.ts view source

(): RouteSpec

Create a public health check route spec.

Infrastructure endpoint for uptime monitors and load balancers. Bootstrap availability is exposed via /api/account/status instead.

returns

RouteSpec

a single health check route spec

create_help
#

cli/help.ts view source

<TCategory extends string>(options: HelpOptions<TCategory>): HelpGenerator

Create a help generator configured for an application.

options

help configuration

type HelpOptions<TCategory>

returns

HelpGenerator

help generator with generate_main_help, generate_command_help, and get_help_text

create_invite_route_specs
#

auth/invite_routes.ts view source

(deps: Pick<RouteFactoryDeps, "log" | "on_audit_event">): RouteSpec[]

Create admin invite route specs.

deps

stateless capabilities (log)

type Pick<RouteFactoryDeps, "log" | "on_audit_event">

returns

RouteSpec[]

route specs for invite management

create_keyring
#

auth/keyring.ts view source

(env_value: string | undefined): Keyring | null

Create a keyring from environment variable.

Keys are separated by __ for rotation support. First key is used for signing, all keys are tried for verification.

CryptoKeys are cached on first use for performance.

Security: key rotation is an operational concern. Old keys remain valid for verification indefinitely โ€” a leaked old key can forge session cookies until it is removed from SECRET_COOKIE_KEYS. After rotating to a new signing key, remove the old key within a grace period (e.g. 24โ€“48 hours, long enough for active sessions to re-sign with the new key via cookie refresh). Treat SECRET_COOKIE_KEYS changes as security-critical deploys.

env_value

the SECRET_COOKIE_KEYS environment variable

type string | undefined

returns

Keyring | null

keyring or null if no keys configured

create_mock_runtime
#

runtime/mock.ts view source

(args?: string[]): MockRuntime

Create a mock RuntimeDeps for testing.

args

CLI arguments

type string[]
default []

returns

MockRuntime

MockRuntime with controllable state

examples

const runtime = create_mock_runtime(['apply', 'tx.ts']); runtime.mock_env.set('HOME', '/home/test'); runtime.mock_fs.set('/home/test/.app/config.json', '{}'); await some_function(runtime); assert.strictEqual(runtime.command_calls.length, 1); assert.deepStrictEqual(runtime.exit_calls, [0]);

create_node_runtime
#

runtime/node.ts view source

(args?: readonly string[]): RuntimeDeps

Create a RuntimeDeps backed by Node.js APIs.

args

CLI arguments (typically process.argv.slice(2))

type readonly string[]
default process.argv.slice(2)

returns

RuntimeDeps

RuntimeDeps implementation using Node.js runtime

create_noop_stub
#

testing/stubs.ts view source

<T = any>(_label: string, overrides?: Record<string, unknown> | undefined): T

Create a Proxy where every method access returns a no-op async function.

Use for deps that may be reached during "correct auth passes guard" tests but whose return values don't matter. Unlike the explicit method listing, this auto-updates when interfaces change.

_label

type string

overrides?

explicit properties to set (e.g. {db: stub_db})

type Record<string, unknown> | undefined
optional

returns

T

create_pg_db
#

db/db_pg.ts view source

(pool: Pool): DbDriverResult

Create a Db backed by a pg Pool.

Owns the transaction implementation (acquires a dedicated pool client per transaction) and returns a close callback bound to pool.end().

pool

an already-constructed pg.Pool

type Pool

returns

DbDriverResult

create_pg_factory
#

testing/db.ts view source

(init_schema: (db: Db) => Promise<void>, test_url?: string | undefined): DbFactory

Create a pg (PostgreSQL) database factory for tests.

Skipped when test_url is not provided. Drops schema_version before running init_schema, forcing migrations to re-evaluate against the actual tables. Prevents stale version entries from skipping migrations when DDL changes between test sessions.

For full clean-slate behavior (recommended), call drop_auth_schema(db) at the start of init_schema before running migrations. This handles upstream schema changes that go beyond adding new tables/columns.

init_schema

callback to initialize the database schema

type (db: Db) => Promise<void>

test_url?

PostgreSQL connection URL (e.g. from TEST_DATABASE_URL)

type string | undefined
optional

returns

DbFactory

a factory that creates pg databases

create_pglite_db
#

db/db_pglite.ts view source

(pglite: PGlite): DbDriverResult

Create a Db backed by a PGlite instance.

Delegates transactions to PGlite's native transaction() method and returns a close callback bound to pglite.close().

pglite

an already-constructed PGlite instance

type PGlite

returns

DbDriverResult

create_pglite_factory
#

testing/db.ts view source

(init_schema: (db: Db) => Promise<void>): DbFactory

Create a pglite (in-memory) database factory for tests.

Always enabled โ€” no external dependencies required. Shares a single PGlite WASM instance across all factories in the same vitest worker thread (one test file). Subsequent create() calls reset the schema via DROP SCHEMA public CASCADE instead of paying the WASM cold-start cost again.

init_schema

callback to initialize the database schema

type (db: Db) => Promise<void>

returns

DbFactory

a factory that creates in-memory pglite databases

create_proxy_middleware
#

http/proxy.ts view source

(options: ProxyOptions): MiddlewareHandler

Create a Hono middleware that resolves the client IP from trusted proxies.

Sets client_ip on the Hono context for downstream use by get_client_ip. All client IPs are normalized (lowercase, IPv4-mapped IPv6 stripped).

Resolution logic: 1. No X-Forwarded-For โ†’ use connection IP directly. 2. X-Forwarded-For present but connection is untrusted โ†’ ignore header (spoofed by a direct attacker), use connection IP. 3. X-Forwarded-For present and connection is trusted โ†’ walk header right-to-left, strip trusted entries, use first untrusted entry.

options

trusted proxy configuration

returns

MiddlewareHandler

create_proxy_middleware_spec
#

http/proxy.ts view source

(options: ProxyOptions): MiddlewareSpec

Create a middleware spec for trusted proxy resolution.

Apply before auth middleware so client_ip is available for rate limiting.

options

trusted proxy configuration

returns

MiddlewareSpec

create_rate_limiter
#

rate_limiter.ts view source

(options?: Partial<RateLimiterOptions> | undefined): RateLimiter

Create a RateLimiter with sensible defaults for per-IP login protection.

options?

override individual options; unset fields use DEFAULT_LOGIN_IP_RATE_LIMIT

type Partial<RateLimiterOptions> | undefined
optional

returns

RateLimiter

create_request_context_middleware
#

auth/request_context.ts view source

(deps: QueryDeps, log: Logger, session_context_key?: string): MiddlewareHandler

Create middleware that builds the request context from a session cookie.

Reads the session identity (set by session middleware), looks up the auth_session, loads account + actor + active permits, and sets the RequestContext on the Hono context.

If the session is invalid or the account is not found, the context is set to null (unauthenticated). No 401 is returned โ€” use require_role or require_auth for enforcement.

deps

query dependencies (pool-level db for middleware)

log

the logger instance

type Logger

session_context_key

the Hono context key where session middleware stored the session token

type string
default 'auth_session_id'

returns

MiddlewareHandler

create_role_schema
#

auth/role_schema.ts view source

<T extends string>(app_roles: Record<T, RoleOptions>): RoleSchemaResult

Create a role schema and config map that extends the builtins with app-defined roles.

Call once at server init. The returned Role schema validates role strings at I/O boundaries (grant endpoint, permit queries). The role_options map is used by middleware to check requires_daemon_token and by admin UI to filter web_grantable roles.

app_roles

app-defined roles with optional config overrides

type Record<T, RoleOptions>

returns

RoleSchemaResult

{Role, role_options} โ€” Zod schema and full config map

examples

// visiones const {Role, role_options} = create_role_schema({ teacher: {}, }); // Role validates 'keeper' | 'admin' | 'teacher' // role_options has all 3 entries with defaults applied

create_server_status_route_spec
#

http/common_routes.ts view source

(options: ServerStatusOptions): RouteSpec

Create an authenticated server status route spec.

Returns version and uptime. Unlike the public health check, this requires authentication.

options

version and uptime source

returns

RouteSpec

route spec for GET /api/server/status

create_session_and_set_cookie
#

create_session_config
#

auth/session_cookie.ts view source

(cookie_name: string): SessionOptions<string>

Create a session config for raw session token identity.

The standard pattern: cookie stores the raw session token, server hashes it (blake3) to look up the auth_session row. Only the cookie_name varies per app.

cookie_name

cookie name (e.g. 'tx_session', 'visiones_session')

type string

returns

SessionOptions<string>

a SessionOptions<string> ready for use with session middleware

create_session_cookie_value
#

create_session_middleware
#

auth/session_middleware.ts view source

<TIdentity>(keyring: Keyring, options: SessionOptions<TIdentity>): MiddlewareHandler

Create session middleware that parses cookies and sets identity on context.

Always sets the identity on context (null when invalid/missing) for type-safe reads. Uses options.context_key as the Hono context variable name.

keyring

key ring for cookie verification

type Keyring

options

session configuration

type SessionOptions<TIdentity>

returns

MiddlewareHandler

create_signup_route_specs
#

create_sse_auth_guard
#

realtime/sse_auth_guard.ts view source

<T>(registry: SubscriberRegistry<T>, required_role: string, log: Logger): (event: AuditLogEvent) => void

Create an audit event handler that closes SSE streams on auth changes.

Closes streams when: - permit_revoke fires for the required_role targeting a connected subscriber - session_revoke_all targets a connected subscriber (consistent invalidation) - password_change targets a connected subscriber (sessions revoked implicitly)

The registry must use account_id as the identity key when subscribing (passed as the third argument to registry.subscribe()).

registry

the subscriber registry to guard

type SubscriberRegistry<T>

required_role

the role that grants access to the SSE endpoint

type string

log

logger for disconnect events

type Logger

returns

(event: AuditLogEvent) => void

an on_audit_event callback

create_sse_response
#

realtime/sse.ts view source

<T = unknown>(c: Context<any, any, {}>, log: Logger): { response: Response; stream: SseStream<T>; }

Create an SSE response for a Hono context.

Wraps Hono's streamSSE to provide a {response, stream} API compatible with SubscriberRegistry push-based broadcasting. The callback suspends via a promise that resolves on client disconnect or explicit close(), keeping the stream alive for external sends.

Uses hono_stream.write() directly (not writeSSE) to avoid Hono's HTML callback resolution โ€” keeps the same data: JSON\n\n format.

c

Hono context

type Context<any, any, {}>

log

type Logger

returns

{ response: Response; stream: SseStream<T>; }

object with response and stream controller

create_standard_adversarial_cases
#

testing/adversarial_headers.ts view source

(allowed_origin: string): AdversarialHeaderCase[]

7 standard adversarial header cases applicable to any middleware stack.

allowed_origin

an origin that passes the origin check

type string

returns

AdversarialHeaderCase[]

the standard adversarial header cases

create_static_middleware
#

server/static.ts view source

(serve_static: ServeStaticFactory, options?: { root?: string | undefined; spa_fallback?: string | undefined; } | undefined): MiddlewareHandler[]

Create static file serving middleware for SvelteKit static builds.

Returns an array of middleware handlers to register on '/*'.

serve_static

runtime-specific serveStatic factory

options?

optional root directory and SPA fallback path

type { root?: string | undefined; spa_fallback?: string | undefined; } | undefined
optional

returns

MiddlewareHandler[]

array of middleware handlers to apply in order

create_stub_api_middleware
#

testing/stubs.ts view source

(options?: { include_daemon_token?: boolean | undefined; } | undefined): MiddlewareSpec[]

Create the API middleware stub array matching create_auth_middleware_specs output.

options?

type { include_daemon_token?: boolean | undefined; } | undefined
optional

returns

MiddlewareSpec[]

create_stub_app_deps
#

create_stub_app_server_context
#

testing/stubs.ts view source

(session_options: SessionOptions<string>): AppServerContext

Create a stub AppServerContext for attack surface testing.

Provides sensible defaults for all fields. Pass session_options since it varies per consumer; other fields use stubs/nulls.

session_options

consumer's session config (required โ€” varies per app)

type SessionOptions<string>

returns

AppServerContext

create_stub_db
#

testing/stubs.ts view source

(): Db

Create a stub Db for handler tests that use apply_route_specs with declarative transactions.

Returns a real Db instance with: - query returns empty rows (safety net for unmocked query functions) - query_one returns undefined - transaction(fn) calls fn(db) synchronously (no real transaction)

returns

Db

create_surface_route_spec
#

http/common_routes.ts view source

(options: SurfaceRouteOptions): RouteSpec

Create an authenticated route spec that serves the AppSurface as JSON.

Surface data reveals API structure (routes, auth, schemas), so this requires authentication like the server status route.

options

surface data source

returns

RouteSpec

route spec for GET /api/surface

create_test_account
#

testing/entities.ts view source

(overrides?: Partial<Account> | undefined): Account

Create a test Account with sensible defaults.

overrides?

type Partial<Account> | undefined
optional

returns

Account

create_test_actor
#

testing/entities.ts view source

(overrides?: Partial<Actor> | undefined): Actor

Create a test Actor with sensible defaults.

overrides?

type Partial<Actor> | undefined
optional

returns

Actor

create_test_app
#

testing/app_server.ts view source

(options: CreateTestAppOptions): Promise<TestApp>

Create a fully assembled test app with a Hono server, middleware, and routes.

Combines create_test_app_server + create_app_server into a single call. Disables rate limiters and logging by default (test-friendly).

A fresh Hono app is created each call โ€” middleware closures bind to the server's deps (db, keyring), so reuse across servers is unsafe. The expensive resource (PGlite WASM) is cached separately in test_db.ts.

options

test app configuration

returns

Promise<TestApp>

a TestApp ready for HTTP testing

create_test_app_from_specs
#

testing/auth_apps.ts view source

(route_specs: RouteSpec[], auth_ctx?: RequestContext | undefined, credential_type?: "session" | "api_token" | "daemon_token" | undefined): Hono<BlankEnv, BlankSchema, "/">

Create a Hono test app from route specs with optional auth context.

route_specs

the route specs to register

type RouteSpec[]

auth_ctx?

optional request context to inject via middleware

type RequestContext | undefined
optional

credential_type?

optional credential type (default: 'session' when auth_ctx provided)

type "session" | "api_token" | "daemon_token" | undefined
optional

returns

Hono<BlankEnv, BlankSchema, "/">

a configured Hono app

create_test_app_server
#

create_test_app_surface_spec
#

testing/stubs.ts view source

(options: CreateTestAppSurfaceSpecOptions): AppSurfaceSpec

Create an AppSurfaceSpec for attack surface testing.

Mirrors create_app_server's route assembly: consumer routes + factory-managed bootstrap routes + surface generation. If create_app_server changes how it wires routes, update this helper to stay in sync (single source of truth for all consumers).

options

surface spec options

returns

AppSurfaceSpec

the surface spec for snapshot and adversarial testing

create_test_context
#

create_test_middleware_stack_app
#

testing/middleware.ts view source

(options?: TestMiddlewareStackOptions | undefined): TestMiddlewareStackApp

Create a Hono app with real proxy + origin + bearer middleware for integration testing.

All DB queries return undefined (no real database needed). The echo route at TEST_MIDDLEWARE_PATH returns {ok, client_ip, has_context}.

options?

middleware stack configuration

type TestMiddlewareStackOptions | undefined
optional

returns

TestMiddlewareStackApp

the app and mock spies (reconfigure via mockImplementation for valid-token paths)

create_test_permit
#

testing/entities.ts view source

(overrides?: Partial<Permit> | undefined): Permit

Create a test Permit with sensible defaults.

overrides?

type Partial<Permit> | undefined
optional

returns

Permit

create_test_request_context
#

testing/auth_apps.ts view source

(role?: string | undefined): RequestContext

Create a mock request context with optional role permit.

role?

optional role to grant

type string | undefined
optional

returns

RequestContext

create_throwing_stub
#

testing/stubs.ts view source

<T = any>(label: string): T

Create a Proxy that throws descriptive errors on any property access or method call.

Use for deps that should never be reached during a test. If a test accidentally calls through to a throwing stub, the error message identifies exactly which stub was hit, catching test bugs that would silently pass with {} as any.

label

descriptive name for error messages (e.g. 'keyring', 'db')

type string

returns

T

create_validated_broadcaster
#

realtime/sse.ts view source

<T extends SseNotification>(broadcaster: { broadcast: (channel: string, data: T) => void; }, event_specs: SseEventSpec[], log: Logger): { broadcast: (channel: string, data: T) => void; }

Create a broadcaster that validates events in DEV mode.

In DEV: warns on unknown methods and invalid params. In production: passes through with zero overhead.

broadcaster

duck-typed broadcaster (e.g. SubscriberRegistry)

type { broadcast: (channel: string, data: T) => void; }

event_specs

event specs to validate against

type SseEventSpec[]

log

type Logger

returns

{ broadcast: (channel: string, data: T) => void; }

validated broadcaster wrapper (passthrough in production)

create_validated_keyring
#

auth/keyring.ts view source

(env_value: string | undefined): ValidatedKeyringResult

Validate and create a keyring in one step.

Returns a discriminated union so callers handle exit/logging their own way (e.g. Deno.exit(1) vs runtime.exit(1)).

env_value

the SECRET_COOKIE_KEYS environment variable

type string | undefined

returns

ValidatedKeyringResult

{ok: true, keyring} or {ok: false, errors}

CreateAccountInput
#

CreateAppBackendOptions
#

server/app_backend.ts view source

CreateAppBackendOptions

Input for create_app_backend().

keyring is passed pre-validated โ€” callers handle their own error reporting (e.g., tx uses runtime.exit(1) on invalid keys).

stat

Get file/directory stats, or null if path doesn't exist.

type (path: string) => Promise<StatResult | null>

read_file

Read a file as text.

type (path: string) => Promise<string>

delete_file

Delete a file.

type (path: string) => Promise<void>

database_url

Database connection URL (postgres://, file://, or memory://).

type string

keyring

Validated cookie signing keyring.

type Keyring

password

Password hashing implementation. Use argon2_password_deps in production.

log

Structured logger instance. Omit for default (new Logger('server')).

type Logger

on_audit_event

Called after each audit log INSERT succeeds. Use to broadcast audit events via SSE. Flows through AppDeps to all route factories automatically. Defaults to a noop.

type (event: AuditLogEvent) => void

CreateDatabaseOptions
#

CreateDbResult
#

db/create_db.ts view source

CreateDbResult

Result of database initialization.

db

type Db

close

Close the database connection. Bound to the actual driver at construction.

type () => Promise<void>

db_type

type DbType

db_name

type string

CreateInviteInput
#

auth/invite_schema.ts view source

CreateInviteInput

Input for creating an invite.

email

type Email | null

username

type Username | null

created_by

type string | null

CreateSessionAndSetCookieOptions
#

auth/session_lifecycle.ts view source

CreateSessionAndSetCookieOptions

keyring

Keyring for cookie signing.

type Keyring

deps

Query deps (needs db for session creation).

c

Hono context for setting the cookie.

type Context

account_id

The account to create a session for.

type string

session_options

Session cookie configuration.

type SessionOptions<string>

max_sessions

Per-account session cap (null to skip enforcement).

type number | null

CreateTestAppOptions
#

CreateTestAppSurfaceSpecOptions
#

testing/stubs.ts view source

CreateTestAppSurfaceSpecOptions

session_options

Consumer's session config (required โ€” varies per app).

type SessionOptions<string>

create_route_specs

Consumer's route factory โ€” receives the same AppServerContext as production.

type (ctx: AppServerContext) => Array<RouteSpec>

env_schema

Env schema for surface generation (default: BaseServerEnv).

type z.ZodObject

event_specs

SSE event specs for surface generation.

type Array<SseEventSpec>

transform_middleware

Transform middleware array (e.g., tx's extend_middleware_for_tx_binary).

type (specs: Array<MiddlewareSpec>) => Array<MiddlewareSpec>

bootstrap_route_prefix

Bootstrap route prefix (default: '/api/account').

type string

CREDENTIAL_TYPE_KEY
#

CREDENTIAL_TYPES
#

hono_context.ts view source

readonly ["session", "api_token", "daemon_token"]

The credential types that can authenticate a request.

CredentialType
#

hono_context.ts view source

ZodEnum<{ session: "session"; api_token: "api_token"; daemon_token: "daemon_token"; }>

Credential type โ€” how a request was authenticated.

DAEMON_TOKEN_HEADER
#

DaemonInfo
#

cli/daemon.ts view source

ZodObject<{ version: ZodNumber; pid: ZodNumber; port: ZodNumber; started: ZodString; app_version: ZodString; }, $strict>

Daemon info schema for ~/.{name}/run/daemon.json.

DaemonToken
#

DaemonTokenRotation
#

DaemonTokenRotationOptions
#

auth/daemon_token_middleware.ts view source

DaemonTokenRotationOptions

Options for daemon token rotation.

app_name

Application name (for ~/.{name}/run/daemon_token).

type string

rotation_interval_ms

Rotation interval in ms. Default: 30000 (30s).

type number

DaemonTokenState
#

auth/daemon_token.ts view source

DaemonTokenState

Mutable runtime state for daemon token rotation.

This is runtime state (not AppDeps or *Options) โ€” it changes during operation. Created at server startup, passed to the middleware factory.

current_token

Current valid token.

type string

previous_token

Previous token, still valid during the race window. null before first rotation.

type string | null

rotated_at

When the last rotation occurred.

type Date

keeper_account_id

The account ID of the keeper (resolved at startup, set by on_bootstrap).

type string | null

DaemonTokenWriteDeps
#

DataExposureTestOptions
#

testing/data_exposure.ts view source

DataExposureTestOptions

build

Build the app surface spec (for schema-level checks).

type () => AppSurfaceSpec

session_options

Session config for runtime tests.

type SessionOptions<string>

create_route_specs

Route spec factory for runtime tests.

type (ctx: AppServerContext) => Array<RouteSpec>

sensitive_fields

Fields that must never appear in any response. Default: SENSITIVE_FIELD_BLOCKLIST.

type ReadonlyArray<string>

admin_only_fields

Fields that must not appear in non-admin responses. Default: ADMIN_ONLY_FIELD_BLOCKLIST.

type ReadonlyArray<string>

app_options

Optional overrides for AppServerOptions.

type Partial< Omit<AppServerOptions, 'backend' | 'session_options' | 'create_route_specs'> >

db_factories

Database factories to run tests against. Default: pglite only.

type Array<DbFactory>

skip_routes

Routes to skip, in 'METHOD /path' format.

type Array<string>

Datatable
#

DATATABLE_COLUMN_WIDTH_DEFAULT
#

DATATABLE_MIN_COLUMN_WIDTH
#

DatatableColumn
#

ui/datatable.ts view source

DatatableColumn<T>

Column definition for a Datatable.

generics

T

default unknown

key

Row data accessor key.

type string & keyof T

label

Header label text.

type string

width

Initial column width in pixels.

type number

min_width

Minimum column width in pixels.

type number

format

Format a cell value for display. Falls back to format_value when absent.

type (value: T[keyof T], row: T) => string

Db
#

db/db.ts view source

Database wrapper providing a consistent query and transaction interface.

Construct via create_pg_db() from db_pg.ts or create_pglite_db() from db_pglite.ts for proper transaction support, or via create_db() for URL-based auto-detection.

examples

const {db, close} = await create_db('postgres://...'); const users = await db.query<User>('SELECT * FROM users WHERE active = $1', [true]); await db.transaction(async (tx) => { await tx.query('INSERT INTO users ...'); await tx.query('INSERT INTO audit_log ...'); }); await close();

client

type DbClient

readonly

constructor

type new (options: DbDeps): Db

options
type DbDeps

query

Execute a query and return all rows.

type <T>(text: string, values?: unknown[] | undefined): Promise<T[]>

text
type string
values?
type unknown[] | undefined
optional
returns Promise<T[]>

query_one

Execute a query and return the first row, or undefined if no rows.

type <T>(text: string, values?: unknown[] | undefined): Promise<T | undefined>

text
type string
values?
type unknown[] | undefined
optional
returns Promise<T | undefined>

transaction

Run a function inside a database transaction.

The callback receives a transaction-scoped Db. Queries inside the callback go through the transaction connection; queries outside use the pool normally. Commits on success, rolls back on error.

type <T>(fn: (tx_db: Db) => Promise<T>): Promise<T>

fn

async function receiving a transaction-scoped Db

type (tx_db: Db) => Promise<T>
returns Promise<T>

the value returned by fn

DbClient
#

db/db.ts view source

DbClient

Minimal interface that both pg and pglite satisfy.

query

type <T = unknown>(text: string, values?: Array<unknown>) => Promise<{rows: Array<T>}>

DbDeps
#

db/db.ts view source

DbDeps

Configuration for constructing a Db with transaction support.

transaction is injected by create_db which knows the driver. For pg: acquires a dedicated pool client per transaction. For PGlite: delegates to pglite.transaction().

client

transaction

type <T>(fn: (tx_db: Db) => Promise<T>) => Promise<T>

DbDriverResult
#

db/db.ts view source

DbDriverResult

Result of constructing a driver-specific Db.

Returned by create_pg_db() and create_pglite_db(). The close callback is bound to the actual driver โ€” callers never need to know which driver is in use.

db

type Db

close

Close the database connection. Bound to the actual driver at construction.

type () => Promise<void>

DbFactory
#

testing/db.ts view source

DbFactory

Factory interface for creating test database instances.

name

type string

create

type () => Promise<Db>

close

type (db: Db) => Promise<void>

skip

type boolean

skip_reason

type string

DbRouteOptions
#

http/db_routes.ts view source

DbRouteOptions

Per-factory configuration for db routes.

db_type

type DbType

db_name

type string

extra_stats

Optional callback to provide app-specific stats in the health response.

type (db: Db) => Promise<Record<string, unknown>>

log

Optional logger for server-side diagnostics (e.g. FK violation details).

type Logger

DbStatus
#

db/status.ts view source

DbStatus

Full database status snapshot.

connected

Whether the database is reachable.

type boolean

error

Error message if connection failed.

type string

table_count

Number of public tables.

type number

tables

Per-table row counts.

type Array<TableStatus>

migrations

Per-namespace migration status.

type Array<MigrationStatus>

DbType
#

DEFAULT_ERROR_SCHEMA_TIGHTNESS
#

testing/surface_invariants.ts view source

ErrorSchemaTightnessOptions

Recommended baseline error schema tightness for consumer projects.

Uses min_specificity: 'enum' (the assertion default) with ignore_statuses for middleware-derived status codes that are commonly generic (auth middleware produces multiple error codes at 401/403, and 429 comes from rate limiters). Consumers can extend with project-specific allowlist entries.

DEFAULT_INTEGRATION_ERROR_COVERAGE
#

testing/error_coverage.ts view source

0.2

Default minimum error coverage threshold for the standard integration and admin test suites. Conservative โ€” not all error paths are exercisable in the composable suites. Consumers should increase as their test suites mature.

DEFAULT_LOGIN_ACCOUNT_RATE_LIMIT
#

DEFAULT_LOGIN_IP_RATE_LIMIT
#

DEFAULT_MAX_BODY_SIZE
#

DEFAULT_MAX_SESSIONS
#

DEFAULT_MAX_TOKENS
#

DEFAULT_ROTATION_INTERVAL_MS
#

default_setup_logger
#

derive_error_schemas
#

http/error_schemas.ts view source

(auth: RouteAuth, has_input: boolean, has_params?: boolean, has_query?: boolean, rate_limit?: RateLimitKey | undefined): Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>>

Derive error schemas from a route's auth requirement, input schema, and rate limit config.

Returns the error schemas that middleware will auto-produce for this route. Route handlers can declare additional error schemas via RouteSpec.errors; explicit entries override auto-derived ones for the same status code.

Derivation rules: - Has input schema (non-null) or has params schema or has query schema: 400 (validation error with issues) - auth: authenticated: 401 - auth: role: 401 + 403 (with required_role) - auth: keeper: 401 + 403 (keeper-specific) - rate_limit: 429 (rate limit exceeded with retry_after)

auth

the route's auth requirement

has_input

whether the route has a non-null input schema

type boolean

has_params

whether the route has a params schema

type boolean
default false

has_query

whether the route has a query schema

type boolean
default false

rate_limit?

the rate limit key type, if any

type RateLimitKey | undefined
optional

returns

Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>>

error schemas keyed by HTTP status code

derive_http_method
#

actions/action_bridge.ts view source

(side_effects: true | null): RouteMethod

Derive the default HTTP method from side effects.

side_effects

type true | null

returns

RouteMethod

describe_adversarial_404
#

testing/adversarial_404.ts view source

(options: AdversarialTestOptions): void

Generate adversarial 404 response validation tests.

For each route with params + 404 in error_schemas: 1. Creates a stub handler returning 404 with the declared error code 2. Fires a request with valid-format params (nil UUIDs for UUID params) 3. Validates response status is 404 4. Validates response body matches the declared 404 Zod schema

options

the test configuration

returns

void

describe_adversarial_auth
#

testing/attack_surface.ts view source

(options: AdversarialTestOptions): void

Generate adversarial HTTP auth enforcement test suites.

Describe blocks: - unauthenticated โ†’ 401 โ€” every protected route - wrong role โ†’ 403 โ€” every role route, tested with all non-matching roles - authenticated without role โ†’ 403 โ€” every role route, no-role context - correct auth passes guard โ€” every protected route, assert not 401/403

options

the test configuration

returns

void

describe_adversarial_input
#

testing/adversarial_input.ts view source

(options: AdversarialTestOptions): void

Generate adversarial input validation test suites.

Tests input body validation and params validation for all routes. Uses correct auth credentials so auth guards pass and validation middleware is actually exercised.

options

the test configuration

returns

void

describe_audit_completeness_tests
#

testing/audit_completeness.ts view source

(options: AuditCompletenessTestOptions): void

Composable audit log completeness test suite.

Verifies that every auth mutation route produces the correct audit log event type. Exercises routes via HTTP requests against a real PGlite database, then queries the audit_log table to verify events.

options

session config, route factory, and optional overrides

returns

void

describe_bearer_auth_cases
#

testing/middleware.ts view source

(suite_name: string, cases: BearerAuthTestCase[], ip_rate_limiter?: RateLimiter | null): void

Run a table of bearer auth middleware test cases.

Generates one test() per case inside a describe() block.

suite_name

the describe block name

type string

cases

the test case table

type BearerAuthTestCase[]

ip_rate_limiter

optional rate limiter shared across cases

type RateLimiter | null
default null

returns

void

describe_data_exposure_tests
#

testing/data_exposure.ts view source

(options: DataExposureTestOptions): void

Composable data exposure test suite.

Three test groups: 1. Schema-level โ€” walk JSON Schema output/error schemas for sensitive field names 2. Runtime โ€” fire real requests and check response bodies against blocklists 3. Cross-privilege โ€” admin routes return 403 for non-admin, error responses contain no sensitive fields

options

test configuration

returns

void

describe_rate_limiting_tests
#

testing/rate_limiting.ts view source

(options: RateLimitingTestOptions): void

Standard rate limiting integration test suite.

Creates 3 test groups: 1. IP rate limiting on login โ€” fires max_attempts + 1 login requests, verifies the last returns 429 with a valid RateLimitError body. 2. Per-account rate limiting on login โ€” fires max_attempts + 1 login requests with the same username, verifies the last returns 429. 3. Bearer auth IP rate limiting โ€” fires max_attempts + 1 bearer requests with an invalid token, verifies the last returns 429.

Each test group asserts that required routes exist, failing with a descriptive message if the consumer's route specs are misconfigured.

options

session config and route factory

returns

void

describe_round_trip_validation
#

testing/round_trip.ts view source

(options: RoundTripTestOptions): void

Run schema-driven round-trip validation tests.

For each route: 1. Resolve URL with valid params 2. Generate a valid request body (or use override) 3. Pick auth headers matching the route's auth requirement 4. Fire the request and validate the response against declared schemas

SSE routes are skipped (Content-Type text/event-stream). Routes returning non-2xx with valid input are still validated against their declared error schemas.

options

round-trip test configuration

returns

void

describe_standard_admin_integration_tests
#

testing/admin_integration.ts view source

(options: StandardAdminIntegrationTestOptions): void

Standard admin integration test suite for fuz_app admin routes.

Exercises account listing, permit grant/revoke, session management, token management, audit log routes, admin-to-admin isolation, and response schema validation.

Each test group asserts that required routes exist, failing with a descriptive message if the consumer's route specs are misconfigured.

options

session config, route factory, and role schema

returns

void

describe_standard_adversarial_headers
#

testing/adversarial_headers.ts view source

(suite_name: string, options: TestMiddlewareStackOptions, allowed_origin: string, extra_cases?: AdversarialHeaderCase[] | undefined): void

Create a middleware stack app with standard adversarial header tests.

Convenience wrapper combining create_test_middleware_stack_app and create_standard_adversarial_cases. Asserts body content for both error and success cases, and checks mock_validate call status via per-case declarative flags.

suite_name

the describe block name

type string

options

middleware stack configuration

allowed_origin

an origin that passes the origin check (used for standard cases)

type string

extra_cases?

additional cases appended after the 7 standard ones

type AdversarialHeaderCase[] | undefined
optional

returns

void

describe_standard_attack_surface_tests
#

testing/attack_surface.ts view source

(options: StandardAttackSurfaceOptions): void

Run the standard attack surface test suite.

Generates 10 test groups: 1. Snapshot โ€” live surface matches committed JSON 2. Determinism โ€” building twice yields identical results 3. Public routes โ€” bidirectional check (no unexpected, no missing) 4. Middleware stack โ€” every API route has the full middleware chain 5. Surface invariants โ€” structural assertions (error schemas, descriptions, duplicates, consistency) 6. Security policy โ€” rate limiting on sensitive routes, no unexpected public mutations, method conventions 7. Error schema tightness audit โ€” informational log of generic vs specific error schemas 8. Adversarial auth โ€” unauthenticated/wrong-role/correct-auth enforcement 9. Adversarial input โ€” input body and params validation 10. Adversarial 404 โ€” stub 404 handlers, validate response bodies against declared schemas

Consumer test files call this with project-specific options, then add any project-specific assertions in additional describe blocks.

options

the test configuration

returns

void

describe_standard_integration_tests
#

testing/integration.ts view source

(options: StandardIntegrationTestOptions): void

Standard integration test suite for fuz_app auth routes.

Exercises login/logout, cookie attributes, session security, session revocation, password change (incl. API token revocation), origin verification, bearer auth (incl. browser context rejection on mutations), token revocation, cross-account isolation, expired credential rejection, signup invite edge cases, and response body validation.

Each test group asserts that required routes exist, failing with a descriptive message if the consumer's route specs are misconfigured.

options

session config and route factory

returns

void

describe_standard_tests
#

testing/standard.ts view source

(options: StandardTestOptions): void

Run both standard integration and admin integration test suites.

Admin tests are only included when roles is provided.

options

session config, route factory, and optional role schema

returns

void

detect_format
#

testing/schema_generators.ts view source

(field_schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string | null

Detect format constraints on a field by converting to JSON Schema. Returns format string (e.g. 'uuid', 'email') or null.

field_schema

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

string | null

DISCONNECT_EVENT_TYPES
#

realtime/sse_auth_guard.ts view source

ReadonlySet<string>

Audit event types that trigger SSE stream disconnection.

permit_revoke requires the revoked role to match the guard's required_role. session_revoke_all and password_change close unconditionally for the target account.

drop_auth_schema
#

testing/db.ts view source

(db: Db): Promise<void>

Drop all auth tables and schema version tracking for a clean slate.

Recommended at the start of init_schema callbacks for create_pg_factory. Persistent test databases can accumulate stale schema from previous fuz_app versions โ€” this ensures migrations run against a truly empty database. Safe on fresh databases (IF EXISTS on all statements). No-op effect for PGlite (already fresh), but harmless to call unconditionally.

db

the database to clean

type Db

returns

Promise<void>

EffectErrorContext
#

server/app_server.ts view source

EffectErrorContext

Context passed to on_effect_error when a pending effect rejects.

method

HTTP method of the request that spawned the effect.

type string

path

URL path of the request that spawned the effect.

type string

Email
#

enter_advance
#

env_schema_to_surface
#

http/surface.ts view source

(schema: ZodObject<$ZodLooseShape, $strip>): AppSurfaceEnv[]

Convert env schema to surface entries using .meta() metadata.

schema

Zod object schema with .meta() on fields

type ZodObject<$ZodLooseShape, $strip>

returns

AppSurfaceEnv[]

array of env surface entries

EnvDeps
#

runtime/deps.ts view source

EnvDeps

Environment variable access.

env_get

Get an environment variable value.

type (name: string) => string | undefined

env_set

Set an environment variable.

type (name: string, value: string) => void

EnvValidationError
#

env/load.ts view source

Error thrown when environment validation fails.

Contains structured information for apps to format their own error messages.

inheritance

extends:
  • Error

raw

The raw env values that were read.

type Record<string, string | undefined>

readonly

zod_error

The Zod validation error.

type z.core.$ZodError

readonly

all_undefined

True if every env var was undefined (nothing loaded).

type boolean

readonly

constructor

type new (raw: Record<string, string | undefined>, zod_error: $ZodError<unknown>): EnvValidationError

raw
type Record<string, string | undefined>
zod_error
type $ZodError<unknown>

format_issues

Format Zod validation issues as human-readable strings.

type (): string[]

returns string[]

array of formatted issue strings like "PORT: Expected number"

EnvValidationResult
#

env/resolve.ts view source

EnvValidationResult

Result of env var validation.

Uses discriminated union for better type narrowing: - ok: true, missing: null โ€” all vars present - ok: false, missing: EnvVarRef[] โ€” some vars missing

EnvVarRef
#

env/resolve.ts view source

EnvVarRef

An env var reference found in a config.

name

Variable name (without $$ delimiters).

type string

path

Path where the reference was found (e.g., "target.host", "resources[3].path").

type string

ERROR_ACCOUNT_NOT_FOUND
#

ERROR_ALREADY_BOOTSTRAPPED
#

ERROR_AUTHENTICATION_REQUIRED
#

ERROR_BEARER_REJECTED_BROWSER
#

ERROR_BOOTSTRAP_NOT_CONFIGURED
#

ERROR_FORBIDDEN_ORIGIN
#

ERROR_FORBIDDEN_REFERER
#

ERROR_FOREIGN_KEY_VIOLATION
#

ERROR_INSUFFICIENT_PERMISSIONS
#

ERROR_INVALID_CREDENTIALS
#

ERROR_INVALID_DAEMON_TOKEN
#

ERROR_INVALID_EVENT_TYPE
#

ERROR_INVALID_JSON_BODY
#

ERROR_INVALID_QUERY_PARAMS
#

ERROR_INVALID_REQUEST_BODY
#

ERROR_INVALID_ROUTE_PARAMS
#

ERROR_INVALID_TOKEN
#

ERROR_INVITE_ACCOUNT_EXISTS_EMAIL
#

ERROR_INVITE_ACCOUNT_EXISTS_USERNAME
#

ERROR_INVITE_DUPLICATE
#

ERROR_INVITE_MISSING_IDENTIFIER
#

ERROR_INVITE_NOT_FOUND
#

ERROR_KEEPER_ACCOUNT_NOT_CONFIGURED
#

ERROR_KEEPER_ACCOUNT_NOT_FOUND
#

ERROR_KEEPER_REQUIRES_DAEMON_TOKEN
#

ERROR_NO_MATCHING_INVITE
#

ERROR_PAYLOAD_TOO_LARGE
#

ERROR_PERMIT_NOT_FOUND
#

ERROR_RATE_LIMIT_EXCEEDED
#

ERROR_ROLE_NOT_WEB_GRANTABLE
#

ERROR_ROW_NOT_FOUND
#

ERROR_SIGNUP_CONFLICT
#

ERROR_TABLE_NO_PRIMARY_KEY
#

ERROR_TABLE_NOT_FOUND
#

ERROR_TOKEN_FILE_MISSING
#

ErrorCoverageCollector
#

testing/error_coverage.ts view source

Tracks which route ร— status combinations have been exercised in tests.

Use record() to log an observed status, or assert_and_record() to combine response validation with tracking. After all tests, call uncovered() to find declared error statuses never exercised.

observed

Observed route ร— status keys: "METHOD /spec-path:STATUS".

type Set<string>

readonly

record

Record an observed error status for a route.

Resolves the concrete request path back to the spec template path (e.g., /api/accounts/abc โ†’ /api/accounts/:id).

type (route_specs: RouteSpec[], method: string, path: string, status: number): void

route_specs

route specs for path resolution

type RouteSpec[]
method

HTTP method

type string
path

request path (may be concrete)

type string
status

observed HTTP status code

type number
returns void

assert_and_record

Validate a response against its route spec and record the status.

Wraps assert_response_matches_spec and records the status code.

type (route_specs: RouteSpec[], method: string, path: string, response: Response): Promise<void>

route_specs

route specs for schema lookup and path resolution

type RouteSpec[]
method

HTTP method

type string
path

request path

type string
response

the Response to validate and record

type Response
returns Promise<void>

uncovered

Find declared error statuses that were never observed.

Computes the declared set from merge_error_schemas for each route spec, then subtracts observed keys.

type (route_specs: RouteSpec[]): { method: string; path: string; status: number; }[]

route_specs

route specs to check coverage against

type RouteSpec[]
returns { method: string; path: string; status: number; }[]

uncovered entries with method, path, and status

ErrorCoverageOptions
#

testing/error_coverage.ts view source

ErrorCoverageOptions

min_coverage

Minimum coverage ratio (0โ€“1). Default 0 (informational only).

type number

ignore_routes

Routes to skip, in 'METHOD /path' format.

type Array<string>

ignore_statuses

HTTP status codes to skip.

type Array<number>

ErrorSchemaAuditEntry
#

ErrorSchemaSpecificity
#

ErrorSchemaTightnessOptions
#

event_spec_from_action
#

actions/action_bridge.ts view source

(spec: { method: string; kind: "request_response" | "remote_notification" | "local_call"; initiator: "frontend" | "backend" | "both"; auth: "public" | "authenticated" | "keeper" | { ...; } | null; ... 4 more ...; description: string; }, options?: ActionEventOptions | undefined): SseEventSpec

Derive an SseEventSpec from an ActionSpec.

Only remote_notification actions can become SSE events.

spec

the action spec (must have kind: 'remote_notification')

type { method: string; kind: "request_response" | "remote_notification" | "local_call"; initiator: "frontend" | "backend" | "both"; auth: "public" | "authenticated" | "keeper" | { role: string; } | null; ... 4 more ...; description: string; }

options?

optional SSE-specific options (channel)

type ActionEventOptions | undefined
optional

returns

SseEventSpec

events_to_surface
#

http/surface.ts view source

(event_specs: SseEventSpec[]): AppSurfaceEvent[]

Convert SSE event specs to surface entries.

event_specs

event specs to convert

type SseEventSpec[]

returns

AppSurfaceEvent[]

array of event surface entries

filter_authenticated_routes
#

http/surface_query.ts view source

(surface: AppSurface): (AppSurfaceRoute & { auth: { type: "authenticated"; }; })[]

Filter routes that require basic authentication (no specific role).

surface

returns

(AppSurfaceRoute & { auth: { type: "authenticated"; }; })[]

filter_keeper_routes
#

http/surface_query.ts view source

(surface: AppSurface): (AppSurfaceRoute & { auth: { type: "keeper"; }; })[]

Filter routes that require keeper credentials.

surface

returns

(AppSurfaceRoute & { auth: { type: "keeper"; }; })[]

filter_mutation_routes
#

filter_protected_routes
#

filter_public_routes
#

filter_rate_limited_routes
#

filter_role_routes
#

http/surface_query.ts view source

(surface: AppSurface): (AppSurfaceRoute & { auth: { type: "role"; role: string; }; })[]

Filter all role-guarded routes (any role).

surface

returns

(AppSurfaceRoute & { auth: { type: "role"; role: string; }; })[]

filter_routes_by_prefix
#

filter_routes_for_role
#

http/surface_query.ts view source

(surface: AppSurface, role: string): (AppSurfaceRoute & { auth: { type: "role"; role: string; }; })[]

Filter routes that require a specific named role.

surface

role

type string

returns

(AppSurfaceRoute & { auth: { type: "role"; role: string; }; })[]

filter_routes_with_input
#

filter_routes_with_params
#

filter_routes_with_query
#

find_auth_route
#

testing/integration_helpers.ts view source

(specs: RouteSpec[], suffix: string, method: RouteMethod): RouteSpec | undefined

Find an auth route by suffix and method.

Useful for discovering login/logout/verify/revoke paths regardless of consumer prefix (/api/account/login, /api/auth/login, etc.).

specs

route specs to search

type RouteSpec[]

suffix

path suffix to match (e.g. '/login')

type string

method

HTTP method

returns

RouteSpec | undefined

matching route spec, or undefined

find_route_spec
#

testing/integration_helpers.ts view source

(specs: RouteSpec[], method: string, path: string): RouteSpec | undefined

Find a route spec matching the given method and path.

Supports both exact matches and parameterized paths (:param segments).

specs

route specs to search

type RouteSpec[]

method

HTTP method

type string

path

request path (exact or with concrete param values)

type string

returns

RouteSpec | undefined

matching route spec, or undefined

ForeignKeyError
#

http/error_schemas.ts view source

ZodObject<{ error: ZodLiteral<"foreign_key_violation">; }, $loose>

Foreign key violation error โ€” returned when a delete is blocked by references.

format_arg_name
#

cli/help.ts view source

(prop: ZodSchemaProperty): string

Format argument name with short aliases for display.

Only single-char aliases are shown (e.g., -h, --help). Flags use snake_case (e.g., --env_file, --detect_only).

prop

schema property

type ZodSchemaProperty

returns

string

formatted name string

format_audit_metadata
#

ui/ui_format.ts view source

(event_type: "login" | "logout" | "bootstrap" | "signup" | "password_change" | "session_revoke" | "session_revoke_all" | "token_create" | "token_revoke" | "token_revoke_all" | "permit_grant" | "permit_revoke" | "invite_create" | "invite_delete" | "app_settings_update", metadata: Record<...> | null): string

Format audit event metadata for display based on event type.

event_type

the audit event type

type "login" | "logout" | "bootstrap" | "signup" | "password_change" | "session_revoke" | "session_revoke_all" | "token_create" | "token_revoke" | "token_revoke_all" | "permit_grant" | "permit_revoke" | "invite_create" | "invite_delete" | "app_settings_update"

metadata

the metadata object (may be null)

type Record<string, unknown> | null

returns

string

human-readable summary string

format_datetime_local
#

ui/ui_format.ts view source

(timestamp: string | number | Date): string

Format a timestamp as an absolute datetime string for title attributes.

timestamp

a date value

type string | number | Date

returns

string

readable absolute datetime like "2026-03-21 14:30:00 UTC"

format_db_status
#

db/status.ts view source

(status: DbStatus): string

Format a DbStatus as a human-readable string for CLI output.

status

the status to format

returns

string

multi-line string suitable for console output

format_env_display_value
#

env/mask.ts view source

(value: unknown, secret: boolean): string

Format an env value for display, masking secrets.

value

the env value to format

type unknown

secret

whether the value is secret and should be masked

type boolean

returns

string

display string โ€” masked placeholder for secrets, string values as-is, non-strings JSON-stringified

format_missing_env_vars
#

env/resolve.ts view source

(missing: EnvVarRef[], options?: FormatMissingEnvVarsOptions | undefined): string

Format missing env vars error message.

Groups refs by variable name so each missing var is shown once with all paths where it's referenced.

missing

missing env var references (may contain duplicate names)

type EnvVarRef[]

options?

formatting options

type FormatMissingEnvVarsOptions | undefined
optional

returns

string

formatted error message for display

format_relative_time
#

ui/ui_format.ts view source

(timestamp: string | number | Date, now?: number): string

Format a timestamp as a relative time string.

timestamp

a date value (string, number, or Date)

type string | number | Date

now

reference time in ms since epoch, defaults to Date.now()

type number
default Date.now()

returns

string

human-friendly relative time (e.g. "2m ago", "3h ago", "5d ago", "2mo ago", "1y ago")

format_route_key
#

format_uptime
#

ui/ui_format.ts view source

(ms: number): string

Format milliseconds as a human-friendly uptime string.

ms

duration in milliseconds

type number

returns

string

human-friendly duration (e.g. "45s", "12m", "3h 15m", "2d 5h")

format_value
#

ui/ui_format.ts view source

(value: unknown): string

Format an arbitrary value for table cell display.

value

the value to format

type unknown

returns

string

string representation suitable for UI display

FormatMissingEnvVarsOptions
#

FsReadDeps
#

runtime/deps.ts view source

FsReadDeps

File system read operations.

stat

Get file/directory stats, or null if path doesn't exist.

type (path: string) => Promise<StatResult | null>

read_file

Read a file as text.

type (path: string) => Promise<string>

FsRemoveDeps
#

runtime/deps.ts view source

FsRemoveDeps

File system remove operations.

remove

Remove a file or directory.

type (path: string, options?: {recursive?: boolean}) => Promise<void>

FsWriteDeps
#

runtime/deps.ts view source

FsWriteDeps

File system write operations.

mkdir

Create a directory.

type (path: string, options?: {recursive?: boolean}) => Promise<void>

write_file

Write text to a file.

type (path: string, content: string) => Promise<void>

rename

Rename (move) a file.

type (old_path: string, new_path: string) => Promise<void>

fuz_auth_guard_resolver
#

fuz_session_config
#

generate_api_token
#

auth/api_token.ts view source

(): { token: string; id: string; token_hash: string; }

Generate a new API token with its hash and public id.

The raw token is returned exactly once โ€” callers must present it to the user immediately.

returns

{ token: string; id: string; token_hash: string; }

the raw token, a public id, and the blake3 hash for storage

generate_app_surface
#

http/surface.ts view source

(options: GenerateAppSurfaceOptions): AppSurface

Generate a JSON-serializable attack surface from middleware, route specs, and optional env/event metadata.

options

the surface generation options

returns

AppSurface

the attack surface

generate_daemon_token
#

generate_input_test_cases
#

testing/adversarial_input.ts view source

(input_schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): InputTestCase[]

Generate adversarial test cases for a route's input schema.

Produces focused, non-redundant cases: - Whole-body: send array instead of object, extra unknown key - Missing required fields (without defaults) - One wrong-type value per field - Null for required non-nullable fields - One format violation per constrained field

input_schema

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

InputTestCase[]

generate_params_test_cases
#

testing/adversarial_input.ts view source

(params_schema: ZodObject<$ZodLooseShape, $strip>): ParamsTestCase[]

Generate adversarial test cases for a route's params schema.

Params are always strings from URL segments. Only generates cases for format-constrained fields (uuid, pattern) since unconstrained string params accept any string value.

params_schema

type ZodObject<$ZodLooseShape, $strip>

returns

ParamsTestCase[]

generate_phase_handlers
#

actions/action_codegen.ts view source

(spec: { method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<unknown, unknown, $ZodTypeInternals<...>>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async: true; } | { ...; } | { ...; }, executor: "frontend" | "backend", imports: ImportBuilder): string

Generates the phase handlers for an action spec using the unified ActionEvent type with the new phase/step type parameters.

spec

type { method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<unknown, unknown, $ZodTypeInternals<...>>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async: ...

executor

type "frontend" | "backend"

imports

returns

string

generate_position_styles
#

ui/position_helpers.ts view source

(position?: Position, align?: Alignment, offset?: string): Record<string, string>

Generates CSS positioning styles for UI elements.

position

where to position the element ('left', 'right', etc.)

default 'center'

align

alignment along the position edge ('start', 'center', 'end')

default 'center'

offset

distance from the position (CSS value)

type string
default '0'

returns

Record<string, string>

CSS styles as a Record

generate_query_test_cases
#

testing/adversarial_input.ts view source

(query_schema: ZodObject<$ZodLooseShape, $strip>): QueryTestCase[]

Generate adversarial test cases for a route's query schema.

Query params are always strings from the URL. Generates cases for: - Missing required fields - Format violations on constrained fields (uuid, pattern)

query_schema

type ZodObject<$ZodLooseShape, $strip>

returns

QueryTestCase[]

generate_random_base64url
#

crypto.ts view source

(byte_length?: number): string

Generate a cryptographically random base64url string.

byte_length

number of random bytes (default 32 = 256 bits)

type number
default 32

returns

string

base64url-encoded string without padding

generate_random_key
#

dev/setup.ts view source

(deps: CommandDeps): Promise<string>

Generate a random base64 key using openssl.

deps

command execution capability

returns

Promise<string>

a random 32-byte base64-encoded key

generate_session_token
#

generate_valid_body
#

testing/schema_generators.ts view source

(input_schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): Record<string, unknown> | undefined

Generate a valid request body for a route's input schema.

Returns undefined for null schemas or schemas that can't be unwrapped to objects. Throws if the generated body fails validation โ€” catches broken generation logic early with a descriptive error instead of a confusing 400 in downstream tests.

input_schema

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

Record<string, unknown> | undefined

generate_valid_value
#

testing/schema_generators.ts view source

(field: ZodFieldInfo, field_schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): unknown

Generate a valid-ish value for a field based on its base type.

field

type ZodFieldInfo

field_schema

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

unknown

GenerateAppSurfaceOptions
#

http/surface.ts view source

GenerateAppSurfaceOptions

route_specs

type Array<RouteSpec>

middleware_specs

type Array<MiddlewareSpec>

env_schema

type z.ZodObject

event_specs

type Array<SseEventSpec>

get_app_dir
#

cli/config.ts view source

(runtime: Pick<EnvDeps, "env_get">, name: string): string | null

Get the CLI config directory path (~/.{name}).

runtime

runtime with env_get capability

type Pick<EnvDeps, "env_get">

name

application name (e.g., "tx", "zzz")

type string

returns

string | null

path to config directory, or null if $HOME is not set

get_audit_metadata
#

auth/audit_log_schema.ts view source

<T extends AuditEventType>(event: AuditLogEvent & { event_type: T; }): AuditMetadataMap[T] | null

Narrow metadata type for a known event type.

Use after checking event_type to get typed metadata access.

event

type AuditLogEvent & { event_type: T; }

returns

AuditMetadataMap[T] | null

get_client_ip
#

http/proxy.ts view source

(c: Context<any, any, {}>): string

Read the resolved client IP from the Hono context.

Returns 'unknown' if the proxy middleware has not run or no IP is available. Set by create_proxy_middleware.

c

type Context<any, any, {}>

returns

string

get_config_path
#

cli/config.ts view source

(runtime: Pick<EnvDeps, "env_get">, name: string): string | null

Get the CLI config file path (~/.{name}/config.json).

runtime

runtime with env_get capability

type Pick<EnvDeps, "env_get">

name

application name

type string

returns

string | null

path to config.json, or null if $HOME is not set

get_daemon_info_path
#

cli/daemon.ts view source

(runtime: Pick<EnvDeps, "env_get">, name: string): string | null

Get the daemon info file path (~/.{name}/run/daemon.json).

runtime

runtime with env_get capability

type Pick<EnvDeps, "env_get">

name

application name

type string

returns

string | null

path to daemon.json, or null if $HOME is not set

get_daemon_token_path
#

auth/daemon_token_middleware.ts view source

(runtime: Pick<EnvDeps, "env_get">, name: string): string | null

Get the daemon token file path (~/.{name}/run/daemon_token).

runtime

runtime with env_get capability

type Pick<EnvDeps, "env_get">

name

application name

type string

returns

string | null

path to daemon_token, or null if $HOME is not set

get_env_var_names
#

env/resolve.ts view source

(value: string): string[]

Get list of env var names referenced in a string.

value

string to scan

type string

returns

string[]

array of variable names (without $$ delimiters)

get_executor_phases
#

actions/action_codegen.ts view source

(spec: { method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<unknown, unknown, $ZodTypeInternals<...>>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async: true; } | { ...; } | { ...; }, executor: "frontend" | "backend"): ("send_request" | ... 7 more ... | "execute")[]

Determines which phases an executor can handle based on the action spec.

spec

type { method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<unknown, unknown, $ZodTypeInternals<...>>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async: ...

executor

type "frontend" | "backend"

returns

("send_request" | "receive_request" | "send_response" | "receive_response" | "send_error" | "receive_error" | "send" | "receive" | "execute")[]

get_handler_return_type
#

actions/action_codegen.ts view source

(spec: { method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<unknown, unknown, $ZodTypeInternals<...>>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async: true; } | { ...; } | { ...; }, phase: "send_request" | ... 7 more ... | "execute", imports: ImportBuilder, path_prefix: string): string

Gets the handler return type for a specific phase and spec. Also adds necessary imports to the ImportBuilder.

spec

type { method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<unknown, unknown, $ZodTypeInternals<...>>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async: ...

phase

type "send_request" | "receive_request" | "send_response" | "receive_response" | "send_error" | "receive_error" | "send" | "receive" | "execute"

imports

path_prefix

type string

returns

string

get_request_context
#

auth/request_context.ts view source

(c: Context<any, any, {}>): RequestContext | null

Get the request context from a Hono context, or null if unauthenticated.

c

the Hono context

type Context<any, any, {}>

returns

RequestContext | null

the request context, or null

get_route_error_schema
#

testing/assertions.ts view source

(lookup: Map<string, Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>>>, route: AppSurfaceRoute, status: number): ZodType<...> | undefined

Look up the merged error schema for a route+status from a pre-built schema lookup.

lookup

map from "METHOD /path" to merged error schemas

type Map<string, Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>>>

route

the surface route to look up

status

HTTP status code

type number

returns

ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined

get_route_input
#

http/route_spec.ts view source

<T>(c: Context<any, any, {}>): T

Get validated input from the Hono context.

Call this in route handlers after the input validation middleware has run. The type parameter should match the route's input schema.

c

type Context<any, any, {}>

returns

T

the validated request body

get_route_params
#

http/route_spec.ts view source

<T>(c: Context<any, any, {}>): T

Get validated URL path params from the Hono context.

Call this in route handlers after the params validation middleware has run. The type parameter should match the route's params schema.

TODO

c

type Context<any, any, {}>

returns

T

the validated path parameters

get_route_query
#

http/route_spec.ts view source

<T>(c: Context<any, any, {}>): T

Get validated URL query params from the Hono context.

Call this in route handlers after the query validation middleware has run. The type parameter should match the route's query schema.

c

type Context<any, any, {}>

returns

T

the validated query parameters

get_session_cookie
#

GrantPermitInput
#

has_env_vars
#

env/resolve.ts view source

(value: string): boolean

Check if a string contains unresolved env var references.

value

string to check

type string

returns

boolean

true if string contains $$VAR$$ patterns

has_role
#

auth/request_context.ts view source

(ctx: RequestContext, role: string, now?: Date): boolean

Check if a request context has an active permit for a given role.

Checks the permits already loaded in the context (no DB query).

ctx

the request context

role

the role to check

type string

now

current time (defaults to new Date(), pass for testability and hot-path efficiency)

type Date
default new Date()

returns

boolean

true if the actor has an active permit for the role

hash_api_token
#

auth/api_token.ts view source

(token: string): string

Hash an API token for storage using blake3.

token

the raw API token

type string

returns

string

hex-encoded blake3 hash

hash_password
#

auth/password_argon2.ts view source

(password: string): Promise<string>

Hash a password using Argon2id.

password

the plaintext password to hash

type string

returns

Promise<string>

the Argon2id hash string

hash_session_token
#

auth/session_queries.ts view source

(token: string): string

Hash a session token to its storage key using blake3.

token

the raw session token

type string

returns

string

hex-encoded blake3 hash

HelpCategory
#

cli/help.ts view source

HelpCategory<TCategory>

Category configuration for help display.

generics

TCategory

constraint string
default string

key

type TCategory

title

type string

HelpGenerator
#

cli/help.ts view source

HelpGenerator

Help generator returned by create_help.

generate_main_help

Generate main help text with all commands grouped by category.

type () => string

generate_command_help

Generate help text for a specific command.

type (command: string, meta: CommandMeta) => string

get_help_text

Get help text for a command or main help.

type (command?: string, subcommand?: string) => string

HelpOptions
#

cli/help.ts view source

HelpOptions<TCategory>

Configuration for create_help.

generics

TCategory

constraint string
default string

name

Application name (e.g., "tx", "zzz").

type string

version

Application version string.

type string

description

Short description for the main help header.

type string

commands

Command registry keyed by command path (e.g., "apply", "daemon start").

type Record<string, CommandMeta<TCategory>>

categories

Category display order for main help.

type Array<HelpCategory<TCategory>>

examples

Example commands for main help.

type Array<string>

global_args_schema

Zod schema for global arguments (shown in all help output).

type z.ZodType

use_colors

Whether to use ANSI colors in output. Defaults to true.

type boolean

ImportBuilder
#

actions/action_codegen.ts view source

Manages imports for generated code, building them on demand. Automatically optimizes type-only imports to use import type syntax.

Why this matters: - import type statements are completely removed during compilation - Mixed imports like import { type A, B } cannot be safely removed - This ensures optimal tree-shaking and smaller bundle sizes

examples

const imports = new ImportBuilder(); imports.add_types('./types.js', 'Foo', 'Bar'); imports.add('./utils.js', 'helper'); imports.add_type('./utils.js', 'HelperOptions'); imports.add('./action_specs.js', '* as specs'); // Generates: // import type {Foo, Bar} from './types.js'; // import {helper, type HelperOptions} from './utils.js'; // import * as specs from './action_specs.js';

imports

type Map<string, Map<string, ImportItem>>

add

Add a value import to be included in the generated code.

type (from: string, what: string): this

from

the module to import from

type string
what

what to import (value)

type string
returns this

add_type

Add a type import to be included in the generated code.

type (from: string, what: string): this

from

the module to import from

type string
what

what to import (type)

type string
returns this

add_many

Add multiple value imports from the same module.

type (from: string, ...items: string[]): this

from
type string
items
type string[]
returns this

add_types

Add multiple type imports from the same module.

type (from: string, ...items: string[]): this

from
type string
items
type string[]
returns this

build

Generate the import statements. If all imports from a module are types, uses import type syntax.

type (): string

returns string

has_imports

Check if the builder has any imports.

type (): boolean

returns boolean

preview

Preview what imports will be generated (useful for debugging).

type (): string[]

returns string[]

array of import statement strings

clear

Clear all imports.

type (): this

returns this

Invite
#

auth/invite_schema.ts view source

Invite

Invite row from the database.

id

type string

email

type Email | null

username

type Username | null

claimed_by

type string | null

claimed_at

type string | null

created_at

type string

created_by

type string | null

INVITE_INDEXES
#

INVITE_SCHEMA
#

auth/ddl.ts view source

"\nCREATE TABLE IF NOT EXISTS invite (\n id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n email TEXT,\n username TEXT,\n claimed_by UUID REFERENCES account(id) ON DELETE SET NULL,\n claimed_at TIMESTAMPTZ,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n created_by UUID REFERENCES actor(id) ON DELETE SET NU...

InviteJson
#

auth/invite_schema.ts view source

ZodObject<{ id: ZodString; email: ZodNullable<ZodEmail>; username: ZodNullable<ZodString>; claimed_by: ZodNullable<ZodString>; claimed_at: ZodNullable<...>; created_at: ZodString; created_by: ZodNullable<...>; }, $strict>

Zod schema for client-safe invite data.

InviteWithUsernamesJson
#

auth/invite_schema.ts view source

ZodObject<{ id: ZodString; email: ZodNullable<ZodEmail>; username: ZodNullable<ZodString>; claimed_by: ZodNullable<ZodString>; ... 4 more ...; claimed_by_username: ZodNullable<...>; }, $strict>

Zod schema for invite data with resolved creator/claimer usernames.

is_action_spec
#

actions/action_spec.ts view source

(value: unknown): value is { method: string; initiator: "frontend" | "backend" | "both"; side_effects: true | null; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; output: ZodType<...>; description: string; kind: "request_response"; auth: "public" | ... 2 more ... | { ...; }; async: true; } | { ...; } | { ...; }

value

type unknown

returns

boolean

IS_CI
#

is_daemon_running
#

cli/daemon.ts view source

(runtime: CommandDeps, pid: number): Promise<boolean>

Check if a process is running by PID.

runtime

runtime with command execution capability

pid

process ID to check

type number

returns

Promise<boolean>

true if the process is running

is_null_schema
#

http/schema_helpers.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean

Check if a schema is exactly z.null().

Uses Zod 4 type introspection (_zod.def.type) rather than runtime parsing to avoid false positives from z.nullable(z.string()) or similar schemas that accept null but also accept other values.

schema

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

boolean

is_permit_active
#

is_pg_unique_violation
#

db/pg_error.ts view source

(error: unknown): boolean

Check if an error is a PostgreSQL unique constraint violation (error code 23505).

error

the caught error

type unknown

returns

boolean

true if the error is a unique constraint violation

is_strict_object_schema
#

http/schema_helpers.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean

Check if a schema is a strict object (z.strictObject()).

Strict objects set catchall to ZodNever to reject unknown keys. Regular z.object() has catchall: undefined (strips unknown keys in Zod 4).

schema

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

boolean

is_trusted_ip
#

http/proxy.ts view source

(ip: string, proxies: ParsedProxy[]): boolean

Check whether ip matches any entry in the trusted proxy list.

Normalizes ip before matching (lowercase, IPv4-mapped IPv6 stripped).

ip

the IP address to check

type string

proxies

parsed proxy entries

type ParsedProxy[]

returns

boolean

KeeperError
#

Keyring
#

auth/keyring.ts view source

Keyring

Opaque keyring that encapsulates secret keys. Only exposes sign/verify operations, never the raw keys.

sign

Sign a value with HMAC SHA-256.

type (value: string) => Promise<string>

verify

Verify a signed value and extract the original. Tries all keys in order to support key rotation.

type (signed_value: string) => Promise<{value: string; key_index: number} | null>

load_config
#

cli/config.ts view source

<T>(runtime: FsReadDeps & LogDeps, path: string, schema: ZodType<T, unknown, $ZodTypeInternals<T, unknown>>): Promise<T | null>

Load CLI configuration from a JSON file with Zod schema validation.

runtime

runtime with file read capability

type FsReadDeps & LogDeps

path

path to the config JSON file

type string

schema

Zod schema to validate against

type ZodType<T, unknown, $ZodTypeInternals<T, unknown>>

returns

Promise<T | null>

parsed config, or null if file doesn't exist or is invalid

load_env
#

env/load.ts view source

<T extends z.ZodObject>(schema: T, get_env: (key: string) => string | undefined): output<T>

Load and validate env vars against a Zod schema.

Reads each key from the schema using get_env, then validates. Throws EnvValidationError on failure.

schema

Zod object schema defining expected env vars

type T

get_env

function to read an env var by key

type (key: string) => string | undefined

returns

output<T>

validated env object

load_env_file
#

env/dotenv.ts view source

(runtime: Pick<FsReadDeps, "read_file">, path: string): Promise<Record<string, string> | null>

Load and parse an env file.

runtime

runtime with read_file capability

type Pick<FsReadDeps, "read_file">

path

path to env file

type string

returns

Promise<Record<string, string> | null>

parsed env record, or null if file doesn't exist

Loadable
#

ui/loadable.svelte.ts view source

Base reactive state class with loading/error management.

Provides the common loading/error pattern shared by all state classes. Subclasses add domain-specific $state fields and methods that call the protected run helper for async operations.

generics

TError

default string

examples

class ItemsState extends Loadable { items: Array<Item> = $state([]); async fetch(): Promise<void> { await this.run(async () => { const response = await fetch('/api/items'); if (!response.ok) throw new Error('failed to fetch'); this.items = await response.json(); }); } }
// structured errors via map_error class FormState extends Loadable<{field: string; message: string}> { async submit(data: FormData): Promise<void> { await this.run( () => post_form(data), (e) => ({field: 'form', message: e instanceof Error ? e.message : 'unknown'}), ); } }

loading

error

type TError | null

error_data

The raw caught value from the last failed run(), for programmatic inspection.

type unknown

run

Run an async operation with loading/error handling.

Sets loading to true, clears error and error_data, runs fn, catches errors. Pass map_error to produce structured errors instead of strings.

type <T>(fn: () => Promise<T>, map_error?: ((e: unknown) => TError) | undefined): Promise<T | undefined>

protected
fn
type () => Promise<T>
map_error?
type ((e: unknown) => TError) | undefined
optional
returns Promise<T | undefined>

the result or undefined if the operation failed

reset

Reset loading and error state. Subclasses override to clear data.

type (): void

returns void

LocalCallActionSpec
#

actions/action_spec.ts view source

ZodObject<{ method: ZodString; initiator: ZodEnum<{ frontend: "frontend"; backend: "backend"; both: "both"; }>; side_effects: ZodUnion<readonly [ZodLiteral<true>, ZodNull]>; ... 5 more ...; auth: ZodDefault<...>; }, $strict>

Local calls can wrap synchronous or asynchronous actions, and are the escape hatch for remote APIs that do not support SAES.

log_db_factory_status
#

testing/db.ts view source

(factories: DbFactory[]): void

Log factory status to console.

factories

the database factories to report on

type DbFactory[]

returns

void

log_env_validation_error
#

env/load.ts view source

(error: EnvValidationError, label?: string | undefined): void

Log formatted env validation issues to stderr.

Handles the common case: labels each Zod issue with an optional prefix. Callers who want app-specific "getting started" instructions should check error.all_undefined before calling this.

error

the env validation error

label?

optional prefix for log lines (e.g., 'tx daemon', 'env')

type string | undefined
optional

returns

void

log_startup_summary
#

server/startup.ts view source

(surface: AppSurface, log: Logger, env_values?: Record<string, unknown> | undefined): void

Log a startup summary from an AppSurface.

Logs route count, middleware count, env breakdown (when non-empty), and event/channel counts (when non-empty). When env_values is provided, non-secret values are logged and secrets are masked with ***.

surface

the app surface to summarize

log

the logger instance

type Logger

env_values?

optional env values to log (secrets are masked)

type Record<string, unknown> | undefined
optional

returns

void

LogDeps
#

runtime/deps.ts view source

LogDeps

Warning/diagnostic output.

warn

Log a warning message.

type (...args: Array<unknown>) => void

LoginForm
#

LogoutButton
#

map_action_auth
#

MASKED_VALUE
#

MenuLink
#

merge_error_schemas
#

http/schema_helpers.ts view source

(spec: { auth: RouteAuth; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; params?: ZodObject<$ZodLooseShape, $strip> | undefined; query?: ZodObject<...> | undefined; rate_limit?: RateLimitKey | undefined; errors?: Partial<...> | undefined; }, middleware_errors?: Partial<...> | ... 1 more ... | undefined): Partial<...> | null

Merge auto-derived, middleware, and explicit error schemas for a route spec.

Merge order: derived -> middleware -> explicit route errors. Later layers override earlier ones for the same status code.

spec

the route spec (needs auth, input, params, rate_limit, errors)

type { auth: RouteAuth; input: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>; params?: ZodObject<$ZodLooseShape, $strip> | undefined; query?: ZodObject<...> | undefined; rate_limit?: RateLimitKey | undefined; errors?: Partial<...> | undefined; }

middleware_errors?

optional middleware error schemas

type Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>> | null | undefined
optional

returns

Partial<Record<number, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>> | null

merged error schemas, or null if empty

middleware_applies
#

http/schema_helpers.ts view source

(mw_path: string, route_path: string): boolean

Check if a middleware path pattern applies to a route path.

Supports Hono-style patterns: - /api/* matches /api/anything - /api/tx/* matches /api/tx/runs but not /api/account/login - Exact match: /health matches /health

mw_path

the middleware path pattern

type string

route_path

the route path

type string

returns

boolean

MiddlewareSpec
#

Migration
#

db/migrate.ts view source

Migration

A migration: either a bare function or a named object with an up function.

Named migrations include their name in error messages for debuggability.

MigrationFn
#

db/migrate.ts view source

MigrationFn

A single migration function that receives a Db and applies DDL/DML.

Runs inside a transaction โ€” throw to rollback.

MigrationNamespace
#

db/migrate.ts view source

MigrationNamespace

A named group of ordered migrations.

Array index = version number: migrations[0] is version 0, etc.

namespace

type string

migrations

type Array<Migration>

MigrationResult
#

db/migrate.ts view source

MigrationResult

Result of running migrations for a single namespace.

namespace

type string

from_version

type number

to_version

type number

migrations_applied

type number

MigrationStatus
#

db/status.ts view source

MigrationStatus

Migration status for a single namespace.

namespace

type string

current_version

Current applied version (0 if never migrated).

type number

available_version

Total available migrations in the namespace.

type number

up_to_date

Whether the schema is up to date.

type boolean

MockExitError
#

runtime/mock.ts view source

Error thrown when mock runtime.exit() is called.

Tests can catch this to verify exit behavior.

inheritance

extends:
  • Error

code

type number

readonly

constructor

type new (code: number): MockExitError

code
type number

MockRuntime
#

runtime/mock.ts view source

MockRuntime

Mock RuntimeDeps with observable state for assertions.

inheritance

extends:

mock_env

Mock environment variables.

type Map<string, string>

mock_fs

Mock file system (path -> content).

type Map<string, string>

mock_dirs

Mock directories that exist.

type Set<string>

exit_calls

Exit calls recorded (exit codes).

type Array<number>

command_calls

Commands executed.

type Array<{cmd: string; args: Array<string>}>

command_inherit_calls

Commands executed with inherit.

type Array<{cmd: string; args: Array<string>}>

stdout_writes

Stdout writes recorded.

type Array<string>

mock_command_results

Mock command results (cmd -> result).

type Map<string, CommandResult>

stdin_buffer

Stdin buffer for input simulation.

type Uint8Array | null

NginxValidationResult
#

server/validate_nginx.ts view source

NginxValidationResult

Result of validating an nginx config template string.

ok

type boolean

warnings

type Array<string>

errors

type Array<string>

no_nested_transaction
#

db/db.ts view source

<T>(fn: (tx_db: Db) => Promise<T>): Promise<T>

Sentinel transaction function for transaction-scoped Db instances.

Throws immediately โ€” nested transactions are not supported. Used by driver adapters when constructing the inner Db passed to transaction callbacks.

fn

type (tx_db: Db) => Promise<T>

returns

Promise<T>

normalize_ip
#

http/proxy.ts view source

(ip: string): string

Normalize an IP address for consistent matching and storage.

- Strips ::ffff: prefix from IPv4-mapped IPv6 addresses (e.g. ::ffff:127.0.0.1 โ†’ 127.0.0.1) - Lowercases for case-insensitive IPv6 comparison - Idempotent: calling twice produces the same result - Safe on non-IP strings: normalize_ip('unknown') returns 'unknown'

ip

IP address string to normalize

type string

returns

string

OpenSignupToggle
#

parse_allowed_origins
#

http/origin.ts view source

(env_value: string | undefined): RegExp[]

Parses ALLOWED_ORIGINS env var into regex matchers for request source verification. Origin allowlisting for locally-running services โ€” not the CSRF layer (that's SameSite: strict on session cookies).

Accepts comma-separated patterns with limited wildcards: - Exact origins: https://api.fuz.dev - Wildcard subdomains: https://*.fuz.dev (matches exactly one subdomain level) - Multiple wildcards: https://*.staging.*.fuz.dev (for deep subdomains) - Wildcard ports: http://localhost:* (matches any port or no port) - IPv6 addresses: http://[::1]:3000, https://[2001:db8::1] - Combined: https://*.fuz.dev:*

Examples: - http://localhost:3000,https://prod.fuz.dev - https://*.api.fuz.dev,http://127.0.0.1:* - http://[::1]:*,https://*.*.corp.fuz.dev:*

env_value

type string | undefined

returns

RegExp[]

throws

  • if - any individual pattern is invalid (missing protocol, partial wildcards, etc.)

parse_command_args
#

cli/args.ts view source

<T extends Record<string, unknown>>(remaining: ParsedArgs, schema: ZodType<T, unknown, $ZodTypeInternals<T, unknown>>): ParseResult<T>

Parse command-specific args against a Zod schema.

Validates remaining args (after global flag extraction) with alias expansion and returns a typed result or a prettified error string.

remaining

remaining args after global flag extraction

type ParsedArgs

schema

Zod schema for the command

type ZodType<T, unknown, $ZodTypeInternals<T, unknown>>

returns

ParseResult<T>

parse result with typed data or error message

parse_db_name
#

dev/setup.ts view source

(url: string): string | null

Extract the database name from a PostgreSQL URL.

url

type string

returns

string | null

the database name, or null if the URL is invalid or has no path

parse_dotenv
#

env/dotenv.ts view source

(content: string): Record<string, string>

Parse a dotenv-format string into a record.

content

dotenv file content

type string

returns

Record<string, string>

parsed key-value pairs

parse_proxy_entry
#

http/proxy.ts view source

(entry: string): ParsedProxy

Parse a trusted proxy entry string into a structured form.

Accepts plain IPs ('127.0.0.1', '::1') and CIDR notation ('10.0.0.0/8', 'fe80::/10'). Plain IPs are normalized (lowercase, IPv4-mapped IPv6 stripped) and validated. CIDR prefixes are validated against address family bounds.

entry

IP address or CIDR notation

type string

returns

ParsedProxy

throws

  • on - invalid IP, invalid CIDR network, or NaN/negative/over-range prefix

parse_response_error
#

ui/ui_fetch.ts view source

(response: Response, fallback?: string | undefined): Promise<string>

Safely extract an error message from a non-ok response.

Handles responses with non-JSON bodies (e.g. HTML 404 pages) that would throw on response.json().

response

the non-ok response

type Response

fallback?

fallback message when no .error field is found

type string | undefined
optional

returns

Promise<string>

error message string

parse_session
#

auth/session_cookie.ts view source

<TIdentity>(signed_value: string | undefined, keyring: Keyring, options: SessionOptions<TIdentity>, now_seconds?: number | undefined): Promise<ParsedSession<...> | null | undefined>

Parse a signed session cookie value.

The signed value format is ${encode(identity)}:${expires_at}. Tries all keys in order to support key rotation.

signed_value

the raw cookie value (signed)

type string | undefined

keyring

key ring for verification

type Keyring

options

session configuration with decode logic

type SessionOptions<TIdentity>

now_seconds?

current time in seconds (for testing)

type number | undefined
optional

returns

Promise<ParsedSession<TIdentity> | null | undefined>

ParsedSession if valid, null if invalid/expired, undefined if empty/missing

ParsedProxy
#

ParsedSession
#

auth/session_cookie.ts view source

ParsedSession<TIdentity>

Result of parsing a signed session cookie.

generics

TIdentity

identity

The decoded identity.

type TIdentity

should_refresh_signature

True if verified with a non-primary key (needs re-signing).

type boolean

key_index

Index of the key that verified the signature.

type number

ParseResult
#

Password
#

auth/password.ts view source

ZodString

Password for account creation or password change โ€” enforces current length policy. Also usable for client-side UX validation.

PASSWORD_LENGTH_MAX
#

PASSWORD_LENGTH_MIN
#

PasswordHashDeps
#

auth/password.ts view source

PasswordHashDeps

Injectable password hashing dependencies.

Groups all three password operations for injection in route factories and other callers. Use Pick<PasswordHashDeps, ...> when only a subset is needed:

examples

// Login handler only needs verification password: Pick<PasswordHashDeps, 'verify_password' | 'verify_dummy'>; // Bootstrap only needs hashing password: Pick<PasswordHashDeps, 'hash_password'>;

hash_password

type (password: string) => Promise<string>

verify_password

type (password: string, password_hash: string) => Promise<boolean>

verify_dummy

type (password: string) => Promise<boolean>

PasswordProvided
#

auth/password.ts view source

ZodString

Password submitted for login or verification โ€” minimal validation for forward-compatibility if length requirements change.

PayloadTooLargeError
#

http/error_schemas.ts view source

ZodObject<{ error: ZodLiteral<"payload_too_large">; }, $loose>

Payload too large error โ€” returned when the request body exceeds the size limit.

PermissionError
#

http/error_schemas.ts view source

ZodObject<{ error: ZodLiteral<"insufficient_permissions">; required_role: ZodString; }, $loose>

Permission error โ€” returned by require_role() when the required role is missing.

Permit
#

auth/account_schema.ts view source

Permit

Permit โ€” time-bounded, revocable grant of a role to an actor.

id

type string

actor_id

type string

role

type string

created_at

type string

expires_at

type string | null

revoked_at

type string | null

revoked_by

type string | null

granted_by

type string | null

PERMIT_INDEXES
#

PERMIT_SCHEMA
#

auth/ddl.ts view source

"\nCREATE TABLE IF NOT EXISTS permit (\n id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n actor_id UUID NOT NULL REFERENCES actor(id) ON DELETE CASCADE,\n role TEXT NOT NULL,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n expires_at TIMESTAMPTZ,\n revoked_at TIMESTAMPTZ,\n revoked_by UUID REFERENCES actor...

PermitHistoryEventJson
#

auth/audit_log_schema.ts view source

ZodObject<{ id: ZodString; seq: ZodNumber; event_type: ZodEnum<{ login: "login"; logout: "logout"; bootstrap: "bootstrap"; signup: "signup"; password_change: "password_change"; session_revoke: "session_revoke"; ... 8 more ...; app_settings_update: "app_settings_update"; }>; ... 8 more ...; target_username: ZodNullab...

Zod schema for permit history events with resolved usernames.

PermitSummaryJson
#

auth/account_schema.ts view source

ZodObject<{ id: ZodString; role: ZodString; created_at: ZodString; expires_at: ZodNullable<ZodString>; granted_by: ZodNullable<ZodString>; }, $strict>

Zod schema for the permit summary returned in admin account listings.

Popover
#

ui/popover.svelte.ts view source

Class that manages state and provides actions for popovers.

visible

Whether the popover is currently visible.

position

Position of the popover relative to its trigger.

type Position

align

Alignment along the position edge.

type Alignment

offset

Distance from the position.

disable_outside_click

Whether to disable closing when clicking outside.

popover_class

Custom class for the popover.

constructor

type new (params?: PopoverParameters | undefined): Popover

params?
type PopoverParameters | undefined
optional

update

Updates the popover configuration.

type (params: PopoverParameters): void

params
returns void

show

Shows the popover.

type (): void

returns void

hide

Hides the popover.

type (): void

returns void

toggle

Toggles the popover visibility.

type (visible?: boolean): void

visible
type boolean
default !this.visible
returns void

container

Attachment for the container element.

type Attachment<HTMLElement>

trigger

Attachment factory for the trigger element that shows/hides the popover.

content

Attachment factory for the popover content element.

PopoverButton
#

ui/PopoverButton.svelte view source

position?

type Position | undefined
optional

align?

type Alignment | undefined
optional

disable_outside_click?

type boolean | undefined
optional

popover_class?

type string | undefined
optional

popover_attrs?

type SvelteHTMLElements['div'] | undefined
optional

popover_content

type Snippet<[popover: Popover]>

popover_container_attrs?

type SvelteHTMLElements['div'] | undefined
optional

button?

type Snippet<[popover: Popover]> | undefined
optional

children?

type Snippet<[popover: Popover]> | undefined
optional

PopoverContentParameters
#

PopoverParameters
#

ui/popover.svelte.ts view source

PopoverParameters

Parameters for configuring the popover.

position

Position of the popover relative to its trigger.

align

Alignment along the position edge.

offset

Distance from the position.

type string

disable_outside_click

Whether to disable closing when clicking outside.

type boolean

popover_class

Custom class for the popover content.

type string

onshow

Optional callback when popover is shown.

type () => void

onhide

Optional callback when popover is hidden.

type () => void

PopoverTriggerParameters
#

Position
#

prefix_route_specs
#

http/route_spec.ts view source

(prefix: string, specs: RouteSpec[]): RouteSpec[]

Prepend a prefix to all route spec paths.

prefix

the path prefix (e.g. /api/account)

type string

specs

route specs to prefix

type RouteSpec[]

returns

RouteSpec[]

new array of specs with prefixed paths

PrimaryKeyInfo
#

process_session_cookie
#

ProcessDeps
#

ProcessSessionResult
#

auth/session_cookie.ts view source

ProcessSessionResult<TIdentity>

Result of processing a session cookie.

generics

TIdentity

valid

Whether the session is valid.

type boolean

action

Action the adapter should take.

type 'none' | 'clear' | 'refresh'

new_signed_value

New signed value when action is 'refresh'.

type string

identity

The decoded identity if the cookie was valid.

type TIdentity

ProxyOptions
#

http/proxy.ts view source

ProxyOptions

Configuration for trusted proxy resolution.

trusted_proxies

Trusted proxy IPs or CIDR ranges (e.g. '127.0.0.1', '10.0.0.0/8', '::1').

type Array<string>

get_connection_ip

Extract the raw TCP connection IP from the Hono context.

type (c: Context) => string | undefined

log

Optional logger for proxy resolution diagnostics.

type Logger

query_account_by_email
#

auth/account_queries.ts view source

(deps: QueryDeps, email: string): Promise<Account | undefined>

Find an account by email (case-insensitive).

deps

email

type string

returns

Promise<Account | undefined>

query_account_by_id
#

query_account_by_username
#

auth/account_queries.ts view source

(deps: QueryDeps, username: string): Promise<Account | undefined>

Find an account by username (case-insensitive).

deps

username

type string

returns

Promise<Account | undefined>

query_account_by_username_or_email
#

auth/account_queries.ts view source

(deps: QueryDeps, input: string): Promise<Account | undefined>

Find an account by username or email.

If the input contains @, tries email lookup first then username. Otherwise tries username first then email. This supports a single login field that accepts either format.

deps

query dependencies

input

username or email address

type string

returns

Promise<Account | undefined>

the matching account, or undefined

query_account_has_any
#

query_actor_by_account
#

auth/account_queries.ts view source

(deps: QueryDeps, account_id: string): Promise<Actor | undefined>

Find the actor for an account.

For v1, each account has exactly one actor.

deps

account_id

type string

returns

Promise<Actor | undefined>

query_actor_by_id
#

query_admin_account_list
#

auth/account_queries.ts view source

(deps: QueryDeps): Promise<{ account: { id: string; username: string; email: string | null; email_verified: boolean; created_at: string; updated_at: string; updated_by: string | null; }; actor: { ...; } | null; permits: { ...; }[]; }[]>

List all accounts with their actors and active permits for admin display.

Uses 3 flat queries instead of N+1 per-account loops.

deps

query dependencies

returns

Promise<{ account: { id: string; username: string; email: string | null; email_verified: boolean; created_at: string; updated_at: string; updated_by: string | null; }; actor: { id: string; name: string; } | null; permits: { ...; }[]; }[]>

admin account entries sorted by creation date

query_api_token_enforce_limit
#

auth/api_token_queries.ts view source

(deps: QueryDeps, account_id: string, max_tokens: number): Promise<number>

Enforce a per-account token limit by evicting the oldest tokens.

Race safety: this function must run inside a transaction alongside the INSERT that created the new token. The caller (POST /tokens/create) uses the default transaction: true (framework-managed transaction wrapping in apply_route_specs), ensuring the INSERT + enforce_limit pair is atomic โ€” concurrent token creation cannot interleave.

deps

query dependencies (must be transaction-scoped)

account_id

the account to enforce the limit for

type string

max_tokens

maximum number of tokens to keep

type number

returns

Promise<number>

the number of tokens evicted

query_api_token_list_for_account
#

auth/api_token_queries.ts view source

(deps: QueryDeps, account_id: string): Promise<Omit<ApiToken, "token_hash">[]>

List all tokens for an account (does not include hashes).

Columns are enumerated explicitly to exclude token_hash. Must be updated if the api_token table gains new columns.

deps

account_id

type string

returns

Promise<Omit<ApiToken, "token_hash">[]>

query_app_settings_load
#

query_app_settings_load_with_username
#

auth/app_settings_queries.ts view source

(deps: QueryDeps): Promise<{ open_signup: boolean; updated_at: string | null; updated_by: string | null; updated_by_username: string | null; }>

Load the current app settings with resolved updater username.

deps

query dependencies

returns

Promise<{ open_signup: boolean; updated_at: string | null; updated_by: string | null; updated_by_username: string | null; }>

the app settings with updated_by_username

query_app_settings_update
#

auth/app_settings_queries.ts view source

(deps: QueryDeps, open_signup: boolean, actor_id: string): Promise<AppSettings>

Update app settings and return the updated row.

deps

query dependencies

open_signup

new value for the open_signup toggle

type boolean

actor_id

the actor making the change

type string

returns

Promise<AppSettings>

the updated app settings row

query_audit_log
#

auth/audit_log_queries.ts view source

<T extends AuditEventType>(deps: QueryDeps, input: AuditLogInput<T>): Promise<AuditLogEvent>

Insert an audit log entry.

Uses RETURNING * to return the full inserted row including DB-assigned fields (id, seq, created_at).

In DEV mode, validates metadata against the per-event-type schema before writing (warns on mismatch, never throws).

deps

query dependencies

input

the audit event to record

type AuditLogInput<T>

returns

Promise<AuditLogEvent>

the inserted audit log row

query_audit_log_cleanup_before
#

auth/audit_log_queries.ts view source

(deps: QueryDeps, before: Date): Promise<number>

Delete audit log entries older than the given date.

deps

query dependencies

before

delete entries created before this date

type Date

returns

Promise<number>

the number of entries deleted

query_audit_log_list
#

auth/audit_log_queries.ts view source

(deps: QueryDeps, options?: AuditLogListOptions | undefined): Promise<AuditLogEvent[]>

List audit log entries, newest first.

deps

query dependencies

options?

filters and pagination

type AuditLogListOptions | undefined
optional

returns

Promise<AuditLogEvent[]>

matching audit log entries

query_audit_log_list_for_account
#

auth/audit_log_queries.ts view source

(deps: QueryDeps, account_id: string, limit?: number): Promise<AuditLogEvent[]>

List audit log entries related to an account (as actor or target).

deps

query dependencies

account_id

the account to query for

type string

limit

maximum entries to return

type number
default AUDIT_LOG_DEFAULT_LIMIT

returns

Promise<AuditLogEvent[]>

query_audit_log_list_permit_history
#

auth/audit_log_queries.ts view source

(deps: QueryDeps, limit?: number, offset?: number): Promise<{ id: string; seq: number; event_type: "login" | "logout" | "bootstrap" | "signup" | "password_change" | "session_revoke" | ... 8 more ... | "app_settings_update"; ... 8 more ...; target_username: string | null; }[]>

List permit grant/revoke events with resolved usernames.

deps

query dependencies

limit

maximum entries to return

type number
default AUDIT_LOG_DEFAULT_LIMIT

offset

number of entries to skip

type number
default 0

returns

Promise<{ id: string; seq: number; event_type: "login" | "logout" | "bootstrap" | "signup" | "password_change" | "session_revoke" | "session_revoke_all" | "token_create" | "token_revoke" | ... 5 more ... | "app_settings_update"; ... 8 more ...; target_username: string | null; }[]>

permit history events with username and target_username

query_audit_log_list_with_usernames
#

auth/audit_log_queries.ts view source

(deps: QueryDeps, options?: AuditLogListOptions | undefined): Promise<{ id: string; seq: number; event_type: "login" | "logout" | "bootstrap" | "signup" | ... 10 more ... | "app_settings_update"; ... 8 more ...; target_username: string | null; }[]>

List audit log entries with resolved usernames, newest first.

deps

query dependencies

options?

filters and pagination

type AuditLogListOptions | undefined
optional

returns

Promise<{ id: string; seq: number; event_type: "login" | "logout" | "bootstrap" | "signup" | "password_change" | "session_revoke" | "session_revoke_all" | "token_create" | "token_revoke" | ... 5 more ... | "app_settings_update"; ... 8 more ...; target_username: string | null; }[]>

matching audit log entries with username and target_username

query_create_account
#

query_create_account_with_actor
#

auth/account_queries.ts view source

(deps: QueryDeps, input: CreateAccountInput): Promise<{ account: Account; actor: Actor; }>

Create an account and its actor in a single operation.

For v1, every account gets exactly one actor with the same name as the username.

deps

query dependencies

input

the account fields

returns

Promise<{ account: Account; actor: Actor; }>

the created account and actor

query_create_actor
#

auth/account_queries.ts view source

(deps: QueryDeps, account_id: string, name: string): Promise<Actor>

Create a new actor for an account.

deps

query dependencies

account_id

the owning account

type string

name

display name (defaults to account username)

type string

returns

Promise<Actor>

the created actor

query_create_api_token
#

auth/api_token_queries.ts view source

(deps: QueryDeps, id: string, account_id: string, name: string, token_hash: string, expires_at?: Date | null | undefined): Promise<ApiToken>

Store a new API token (the hash, not the raw token).

deps

query dependencies

id

the public token id (e.g. tok_abc123)

type string

account_id

the owning account

type string

name

human-readable name

type string

token_hash

blake3 hash of the raw token

type string

expires_at?

optional expiration

type Date | null | undefined
optional

returns

Promise<ApiToken>

the stored token record

query_create_invite
#

query_create_session
#

auth/session_queries.ts view source

(deps: QueryDeps, token_hash: string, account_id: string, expires_at: Date): Promise<void>

Create a new auth session.

deps

query dependencies

token_hash

blake3 hash of the session token (use hash_session_token)

type string

account_id

the account this session belongs to

type string

expires_at

when the session expires

type Date

returns

Promise<void>

query_db_status
#

db/status.ts view source

(db: Db, namespaces?: MigrationNamespace[] | undefined): Promise<DbStatus>

Query database status including connectivity, tables, and migration versions.

Designed for CLI db:status commands. Does not modify the database.

db

the database instance

type Db

namespaces?

migration namespaces to check versions for

type MigrationNamespace[] | undefined
optional

returns

Promise<DbStatus>

a snapshot of database status

query_delete_account
#

query_grant_permit
#

auth/permit_queries.ts view source

(deps: QueryDeps, input: GrantPermitInput): Promise<Permit>

Grant a permit to an actor. Idempotent โ€” if an active permit already exists for this actor and role, returns the existing permit instead of creating a duplicate.

deps

query dependencies

input

the permit fields

returns

Promise<Permit>

the created or existing active permit

query_invite_claim
#

auth/invite_queries.ts view source

(deps: QueryDeps, invite_id: string, account_id: string): Promise<boolean>

Claim an invite by setting the claimed_by and claimed_at fields.

deps

query dependencies

invite_id

the invite to claim

type string

account_id

the account claiming the invite

type string

returns

Promise<boolean>

true if the invite was claimed, false if already claimed or not found

query_invite_delete_unclaimed
#

auth/invite_queries.ts view source

(deps: QueryDeps, id: string): Promise<boolean>

Delete an unclaimed invite.

deps

query dependencies

id

the invite id

type string

returns

Promise<boolean>

true if deleted, false if not found or already claimed

query_invite_find_unclaimed_by_email
#

auth/invite_queries.ts view source

(deps: QueryDeps, email: string): Promise<Invite | undefined>

Find an unclaimed invite by email (case-insensitive).

deps

email

type string

returns

Promise<Invite | undefined>

query_invite_find_unclaimed_by_username
#

auth/invite_queries.ts view source

(deps: QueryDeps, username: string): Promise<Invite | undefined>

Find an unclaimed invite by username (case-insensitive).

deps

username

type string

returns

Promise<Invite | undefined>

query_invite_find_unclaimed_match
#

auth/invite_queries.ts view source

(deps: QueryDeps, email: string | null, username: string): Promise<Invite | undefined>

Find an unclaimed invite matching email and/or username using three scoping modes:

- Email-only invite (email set, username NULL) โ†’ matches only if signup provides matching email. - Username-only invite (username set, email NULL) โ†’ matches only if signup provides matching username. - Both-field invite (both set) โ†’ requires BOTH email and username to match.

deps

query dependencies

email

email to match (or null if signup provides none)

type string | null

username

username to match

type string

returns

Promise<Invite | undefined>

the matching invite, or undefined

query_invite_list_all
#

query_invite_list_all_with_usernames
#

auth/invite_queries.ts view source

(deps: QueryDeps): Promise<{ id: string; email: string | null; username: string | null; claimed_by: string | null; claimed_at: string | null; created_at: string; created_by: string | null; created_by_username: string | null; claimed_by_username: string | null; }[]>

List all invites with resolved creator/claimer usernames, newest first.

deps

query dependencies

returns

Promise<{ id: string; email: string | null; username: string | null; claimed_by: string | null; claimed_at: string | null; created_at: string; created_by: string | null; created_by_username: string | null; claimed_by_username: string | null; }[]>

invites with created_by_username and claimed_by_username

query_permit_find_account_id_for_role
#

auth/permit_queries.ts view source

(deps: QueryDeps, role: string): Promise<string | null>

Find the account ID of an account that holds an active permit for a given role.

Joins permit โ†’ actor โ†’ account. Returns the first match, or null if none.

deps

query dependencies

role

the role to search for

type string

returns

Promise<string | null>

the account ID, or null

query_permit_find_active_for_actor
#

auth/permit_queries.ts view source

(deps: QueryDeps, actor_id: string): Promise<Permit[]>

Find all active (non-revoked, non-expired) permits for an actor.

deps

actor_id

type string

returns

Promise<Permit[]>

query_permit_has_role
#

auth/permit_queries.ts view source

(deps: QueryDeps, actor_id: string, role: string): Promise<boolean>

Check if an actor has an active permit for a given role.

deps

actor_id

type string

role

type string

returns

Promise<boolean>

query_permit_list_for_actor
#

auth/permit_queries.ts view source

(deps: QueryDeps, actor_id: string): Promise<Permit[]>

List all permits for an actor (including revoked/expired).

deps

actor_id

type string

returns

Promise<Permit[]>

query_permit_revoke_role
#

auth/permit_queries.ts view source

(deps: QueryDeps, actor_id: string, role: string, revoked_by: string | null): Promise<boolean>

Revoke the active permit for an actor with a given role.

Due to the unique partial index on (actor_id, role) WHERE revoked_at IS NULL, at most one active permit exists per actor+role combination.

deps

query dependencies

actor_id

the actor whose permit to revoke

type string

role

the role to revoke

type string

revoked_by

the actor who revoked it (for audit trail)

type string | null

returns

Promise<boolean>

true if a permit was revoked, false if none was active

query_revoke_all_api_tokens_for_account
#

auth/api_token_queries.ts view source

(deps: QueryDeps, account_id: string): Promise<number>

Revoke all tokens for an account.

deps

query dependencies

account_id

the account whose tokens to revoke

type string

returns

Promise<number>

the number of tokens revoked

query_revoke_api_token_for_account
#

auth/api_token_queries.ts view source

(deps: QueryDeps, id: string, account_id: string): Promise<boolean>

Revoke a token only if it belongs to the specified account.

Prevents cross-account token revocation.

deps

query dependencies

id

the public token id

type string

account_id

the account that must own the token

type string

returns

Promise<boolean>

true if a token was revoked, false if not found or wrong account

query_revoke_permit
#

auth/permit_queries.ts view source

(deps: QueryDeps, permit_id: string, actor_id: string, revoked_by: string | null): Promise<{ id: string; role: string; } | null>

Revoke a permit by id, constrained to a specific actor.

Requires actor_id to prevent cross-account revocation (IDOR guard). Returns null if the permit is not found, already revoked, or belongs to a different actor. Returns {id, role} on success for audit logging.

deps

query dependencies

permit_id

the permit to revoke

type string

actor_id

the actor that must own the permit

type string

revoked_by

the actor who revoked it (for audit trail)

type string | null

returns

Promise<{ id: string; role: string; } | null>

query_session_cleanup_expired
#

query_session_enforce_limit
#

auth/session_queries.ts view source

(deps: QueryDeps, account_id: string, max_sessions: number): Promise<number>

Enforce a per-account session limit by evicting the oldest sessions.

Keeps the newest max_sessions sessions and deletes the rest.

Race safety: this function must run inside a transaction alongside the INSERT that created the new session. All callers satisfy this requirement: - POST /login and POST /tokens/create use the default transaction: true (framework-managed transaction wrapping in apply_route_specs) - POST /bootstrap and POST /signup manage their own transactions and pass the transaction-scoped deps to create_session_and_set_cookie

The transaction ensures the INSERT + enforce_limit pair is atomic โ€” concurrent session creation cannot interleave between the two statements.

deps

query dependencies (must be transaction-scoped)

account_id

the account to enforce the limit for

type string

max_sessions

maximum number of sessions to keep

type number

returns

Promise<number>

the number of sessions evicted

query_session_get_valid
#

auth/session_queries.ts view source

(deps: QueryDeps, token_hash: string): Promise<AuthSession | undefined>

Get a session if it exists, is not expired, and has not been revoked.

deps

query dependencies

token_hash

blake3 hash of the session token

type string

returns

Promise<AuthSession | undefined>

query_session_list_all_active
#

auth/session_queries.ts view source

(deps: QueryDeps, limit?: number): Promise<(AuthSession & { username: string; })[]>

List all active sessions across all accounts with usernames.

deps

query dependencies

limit

maximum entries to return

type number
default 200

returns

Promise<(AuthSession & { username: string; })[]>

active sessions joined with account usernames, newest activity first

query_session_list_for_account
#

auth/session_queries.ts view source

(deps: QueryDeps, account_id: string, limit?: number): Promise<AuthSession[]>

List sessions for an account, newest first.

deps

account_id

type string

limit

type number
default 50

returns

Promise<AuthSession[]>

query_session_revoke_all_for_account
#

auth/session_queries.ts view source

(deps: QueryDeps, account_id: string): Promise<number>

Revoke all sessions for an account.

deps

account_id

type string

returns

Promise<number>

the number of sessions revoked

query_session_revoke_by_hash
#

auth/session_queries.ts view source

(deps: QueryDeps, token_hash: string): Promise<void>

Revoke (delete) a session by its token hash.

No account_id constraint โ€” caller must ensure the hash comes from a trusted source (e.g. the authenticated session cookie). For user-facing revocation of a specific session by ID, prefer query_session_revoke_for_account which includes an IDOR guard.

deps

token_hash

type string

returns

Promise<void>

query_session_revoke_for_account
#

auth/session_queries.ts view source

(deps: QueryDeps, token_hash: string, account_id: string): Promise<boolean>

Revoke a session only if it belongs to the specified account.

Prevents cross-account session revocation.

deps

query dependencies

token_hash

blake3 hash of the session token

type string

account_id

the account that must own the session

type string

returns

Promise<boolean>

true if a session was revoked, false if not found or wrong account

query_session_touch
#

query_update_account_password
#

auth/account_queries.ts view source

(deps: QueryDeps, id: string, password_hash: string, updated_by: string | null): Promise<void>

Update the password hash for an account.

deps

id

type string

password_hash

type string

updated_by

type string | null

returns

Promise<void>

query_validate_api_token
#

auth/api_token_queries.ts view source

(deps: ApiTokenQueryDeps, raw_token: string, ip: string | undefined, pending_effects: Promise<void>[] | undefined): Promise<ApiToken | undefined>

Validate a raw API token and return the token record.

Hashes the token with blake3, looks up the hash, and checks expiration. Updates last_used_at and last_used_ip on success (fire-and-forget โ€” errors logged, never thrown).

deps

query dependencies with logger

raw_token

the raw API token from the Authorization header

type string

ip

the client IP address (for audit)

type string | undefined

pending_effects

optional array to register the usage-tracking effect for later awaiting

type Promise<void>[] | undefined

returns

Promise<ApiToken | undefined>

the token record if valid, or undefined

QueryDeps
#

rate_limit_exceeded_response
#

rate_limiter.ts view source

(c: Context<any, any, {}>, retry_after: number): Response

Build a 429 rate-limit-exceeded JSON response with Retry-After header.

c

Hono context

type Context<any, any, {}>

retry_after

seconds until the client should retry

type number

returns

Response

a 429 Response

RateLimiter
#

rate_limiter.ts view source

In-memory sliding window rate limiter.

Stores an array of timestamps per key. On check/record, timestamps outside the window are pruned. retry_after reports seconds until the oldest active timestamp expires.

Parameters that accept RateLimiter | null (e.g. ip_rate_limiter, login_account_rate_limiter) silently disable rate limiting when null is passed โ€” no checks are performed and all requests are allowed through.

options

type RateLimiterOptions

readonly

constructor

type new (options: RateLimiterOptions): RateLimiter

options

check

Check whether key is allowed without recording an attempt.

type (key: string, now?: number): RateLimitResult

key

rate limit key (e.g. IP address)

type string
now

current timestamp in ms (defaults to Date.now())

type number
default Date.now()

record

Record a failed attempt for key and return the updated result.

type (key: string, now?: number): RateLimitResult

key

rate limit key (e.g. IP address)

type string
now

current timestamp in ms (defaults to Date.now())

type number
default Date.now()

reset

Clear all attempts for key (e.g. after successful login).

type (key: string): void

key
type string
returns void

cleanup

Remove entries whose timestamps are all outside the window.

type (now?: number): void

now

current timestamp in ms (defaults to Date.now())

type number
default Date.now()
returns void

dispose

Stop the cleanup timer. Safe to call multiple times.

type (): void

returns void

RateLimiterOptions
#

rate_limiter.ts view source

RateLimiterOptions

Configuration for a rate limiter instance.

max_attempts

Maximum allowed attempts within the window.

type number

window_ms

Sliding window duration in milliseconds.

type number

cleanup_interval_ms

Interval for pruning stale entries (0 disables the timer).

type number

RateLimitError
#

http/error_schemas.ts view source

ZodObject<{ error: ZodLiteral<"rate_limit_exceeded">; retry_after: ZodNumber; }, $loose>

Rate limit error โ€” returned when a rate limiter rejects the request.

RateLimitingTestOptions
#

testing/rate_limiting.ts view source

RateLimitingTestOptions

Configuration for describe_rate_limiting_tests.

session_options

Session config for cookie-based auth.

type SessionOptions<string>

create_route_specs

Route spec factory โ€” same one used in production.

type (ctx: AppServerContext) => Array<RouteSpec>

app_options

Optional overrides for AppServerOptions.

type Partial< Omit<AppServerOptions, 'backend' | 'session_options' | 'create_route_specs'> >

db_factories

Database factories to run tests against. Default: pglite only.

type Array<DbFactory>

max_attempts

Maximum attempts before rate limiting kicks in. Default: 2 (tight limit for fast tests).

type number

RateLimitKey
#

http/error_schemas.ts view source

RateLimitKey

Rate limit key type โ€” declares what a route's rate limiter is keyed on.

- 'ip' โ€” per-IP rate limiting (bootstrap, password change, bearer auth) - 'account' โ€” per-account rate limiting (keyed on submitted identifier) - 'both' โ€” both per-IP and per-account (login)

RateLimitResult
#

rate_limiter.ts view source

RateLimitResult

Result of a rate limit check or record operation.

allowed

Whether the request is allowed.

type boolean

remaining

Remaining attempts before blocking.

type number

retry_after

Seconds until the oldest active attempt expires (0 if allowed).

type number

read_daemon_info
#

cli/daemon.ts view source

(runtime: Pick<EnvDeps, "env_get"> & FsReadDeps & LogDeps, name: string): Promise<{ version: number; pid: number; port: number; started: string; app_version: string; } | null>

Read and validate daemon info from the PID file.

runtime

runtime with file read and env capabilities

type Pick<EnvDeps, "env_get"> & FsReadDeps & LogDeps

name

application name

type string

returns

Promise<{ version: number; pid: number; port: number; started: string; app_version: string; } | null>

parsed daemon info, or null if missing or invalid

read_env_var
#

dev/setup.ts view source

(deps: FsReadDeps, env_path: string, name: string): Promise<string | undefined>

Read a single env var from a dotenv-style file.

deps

file read capability

env_path

path to the .env file

type string

name

the variable name to read

type string

returns

Promise<string | undefined>

the value, or undefined if the file or variable doesn't exist

refresh_permits
#

auth/request_context.ts view source

(ctx: RequestContext, deps: QueryDeps): Promise<RequestContext>

Reload active permits from the database, returning a new request context.

Useful for long-lived WebSocket connections where permits may change (grant or revoke) during the connection lifetime. Call periodically or after receiving a revocation signal.

Returns a new RequestContext with updated permits โ€” the original context is not mutated, making concurrent calls safe.

ctx

the request context to refresh

deps

query dependencies

returns

Promise<RequestContext>

a new RequestContext with fresh permits

RemoteNotificationActionSpec
#

actions/action_spec.ts view source

ZodObject<{ method: ZodString; initiator: ZodEnum<{ frontend: "frontend"; backend: "backend"; both: "both"; }>; input: ZodCustom<ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>, ZodType<...>>; ... 5 more ...; async: ZodDefault<...>; }, $strict>

REQUEST_CONTEXT_KEY
#

RequestContext
#

RequestResponseActionSpec
#

actions/action_spec.ts view source

ZodObject<{ method: ZodString; initiator: ZodEnum<{ frontend: "frontend"; backend: "backend"; both: "both"; }>; side_effects: ZodUnion<readonly [ZodLiteral<true>, ZodNull]>; ... 5 more ...; async: ZodDefault<...>; }, $strict>

require_auth
#

auth/request_context.ts view source

(c: Context<any, string, {}>, next: Next): Promise<void | Response>

Middleware that requires authentication.

Returns 401 if no request context is set.

c

type Context<any, string, {}>

next

type Next

returns

Promise<void | Response>

require_keeper
#

auth/require_keeper.ts view source

(c: Context<any, string, {}>, next: Next): Promise<void | Response>

Middleware that requires keeper credentials.

Returns 401 if unauthenticated, 403 if credential type is not daemon_token or if the keeper role is missing.

c

type Context<any, string, {}>

next

type Next

returns

Promise<void | Response>

require_request_context
#

auth/request_context.ts view source

(c: Context<any, any, {}>): RequestContext

Get the request context, throwing if unauthenticated.

Use in route handlers where auth middleware guarantees a context exists (i.e., routes with auth: {type: 'authenticated'} or stricter). Prefer this over get_request_context(c)! for explicit error handling.

c

the Hono context

type Context<any, any, {}>

returns

RequestContext

the request context (never null)

throws

  • Error - if no request context is set (middleware misconfiguration)

require_role
#

auth/request_context.ts view source

(role: string): MiddlewareHandler

Create middleware that requires a specific role.

Returns 401 if unauthenticated, 403 if the role is missing.

role

the required role

type string

returns

MiddlewareHandler

reset_bootstrap_token
#

dev/setup.ts view source

(deps: FsReadDeps & FsWriteDeps & FsRemoveDeps & CommandDeps & EnvDeps, app_name: string, options?: SetupBootstrapTokenOptions | undefined): Promise<...>

Remove an existing bootstrap token and create a new one.

deps

file, command, env, and remove capabilities

type FsReadDeps & FsWriteDeps & FsRemoveDeps & CommandDeps & EnvDeps

app_name

application name

type string

options?

state_dir override, permissions, logger

type SetupBootstrapTokenOptions | undefined
optional

returns

Promise<SetupTokenResult>

result from creating the new token

reset_database
#

dev/setup.ts view source

(deps: CommandDeps & FsReadDeps & FsRemoveDeps, database_url: string, options?: ResetDatabaseOptions | undefined): Promise<...>

Reset a database to a clean slate.

For PostgreSQL: drops and recreates the database. For pglite: removes the data directory if pglite_data_dir is provided. For empty/missing URLs: skips.

deps

command and file capabilities

type CommandDeps & FsReadDeps & FsRemoveDeps

database_url

the DATABASE_URL value

type string

options?

pglite_data_dir, logger

type ResetDatabaseOptions | undefined
optional

returns

Promise<ResetDbResult>

result describing what happened

reset_mock_runtime
#

reset_pglite
#

testing/db.ts view source

(db: Db): Promise<void>

Reset a PGlite database to a clean state by dropping and recreating the public schema.

Removes all tables, sequences, indexes, types, and functions. The database instance remains usable after reset.

db

the database to reset

type Db

returns

Promise<void>

ResetDatabaseOptions
#

ResetDbResult
#

dev/setup.ts view source

ResetDbResult

Result of reset_database.

reset

Whether the database was actually reset.

type boolean

skipped

Whether the operation was skipped (e.g. pglite with no data dir).

type boolean

db_type

What type of database was detected.

type 'postgres' | 'pglite' | 'none'

resolve_client_ip
#

http/proxy.ts view source

(forwarded_for: string, proxies: ParsedProxy[]): string | undefined

Resolve the real client IP from an X-Forwarded-For header value.

Walks right-to-left, skipping trusted proxy entries. The first non-trusted entry is the client IP. If all entries are trusted, returns the leftmost entry. All entries are normalized before matching and in the returned value.

forwarded_for

the X-Forwarded-For header value

type string

proxies

parsed trusted proxy entries

type ParsedProxy[]

returns

string | undefined

the normalized client IP, or undefined if the header is empty

resolve_env_vars
#

env/resolve.ts view source

(runtime: Pick<EnvDeps, "env_get">, value: string): string

Resolve environment variable references in a string.

Uses $$VAR$$ syntax (bookended double-dollar signs). Only resolves variables that are actually set in the environment. Unset variables are left as-is for clear error messages.

runtime

runtime with env_get capability

type Pick<EnvDeps, "env_get">

value

string that may contain $$VAR$$ references

type string

returns

string

string with env vars resolved

resolve_env_vars_in_object
#

env/resolve.ts view source

<T extends Record<string, unknown>>(runtime: Pick<EnvDeps, "env_get">, obj: T): T

Resolve env vars in an object's string values (shallow).

runtime

runtime with env_get capability

type Pick<EnvDeps, "env_get">

obj

object with string values

type T

returns

T

new object with env vars resolved

resolve_env_vars_required
#

env/resolve.ts view source

(runtime: Pick<EnvDeps, "env_get">, value: string, context: string): string

Resolve env vars and throw if any are missing/empty.

Use this for values that must be present.

runtime

runtime with env_get capability

type Pick<EnvDeps, "env_get">

value

string with $$VAR$$ references

type string

context

description for error message (e.g., "target.host")

type string

returns

string

resolved string

throws

  • error - if any referenced env var is missing or empty

resolve_fixture_path
#

testing/assertions.ts view source

(filename: string, import_meta_url: string): string

Resolve an absolute path relative to the caller's module.

filename

the filename to resolve

type string

import_meta_url

the caller's import.meta.url

type string

returns

string

absolute path

resolve_keeper_account_id
#

auth/daemon_token_middleware.ts view source

(deps: QueryDeps): Promise<string | null>

Resolve the keeper account ID by querying for the account with an active keeper permit.

There is exactly one keeper account (the bootstrap account). Runs once at server startup โ€” the result is cached in DaemonTokenState.keeper_account_id.

deps

query dependencies

returns

Promise<string | null>

the keeper account ID, or null if no keeper exists yet (pre-bootstrap)

resolve_test_path
#

testing/auth_apps.ts view source

(path: string): string

Replace Hono route params (:foo) with dummy values for HTTP testing.

path

type string

returns

string

resolve_valid_path
#

testing/schema_generators.ts view source

(path: string, params_schema?: ZodObject<$ZodLooseShape, $strip> | undefined): string

Resolve a route path with valid-ish param values so params validation passes. Used when testing input on routes that also have params.

path

type string

params_schema?

type ZodObject<$ZodLooseShape, $strip> | undefined
optional

returns

string

ROLE_ADMIN
#

ROLE_KEEPER
#

RoleName
#

RoleOptions
#

auth/role_schema.ts view source

RoleOptions

Configuration for a role.

Builtin roles have fixed configs. App-defined roles get sensible defaults (requires_daemon_token: false, web_grantable: true).

requires_daemon_token

If true, exercising this role requires daemon token authentication. Only keeper for now.

type boolean

web_grantable

If true, admins can grant this role via the web UI. Default true.

type boolean

RoleSchemaResult
#

auth/role_schema.ts view source

RoleSchemaResult

The result of create_role_schema โ€” a Zod schema and config map for all roles.

Role

Zod schema that validates role strings. Use at I/O boundaries (grant endpoint, permit queries).

type z.ZodType<string>

role_options

Options for every role (builtins + app-defined). Keyed by role name.

type ReadonlyMap<string, Required<RoleOptions>>

RoundTripTestOptions
#

testing/round_trip.ts view source

RoundTripTestOptions

session_options

Session config for cookie-based auth.

type SessionOptions<string>

create_route_specs

Route spec factory โ€” same one used in production.

type (ctx: AppServerContext) => Array<RouteSpec>

app_options

Optional overrides for AppServerOptions.

type Partial< Omit<AppServerOptions, 'backend' | 'session_options' | 'create_route_specs'> >

db_factories

Database factories to run tests against. Default: pglite only.

type Array<DbFactory>

skip_routes

Routes to skip, in 'METHOD /path' format.

type Array<string>

input_overrides

Override generated bodies for specific routes ('METHOD /path' โ†’ body).

type Map<string, Record<string, unknown>>

route_spec_from_action
#

actions/action_bridge.ts view source

(spec: { method: string; kind: "request_response" | "remote_notification" | "local_call"; initiator: "frontend" | "backend" | "both"; auth: "public" | "authenticated" | "keeper" | { ...; } | null; ... 4 more ...; description: string; }, options: ActionRouteOptions): RouteSpec

Derive a RouteSpec from an ActionSpec and options.

Only request_response actions (which require non-null auth) can become routes. remote_notification actions (auth null) should use event_spec_from_action. local_call actions are not for HTTP transport.

Error schemas are transport-specific (keyed by HTTP status codes) and belong on the options, not the action spec. Action specs define the contract; transport concerns like HTTP error codes are added at the bridge layer.

spec

the action spec (must have non-null auth)

type { method: string; kind: "request_response" | "remote_notification" | "local_call"; initiator: "frontend" | "backend" | "both"; auth: "public" | "authenticated" | "keeper" | { role: string; } | null; ... 4 more ...; description: string; }

options

HTTP-specific options (path, handler, optional overrides)

returns

RouteSpec

throws

  • if - `spec.auth` is null

RouteAuth
#

http/route_spec.ts view source

RouteAuth

Auth requirement for a route โ€” none, authenticated, a specific role, or keeper.

{type: 'none'} means the route is open to all clients โ€” including non-browser callers (CLI, API tokens, scripts). No session or auth middleware guards are applied.

RouteContext
#

http/route_spec.ts view source

RouteContext

Per-request deps provided by the framework to route handlers.

db is transaction-scoped for mutation routes and pool-level for reads. background_db is always pool-level โ€” use it for fire-and-forget effects that must outlive the transaction.

db

Transaction-scoped for mutations, pool-level for reads.

type Db

background_db

Always pool-level โ€” for fire-and-forget effects that outlive the transaction.

type Db

pending_effects

Fire-and-forget side effects โ€” push here for post-response flushing.

type Array<Promise<void>>

RouteErrorSchemas
#

RouteFactoryDeps
#

RouteHandler
#

http/route_spec.ts view source

RouteHandler

Route handler function โ€” receives the Hono context and a RouteContext with per-request deps (db, background_db, pending_effects).

TypeScript allows fewer params, so handlers that don't need route can use (c) => ... without changes.

RouteMethod
#

routes_by_auth_type
#

http/surface_query.ts view source

(surface: AppSurface): Map<string, AppSurfaceRoute[]>

Group routes by auth type.

surface

returns

Map<string, AppSurfaceRoute[]>

a map from auth type string to route arrays, with role routes keyed as 'role:name'

RouteSpec
#

http/route_spec.ts view source

RouteSpec

A single route definition โ€” the unit of the surface map.

input and output schemas align with SAES ActionSpec naming. Use z.null() for routes with no request body (GET, DELETE without body).

method

path

type string

auth

Auth requirement for this route.

{type: 'none'} means the route is open to all clients including non-browser callers (CLI, scripts) โ€” no auth guards are applied.

handler

description

type string

params

URL path parameter schema. Use z.strictObject() with string fields matching :param segments.

TODO

type z.ZodObject

query

URL query parameter schema. Use z.strictObject() with string fields.

type z.ZodObject

input

Request body schema. Use z.null() for routes with no body.

type z.ZodType

output

Success response body schema.

type z.ZodType

rate_limit

Rate limit key type โ€” declares what this route's rate limiter is keyed on.

When set, 429 (RateLimitError) is auto-derived in derive_error_schemas. The actual RateLimiter instance is still wired imperatively in the handler โ€” this field is metadata for surface introspection and policy invariants.

errors

Handler-specific error response schemas keyed by HTTP status code.

Middleware errors (auth 401/403, validation 400, rate limit 429) are auto-derived from auth, input, and rate_limit. Declare handler-specific errors here (e.g., 404 for not-found, 409 for conflicts).

Explicit entries override auto-derived ones for the same status code.

transaction

Whether to wrap the handler in a database transaction.

When omitted, defaults are derived from the HTTP method: - GET โ†’ false (read-only, no transaction) - All others (POST, PUT, DELETE, PATCH) โ†’ true

Set explicitly to override the default (e.g., false for a POST that manages its own transaction like signup).

type boolean

run_local
#

cli/util.ts view source

(runtime: CommandDeps, command: string, args: string[]): Promise<CommandResult>

Run a local command and return the result.

runtime

runtime with run_command capability

command

command to run

type string

args

command arguments

type string[]

returns

Promise<CommandResult>

command result

run_migrations
#

db/migrate.ts view source

(db: Db, namespaces: MigrationNamespace[]): Promise<MigrationResult[]>

Run pending migrations for each namespace.

Creates the schema_version tracking table if it does not exist, then for each namespace: acquires an advisory lock, reads the current version, runs pending migrations in order (each in its own transaction), updates the stored version, and releases the lock.

Concurrency: Uses PostgreSQL advisory locks to serialize concurrent callers on the same namespace. Safe for multi-instance deployments.

db

the database instance

type Db

namespaces

migration namespaces to process in order

type MigrationNamespace[]

returns

Promise<MigrationResult[]>

results per namespace (only includes namespaces that had work to do)

RuntimeDeps
#

runtime/deps.ts view source

RuntimeDeps

Full runtime capabilities returned by create_deno_runtime or create_node_runtime.

Extends all *Deps interfaces with additional app-level capabilities. Functions should accept narrow *Deps interfaces, not this full type โ€” this type is for the wiring layer that creates and passes the runtime.

inheritance

env_all

Get all environment variables.

type () => Record<string, string>

args

CLI arguments passed to the program.

type ReadonlyArray<string>
readonly

cwd

Get current working directory.

type () => string

run_command_inherit

Run a command with inherited stdout/stderr (output goes directly to terminal).

type (cmd: string, args: Array<string>) => Promise<number>

save_config
#

cli/config.ts view source

<T>(runtime: FsWriteDeps, path: string, dir: string, config: T): Promise<void>

Save CLI configuration to a JSON file.

Creates parent directories if they don't exist.

runtime

runtime with file write capability

path

path to the config JSON file

type string

dir

directory containing the config file (created if missing)

type string

config

configuration to save

type T

returns

Promise<void>

scan_env_vars
#

env/resolve.ts view source

(obj: unknown): EnvVarRef[]

Recursively scan an object for $$VAR$$ env var references.

Walks all string values in the object tree and extracts env var names with their path context for error reporting.

obj

object to scan (typically a config)

type unknown

returns

EnvVarRef[]

array of env var references with paths

schema_to_surface
#

http/schema_helpers.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): unknown

Convert a Zod schema to a JSON-serializable representation for the surface.

Returns null for null schemas, JSON Schema for object schemas.

schema

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

unknown

SchemaFieldMeta
#

schema_meta.ts view source

SchemaFieldMeta

Zod .meta() shape for fuz_app schema metadata conventions.

description

type string

sensitivity

Sensitivity level for masking/redaction. 'secret' masks the value.

select_auth_app
#

testing/auth_apps.ts view source

(apps: AuthTestApps, auth: RouteAuth): Hono<BlankEnv, BlankSchema, "/">

Select the Hono test app with correct auth for a route.

apps

the pre-built auth test apps

auth

the route's auth options

returns

Hono<BlankEnv, BlankSchema, "/">

the correctly-authenticated Hono app

SENSITIVE_FIELD_BLOCKLIST
#

Sensitivity
#

sensitivity.ts view source

"secret"

Sensitivity level for a schema field.

- 'secret' โ€” value is masked in logs and UI (e.g. passwords, API keys, signing keys)

ServerEnvOptions
#

server/env.ts view source

ServerEnvOptions

Validated server env config โ€” the artifacts create_app_server() needs.

ok

type true

keyring

type Keyring

allowed_origins

type Array<RegExp>

bootstrap_token_path

type string | null

ServerEnvOptionsError
#

server/env.ts view source

ServerEnvOptionsError

Error from validate_server_env โ€” keyring or origin validation failed.

ok

type false

field

type 'SECRET_COOKIE_KEYS' | 'ALLOWED_ORIGINS'

errors

type Array<string>

ServerEnvOptionsResult
#

ServerStatusOptions
#

http/common_routes.ts view source

ServerStatusOptions

Options for the authenticated server status route.

version

Application version string.

type string

get_uptime_ms

Returns milliseconds since server start.

type () => number

ServeStaticFactory
#

server/static.ts view source

ServeStaticFactory

Factory function that creates a static file serving middleware.

Matches the signature of serveStatic from hono/deno and @hono/node-server/serve-static.

ServeStaticOptions
#

server/static.ts view source

ServeStaticOptions

Options for serve_static factory functions (matches Hono's serveStatic signature).

root

type string

rewriteRequestPath

type (path: string) => string

mimes

type Record<string, string>

SESSION_AGE_MAX
#

SESSION_COOKIE_OPTIONS
#

session_touch_fire_and_forget
#

auth/session_queries.ts view source

(deps: QueryDeps, token_hash: string, pending_effects: Promise<void>[] | undefined, log: Logger): Promise<void>

Touch a session without blocking the caller.

Errors are logged to console โ€” session touching never breaks request flows. Pass pending_effects (from c.var.pending_effects) to register the promise for test flushing.

deps

query dependencies

token_hash

blake3 hash of the session token

type string

pending_effects

optional array to register the effect for later awaiting

type Promise<void>[] | undefined

log

the logger instance

type Logger

returns

Promise<void>

the settled promise (callers may ignore it โ€” fire-and-forget semantics preserved)

SessionAccount
#

auth/account_schema.ts view source

SessionAccount

Account without sensitive fields, scoped to the authenticated user's own session.

id

type string

username

email

type Email | null

email_verified

type boolean

created_at

type string

SessionAccountJson
#

auth/account_schema.ts view source

ZodObject<{ id: ZodString; username: ZodString; email: ZodNullable<ZodEmail>; email_verified: ZodBoolean; created_at: ZodString; }, $strict>

Zod schema for SessionAccount โ€” account without sensitive fields.

SessionCookieOptions
#

auth/session_cookie.ts view source

SessionCookieOptions

Cookie options for session cookies.

path

type string

httpOnly

type boolean

secure

type boolean

sameSite

type 'strict' | 'lax' | 'none'

maxAge

type number

SessionOptions
#

auth/session_cookie.ts view source

SessionOptions<TIdentity>

Configuration for a session cookie format.

Apps provide encode/decode to control the identity portion of the cookie payload.

The TIdentity type parameter determines the trust model: - string (e.g. a session_id) โ€” the cookie references a server-side session record, enabling per-session revocation and metadata. Use when you need admin controls like "revoke all sessions" or per-session audit trails. - number (e.g. an account_id) โ€” the cookie directly encodes the user identity, requiring no server-side session state. Simpler, but individual sessions can only be invalidated by rotating the signing key (which invalidates all sessions).

generics

TIdentity

examples

// tx: 3-part format (admin:session_id) const tx_config: SessionOptions<string> = { cookie_name: 'tx_session', context_key: 'auth_session_id', encode_identity: (session_id) => `admin:${session_id}`, decode_identity: (payload) => { const parts = payload.split(':'); if (parts.length !== 2 || parts[0] !== 'admin') return null; return parts[1] || null; }, }; // visiones: 1-part format (account_id) const visiones_config: SessionOptions<number> = { cookie_name: 'session_id', context_key: 'auth_session_id', encode_identity: (id) => String(id), decode_identity: (payload) => { const n = parseInt(payload, 10); return Number.isFinite(n) && n > 0 ? n : null; }, };

cookie_name

type string

context_key

Hono context variable name for the identity.

type string

max_age

type number

cookie_options

type Partial<SessionCookieOptions>

encode_identity

Encode identity into the cookie payload (before the :expires_at suffix).

type (identity: TIdentity) => string

decode_identity

Decode identity from cookie payload. Return null if invalid.

type (payload: string) => TIdentity | null

set_mock_stdin
#

set_session_cookie
#

setup_bootstrap_token
#

dev/setup.ts view source

(deps: FsReadDeps & FsWriteDeps & CommandDeps & EnvDeps, app_name: string, options?: SetupBootstrapTokenOptions | undefined): Promise<...>

Create a bootstrap token file if it doesn't exist.

The token is a one-shot secret used to create the first admin account. Stored at ~/.{app_name}/secret_bootstrap_token by default.

deps

file, command, and env capabilities

type FsReadDeps & FsWriteDeps & CommandDeps & EnvDeps

app_name

application name (used for default state directory)

type string

options?

state_dir override, permissions, logger

type SetupBootstrapTokenOptions | undefined
optional

returns

Promise<SetupTokenResult>

result indicating whether a token was created

setup_env_file
#

dev/setup.ts view source

(deps: FsReadDeps & FsWriteDeps & CommandDeps, env_path: string, example_path: string, options?: SetupEnvOptions | undefined): Promise<...>

Create an env file from its example template, auto-generating SECRET_COOKIE_KEYS.

If the file already exists, backfills any empty values that have generators. Idempotent โ€” safe to re-run.

deps

file read, write, and command capabilities

type FsReadDeps & FsWriteDeps & CommandDeps

env_path

path for the env file (e.g. .env.development)

type string

example_path

path to the example template

type string

options?

extra replacements, permissions, logger

type SetupEnvOptions | undefined
optional

returns

Promise<SetupEnvResult>

result indicating whether the file was created or updated

SetupBootstrapTokenOptions
#

dev/setup.ts view source

SetupBootstrapTokenOptions

state_dir

State directory override. Defaults to ~/.{app_name}.

type string

set_permissions

Optional callback to set file/directory permissions.

type (path: string, mode: number) => Promise<void>

log

SetupEnvOptions
#

dev/setup.ts view source

SetupEnvOptions

Options for setup_env_file.

replacements

Extra env var replacements beyond the default SECRET_COOKIE_KEYS.

Keys are env var names, values are async generators. Replaces ^KEY=$ (empty value) patterns in the env file.

type Record<string, () => Promise<string>>

set_permissions

Optional callback to set file permissions (e.g. Deno.chmod).

type (path: string, mode: number) => Promise<void>

log

SetupEnvResult
#

dev/setup.ts view source

SetupEnvResult

Result of setup_env_file.

created

Whether a new file was created (vs updating existing).

type boolean

updated

Whether any values were generated/replaced.

type boolean

path

The env file path.

type string

SetupLogger
#

dev/setup.ts view source

SetupLogger

Optional logger for setup helpers.

Functions that accept a logger use it for status messages. When omitted, a default bracket-format logger writes to console.

ok

type (msg: string) => void

skip

type (msg: string) => void

error

type (msg: string) => void

SetupTokenResult
#

should_allow_origin
#

http/origin.ts view source

(origin: string, allowed_patterns: RegExp[]): boolean

Tests if a request source (origin or referer) matches any of the allowed patterns. Pattern matching is case-insensitive for domains (as per web standards).

origin

type string

allowed_patterns

type RegExp[]

returns

boolean

sidebar_state_context
#

SidebarState
#

ui/sidebar_state.svelte.ts view source

constructor

type new (options?: SidebarStateOptions | undefined): SidebarState

options?
type SidebarStateOptions | undefined
optional

toggle_sidebar

type (value?: boolean): void

value
type boolean
default !this.show_sidebar
returns void

activate

Activates the sidebar, showing it and enabling the toggle. Returns a cleanup function that deactivates.

type (): () => void

returns () => void

SidebarStateOptions
#

SignupForm
#

SignupRouteOptions
#

auth/signup_routes.ts view source

SignupRouteOptions

Per-factory configuration for signup route specs.

inheritance

signup_account_rate_limiter

Rate limiter for signup attempts, keyed by submitted username. Pass null to disable.

type RateLimiter | null

app_settings

Mutable ref to app settings โ€” when open_signup is true, invite check is skipped.

SSE_CONNECTED_COMMENT
#

realtime/sse.ts view source

": connected\n\n"

SSE comment sent on connect to flush headers through proxies. Exported for test assertions.

SseEventSpec
#

realtime/sse.ts view source

SseEventSpec

Spec for an SSE event โ€” declares params schema, description, and channel.

method

type string

params

type z.ZodType

description

type string

channel

type string

SseNotification
#

realtime/sse.ts view source

SseNotification

Notification shape aligned with JSON-RPC 2.0.

Uses {method, params} to match the JSON-RPC notification format.

method

Notification method name (e.g. 'run_created', 'host_updated').

type string

params

Method-specific payload.

type unknown

SseStream
#

realtime/sse.ts view source

SseStream<T>

Generic SSE stream controller interface.

Transport-agnostic โ€” works with any serializable type.

generics

T

default unknown

send

Send data to the client as a JSON SSE event.

type (data: T) => void

comment

Send a comment (for keep-alive pings).

type (text: string) => void

close

Close the stream.

type () => void

on_close

Register a listener called when the stream closes (client disconnect or explicit close).

type (fn: () => void) => void

StandardAdminIntegrationTestOptions
#

testing/admin_integration.ts view source

StandardAdminIntegrationTestOptions

session_options

Session config for cookie-based auth.

type SessionOptions<string>

create_route_specs

Route spec factory โ€” same one used in production.

type (ctx: AppServerContext) => Array<RouteSpec>

roles

Role schema result from create_role_schema() โ€” used to determine valid/invalid/web-grantable roles.

admin_prefix

Path prefix where admin routes are mounted (e.g., '/api/admin'). Used by the schema validation test to scope to fuz_app admin routes only, avoiding app-specific admin-gated routes that may use stub deps. Default '/api/admin'.

type string

app_options

Optional overrides for AppServerOptions.

type Partial< Omit<AppServerOptions, 'backend' | 'session_options' | 'create_route_specs'> >

db_factories

Database factories to run tests against. Default: pglite only. Pass consumer factories (e.g. [pglite_factory, pg_factory]) to also test against PostgreSQL.

type Array<DbFactory>

StandardAttackSurfaceOptions
#

testing/attack_surface.ts view source

StandardAttackSurfaceOptions

Options for the standard attack surface test suite.

build

Build the app surface bundle (surface + route specs + middleware specs).

type () => AppSurfaceSpec

snapshot_path

Absolute path to the committed snapshot JSON file.

type string

expected_public_routes

Expected public routes, e.g. ['GET /health', 'POST /api/account/login'].

type Array<string>

expected_api_middleware

Expected middleware names for API routes, e.g. ['origin', 'session', 'request_context', 'bearer_auth'].

type Array<string>

roles

All roles in the app (e.g. ['admin', 'keeper']).

type Array<string>

api_path_prefix

Path prefix for middleware stack assertion. Default '/api/'.

type string

security_policy

Security policy configuration. Omit for sensible defaults.

error_schema_tightness

Error schema tightness assertion. Omit for informational-only behavior.

StandardIntegrationTestOptions
#

testing/integration.ts view source

StandardIntegrationTestOptions

session_options

Session config for cookie-based auth.

type SessionOptions<string>

create_route_specs

Route spec factory โ€” same one used in production.

type (ctx: AppServerContext) => Array<RouteSpec>

app_options

Optional overrides for AppServerOptions.

type Partial< Omit<AppServerOptions, 'backend' | 'session_options' | 'create_route_specs'> >

db_factories

Database factories to run tests against. Default: pglite only. Pass consumer factories (e.g. [pglite_factory, pg_factory]) to also test against PostgreSQL.

type Array<DbFactory>

StandardTestOptions
#

testing/standard.ts view source

StandardTestOptions

Configuration for describe_standard_tests.

session_options

Session config for cookie-based auth.

type SessionOptions<string>

create_route_specs

Route spec factory โ€” same one used in production.

type (ctx: AppServerContext) => Array<RouteSpec>

app_options

Optional overrides for AppServerOptions.

type Partial< Omit<AppServerOptions, 'backend' | 'session_options' | 'create_route_specs'> >

db_factories

Database factories to run tests against. Default: pglite only.

type Array<DbFactory>

roles

Role schema result from create_role_schema(). When provided, admin integration tests are included.

admin_prefix

Path prefix where admin routes are mounted. Default '/api/admin'.

type string

start_daemon_token_rotation
#

auth/daemon_token_middleware.ts view source

(runtime: Pick<EnvDeps, "env_get"> & FsWriteDeps & { chmod?: ((path: string, mode: number) => Promise<void>) | undefined; } & FsRemoveDeps, deps: QueryDeps, options: DaemonTokenRotationOptions, log: Logger): Promise<...>

Start daemon token rotation.

Generates an initial token, writes it to disk, resolves the keeper account, and sets up periodic rotation. Returns the mutable state object and a stop function.

runtime

runtime with file, env, and remove capabilities

type Pick<EnvDeps, "env_get"> & FsWriteDeps & { chmod?: ((path: string, mode: number) => Promise<void>) | undefined; } & FsRemoveDeps

deps

query dependencies for resolving keeper account

options

rotation configuration

log

the logger instance

type Logger

returns

Promise<DaemonTokenRotation>

rotation state and stop function

StatResult
#

stop_daemon
#

cli/daemon.ts view source

(runtime: Pick<EnvDeps, "env_get"> & FsReadDeps & FsRemoveDeps & CommandDeps & LogDeps, name: string): Promise<...>

Stop a running daemon by sending SIGTERM and cleaning up the PID file.

Returns a result object instead of logging directly, separating lifecycle from presentation.

runtime

runtime with command, file, and env capabilities

type Pick<EnvDeps, "env_get"> & FsReadDeps & FsRemoveDeps & CommandDeps & LogDeps

name

application name

type string

returns

Promise<StopDaemonResult>

result describing the outcome

StopDaemonResult
#

cli/daemon.ts view source

StopDaemonResult

Result of a stop_daemon operation.

stopped

Whether a daemon was stopped.

type boolean

pid

PID of the stopped daemon, if any.

type number

message

Human-readable message describing the outcome.

type string

stub
#

stub_app_deps
#

stub_handler
#

stub_mw
#

testing/stubs.ts view source

(_c: any, next: any): Promise<void>

Stub middleware that passes through.

_c

type any

next

type any

returns

Promise<void>

stub_password_deps
#

testing/app_server.ts view source

PasswordHashDeps

Fast password stub for tests that don't exercise login/password flows.

Hashes are deterministic (stub_hash_<password>) and verify correctly, so auth bootstrap and session creation work without Argon2 overhead.

Subscriber
#

realtime/subscriber_registry.ts view source

Subscriber<T>

generics

T

stream

type SseStream<T>

channels

Channels this subscriber listens to. null means all channels.

type Set<string> | null

identity

Optional identity key for targeted disconnection (e.g., account_id).

type string | null

SubscriberRegistry
#

realtime/subscriber_registry.ts view source

Generic subscriber registry with channel-based filtering and identity-keyed disconnection.

Subscribers connect with optional channel filters and an optional identity key. Broadcasts go to a specific channel and reach only matching subscribers. close_by_identity force-closes all subscribers with a given identity โ€” use for auth revocation (close streams when a user's permissions change).

generics

T

examples

const registry = new SubscriberRegistry<SseNotification>(); // subscriber connects (from SSE endpoint) const unsubscribe = registry.subscribe(stream, ['runs']); // when a run changes registry.broadcast('runs', {method: 'run_created', params: {run}}); // subscriber disconnects unsubscribe();
// identity-keyed subscription for auth revocation const unsubscribe = registry.subscribe(stream, ['audit_log'], account_id); // when admin revokes the user's role โ€” close their streams registry.close_by_identity(account_id);

subscribe

Add a subscriber.

type (stream: SseStream<T>, channels?: string[] | undefined, identity?: string | undefined): () => void

stream

SSE stream to send data to

type SseStream<T>
channels?

channels to subscribe to (undefined or empty = all channels)

type string[] | undefined
optional
identity?

optional identity key for targeted disconnection

type string | undefined
optional
returns () => void

unsubscribe function

broadcast

Broadcast data to all subscribers on a channel.

Subscribers with no channel filter receive all broadcasts. Subscribers with a channel filter only receive matching broadcasts.

type (channel: string, data: T): void

channel

the channel to broadcast on

type string
data

the data to send

type T
returns void

close_by_identity

Force-close all subscribers with the given identity.

Closes each matching stream and removes the subscriber from the registry. Use for auth revocation โ€” when a user's permissions change, close their SSE connections so they must reconnect and re-authenticate.

type (identity: string): number

identity

the identity key to match

type string
returns number

the number of subscribers closed

surface_auth_summary
#

http/surface_query.ts view source

(surface: AppSurface): { none: number; authenticated: number; role: Map<string, number>; keeper: number; }

Summarize route auth distribution across the surface.

surface

returns

{ none: number; authenticated: number; role: Map<string, number>; keeper: number; }

counts by auth type, with role counts broken out by role name

SurfaceExplorer
#

SurfaceRouteOptions
#

SurfaceSecurityPolicyOptions
#

testing/surface_invariants.ts view source

SurfaceSecurityPolicyOptions

Configuration for security policy invariants.

All fields have sensible defaults. Pass overrides for project-specific needs.

sensitive_route_patterns

Path patterns for routes that should be rate-limited. Default: common sensitive patterns (login, password, bootstrap, tokens/create).

type Array<string | RegExp>

public_mutation_allowlist

Routes explicitly allowed to be public mutations (e.g., webhooks, bootstrap). Format: 'METHOD /path' (e.g., 'POST /api/account/login').

type Array<string>

keeper_route_prefixes

Allowed path prefixes for keeper-protected routes. Default: ['/api/']. Catches keeper routes outside expected namespaces.

type Array<string>

TABLE_LIMIT_MAX
#

TableInfo
#

TableState
#

ui/table_state.svelte.ts view source

inheritance

extends:

table_name

type string

columns

type Array<ColumnInfo>

rows

type Array<Record<string, unknown>>

total

offset

limit

primary_key

type string | null

deleting

type string | null

delete_error

type string | null

showing_start

readonly

showing_end

readonly

has_prev

readonly

has_next

readonly

fetch

type (table_name: string, offset?: number, limit?: number): Promise<void>

table_name
type string
offset
type number
default 0
limit
type number
default 100
returns Promise<void>

go_prev

type (): void

returns void

go_next

type (): void

returns void

delete_row

type (row: Record<string, unknown>): Promise<boolean>

row
type Record<string, unknown>
returns Promise<boolean>

TableStatus
#

TableWithCount
#

TerminalDeps
#

runtime/deps.ts view source

TerminalDeps

Terminal I/O operations.

stdout_write

Write bytes to stdout.

type (data: Uint8Array) => Promise<number>

stdin_read

Read bytes from stdin, or null on EOF.

type (buffer: Uint8Array) => Promise<number | null>

TEST_CLIENT_IP
#

TEST_COOKIE_SECRET
#

TEST_MIDDLEWARE_PATH
#

TestAccount
#

testing/app_server.ts view source

TestAccount

A bootstrapped test account with credentials.

account

type {id: string; username: string}

actor

type {id: string}

session_cookie

Signed session cookie value.

type string

api_token

Raw API token for Bearer auth.

type string

create_session_headers

Build request headers with this account's session cookie.

type (extra?: Record<string, string>) => Record<string, string>

create_bearer_headers

Build request headers with this account's Bearer token.

type (extra?: Record<string, string>) => Record<string, string>

TestApp
#

testing/app_server.ts view source

TestApp

A fully assembled test app โ€” Hono app + backend + helpers.

app

type Hono

backend

surface

route_specs

type Array<RouteSpec>

create_session_headers

Build request headers with the bootstrapped session cookie.

type (extra?: Record<string, string>) => Record<string, string>

create_bearer_headers

Build request headers with the bootstrapped Bearer token.

type (extra?: Record<string, string>) => Record<string, string>

create_account

Create an additional account with credentials.

type (options?: { username?: string; password_value?: string; roles?: Array<string>; }) => Promise<TestAccount>

cleanup

Cleanup resources (delegates to TestAppServer.cleanup).

type () => Promise<void>

TestAppServer
#

testing/app_server.ts view source

TestAppServer

An AppBackend with a bootstrapped account, API token, and session cookie.

inheritance

extends:

account

The bootstrapped account.

type {id: string; username: string}

actor

The actor linked to the account.

type {id: string}

api_token

Raw API token for Bearer auth.

type string

session_cookie

Signed session cookie value for cookie auth.

type string

keyring

Keyring used for cookie signing โ€” exposed for forging expired/tampered cookies in tests.

type Keyring

cleanup

Release test resources (no-op when DB is injected or factory-cached).

type () => Promise<void>

TestAppServerOptions
#

testing/app_server.ts view source

TestAppServerOptions

Configuration for create_test_app_server.

session_options

Session options โ€” needed for cookie signing.

type SessionOptions<string>

db

Existing database โ€” skips internal DB creation when provided. Caller owns the DB lifecycle.

type Db

db_type

Database driver type โ€” only used when db is provided. Default: 'pglite-memory'.

type DbType

password

Password implementation. Default: stub_password_deps. Pass argon2_password_deps for tests that exercise login.

username

Username for the bootstrapped account. Default: 'keeper'.

type string

password_value

Password for the bootstrapped account. Default: 'test-password-123'.

type string

roles

Roles to grant. Default: [ROLE_KEEPER].

type Array<string>

TestMiddlewareStackApp
#

TestMiddlewareStackOptions
#

testing/middleware.ts view source

TestMiddlewareStackOptions

trusted_proxies

Trusted proxy IPs.

type Array<string>

allowed_origins

Comma-separated allowed origin patterns.

type string

connection_ip

Connection IP or factory.

type string | (() => string | undefined)

ip_rate_limiter

Rate limiter for bearer auth.

type RateLimiter | null

to_admin_account
#

auth/account_schema.ts view source

(account: Account): { id: string; username: string; email: string | null; email_verified: boolean; created_at: string; updated_at: string; updated_by: string | null; }

Convert an Account to an AdminAccountJson for admin listings.

account

the full account record

type Account

returns

{ id: string; username: string; email: string | null; email_verified: boolean; created_at: string; updated_at: string; updated_by: string | null; }

the admin-safe account with audit fields

to_max_length
#

cli/help.ts view source

<T>(items: T[], to_string: (item: T) => string): number

Get maximum length from array.

items

array of items

type T[]

to_string

function to convert item to string for length measurement

type (item: T) => string

returns

number

maximum string length

to_session_account
#

TransitionFunction
#

truncate_middle
#

ui/ui_format.ts view source

(str: string, max_length: number, separator?: string): string

Truncate a string by keeping the start and end, with a separator in the middle.

str

the string to truncate

type string

max_length

maximum total length including separator

type number

separator

the middle separator

type string
default 'โ€ฆ'

returns

string

the truncated string, or the original if it fits

truncate_uuid
#

ui/ui_format.ts view source

(uuid: string): string

Truncate a UUID for display, keeping start and end visible.

uuid

the UUID string to truncate

type string

returns

string

a 12-character truncated UUID like a1b2cโ€ฆ7890

ui_fetch
#

ui/ui_fetch.ts view source

(input: RequestInfo | URL, init?: RequestInit | undefined): Promise<Response>

Fetch with credentials included (sends cookies).

input

the request URL or Request object

type RequestInfo | URL

init?

optional fetch init options

type RequestInit | undefined
optional

returns

Promise<Response>

fetch response promise

UpdateAppSettingsInput
#

Username
#

auth/account_schema.ts view source

ZodString

Username for account creation โ€” starts with letter, alphanumeric/dash/underscore middle, ends with alphanumeric. No @ or . allowed.

USERNAME_LENGTH_MAX
#

USERNAME_LENGTH_MIN
#

USERNAME_PROVIDED_LENGTH_MAX
#

UsernameProvided
#

VALID_SQL_IDENTIFIER
#

db/sql_identifier.ts view source

RegExp

Pattern matching valid SQL identifiers: starts with a letter or underscore, followed by letters, digits, or underscores.

validate_daemon_token
#

auth/daemon_token.ts view source

(provided: string, state: DaemonTokenState): boolean

Validate a daemon token against the current state.

Accepts both the current and previous token (2-token race window). Uses timing-safe comparison.

provided

the token from the X-Daemon-Token header

type string

state

the daemon token state

returns

boolean

true if the token is valid

validate_env_vars
#

env/resolve.ts view source

(runtime: Pick<EnvDeps, "env_get">, refs: EnvVarRef[]): EnvValidationResult

Validate that all referenced env vars exist in the environment.

Returns all missing refs (including duplicates by name). Grouping and deduplication is handled by format_missing_env_vars at display time.

runtime

runtime with env_get capability

type Pick<EnvDeps, "env_get">

refs

env var references from scan_env_vars

type EnvVarRef[]

returns

EnvValidationResult

validation result with any missing vars

validate_keyring
#

auth/keyring.ts view source

(env_value: string | undefined): string[]

Validate key ring configuration.

env_value

the SECRET_COOKIE_KEYS environment variable

type string | undefined

returns

string[]

array of validation errors (empty if valid)

validate_nginx_config
#

server/validate_nginx.ts view source

(config: string): NginxValidationResult

Validate an nginx config template string for security properties.

Checks for required security headers, Authorization stripping in /api blocks, and the nginx add_header inheritance gotcha. Designed for fuz_app consumer deploy configs (tx.ts NGINX_CONFIG constants).

Limitations: string pattern matching, not a real nginx parser. Catches common omissions in fuz_app deploy configs but won't catch all possible misconfigurations.

config

nginx config template string

type string

returns

NginxValidationResult

validation result with ok status, warnings, and errors

validate_server_env
#

server/env.ts view source

(env: { NODE_ENV: "development" | "production"; PORT: number; HOST: string; DATABASE_URL: string; SECRET_COOKIE_KEYS: string; ALLOWED_ORIGINS: string; PUBLIC_API_URL: string; PUBLIC_WEBSOCKET_URL?: string | undefined; ... 4 more ...; SMTP_PASSWORD?: string | undefined; }): ServerEnvOptionsResult

Validate a loaded BaseServerEnv and produce the artifacts needed for server init.

Handles keyring validation, origin parsing, and bootstrap token path extraction. Returns a Result so callers handle errors their own way (exit, logging, etc).

env

a loaded and Zod-validated BaseServerEnv

type { NODE_ENV: "development" | "production"; PORT: number; HOST: string; DATABASE_URL: string; SECRET_COOKIE_KEYS: string; ALLOWED_ORIGINS: string; PUBLIC_API_URL: string; PUBLIC_WEBSOCKET_URL?: string | undefined; ... 4 more ...; SMTP_PASSWORD?: string | undefined; }

returns

ServerEnvOptionsResult

{ok: true, keyring, allowed_origins, bootstrap_token_path} or {ok: false, field, errors}

ValidatedKeyringResult
#

ValidationError
#

http/error_schemas.ts view source

ZodObject<{ error: ZodString; issues: ZodArray<ZodObject<{ code: ZodString; message: ZodString; path: ZodArray<ZodUnion<readonly [ZodString, ZodNumber]>>; }, $loose>>; }, $loose>

Input validation error โ€” returned when the request body fails Zod parsing.

issues contains the Zod validation issues for diagnostic display.

verify_dummy
#

auth/password_argon2.ts view source

(password: string): Promise<boolean>

Verify a password against a dummy hash for timing attack resistance.

Always returns false, but takes the same time as a real verification. Call when account lookup fails to prevent timing-based user enumeration.

password

the plaintext password to "verify"

type string

returns

Promise<boolean>

always false

verify_password
#

auth/password_argon2.ts view source

(password: string, password_hash: string): Promise<boolean>

Verify a password against an Argon2id hash.

password

the plaintext password to verify

type string

password_hash

the Argon2id hash to verify against

type string

returns

Promise<boolean>

true if the password matches

verify_request_source
#

http/origin.ts view source

(allowed_patterns: RegExp[]): Handler

Middleware that verifies the request source against an allowlist.

Origin allowlisting (not the CSRF layer โ€” that's SameSite: strict cookies) that: - Checks the Origin header first (if present) - Falls back to Referer header (if no Origin) - Allows requests without Origin/Referer headers (direct access, curl, etc.)

This is useful for: - Protecting locally-running services from being called by untrusted websites as the user browses the web - Restricting which domains can make requests to your API - Preventing embedding of your service in unexpected sites - Basic source verification for locally-running services

allowed_patterns

array of compiled regex patterns from parse_allowed_origins

type RegExp[]

returns

Handler

write_daemon_info
#

cli/daemon.ts view source

(runtime: Pick<EnvDeps, "env_get"> & FsWriteDeps, name: string, info: { version: number; pid: number; port: number; started: string; app_version: string; }): Promise<...>

Write daemon info to the PID file, creating directories as needed.

runtime

runtime with file write and env capabilities

type Pick<EnvDeps, "env_get"> & FsWriteDeps

name

application name

type string

info

daemon info to write

type { version: number; pid: number; port: number; started: string; app_version: string; }

returns

Promise<void>

write_daemon_token
#

auth/daemon_token_middleware.ts view source

(runtime: DaemonTokenWriteDeps, token_path: string, token: string): Promise<void>

Write the current token to disk atomically.

Uses write_file_atomic (temp file + rename) and optionally sets mode 0600.

runtime

runtime with file write capabilities

token_path

path to write the token

type string

token

the raw token string

type string

returns

Promise<void>

write_file_atomic
#

runtime/fs.ts view source

(deps: Pick<FsWriteDeps, "write_file" | "rename">, path: string, content: string): Promise<void>

Write a file atomically via temp file + rename.

deps

deps with file write capabilities

type Pick<FsWriteDeps, "write_file" | "rename">

path

destination file path

type string

content

file contents to write

type string

returns

Promise<void>