Audit log
Record events, and list, reveal and export a tenant's audit entries as NDJSON, CSV or OCSF, and purge them per tenant's retention.
The audit SQL module records row changes and audit_event() calls (see
SQL modules). The audit block reads that log
from TypeScript: a list for an activity page, an export for customers and
SIEMs, and retention.
better-supabase add auditTurn on readPolicy so members read their tenant's entries with
audit.read, and platform staff read every entry:
export default defineConfig({
blocks: { audit: { options: { readPolicy: true } } },
});Recording events
audit.record writes a semantic event through audit_event and returns the
entry id. Call it with a service-role transport from a job, a webhook
handler or an API route:
const id = await audit
.record({
eventType: "ticket.escalated",
category: "support",
organizationId,
record: ticket.id,
summary: "Escalated to the on-call team",
requestId: ctx.requestId,
correlationId: ctx.correlationId,
metadata: { ticketId: ticket.id, priority: 2 },
})
.orThrow();Its fields are the arguments of audit_event. actorId, actorKind,
actorLabel, ip, userAgent, sessionId, requestId and scope count
only for the service role and direct admin connections; any other caller
gets its own user and the request's id. supportSessionId, impersonatedBy
and impersonationReason fill the impersonation columns, such as for an
entry about a support session that the admin's own token records. Any
caller but the service role may only name itself as impersonatedBy, from
a token without an act claim; otherwise the claim's values are stored. Pass ctx.requestId and
ctx.correlationId from the server context
so the event and the row changes of the same action share them; without
them, audit_event reads the request's settings and headers (see
Request and correlation ids).
An id that isn't 1 to 128 safe characters is dropped. scope defaults
to tenant with an organization and platform without one, and an adopted
log can take its own value (region, say). An adopted log's columns outside
the module's model are filled from metadata keys with
blocks.audit.options.metadataColumns (see
SQL modules). A key the event leaves out
leaves its column to the column's default, so a not null default column
keeps working, and the mapped keys are removed from the stored metadata
unless keepMappedMetadata is true. list and export return those
columns by name under columns; pass their types to createAudit to
type them:
Server code calls the audit instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useAudit } = defineDataHooks(
"audit",
(db: AppDb) => db.audit,
);const rows = await db.audit.list({ limit: 50 }).orThrow();"use client";
import { useAudit } from "@/lib/supabase/hooks";
const rows = useAudit({ limit: 50 });A column that follows from what the module already records, such as a flag
for entries by platform staff, needs no metadata key: make it a generated
column of the adopted log. Postgres fills it for every entry, from
audit_event and from the row-change trigger alike, and the module never
writes it:
alter table public.audit_logs
drop column actor_is_platform_admin,
add column actor_is_platform_admin boolean not null
generated always as (coalesce(actor_kind = 'platform_admin', false)) stored;With values: { actorKind: { support: "platform_admin" } }, a support
session's entries and a service call with actorKind: "support" store
platform_admin, and the flag follows. An expression that needs another
table (a role lookup) can't be a generated column; pass that value as a
metadata key instead.
Client address, staff and subject columns
ip defaults to the last hop of the x-forwarded-for header, which is the
address Supabase's gateway saw. Behind another proxy, name the header and the
hop with ipHeader. With staffClaim, a caller whose token carries that
claim is recorded with actor_kind = 'staff' instead of user.
subjectColumns adds a typed, indexed column per key, generated from the new
row, the old row or the metadata, so you can list every entry about one job
without scanning jsonb. tables reads another key for the rows of one
table: the jobs table's own rows have no job_id, so { "public.jobs": "id" }
fills the column with the job's id there. An id key falls back to the
entry's record_id, so the column is filled on a restricted log too, whose
entries keep no row data:
blocks: {
audit: {
options: {
ipHeader: { name: "cf-connecting-ip" },
staffClaim: "app_metadata.platform_role",
subjectColumns: {
job_id: { type: "uuid", tables: { "public.jobs": "id" } },
ticket_no: { type: "bigint", from: "ticket" },
},
},
},
},| Option | Default | What it does |
|---|---|---|
ipHeader | last x-forwarded-for | a header name, or { name, hop: "first" | "last" } for a comma-separated list |
staffClaim | none | a dotted claim path; a caller carrying it is recorded as staff |
subjectColumns | {} | { <column>: { type: "text" | "uuid" | "bigint", from?, tables? } }; from is the key to read and defaults to the name |
A value that doesn't parse as the column's type stores null instead of
failing the audited write.
Row entries for block tables
Every table a block owns writes a row entry when something changes it outside a block function. Block functions already call ctx.record, and the row trigger skips a row that function recorded in the same transaction, so a change appears once. The triggers are deferred to commit, so a later direct write to the same row in that transaction is not listed.
blocks.audit.options.blockTables sets the scope: "entities" (the default) covers each module's entity tables, "all" adds the other block tables, and "none" turns it off. A module with audit: false gets no row triggers, and the audit block's own tables never write row entries.
Bulk writes
A row trigger runs once for every row a statement changes, so a bulk import or a nightly job that updates 50,000 rows writes 50,000 inserts into the log. Pass statement => true to audit the table with statement-level triggers instead. They read the statement's transition tables and write all entries in one insert.
select better_supabase.audit(
'public.customers',
ignore => '{updated_at}',
redact => '{api_key}',
statement => true
);Entries look the same as the row trigger's, with the same actor, tenant, redaction and ignore handling: a row whose only change is in ignore writes nothing. The mode has limits:
- The table needs a primary key, because the old and new rows of an update are paired on it. An update that changes a key column is recorded as a delete and an insert.
- It doesn't combine with
deferred,tenant_pathortenant_function.audit()raises an error for each of these. - With a restricted details table (
options.restricted, ortables.restrictedfor your own table), the statement writes the restricted rows in one more insert, so a statement costs two inserts however many rows it changes. - A row that
audit_eventrecorded in the same transaction is skipped, as it is with the row trigger.
On in-process Postgres (PGlite) with the restricted table on, an update of 48 rows took a median of 20.3 ms with the row trigger and 8.5 ms with statement triggers, and an update of 5,000 rows took 937 ms and 504 ms. tests/bench/audit-statement.ts repeats the measurement.
Module actions
Every SQL module records its security-relevant actions in the log once the
audit module is installed: a membership change, an API key, a setting, a
flag, a credential, a connector, a webhook secret or a support session each
write one entry, in the same transaction as the outbox event. The modules use
one set of categories:
| Category | Actions |
|---|---|
membership | invitations, member roles, removals, ownership, the waitlist |
access | roles, permissions and overrides in the access catalog |
security | API keys, credentials, provider keys, support sessions, SSO |
configuration | organizations, settings, flags, announcements, workflows |
billing | billing customers |
data | row changes from the table trigger, attachments, exports |
ai | agents, tool policies and approvals, chat shares |
integration | connectors, incoming and outgoing webhooks |
read | decrypted or sensitive values, when a table opts in |
An adopted log whose category column has a check of its own maps the
shared names with values, the same way it maps actor kinds:
audit: {
options: {
values: {
category: { membership: "users", configuration: "settings" },
},
},
},Set audit: false on a module to keep its actions and the row triggers on
its tables out of the log; its events still reach the outbox:
blocks: { "flags": { audit: false } },options.auditCategory on organizations, organizations-suspension and
impersonation still works and puts every entry of that module under one
category, but it is deprecated: map the shared categories with values
instead.
Read audits
A clinic or a regulated app has to show who looked at a record, not only who changed it. Reads are audited where values are decrypted, so a query that skips the definer path can't read the value either:
- an app table with
auditReads: truewrites<type>.viewedfor each<table>_revealcall; custom-fieldswithoptions.auditReadswritesfield_value.viewedfor eachreadValuescall that returns an encrypted or sensitive value.
Each entry has the category read, the acting member and the tenant, and
names the rows in metadata.ids. One call writes one entry per tenant
whatever the number of rows, so listing a page of records costs one insert.
List them with category: "read"; retention purges them with
the other entries.
Read logging
A record type with
subjects.<type>.auditReads logs each
read through the blocks' read functions as a subject.accessed entry under
the read category. The entry carries the fields NEN 7513 asks of a health
record's access log:
| NEN 7513 asks for | Where the entry keeps it |
|---|---|
| Who | actor_id, and actorName in subject_access_log |
| Which record | metadata.subjectType and metadata.subjectId, with record_id and the tenant |
| When | occurred_at |
| How | metadata.block and metadata.function: the read function that returned the record |
| Why | metadata.purpose, when the caller passes one to reads.log |
| Under what access | metadata.emergency: the reader held emergency access to the record |
Reads by one member of one record within 60 seconds, for the same purpose
and under the same access, collapse into one entry
(blocks.subjects.options.reads.collapseSeconds). A plain select over the
Data API, the service role and SQL that doesn't call a read function are not
logged; revoke select on the table to send every read through the
functions. A read-only support session can't write the entry, so its logged
reads fail with ACTOR_READ_ONLY.
subjects.reads.list(subject, { since }) returns a record's read log to the
holders of audit.read, the record team's leads, and the record's own guest
or a representative with act authority, so a client can ask who looked at
their file:
import { createSubjects } from "better-supabase/blocks/subjects";
const subjects = createSubjects({ transport });
await subjects.reads
.log({ type: "patient", id: patientId }, { purpose: "treatment" })
.orThrow();
const reads = await subjects.reads
.list({ type: "patient", id: patientId })
.orThrow();
// [{ id, actorId, actorName, at, purpose, emergency, block, function }]Recording CloudEvents
audit.sink() returns an EventSink that records each CloudEvent it
receives, so the events another part of the app already sends reach the log:
import { forwardBlockEvents } from "better-supabase/events";
forwardBlockEvents(betterSupabase, audit.sink(), {
source: "/crm",
types: ["organization.*", "impersonation.*"],
});auditEventOf(event) is the mapping it uses:
| Audit field | From the CloudEvent |
|---|---|
eventType | type without the dev.better-supabase. prefix (typePrefix option) |
category | security for account.* and impersonation.* (category option) |
record | subject |
organizationId | the memberships or partitionkey extension, then data.organizationId |
actorId | data.actorId |
metadata | data |
idempotencyKey | source and id, so a redelivered event is recorded once |
supportSessionId, impersonatedBy, impersonationReason | data.sessionId, data.adminId and data.reason of a impersonation.* event |
category takes the event type without its prefix and returns one of the
module categories above, or undefined for none, so app events land next to
the module actions:
audit.sink({
category: (type) => (type.startsWith("invoice.") ? "billing" : undefined),
});The sink records up to 1,000 events per call through
better_supabase.audit_event_many(events jsonb), which runs audit_event
for each element with the same checks. audit.recordMany(events) calls it
directly and returns one Result per event, so one bad event doesn't stop
the others.
send throws when an entry fails, after trying the rest, so an outbox relay
retries the batch. Build the log on a service-role transport: only the
service role can set the actor. The server's audit option takes the same
sink (see Account deletion).
Listing entries
createAudit reads the log through the module's own functions, as the
caller, so the read policy decides what each member sees and an adopted log's
column mappings are already applied. It needs no generated types and no
exposed schema: pass sqlTransport(ctx.postgres) (direct Postgres as the
user), or rpcTransport(supabase, { schema: "api" }) with the module's
API schema.
import { createAudit, sqlTransport } from "better-supabase/blocks/audit";
const audit = createAudit({ transport: sqlTransport(ctx.postgres) });
const page = await audit
.list({ organizationId, eventType: "invoice.sent", since, limit: 50 })
.orThrow();
// page.entries: id, occurredAt, eventType, actorId, actorLabel, summary, targetLabel, ...
const older = await audit.list({ organizationId, cursor: page.next });list calls list_audit_events with the tenant, event type, actor, target
type, record, category, outcome, source, actor kind, correlation id and time
filters, newest first; pass
page.next as cursor for the next page. Every filter but the times takes
one value or a list, search matches text in the event type, summary,
target, actor and tenant labels, record and table (case-insensitive),
order: "asc" lists oldest first, and count: true adds page.total, the
number of entries the filters match, from count_audit_events:
const page = await audit
.list({
organizationId,
eventType: ["invoice.sent", "invoice.paid"],
outcome: "failure",
search: "acme",
order: "asc",
count: true,
})
.orThrow();
// page.total: 12A table with page numbers opens page N with offset next to count:
const page = await audit
.list({
organizationId,
limit: 25,
offset: (pageNumber - 1) * 25,
count: true,
})
.orThrow();
// page.entries: the entries of that page; page.total: every matchoffset skips that many entries after the filters (and after before, when
both are set), and export takes it too, to start an export at that entry.
export takes the same filters, search and order. Restricted details (row snapshots, IP, user agent) are
never in the list. audit.reveal(entryId) returns them for a member with the
reveal permission in the entry's tenant, or platform staff who hold
permissions.revealPlatform, a platform key you set (without it only the
service role reveals across tenants), and records the look as an audit.revealed entry; anyone else
gets not_found (AUDIT_ENTRY_NOT_FOUND).
auditListQuery is the older path: a list query
over the audit table with facets for table, record, op, actor,
event, category, outcome and target. It reads the table itself, so it
needs the table in your generated models and follows the managed column
names; use it with ctx.sql over direct Postgres, since the module schema is
not exposed to the Data API.
export const auditList = auditListQuery(betterSupabase, "auditEvents");
const page = await auditList
.run(ctx.sql, query.value, {
where: { organizationId, ...auditList.between(from, to) },
})
.orThrow();In the browser
useAuditLog loads the newest page through the provider's client, as the caller, so the read policy
applies as it does for list. setFilters({ actorId, eventType, search })
narrows the table and loads the first page again (an empty value matches
every entry), and loadMore() appends the next, older page while
hasMore is true. The same hook runs in React DOM and React Native. It
is a registry item: install it with
npx shadcn add @better-supabase/use-audit, which writes
hooks/use-audit.ts into the app.
import { useAuditLog } from "@/hooks/use-audit";
const { entries, filters, hasMore, setFilters, loadMore } = useAuditLog({
organizationId,
schema: "api",
});createAuditLogController from better-supabase/blocks/audit is the same
logic without React. Vue, Svelte and Solid run it with useBlockController
from better-supabase/vue, /svelte and /solid, passing a client from
createAudit, with auth from the provider (see
Block controllers). The
audit log table recipe shows it in the Next.js
and Expo examples.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createAudit,
createAuditLogController,
rpcTransport,
} from "better-supabase/blocks/audit";
const props = defineProps<{ organizationId: string }>();
const supabase = useSupabase();
const { state, actions } = useBlockController(createAuditLogController, {
client: createAudit({ transport: rpcTransport(supabase), schema: "api" }),
organizationId: props.organizationId,
});
</script>
<template>
<p v-for="entry in state.entries" :key="entry.id">{{ entry.eventType }}</p>
<button v-if="state.hasMore" @click="actions.loadMore()">Load more</button>
</template><script lang="ts">
import {
betterSupabase,
useBlockController,
} from "better-supabase/svelte";
import {
createAudit,
createAuditLogController,
rpcTransport,
} from "better-supabase/blocks/audit";
let { organizationId }: { organizationId: string } = $props();
const { supabase } = betterSupabase();
const audit = useBlockController(createAuditLogController, {
client: createAudit({ transport: rpcTransport(supabase), schema: "api" }),
organizationId,
});
</script>
<p>{$audit.entries?.length ?? 0} entries</p>import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createAudit,
createAuditLogController,
rpcTransport,
} from "better-supabase/blocks/audit";
export function AuditLog(props: { organizationId: string }) {
const supabase = useSupabase();
const { state } = useBlockController(createAuditLogController, {
client: createAudit({ transport: rpcTransport(supabase), schema: "api" }),
organizationId: props.organizationId,
});
return <p>{state().entries?.length ?? 0} entries</p>;
}A page with the total and actor names
page(options) is list with the total for the same filters, shaped for an audit screen: entries, next and total, with an actorName on each entry. actorName is the entry's actorLabel, the name or service the writer recorded when the entry was made, so it needs no join and stays correct after the member is renamed or removed; it is null for an entry without a label. page calls list with count: true, so list hooks run and the read policy decides which entries are counted. It takes the same filters as list, except count.
const { entries, total, next } = await audit
.page({ organizationId, category: "billing", limit: 25 })
.orThrow();Translating summaries
summary is English text. Each entry also keeps summaryKey and
summaryParams, so a page in another locale words the entry itself. A block
action's key is its event type (accounting_entry.posted), from the event
table on Events, and an entry audit_event records
gets the key you pass as summary_key, else its event_type.
summaryParams holds the raw values the summary names: ids as ids, dates as
ISO strings, amounts as numbers or minor units. It is null when the summary
names no values, and row entries have no key. Fall back to summary for a key
your catalog lacks:
const text = (entry: AuditRecord) =>
entry.summaryKey && t.has(`audit.${entry.summaryKey}`)
? t(`audit.${entry.summaryKey}`, entry.summaryParams ?? {})
: (entry.summary ?? entry.eventType);An app that ignores the keys keeps showing summary as before. Entries
written before version 15 of the module have neither column filled. An
adopted log stores them only when blocks.audit.columns.log maps
summaryKey and summaryParams.
Large logs
A log of millions of entries needs a few habits on the audit screen:
- Always pass
organizationId. The log has indexes that lead with the tenant:(tenant, occurred_at, id),(tenant, actor, occurred_at, id)and(tenant, event_type, occurred_at, id), so a page, an actor filter and an event type filter each read in index order. Without a tenant the planner walks the whole log for a rare filter. - Pass
fields: "summary"tolist. It leaves outold,new,changedandmetadata, which make a row large.audit.get(entryId)returns one full entry when the reader opens it. - Pass
since. A search matches text in every row of its window, so search always carries a time window. - Pass
countCapwithcount: true, or show an estimate. WithcountCap: 10000the count stops there andtotalmeans "10,000 or more". audit.eventTypes({ organizationId })returns the distinct event types for a filter menu by skipping through the event type index, in a few milliseconds on a log of millions of rows.
const page = await audit
.list({
organizationId,
since: Temporal.Now.instant().subtract({ hours: 24 * 30 }),
fields: "summary",
count: true,
countCap: 10_000,
})
.orThrow();Reverting changes
audit.revert(entryIds) writes the old values of row changes back, newest
entry first, all or nothing. It runs as the caller, so the target table's
policies and grants decide whether each write is allowed, and the revert is
itself audited. The caller needs audit.revert in each entry's organization
(admins and owners have it by default).
const { reverted, undo } = await audit.revert([entry.id]).orThrow();| Entry | Revert |
|---|---|
update | Restores the changed columns, if the row still holds the new values |
insert | Deletes the row, if it still holds the inserted values |
delete | Inserts the row again with its old values, generated columns aside |
| Hint | When |
|---|---|
AUDIT_ENTRY_NOT_FOUND | An entry is missing or the caller lacks audit.revert in its tenant |
AUDIT_ENTRY_NOT_REVERTIBLE | The entry is an event, or its table no longer exists |
AUDIT_ENTRY_REDACTED | A value the revert needs was redacted when it was logged |
ROW_CHANGED_SINCE | The row changed after the entry, or a deleted row exists again |
AUDIT_REVERT_FORBIDDEN | The table's policies hide the row from the caller |
AUDIT_REVERT_TOO_MANY | More than 1000 entries in one call |
Reverting needs the row snapshots (old and new on the log, or in the
restricted table) and the access module. An adopted log without them gets no
revert_audit_entries function.
Undo tokens
Methods whose change has an inverse return an undo token: relations.link,
relations.unlink and audit.revert. The token is plain JSON, so a server
action can return it to a toast, and applying it runs the inverse as the
caller, with the same permission checks as any other write. A revert's token
names the entries the revert wrote, found by the correlation id it sets, so
applying it reverts the revert. An adopted log without a correlation id column
returns undo: null.
Apply a token with createUndo from better-supabase/blocks/undo, or keep a
stack of them in the browser with useUndoStack; see
Undo. Bulk actions return no token, because a row's
inverse depends on the action; revert their audit entries instead.
Exporting
audit.export() streams every entry the caller can read as NDJSON, CSV or
OCSF, one list_audit_events page at a time, so memory stays flat however
long the log is, and it reads an adopted log and the version 3 columns
(actorLabel, summary, requestId and the rest) like list does:
export const GET = bsb.handler(async (request, ctx) => {
const audit = createAudit({
transport: sqlTransport(postgres.asUser(ctx.auth.claims)),
});
const stream = audit.export({ organizationId, since, format: "csv" });
return new Response(stream, { headers: { "content-type": "text/csv" } });
});format: "csv" writes a header row and one row per entry, with text that
starts like a spreadsheet formula prefixed with '. columns picks and
orders the columns (a record key, a key with its header label,
columns.<name> for a column metadataColumns fills, or
restricted.<field> for restricted details), preamble writes lines
before the header row, and formatRow changes each row before it is
written:
const stream = audit.export({
organizationId,
format: "csv",
preamble: [`Audit log for ${organization.name}`, `Exported ${now}`],
columns: [
{ key: "occurredAt", label: "Time" },
{ key: "actorLabel", label: "Who" },
"eventType",
{ key: "columns.ticket_id", label: "Ticket" },
{ key: "restricted.ip", label: "IP address" },
],
formatRow: (row, record) => ({
...row,
occurredAt: record.occurredAt.toLocaleString("en-GB"),
}),
});A restricted.<field> column (ip, userAgent, sessionId, metadata,
old, new or changes) reads each page's details through
reveal_audit_entries(entries), which returns them for the entries the
caller may reveal (the same check as reveal), leaves the cells of the
others empty, and records one audit.revealed entry per tenant with the
revealed ids in metadata.entries. It needs the restricted option and
the access module. Without columns, the export keeps its default
columns. For an export that runs
in the background (a jobs handler that emails a link, say),
audit.exportToStorage({ storage, bucket, path, signedUrlTtl, ...filters })
writes the file to Storage, such as the data lifecycle data-exports
bucket, and returns its path and a signed download URL.
exportAuditLog(sql, options) streams NDJSON or OCSF straight from the
managed table's columns. Keep it for a managed log; audit.export() covers
adopted logs and CSV.
format: "ocsf" maps each entry to an
OCSF event (SPEC_PINS.ocsf). Row changes
are Entity Management (class_uid 3004) with the table and record as the
entity; audit_event() entries are API Activity (6003) with the event type
as api.operation. The activity comes from the event type's last segment:
created is Create, exported is Read, renamed is Update and revoked is
Delete; anything else is Other (99) with the event type as activity_name.
toOcsf(entry, product) maps one entry.
Retention
Nothing is deleted until you choose a retention. options.retention keeps
entries for an interval and adds an audit_retention job to the
housekeeping block's maintenance(), which it
installs:
export default defineConfig({
blocks: { audit: { options: { retention: { keep: "1 year" } } } },
});Each run deletes up to batch entries (default 10,000) past keep through
purge_audit_log, so the hooks and legal holds below still apply. On a
partitioned log it also creates the coming months. With
onExpire: "detach", a month wholly past keep is detached from a
partitioned log the block owns and stays as its own table
(audit_events_p202401) for you to archive and drop; its restricted rows
stay too. An adopted log (tables.log names your table) gets the batched
deletes only, because partitioning needs a log the block creates. The job
returns { purged, detached, partitionsCreated }, and
better_supabase.maintenance_jobs shows when it last ran.
You can also run the purge yourself. purgeAuditLog deletes entries past their retention and returns how many.
Without retention it calls purge_audit_log, which honours an
audit_retention SQL hook; with it, each tenant is purged with its own
number of days. setAuditRetention reads those days from a column:
import { purgeAuditLog, setAuditRetention } from "better-supabase/blocks/audit";
await purgeAuditLog(postgres.admin, {
olderThan: "1 year",
retention: setAuditRetention(postgres.admin, {
table: "public.organizations",
column: "audit_retention_days",
}),
});purgeAuditLog reads every tenant's days in one query. A tenant whose
column is null keeps the olderThan default. Run the job
until it returns 0; each call deletes at most batch entries per tenant.
purgeAuditLog also takes a service-role transport instead of the SQL
connection, such as rpcTransport(admin, { schema: "api" }) over the
wrappers blocks.audit.api writes.
With the data-lifecycle module, purge_audit_log also follows the
audit retention policies and legal holds.
Partitioned log
options.partitioned creates a new managed log partitioned by month on
occurred_at, so a purge drops whole months instead of deleting rows:
export default defineConfig({
blocks: { audit: { options: { partitioned: true } } },
});The module creates this month's partition and the next three, plus a
default partition for anything outside them. Schedule
better_supabase.maintain_partitions() once a month to add the months
ahead. purge_audit_log drops every month past the cutoff, which is the
longest audit retention policy or older_than, and deletes the dropped
entries' restricted details. It deletes rows one by one instead while a
legal hold covers audit entries, when an audit_retention hook exists, or
for one tenant.
The option applies when the module creates the log. An existing log stays
as it is, and better-supabase doctor reports it as BS335. With the option
on, upgrade also writes the procedure
better_supabase.convert_audit_log_to_partitioned(batch_size, drop_old),
which moves the existing log onto partitions while it keeps taking writes.
Run it with call outside a transaction block, as the service role:
call better_supabase.convert_audit_log_to_partitioned(50000);It builds the partitioned table and its indexes beside the old one, copies
the rows in committed batches by id, then takes a short lock that blocks
writes but not reads, copies the rows written since, swaps the names and
moves the grants, policies and triggers. The old table stays as
audit_events_unpartitioned until you call it with drop_old => true. The
unique idempotency index gains occurred_at, because a partitioned key must
include the partition column. Run it again after a failure and it resumes
from the rows already copied. On 5.0M entries with writes running, it took
30 seconds, and no entry written meanwhile was lost. An adopted log is never
partitioned.
Hash chain
options.chain tags the audit log chain (see below), which links each tenant's entries in a hash chain: every entry
stores its position, the previous entry's hash and its own hash, a SHA-256
of the row and the previous hash. Changing, deleting or inserting an entry
afterwards breaks the chain from that point. createChain checks it
and signs its heads, pointed at the audit log and its tenant column:
import { createChain, sqlTransport } from "better-supabase/blocks/audit";
import { createSigningKeys } from "better-supabase/blocks/signing-keys";
const signingKeys = createSigningKeys({
transport: sqlTransport(postgres.admin),
});
const chain = createChain({
transport: sqlTransport(postgres.admin),
table: "better_supabase.audit_events",
tenantColumn: "organization_id",
signer: signingKeys.signer(
{ type: "app", id: "audit" },
{ create: "Ed25519" },
),
issuer: "https://app.example.com",
});
await chain.checkpoint().orThrow();
const verdict = await chain.verify({ organizationId }).orThrow();
// { valid: true, checked: 1204, seq: 1204, hash: "9f2c…" }
// { valid: false, checked: 311, seq: 312, reason: "hash" }| Method | What it does |
|---|---|
verify(range?) | Checks a tenant's entries in order, optionally between from and to |
heads() | Each tenant's latest entry that no checkpoint covers yet |
checkpoint() | Signs every head as a JWS and records it in chain_checkpoints |
checkpoints(opts?) | A tenant's recorded checkpoints, newest first |
A verdict's reason is hash (an entry changed), link (an entry points
at the wrong predecessor), gap (an entry is missing) or checkpoint (a signed head no longer
matches). Without a to, verify checks up to the latest checkpoint, so
deleting the newest entries is caught once a checkpoint covers them. The checkpoint JWS carries sub (the
tenant), seq, hash, entry and iat; publish the signer's
JWK Set so an auditor can check the
checkpoints without database access. Run checkpoint() on a schedule:
an entry rewritten together with every later hash still fails against the
last signed head.
Every chain function is service-role only. The chain starts with the first entry written after the option is on; older entries stay outside it. It needs a managed log.
Chains on your own tables
Tag a table append-only and chain (see tables)
and createChain signs and verifies it the way it does for the audit log, which uses
the same functions (verify_chain, chain_checkpoints). It also builds the proof for one row, which an auditor checks
without a database:
import {
createChain,
evidenceBundle,
sqlTransport,
verifyEvidenceBundle,
} from "better-supabase/blocks/audit";
const chain = createChain({
transport: sqlTransport(pg),
table: "public.facts",
tenantColumn: "organization_id",
signer,
});
await chain.checkpoint().orThrow();
const proof = await chain.proof({ seq, tenant: organizationId }).orThrow();
const bundle = await evidenceBundle({
subject: { type: "filing", id },
proofs: [proof],
sections: { auditEntries },
generatedAt: new Date().toISOString(),
});
// Anywhere, with the public keys:
await verifyEvidenceBundle(bundle, jwks, { requireSigned: true });A proof holds the rows from the one you asked for up to the first signed
checkpoint that covers it. verifyChainProof recomputes each hash from the
row text, checks the links and checks the checkpoint's signature on WebCrypto
alone. evidenceBundle seals proofs and other sections you pass with a
content hash; write it to storage under a legal hold.
Without the client
db.audit is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const audit = createAudit<{ ticket_id: string | null; priority: number }>({
transport: sqlTransport(ctx.postgres),
});
const page = await audit.list({ organizationId }).orThrow();
// page.entries[0].columns: { ticket_id: "...", priority: 2 }One request's entries
correlated({ correlationId, organizationId?, limit? }) returns every entry the caller can read that shares the correlation id, oldest first, so one request or job reads as one story. It pages through list (200 entries per page, up to limit, default 1000), so your list hooks see each page.
Last updated on