auth/audit_emitter.ts

Bound audit-emit capability.

AuditEmitter closes over the pool-level Db, its registered listeners, and the optional AuditLogConfig. Built by the consumer's audit_factory callback on CreateAppBackendOptions — create_app_backend invokes the factory once with its constructed {db, log} and lands the result on AppDeps.audit. Consumers reach for await deps.audit.emit(ctx, input); the emitter picks where the row is written (see "Where a row is written").

These methods cover every fan-out shape the auth domain needs (add_listener and listener_count manage the listener chain):

  • emit(ctx, input) — the request-scoped emit. A success row inside a request transaction is written in it and the promise rejects when the INSERT fails; every other row is a fire-and-forget pool write whose in-flight promise goes on ctx.pending_effects, and the returned promise resolves at once.
  • emit_role_grant_target(ctx, auth, input) — wrapper that lifts the actor_id / account_id / ip boilerplate every role-grant-shape audit site repeated. Delegates to emit.
  • emit_pool(input) — awaitable pool write for code paths without a request transaction (maintenance scripts, a post-commit thunk). Writes, then notifies.
  • notify(event) — fan out an already-written audit row (e.g. rows returned by query_accept_offer that were inserted in-transaction by the query layer, or the offer-expiry rows auth/cleanup.ts writes in its sweep transaction). Runs every registered listener; per-listener throws are isolated.
  • drain_inflight() — test-binary barrier: await every in-flight emit write, on an emitter built with track_inflight: true.
  • is_tracking_inflight() — whether that barrier can wait on anything, so a test binary built without tracking is caught rather than racing.

Where a row is written

The routing reads two things: the row's outcome and whether ctx.db is a transaction (Db.in_transaction).

  • A success row emitted inside a request transaction (an action with side_effects, a route with transaction: true) is written in that transaction: the change and the row that reports it commit together or not at all. The INSERT is awaited, and a failed one rejects emit, so the handler throws and its transaction rolls back — a committed change is never left unaudited.
  • A failure row is written on the pool, outside the request's transaction, so it survives the rollback that usually follows it — the forensic record of a refused attempt.
  • A success row emitted with no request transaction open (a GET, or a route that runs transaction: false and opens its own around just its writes, like /login and /password, which emit once that transaction has committed) is written on the pool too — there is no transaction to join.

A pool write is fail-open: a failed one is counted (get_audit_write_failures) and logged as one error line carrying the whole row, secret metadata masked (to_dropped_audit_row), and the request goes on. Its checkout waits the backend's audit bound (FUZ_DB_AUDIT_CHECKOUT_TIMEOUT_MS, 30 s by default — create_app_backend hands the factory its pool Db through Db.with_checkout_timeout), longer than a request's, so a pool saturated enough to shed requests with a 503 does not also drop the failure rows recording them.

This is the Rust spine's split: fuz_auth's route_audit_emit writes an action's success row in the request transaction (emit_in_tx) and every failure row on the pool (emit), and its REST handlers (/login, /password, signup, bootstrap) emit on the pool. Two rows differ in routing between the twins, visible on the wire only when the audit INSERT fails: the TS /logout runs in a route transaction, so its success row is written in it (Rust writes it on the pool), and db_admin_row_delete is written on the pool after the commit on both (http/db_routes.ts, through emit_pool).

When listeners hear about a row

  • A failure row is announced as soon as it is written. It records an attempt, which happened whether or not the request's transaction commits.
  • A success row is announced only after the request's transaction commits (after the handler returns, on a route without one), and never when the handler throws: the fan-out is queued on ctx.post_commit_effects. A success row reports a state change, and the listeners act on it — the revocation listeners close connections, the audit stream broadcasts it. Announced before the commit, a close could run while the revoked credential still reads as valid, and a rolled-back revocation would close connections anyway.

Listeners are a documented registration seam — create_app_server registers additional listeners via add_listener after the backend is built (the factory-managed audit-log SSE, the revocation guard) before the first request runs, and removes each through the remover add_listener returns when its assembly fails or the server closes. Consumers can also register listeners directly on the emitter they return from audit_factory for setups that don't pass through create_app_server.

view source

Declarations
#

11 declarations

AuditEmitFn
#

auth/audit_emitter.ts view source

