@xtandard/audit
The self-hosted, embeddable, tamper-evident audit-log control plane for B2B SaaS, in one import.
The root export: the core and its types (also on /core and /schema), the
buffered recorder, transforms, integrity (hash chain, checkpoints, signers),
exports, the stream runner and sinks contract, portal tokens, the hooks
contract, the auth/authorization contracts, and the panel’s web-standard
fetch handler. Storage adapters, auth providers, framework adapters, sinks
with peers and the React embeds are separate subpaths.
import { … } from "@xtandard/audit";Also re-exports symbols of @xtandard/audit/core, @xtandard/audit/schema, documented on those pages.
Functions
Section titled “Functions”| Name | Summary |
|---|---|
applyTransforms |
Run transforms in order. |
buildOpenApiDocument |
Build the OpenAPI 3.1 document for the panel API. Pure — safe to call anywhere. |
callbackSink |
A sink that calls your function (tests, custom destinations). |
chainHeader |
The chained header for an event (what hash is computed over). |
computeDigests |
Compute every section digest of an (unerased) event. |
createFetchHandler |
Build the panel fetch handler. |
createKvEventLog |
The generic event log over the four-method KV contract. |
createPortalToken |
Mint a portal token granting read access to tenant’s log until expiresIn elapses (default 1 hour). Call this server-side — anyone holding the portal secret can mint tokens for any tenant. |
createRecorder |
Create a buffered recorder. |
createStreamRunner |
Create a stream runner over a core. The panel creates and starts one when given streams; call start() yourself otherwise (timers are unrefed). |
csvCell |
Quote a CSV cell (RFC 4180) and neutralize spreadsheet formulas. |
decodeCursor |
Decode an opaque cursor; throws QueryError when malformed. |
defineActions |
Declare the typed action catalog. Identity at runtime; preserves the literal types so core.record() can infer action names and metadata shapes. |
durationToMs |
Convert a duration ("5s", "30m", "2h", "7d", or a number of milliseconds) to milliseconds. Throws on malformed strings or negative / non-finite numbers. |
ed25519Signer |
An Ed25519 signer from a private JWK (from generateSigningKeyPair or xtandard-audit keygen). The public half is served as a JWKS so customers can verify checkpoints themselves. |
encodeCursor |
Encode a keyset position as an opaque cursor. |
eventToCsvRow |
One event as a CSV row. |
exportEvents |
Stream a query (or, for "bundle", a tenant’s whole retained chain) in the given format. Requires query.tenant for every format (exports are always per tenant). |
generateSigningKeyPair |
Generate an Ed25519 key pair as JWKs (store privateJwk as a secret). |
hasEventLog |
Runtime feature-detection: does this storage implement the native event log? |
hashValue |
Replace values with a SHA-256 digest (sha256:…). Pass a salt (a secret) to keep low-entropy values (emails, IPs) from being confirmed by brute force; equal inputs still produce equal digests, so you can correlate without storing. |
hmacSigner |
A symmetric HMAC-SHA256 signer: simplest setup, but only holders of the secret can verify — prefer ed25519Signer when customers verify. |
idPattern |
The regex an id with prefix must match. |
idTime |
The unix-ms timestamp embedded in an id, or null when malformed. |
intersectActions |
Intersect two action include-lists (each an OR of exact names and families). Returns the narrowest list matching exactly what both match; [] means “nothing matches”. |
isMutatingAction |
True if the action mutates state. |
mask |
Partially mask string values: emails become j***@e***.com, short strings ****, longer strings keep their last four characters. |
maskValue |
The masking used by mask. |
matchesQuery |
Does event satisfy every filter of q (ignoring pagination)? |
newId |
A new id, e.g. newId("evt") → "evt_01JD…". ms overrides the clock for this id. |
normalizeQuery |
Validate and default a query. |
omit |
Remove the values at paths entirely. |
pgListenNotify |
A WatchSubscribe backed by Postgres LISTEN/NOTIFY. Pair with withWatch for the postgres or drizzle-over-pg adapters. Your migration owns the trigger that pg_notifys channel with the changed key as payload; this only LISTENs. client is a dedicated listening connection (a pg Client, not a Pool). |
portalCanSee |
Is event inside the grant’s view (its tenant, and its filter)? |
redact |
Replace the values at paths with "[REDACTED]". |
requirePeer |
Helper for adapters whose subpath requires an optional peer dependency. Throws a clear, actionable error when the peer is missing. |
resolveEventLog |
Resolve the event log for a storage: native capability or the KV fallback. |
runStandardSchema |
Run a Standard Schema validator; returns the output or the issue messages. |
scopeQueryToPortal |
Force a client query into a portal grant: the tenant is the token’s, and every filter field is AND-ed in. A client parameter can only narrow the view — action lists are intersected, exclusions are unioned, and a client actorId / targetType / targetId that differs from the token’s makes the result empty (empty: true) instead of widening it. |
sealChain |
Seal a batch for one tenant, linking each event to the previous one. |
sealEvent |
Seal an event: compute its digests and its chain hash linked to prevHash. |
sectionDigest |
Salted digest of one section’s value. |
signCheckpoint |
Sign an unsigned checkpoint. |
validateActionDefinition |
Validate an action catalog entry. |
validateEventInput |
Validate the structure of a record input (not the action’s metadata schema). |
validateTenant |
Validate a tenant key. |
verifyPortalToken |
Verify a portal token: format, signature (constant time), then expiry. Returns the grant on success; throws PortalTokenError otherwise. |
Classes
Section titled “Classes”| Name | Summary |
|---|---|
ChainConflictError |
Thrown by EventLogStorage.appendEvents when the tenant’s chain moved underneath the writer (another process appended first). The core re-reads the head, re-chains the batch, and retries. |
QueryError |
Thrown for a malformed cursor or an invalid query value. Maps to HTTP 400. |
RecorderOverflowError |
Thrown by Recorder.record when the queue is full. |
Interfaces
Section titled “Interfaces”| Name | Summary |
|---|---|
ActionSpec |
One action’s definition in code. |
AuditPanelOptions |
Options for the panel handler (shared by every framework adapter). |
AuditPortalOptions |
Portal composition for the panel: when set, requests bearing a valid audpt_… token act as a portal principal scoped to the token’s tenant and view filter. |
AuditSigner |
Signs checkpoints. Implement your own (KMS, HSM) or use the built-ins. |
AuditSink |
A destination. send must resolve only once the batch is durably accepted (2xx, flushed, …) and throw otherwise — the cursor advances on resolve. |
CreateFetchHandlerResult |
Return shape of createFetchHandler. |
EventLogStorage |
Storage that stores and queries audit events natively (indexes, SQL WHERE, Mongo filters) instead of through the generic KV index fallback in the core (ADR 0005). Control data (catalog, heads, checkpoints, cursors) still lives in the KV methods. |
ExportOptions |
Options for exportEvents. |
HookActor |
Who performed a control-plane operation (from the authenticated principal). |
NormalizedQuery |
A validated, defaulted query — what storage drivers receive. List filters are split into exact names and prefix. families; search is lower-cased. |
OpenApiOptions |
Options for buildOpenApiDocument. |
PanelConfig |
The bootstrap config served at /config (and injected into the SPA). |
PortalFilter |
A server-side view filter carried inside a portal token. Every field is AND-ed into every query, export and single-event read the bearer makes; a client parameter can only narrow it, never widen it. |
PortalGrant |
What a verified token grants. |
PortalTokenOptions |
Options for createPortalToken. |
QueryPosition |
A keyset position: the (occurredAt, id) of the last item of a page. |
Recorder |
A buffered recorder over a core. |
RecorderFallback |
Where batches go when storage keeps failing (e.g. a JSONL file, stderr, a queue). |
RecorderOptions |
Options for createRecorder. |
StandardSchemaV1 |
The Standard Schema v1 interface (vendored, type-only). |
StreamBatch |
A batch for one tenant. |
StreamCursor |
Persisted per-tenant cursor state. |
StreamDefinition |
A stream definition. |
StreamRunner |
A started (or startable) stream runner. |
StreamRunnerOptions |
Options for createStreamRunner. |
StreamStatus |
Runtime status of one stream (the admin UI’s Streams view). |
Type aliases
Section titled “Type aliases”| Name | Summary |
|---|---|
ActionMap |
A map of action name → spec. |
ActionMetadataInput |
The metadata input type of one action. |
AfterEvent |
Event delivered to AuditHooks.after — the committed mutation. |
AfterEventType |
|
AuditAction |
The full set of authorizable actions. |
AuditCorsOptions |
CORS for the panel: origin (a string, a list, or a predicate; "*" with credentials echoes the caller’s origin), credentials, methods, headers and maxAge. |
AuditHooks |
A control-plane hook. Implement before (runs before a mutation commits; throw to deny, e.g. a HookDeniedError with a clean HTTP status), after (side effects once it committed; errors are isolated and reported via onHookError), or both. Pass one — or an array — to ../core.createAuditCore via hooks. |
AuditHooksInput |
Accepts a single hook, an array, or nothing. |
AuditJwk |
A JWK with its key id. |
AuditResource |
The resource an action targets. An absent tenant / name means “across all” (listings, the cross-tenant event search, a global prune). |
AuditTransform |
A transform: sync or async, returns the (possibly new) event. |
AuthorizationProvider |
Decides whether an action is permitted. |
AuthorizeInput |
Input passed to AuthorizationProvider.authorize. |
BeforeEvent |
Event delivered to AuditHooks.before — the proposed mutation, before it commits. Throw from the handler to deny it. |
BeforeEventType |
The discriminant strings of BeforeEvent / AfterEvent. |
EventLog |
The event-log operations the core needs (the native capability minus KV). |
ExportFormat |
Export formats. |
HookErrorReporter |
Reports an error thrown by an after hook. |
IdPrefix |
Id prefixes: events and checkpoints. |
PortalTokenError |
An invalid portal token (see the PortalTokenError class). |
ScopedQuery |
The result of applying a portal filter to a client query. |
StreamItem |
One item a sink receives. |
TransformableEvent |
The event shape transforms see: fully resolved, not yet chained. |
UnsealedEvent |
An event before it is sealed into the chain. |
Variables
Section titled “Variables”| Name | Summary |
|---|---|
ACTION_REGEX |
Allowed characters for action names (invoice.paid, member:role_changed). |
ALL_ACTIONS |
Every action, in a stable order (the UI and /config allowed use it). |
CSV_COLUMNS |
CSV columns, in order. |
DEFAULT_MAX_EVENT_BYTES |
Maximum serialized size of one event’s free-form sections, in bytes. Default for maxEventBytes. |
DEFAULT_PORTAL_ACTIONS |
The default portal grant: browse, export and verify the tenant’s own log, and read the action catalog. Nothing mutating. |
DEFAULT_QUERY_LIMIT |
Default page size. |
defaultHookErrorReporter |
Default after-hook error reporter: console.warn with the [@xtandard/audit] prefix. |
EXPORT_CONTENT_TYPES |
The MIME type of each format. |
MAX_QUERY_LIMIT |
Maximum page size. |
MUTATING_ACTIONS |
Actions that mutate state — blocked (423) when the panel is readonly. |
PORTAL_TOKEN_PREFIX |
Prefix of every portal token. |
PortalTokenError |
Thrown by verifyPortalToken for any invalid token — malformed, bad signature, or expired. Maps to HTTP 401 at the API layer. |
REDACTED |
Replacement value used by redact. |
TENANT_REGEX |
Allowed characters for tenant keys. |
VERSION |
The published package version. |