Skip to content

Package reference

Mirrors the package README (single source). Install @basaltkit/audit-prisma v2.1.1 — npm · source.

<p align="center"> <a href="https://basaltkit-docs.pages.dev"> <img src="https://basaltkit-docs.pages.dev/social-card.png" alt="Basalt" width="440"> </a> </p>

@basaltkit/audit-prisma ​

Prisma-backed implementation of the @basaltkit/auditAuditStore — the append-only audit trail — for production databases (PostgreSQL, MySQL, …).

You bring a generated PrismaClient with the AuditEntry model; the store only touches that delegate. The production counterpart to @basaltkit/audit-sqlite.

bash
pnpm add @basaltkit/audit-prisma   # peer: @basaltkit/audit ; you already have @prisma/client

1. Add the model ​

Copy the model from the bundled reference schema (@basaltkit/audit-prisma/schema.prisma) into your schema.prisma:

prisma
model AuditEntry {
  id        String   @id
  source    String
  event     String
  payload   String?
  actorId   String?
  tenantId  String?
  requestId String?
  at        DateTime
  ip        String?   // requestContext (PII)
  userAgent String?   // requestContext
  chain     String?   // hash chain: 't:<tenantId>' or '@system'
  seq       Int?
  prevHash  String?
  hash      String?
  redaction  String?  // attested erasure (audit.redact): the erased set
  redactedBy String?  // ... and the id of the audit:redacted entry
  nonce      String?  // v3 hashes (integrity.erasable)
  @@index([tenantId, at])
  @@unique([chain, seq])
  @@map("audit_entries")
}

Then prisma migrate dev and prisma generate.

Upgrading from 1.1 ​

1.2 adds six nullable columns and a unique index for the hash chain and the request context. They are only written when you enable auditPlugin({ integrity: 'hash-chain' }) or requestContext — an app that upgrades without enabling them keeps working on the old schema. Before enabling them, add the columns to the model above and migrate; on PostgreSQL the migration is:

sql
ALTER TABLE "audit_entries"
  ADD COLUMN "ip" TEXT,
  ADD COLUMN "userAgent" TEXT,
  ADD COLUMN "chain" TEXT,
  ADD COLUMN "seq" INTEGER,
  ADD COLUMN "prevHash" TEXT,
  ADD COLUMN "hash" TEXT;
CREATE UNIQUE INDEX "audit_entries_chain_seq_key" ON "audit_entries"("chain", "seq");

Existing rows keep NULLs: audit.verify() reports them as unchained (legacy), not broken. A row outside the chain that is not legacy — a seq with a NULL or foreign chain, or a seq-less row written after the chain began — is reported in unverified and fails the verification. verifyAll() also visits tenants that have rows but no chain, found with one SELECT DISTINCT "tenantId" (auditTenants()) rather than a read of the whole trail. With schema-per-tenant, migrate every tenant schema (basalt tenant:migrate).

Upgrading from 2.0 ​

2.1 adds three nullable columns for erasing personal data: redaction and redactedBy (written by audit.redact()) and nonce (written only with integrity: { …, erasable: true }). Nothing writes them until you opt in, so an app that does neither needs no migration. Before the first erasure (or before turning erasable on), migrate — on PostgreSQL:

sql
ALTER TABLE "audit_entries"
  ADD COLUMN "redaction" TEXT,
  ADD COLUMN "redactedBy" TEXT,
  ADD COLUMN "nonce" TEXT;

On MySQL, schema.mysql.prisma makes them TEXT, VARCHAR(191) and VARCHAR(191). With erasable on, Audit reads its first entry back and throws if the nonce did not round-trip, rather than writing v3 entries that could never verify.

Harden the table ​

The @@unique([chain, seq]) constraint is what stops two replicas from forking a chain: the losing insert fails with P2002, which the store maps to AuditChainConflictError, and Audit retries on the new head. Also make the database enforce append-only, so the application role cannot rewrite history even if it is compromised:

sql
REVOKE UPDATE, DELETE, TRUNCATE ON "audit_entries" FROM app_role;
GRANT SELECT, INSERT ON "audit_entries" TO app_role;

Run migrations with a separate owner role. This stays the default even if you erase personal data — erasure goes through a dedicated role, below. See the @basaltkit/audit README for keyed chains (HMAC), anchoring the head, and basalt audit:verify. A hash (and prevHash) is self-describing — v2:hmac-sha256:<keyId>:<hex> — and holds up to 144 characters, which the VARCHAR(191) of schema.mysql.prisma fits; no migration is needed for key ids or key rotation.

Erasing personal data ​

audit.redact() / audit.systemRedact() (see the @basaltkit/audit README) work on this store: get() reads one row (findUnique, or findMany on a client without it), and redact() runs in one interactive $transaction — an updateMany that only matches while the row's hash and redactedBy are unchanged (AuditRedactionConflictError otherwise), then the attestation's create under @@unique([chain, seq]). Any error rolls both back. A client without $transaction / updateMany is refused with AuditRedactionRefusedError ('unsupported-store') before anything is written.

The eraser role ​

Keep the blanket REVOKE UPDATE above for the application role. Erasure is a rare, privileged operation: give it its own role, which may update only the columns erasure writes:

sql
CREATE ROLE audit_eraser LOGIN PASSWORD '…';
GRANT SELECT, INSERT ON "audit_entries" TO audit_eraser;
GRANT UPDATE ("payload", "ip", "userAgent", "nonce", "redaction", "redactedBy") ON "audit_entries" TO audit_eraser;

On MySQL: GRANT SELECT, INSERT, UPDATE (payload, ip, userAgent, nonce, redaction, redactedBy) ON audit_entries TO 'audit_eraser'@'%'.