AuditEmitFn import type {AuditEmitFn} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Signature of AuditEmitter.emit — captured by the inner closure so emit_role_grant_target reaches the decorated function rather than a this.emit lookup. Exposed as a type so EmitDecorator can name the inner / outer slot.

(call)

type <T extends string>(ctx: AuditEmitterContext, input: AuditLogInput<T>): Promise<void>

ctx

input

returns Promise<void>

AuditEmitRoleGrantContext
#

auth/audit_emitter.ts view source

AuditEmitRoleGrantContext import type {AuditEmitRoleGrantContext} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Context required by AuditEmitter.emit_role_grant_target — adds client_ip so the helper can lift the ip: ctx.client_ip boilerplate every role-grant-shape emit site repeated.

inheritance

client_ip

Resolved client IP from the trusted-proxy middleware — 'unknown' if not resolved.

type string

AuditEmitRoleGrantInput
#

auth/audit_emitter.ts view source

AuditEmitRoleGrantInput<T> import type {AuditEmitRoleGrantInput} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Input to AuditEmitter.emit_role_grant_target — the event fields that vary per call site; actor_id, account_id, and ip are lifted from the auth and request contexts.

generics

AuditEmitRoleGrantInput<T extends string>
T
constraint string

event_type

type T

target_account_id

type Branded | null

target_actor_id

type Branded | null

metadata

type (T extends "login" | "logout" | "bootstrap" | "signup" | "password_change" | "session_revoke" | "session_revoke_all" | "token_create" | "token_revoke" | "token_revoke_all" | "role_grant_create" | "role_grant_revoke" | "role_grant_offer_create" | "role_grant_offer_accept" | "role_grant_offer_decline" | "role_grant_offer_retract" | "role_grant_offer_expire" | "role_grant_offer_supersede" | "invite_create" | "invite_delete" | "account_delete" | "account_purge" | "account_undelete" | "actor_delete" | "actor_purge" | "actor_undelete" | "app_settings_update" | "db_admin_row_delete" ? (AuditMetadataMap[T] & Record<string, unknown>) | null : Record<string, unknown> | null) | undefined

outcome?

Default 'success', as for emit.

type "success" | "failure"

AuditEmitter
#

auth/audit_emitter.ts view source

AuditEmitter import type {AuditEmitter} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Bound audit-emit capability. Built once at backend assembly via create_audit_emitter; lives on AppDeps.audit so factories never see the pool.

emit

Write an audit row for a request, routed by outcome and ctx.db (module doc, "Where a row is written").

A success row inside a request transaction is written in it: the promise settles once the INSERT has run, and rejects when it fails, so the handler throws and the change rolls back with its row. Any other row is a fire-and-forget pool write: its in-flight promise goes on ctx.pending_effects (so tests with await_pending_effects: true can assert it inline), its errors are logged and counted, never thrown, and the returned promise resolves at once.

A written row fans out to every listener on the chain (notify): a failure row as soon as it is written, a success row from ctx.post_commit_effects — after the request's transaction commits, and never when the handler throws.

Always await it — the twin of the Rust ctx.audit_emit(db, input).await?.

type <T extends string>(ctx: AuditEmitterContext, input: AuditLogInput<T>): Promise<void>

ctx

input

returns Promise<void>

throws

  • Error - when an in-transaction INSERT fails

mutates

  • audit_log table — inserts the row in `ctx.db`'s transaction or via the captured pool
  • ctx.pending_effects — appends a pool write's in-flight settled promise
  • ctx.post_commit_effects — appends a success row's listener fan-out

emit_role_grant_target

Emit a role-grant-shape audit event with actor_id / account_id / ip lifted from auth + ctx. Delegates to emit.

Use for any event populating one of the target_*_id columns. Reach for the lower-level emit only when the event is non-role-grant shape (e.g. app_settings_update, bootstrap, signup).

type <T extends string>(ctx: AuditEmitRoleGrantContext, auth: RequestActorContext, input: AuditEmitRoleGrantInput<T>): Promise<...>

ctx

auth

input

returns Promise<void>

emit_pool

Awaitable pool write for code paths without a request transaction — a maintenance script, or a post-commit thunk whose transaction has ended (db_admin_row_delete, http/db_routes.ts).

