On this page
  1. Install
  2. Compose event-driven audit
  3. Configuration reference
  4. Audit entry properties
  5. Persistence bridge
  6. Retention and scoped erasure
  7. Direct application routes
  8. Boundary
  9. API entry points and requirements
  10. Peer dependencies

This guide describes upcoming source contracts, not a publication receipt. Check release availability and keep your complete Playstack graph on one verified version.

@playstack/audit

Append-only, per-scope tamper-evident audit chains for Node and Workers.

Reference: @playstack/audit@0.1.0-beta.5 · TypeScript

Pro. Covered by the Playstack Pro License. Registry access is required; check preview availability before installing. See package access.

@playstack/audit records security- and administration-relevant activity in append-only, per-scope tamper-evident chains for Node and Workers.

Install

sh
npm install @playstack/audit @playstack/core @playstack/events

Compose event-driven audit

ts
import {
  bindAuditRegistry,
  createAuditService,
  Sha256AuditHash,
} from '@playstack/audit'

const audit = createAuditService({
  persistence,
  hash: new Sha256AuditHash(applicationCrypto),
  clock,
  ids,
  mapper: {
    map: (event, payload) => ({
      scopeType: event.context.scope?.type ?? 'system',
      scopeId: event.context.scope?.id ?? 'global',
      actorType: event.context.actor?.type ?? 'system',
      actorId: event.context.actor?.id,
      resourceType: payload.resourceType as string,
      resourceId: payload.resourceId as string,
    }),
  },
  retention: {
    mode: 'calendar-months',
    months: 84,
    policyReference: 'docs/policies/audit-retention.md',
  },
})

const dispose = bindAuditRegistry(events, registry, audit)
events.assertReady()

The event definition chooses the audit tier and projected fields. The application mapper supplies scope, actor, resource, and impersonation facts because those cannot be inferred safely from arbitrary payload names. The recorded action defaults to the event name without its first (package) segment, so accounts.member.joined is audited as member.joined; a mapper may return action to override that, for example to keep the full event name when two packages share a suffix.

Configuration reference

AuditServiceOptions propertyRequiredPurpose
persistenceYesTransactional append, locked chain-tail lookup, query, and integrity reads.
hashYesdigest(value) for canonical entry hashing.
clock, idsYesApplication-owned timestamps and entry identifiers.
mapperYesMaps a typed event and projected payload to scope, actor, and resource facts.
retention.modeYescalendar-months, duration, or until-deletion; select one explicit policy.
retention.monthsFor calendar-monthsPositive whole calendar months, aligned to the UTC month boundary.
retention.durationMsFor durationPositive safe-integer milliseconds; for example, 30 * 24 * 60 * 60 * 1000 for exactly 30 days.
retention.policyReferenceYesApplication-owned policy document that justifies the selected policy.

The validated retention policy is exposed as audit.retention so storage, scheduled partition maintenance, and framework adapters use the same decision.

prune(scopeType, scopeId, limit) preserves a verified chain checkpoint while removing a bounded expired prefix. Duration policies use the exact current clock minus durationMs; calendar policies use the first day of the current UTC month minus months. Entries exactly at the cutoff remain. until-deletion disables age pruning and does not load the history merely to return zero.

Retention does not install a deletion worker. For any selected mode, compose scopeLifecycle.isOpen(scope, transaction) with the authoritative user/account lifecycle and invoke erase(scopeType, scopeId, transaction) only after that scope is closed, on the same physical transaction. Unavailable authority must throw, and scope IDs must never be reused. until-deletion expresses the absence of an age cutoff; the application still owns the deletion trigger and qualification.

Audit entry properties

GroupProperties
Identityid, at, scopeType, scopeId.
ActoractorType, optional actorId, onBehalfOfId, and apiKeyId.
Actionaction, resourceType, resourceId.
DetailOptional changes and context; secret- and PII-shaped keys are recursively redacted.
ChainOptional prevHash and required hash.

Queries always require scopeType and scopeId, with optional actor, resource, action, time range, cursor, and limit filters.

Built-in actor types are user, apiKey, staff, and system. The string contract is intentionally extensible, so applications can record actors such as partner, service, or another authenticated principal without converting them into a user. Actor identifiers remain optional only for system activity.

Persistence bridge

AuditPersistence must lock the scopeType/scopeId chain while reading its tail and appending the next record—even when the chain is empty. Transactional event handlers receive the emitting transaction and fail the mutation if audit storage fails. Queued handlers open their own transaction after outbox delivery.

@playstack/audit/prisma requires an explicit trusted schema, for example new PrismaAuditPersistence(client, { schema: 'app' }). Every history, checkpoint, head and replay-receipt query is qualified to that schema; temporary tables and search_path changes cannot redirect native append or verification.

Compose the managed Prisma fragment, then apply the immutable @playstack/audit/postgres-protection.sql resource in a reviewed owner-run migration. Prisma tables alone do not install the required protection. The package-owned INSERT trigger advances AuditAppendHead atomically, allowing ordinary non-owner writers SELECT/INSERT-only access to history. Checkpoints remain maintenance-owned and unchanged by append. Verification checks both the trusted checkpoint-time tail and the exact protected current head.

Use separate writer, verifier and maintenance credentials; writers cannot rewrite history, heads or trusted anchors. Native append refuses to acknowledge a write when its head did not advance, so a propagated transaction failure also rolls back application changes. First activation on populated history/checkpoints refuses rather than inventing a trusted head; existing data needs an explicit reviewed activation. The application owns migrations, grants, partition operations and maintenance scheduling.

Retention and scoped erasure

Select an explicit retention mode: calendar months, exact duration or retention until owner erasure. Native pruning is checkpoint-aware; adopt the complete history, protected append-head and checkpoint schema with their reviewed role grants. Ordinary append writers must not be able to forge maintenance anchors.

Scoped erasure is authorized maintenance, not a deletion scheduler or a complete cross-store privacy workflow. Keep required lifecycle evidence and local cleanup on the same transaction, preserve retained-chain verification and reconcile external stores/backups separately. Qualify real non-owner writer/verifier/ maintenance grants, rollback and tamper refusal before activation. Choosing the legal retention policy and scheduling maintenance remain application decisions.

Direct application routes

Package events are the authoritative audit path for security-critical domain operations. Use @playstack/nest-audit for explicitly declared application routes whose successful responses should be recorded on a best-effort basis.

Boundary

Audit is not the general event store and does not record every event. The application owns retention policy, storage access control, operator workflows, partition operations, and the decision about which application-specific events are auditable.

API entry points and requirements

Reference snapshot: @playstack/audit@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.

Public entry pointDeclaration file
@playstack/audit./dist/index.d.ts
@playstack/audit/errors./dist/errors.d.ts
@playstack/audit/prisma./dist/prisma.d.ts
@playstack/audit/testing./dist/testing.d.ts
@playstack/audit/playstack.artifacts.jsonNo TypeScript declaration (asset or metadata export).
@playstack/audit/package.jsonNo TypeScript declaration (asset or metadata export).
@playstack/audit/postgres-protection.sqlNo TypeScript declaration (asset or metadata export).

Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.

Peer dependencies

This package declares no peer dependencies. Its ordinary dependencies are resolved by the package manager.

For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.

Go

Playstack Pro tag
OriginsPricingBlogChangelogStatus

© 2026 Playstack. All rights reserved.

With OSS

By

Commune Software