Give the data-subject-request job — and only it — a second client connected as that role, and an Audit configured like the application's:

ts
const eraserAudit = new Audit(prismaAuditStore(eraserPrisma).store, undefined, () => true, sameAuditOptions)
await eraserAudit.systemRedact(entryId, { payload: ['customer.email'], reasonRef: 'DSR-2026-114' })

The two instances can race safely: the store's optimistic check and the (chain, seq) constraint resolve it.

Optionally, a trigger makes even the eraser role unable to touch anything but an attested redaction (header and hash columns unchanged, redactedBy set, a nonce never restored). It guards against bugs and a stolen eraser credential alike, but not against the table owner:

<!-- audit-prisma:postgres-guard -->

sql
CREATE OR REPLACE FUNCTION audit_entries_redaction_only() RETURNS trigger AS $$
BEGIN
  IF NEW."id" IS DISTINCT FROM OLD."id" OR NEW."source" IS DISTINCT FROM OLD."source"
     OR NEW."event" IS DISTINCT FROM OLD."event" OR NEW."actorId" IS DISTINCT FROM OLD."actorId"
     OR NEW."tenantId" IS DISTINCT FROM OLD."tenantId" OR NEW."requestId" IS DISTINCT FROM OLD."requestId"
     OR NEW."at" IS DISTINCT FROM OLD."at" OR NEW."chain" IS DISTINCT FROM OLD."chain"
     OR NEW."seq" IS DISTINCT FROM OLD."seq" OR NEW."prevHash" IS DISTINCT FROM OLD."prevHash"
     OR NEW."hash" IS DISTINCT FROM OLD."hash" OR NEW."redactedBy" IS NULL
     OR (OLD."nonce" IS NULL AND NEW."nonce" IS NOT NULL) THEN
    RAISE EXCEPTION 'audit_entries: only an attested redaction may update a row';
  END IF;
  RETURN NEW;
END
$$ LANGUAGE plpgsql;

CREATE OR REPLACE TRIGGER audit_entries_redaction_only
  BEFORE UPDATE ON "audit_entries"
  FOR EACH ROW EXECUTE FUNCTION audit_entries_redaction_only();

<!-- /audit-prisma:postgres-guard -->

2. Wire the store ​

ts
import { auditPlugin } from '@basaltkit/audit'
import { prismaAuditStore } from '@basaltkit/audit-prisma'
import { PrismaClient } from '@prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! })

const prisma = new PrismaClient({ adapter })
const a = prismaAuditStore(prisma)   // pass your client directly, no cast

createApp({ plugins: [auditPlugin({ store: a.store })] })

MySQL ​

The reference schema above is written for PostgreSQL (and works on SQLite), where a bare String is TEXT. On MySQL Prisma makes it VARCHAR(191), and a server outside strict mode truncates a longer value silently — the write succeeds, and the value read back is not the one written. For an audit trail that is worse than lost data: a truncated payload or hash breaks the hash chain, and audit.verify() fails on that row forever. With the guard the append is refused before the insert, and the chain stays as it was.

  • Copy schema.mysql.prisma instead (exported as @basaltkit/audit-prisma/schema.mysql.prisma; basalt prisma:sync picks it when your datasource is mysql): the free-text columns are widened with native types, the keys stay VARCHAR(191) so they can be indexed.

  • Turn on the guard, so a value that still would not fit is refused (ColumnLengthError, code COLUMN_LENGTH_EXCEEDED, status 422, nothing written) instead of cut:

    ts
    prismaAuditStore(prisma, { columnLimits: 'mysql' })

    'mysql' is auditMysqlColumnLimits — the capacities of schema.mysql.prisma. A number is a limit in characters (VARCHAR(n)), { bytes: n } a limit in UTF-8 bytes (the TEXT family). Widened a column yourself? Spread the preset and raise it: { AuditEntry: { ...auditMysqlColumnLimits.AuditEntry, event: 500 } }.

  • Keep MySQL in strict mode (STRICT_TRANS_TABLES) as well.

Unset (the default), nothing is checked — PostgreSQL and SQLite are unaffected. See the MySQL section of the persistence guide.

Notes ​

  • Append-only by contract — no delete, and no update but the attested erasure (enforce it in the database too — see above).
  • PrismaAuditClient also accepts optional count, findUnique and updateMany delegates and $transaction (every generated client has them): count lets verify() count unchained legacy rows; the others back get() / redact().
  • Queries return newest-first with the same filters as the in-memory store (tenantId, actorId, since, chainedOnly, and the event wildcard auth:**). limit always counts only pattern-matched rows.
  • Filters are type-checked before Prisma sees them (assertAuditQuery), even when the store is called directly. tenantId, actorId and event go into where as values, so an object such as { not: 'x' } — what qs makes of ?tenantId[not]=x — would be read by Prisma as an operator; it throws a TypeError instead, as does a limit that is not a non-negative safe integer.
  • The payload is stored as JSON text and round-trips unchanged.
  • For database-per-tenant, route the store through the active tenant's client — see the Database-per-tenant guide.
  • PrismaAuditClient types delegate arguments as any (returns stay precise) so a real PrismaClient is assignable and passes directly.
  • Query pushdown. Every exact filter — tenant, actor, since, and an event name with no wildcard — plus the limit go into the database (take / LIMIT). Only a wildcard pattern still needs matching in code, and then rows are read in bounded 500-row pages that stop as soon as the limit is satisfied, so a limit: 50 query never materialises the whole trail. A pattern containing . is deliberately not pushed down: patternMatches treats . and : as interchangeable separators, so an equality would miss a:b for a.b.

License ​

MIT

Released under the MIT License.