Writes, then notifies the listeners, whatever the outcome — there is no request transaction to order the fan-out against. Tracked by drain_inflight like emit's pool writes. Errors are logged and swallowed (resolved void), so callers can sequence writes with await audit.emit_pool(...) without try/catch boilerplate.

Not for a success audit paired with a state mutation: the pool write can't roll back with the state, and a swallowed error leaves the mutation unaudited. Write those in the mutation's transaction (query_audit_log against the tx) and notify after the commit — the shape auth/cleanup.ts's offer sweep and query_accept_offer use.

type <T extends string>(input: AuditLogInput<T>): Promise<void>

input

returns Promise<void>

mutates

  • audit_log table — inserts the row via the captured pool

notify

Fan out an already-written audit row to the registered listeners.

Use only when the row was inserted in-transaction by a query helper that returned the AuditLogEvent (e.g. query_accept_offer.audit_events). Per-listener exceptions are caught and logged; one failing listener does not starve siblings.

type (event: AuditLogEvent): void

event

returns void

add_listener

Register an audit-event listener. Listeners fire in registration order for every row emit / emit_pool wrote and on every notify.

Returns a remover that unregisters this registration. Each call is its own registration: the same function registered twice fires twice, and each remover takes out only the registration it was returned for, leaving the others in place and in order. Calling a remover again is a no-op. A notify already in progress still runs a listener removed during its fan-out — it iterates a snapshot — and the next one does not.

create_app_server registers the factory-managed audit-log SSE listener and the one revocation guard (create_revocation_guard) here so SSE + WS fan-out compose on top of the consumer's on_audit_event callback without shallow-copying AppDeps, and removes them when its assembly fails or the server closes. Consumers can also register listeners directly for setups that don't run through create_app_server. The on_audit_event passed at construction has no remover — it lives as long as the emitter.

Twin of the Rust fuz_auth AuditEmitter::add_listener in what registration means — firing order, snapshot-at-notify.

type (listener: (event: AuditLogEvent) => void): () => void

listener

called with each announced audit row

type (event: AuditLogEvent) => void
returns () => void

a remover for this registration, idempotent

listener_count

Count of registered listeners, the construction-time on_audit_event included — introspection for tests and diagnostics.

type (): number

returns number

drain_inflight

Await every fire-and-forget emit write in flight — the deterministic barrier behind the _testing_drain_effects test action.

Waits until no tracked write is outstanding, so a write that starts while the drain is waiting (an emit from a post-commit thunk) is awaited too. Once it resolves, a following audit_log_list read sees every row whose emit ran before the drain was called. A write that starts after the drain resolves is not covered. A success row's listener fan-out runs as a post-commit effect and is not tracked, so an SSE broadcast or an auth-guard close driven by one isn't guaranteed done when the drain resolves — the row itself is.

Resolves at once unless the emitter was built with track_inflight: true — production never tracks, so there is nothing to wait for. Twin of the Rust fuz_auth AuditEmitter::drain_inflight.

type (): Promise<void>

returns Promise<void>

is_tracking_inflight

Whether this emitter tracks its in-flight emit writes — true only when built with track_inflight: true. When false, drain_inflight resolves at once and waits on nothing.

The _testing_drain_effects action reports it as tracked, and the list_audit_events reads refuse false: a test binary whose emitter was built without tracking would otherwise answer the drain at once and its audit reads would race the writes. Twin of the Rust fuz_auth AuditEmitter::is_tracking_inflight.

type (): boolean

returns boolean

AuditEmitterContext
#

auth/audit_emitter.ts view source

AuditEmitterContext import type {AuditEmitterContext} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Per-request context required by AuditEmitter.emit — the request's db and its two side-effect queues. The bound emitter carries its own log reference inside the closure, so per-call contexts don't need one.

db decides where a success row is written: inside the request's transaction when db.in_transaction, else on the pool (module doc, "Where a row is written"). A pool write is eager — the emitter fires it immediately and pushes the in-flight Promise<void> onto pending_effects. A success row's listener fan-out goes on post_commit_effects (module doc, "When listeners hear about a row").

Both RouteContext and ActionContext structurally satisfy this shape, so handlers pass route / ctx directly. Never pass one from a post-commit thunk: its transaction has ended — use emit_pool there.

inheritance

pending_effects

type Promise<void>[]

create_audit_emitter
#

auth/audit_emitter.ts view source

(options: CreateAuditEmitterOptions): AuditEmitter import {create_audit_emitter} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Build a bound AuditEmitter. Typical caller is the consumer's audit_factory callback on CreateAppBackendOptions — create_app_backend invokes that callback with its constructed {db, log} and lands the result on AppDeps.audit.

options

pool, logger, optional initial subscriber, optional config

returns

AuditEmitter

the bound emitter; closes over the pool + config + listener chain

CreateAuditEmitterOptions
#

auth/audit_emitter.ts view source

CreateAuditEmitterOptions import type {CreateAuditEmitterOptions} from '@fuzdev/fuz_app/auth/audit_emitter.js';

db

Pool-level Db. Captured by every emit call.

type Db

log

Logger for write + listener-callback failures.

type Logger

on_audit_event?

Initial listener — registered as the first listener when set. Omit for backends that compose listeners post-assembly (e.g. via audit_log_sse).

type ((event: AuditLogEvent) => void) | null

audit_log_config?

Audit-log config. Defaults to builtin_audit_log_config. Consumer- extended configs from create_audit_log_config({extra_events}) get registered here once at backend assembly.

type AuditLogConfig

emit_decorator?

Test-only hook to wrap emit at construction time. The decorated function is captured by emit_role_grant_target's closure and is the function exposed on the returned AuditEmitter, so both call shapes route through it — see EmitDecorator for the rationale.

Leave unset in production — it is a test instrumentation seam.

type (inner: AuditEmitFn): AuditEmitFn

inner

returns AuditEmitFn

track_inflight?

Track every in-flight emit write so drain_inflight can await it. Defaults to false, which makes drain_inflight resolve at once.

Test binaries only. A transport can reply before a request's writes settle — a WebSocket message is answered before its effects flush — so a test reading the audit log after a reply needs this barrier. In production the tracking is pure overhead and nothing drains it. Twin of the Rust fuz_auth AuditEmitter::new_with_inflight_tracking.

type boolean

EmitDecorator
#

auth/audit_emitter.ts view source

EmitDecorator import type {EmitDecorator} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Wrap the bound emit before it gets captured by emit_role_grant_target's closure and exposed on the returned AuditEmitter. Test instrumentation uses this to record emit invocations against external markers on a frozen emitter, whose slots can't be patched after construction.

Because the inner closure captures the decorated function (not the outer slot reference), emit_role_grant_target also routes through the wrap — the decorator sees role-grant-shape emissions, not just bare emit calls. Production never sets this.

(call)

type (inner: AuditEmitFn): AuditEmitFn

inner

returns AuditEmitFn

get_audit_write_failures
#

auth/audit_emitter.ts view source

(): number import {get_audit_write_failures} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Number of audit rows an emitter failed to write since process start.

returns

number

reset_audit_write_failures
#

auth/audit_emitter.ts view source

(): void import {reset_audit_write_failures} from '@fuzdev/fuz_app/auth/audit_emitter.js';

Reset the counter — for tests only.

returns

void

to_dropped_audit_row
#

auth/audit_emitter.ts view source

<T extends string>(input: AuditLogInput<T>, config: AuditLogConfig): Record<string, unknown> import {to_dropped_audit_row} from '@fuzdev/fuz_app/auth/audit_emitter.js';

The whole row a dropped pool write would have inserted, as the one JSON object its audit row dropped log line carries: event_type, outcome, the four id columns, ip, and metadata — with each metadata field whose schema in config is marked sensitivity: 'secret' replaced by MASKED_VALUE. No builtin event declares a secret field, so a builtin row logs whole, as the Rust twin's fuz_auth::dropped_row_json does.

The masking reads only the entries an object metadata schema declares (find_schema_sensitivity over the entries get_schema_entries finds under any wrapper), a key matching only an own entry, never a name the entries inherit such as constructor. A secret field nested under an object field, a field of a union or variant metadata schema, a sensitivity: 'secret' on the object schema itself, and a key only a rest schema covers are logged in clear, and so is every sensitivity: 'personal' field. Keep secrets out of audit metadata — they would land in audit_log too.

input

the row's input

config

the emitter's AuditLogConfig, whose event schemas mark secret fields

returns

Record<string, unknown>

the row, ready to JSON.stringify

generics

to_dropped_audit_row<T extends string>
T
constraint string

Depends on
#

Imported by
#