@auditstream/node 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,348 @@
1
+ # @auditstream/node
2
+
3
+ Actor context propagation, application event logging, history helpers, and web framework integrations for [Auditstream](https://github.com/auditstream/auditstream).
4
+
5
+ `@auditstream/node` tracks who initiated each request with `AsyncLocalStorage`. ORM adapters read that scope and pass it to PostgreSQL triggers.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @auditstream/node
11
+ ```
12
+
13
+ Framework subpaths have optional peer dependencies. Install only the framework your app uses:
14
+
15
+ ```sh
16
+ pnpm add @auditstream/node express
17
+ pnpm add @auditstream/node hono
18
+ pnpm add @auditstream/node next
19
+ ```
20
+
21
+ ## Supported versions
22
+
23
+ | Dependency | Supported in v0.1 |
24
+ | --- | --- |
25
+ | Node.js | `22.12` or newer (CI tests `22`, `24`, and `26`) |
26
+ | PostgreSQL | `15` to `19` |
27
+ | Prisma | `@prisma/client` `7.1` or newer within `7.x` (Prisma 6 is unsupported; Prisma 8 follows its stable release; the `prisma` CLI is never a peer) |
28
+ | Drizzle | `0.45` and `1.x` |
29
+ | Runtimes | Node.js (reference), Bun and Deno (tested in CI), Cloudflare Workers (`nodejs_als` flag or compatibility date `2026-08-04` or later) |
30
+
31
+ `@auditstream/node` is ESM-only so every package shares one `AsyncLocalStorage` instance.
32
+
33
+ ## Quick start
34
+
35
+ ### Actor scope and current actor
36
+
37
+ Wrap request work in `audit.as()` and inspect the active scope with `audit.current()`.
38
+
39
+ ```ts
40
+ import {
41
+ type Actor,
42
+ type ActorType,
43
+ type AuditAsOptions,
44
+ type AuditContext,
45
+ type AuditNamespace,
46
+ type AuditScope,
47
+ AuditstreamError,
48
+ type AuditstreamErrorCode,
49
+ audit,
50
+ MAX_PAYLOAD_BYTES,
51
+ type NestedActor,
52
+ PACKAGE_NAME,
53
+ } from "@auditstream/node";
54
+
55
+ const delegate: NestedActor = { type: "user", id: "usr_42", tenant: "org_acme" };
56
+ const actorType: ActorType = "ai_agent";
57
+ const actor: Actor = { type: actorType, id: "billing-agent", onBehalfOf: delegate };
58
+ const context: AuditContext = { requestId: "req_123", source: "api" };
59
+ const options: AuditAsOptions = { context };
60
+ const ns: AuditNamespace = audit;
61
+
62
+ const result = await ns.as(
63
+ actor,
64
+ async () => {
65
+ const scope: AuditScope | undefined = ns.current();
66
+ return scope?.actor.id;
67
+ },
68
+ options,
69
+ );
70
+
71
+ const err = new AuditstreamError("INVALID_ACTOR", "actor.id is required");
72
+ const code: AuditstreamErrorCode = err.code;
73
+ void [result, code, MAX_PAYLOAD_BYTES, PACKAGE_NAME];
74
+ ```
75
+
76
+ ### Application events (`audit.log`)
77
+
78
+ Record domain events that do not modify a table through `auditstream.log_event()`.
79
+
80
+ ```ts
81
+ import {
82
+ type AuditLogEvent,
83
+ type AuditLogExecutor,
84
+ type AuditLogValues,
85
+ audit,
86
+ LOG_EVENT_SQL,
87
+ MAX_ACTION_LENGTH,
88
+ } from "@auditstream/node";
89
+
90
+ const exec: AuditLogExecutor = async (text: string, values: AuditLogValues) => {
91
+ void [text, values];
92
+ };
93
+
94
+ const event: AuditLogEvent = {
95
+ action: "invoice.exported",
96
+ target: { invoice_id: 42 },
97
+ data: { format: "csv" },
98
+ };
99
+
100
+ await audit.as({ type: "user", id: "usr_42" }, () => audit.log(exec, event));
101
+ void [LOG_EVENT_SQL, MAX_ACTION_LENGTH];
102
+ ```
103
+
104
+ ### Reading record history and export records
105
+
106
+ Query a record's audit timeline with `audit.history()`, or validate JSON Lines export rows with `parseExportRecord()`.
107
+
108
+ ```ts
109
+ import {
110
+ type ActorSource,
111
+ type AuditHistoryExecutor,
112
+ type AuditHistoryQuery,
113
+ type AuditHistoryQueryResult,
114
+ type AuditHistoryValues,
115
+ type AuditOp,
116
+ audit,
117
+ type DbOp,
118
+ DEFAULT_HISTORY_LIMIT,
119
+ type EventSourceKind,
120
+ type ExportRecord,
121
+ type HistoryEntry,
122
+ type JsonObject,
123
+ type JsonPrimitive,
124
+ type JsonValue,
125
+ MAX_HISTORY_LIMIT,
126
+ parseExportRecord,
127
+ SUPPORTED_SCHEMA_VERSION,
128
+ } from "@auditstream/node";
129
+
130
+ const exec: AuditHistoryExecutor = async (
131
+ _text: string,
132
+ _values: AuditHistoryValues,
133
+ ): Promise<AuditHistoryQueryResult> => ({ rows: [] });
134
+
135
+ const recordId: JsonObject = { id: 42 };
136
+ const query: AuditHistoryQuery = {
137
+ table: "invoice",
138
+ recordId,
139
+ limit: DEFAULT_HISTORY_LIMIT,
140
+ };
141
+
142
+ const entries: HistoryEntry[] = await audit.history(exec, query);
143
+ const exported: ExportRecord = parseExportRecord(
144
+ JSON.stringify({
145
+ event_id: "01955f2e-7b2a-7c10-9a11-111111111111",
146
+ occurred_at: "2026-11-24T12:00:00.000000Z",
147
+ source: "db" satisfies EventSourceKind,
148
+ schema_name: "public",
149
+ table_name: "invoice",
150
+ op: "UPDATE" satisfies DbOp satisfies AuditOp,
151
+ record_id: recordId,
152
+ before: { status: "open" },
153
+ after: { status: "paid" },
154
+ changed: ["status"],
155
+ actor: { type: "user", id: "usr_42" },
156
+ context: null,
157
+ actor_source: "comment" satisfies ActorSource,
158
+ db_user: "app_user",
159
+ schema_version: SUPPORTED_SCHEMA_VERSION,
160
+ }),
161
+ );
162
+
163
+ const prim: JsonPrimitive = "ok";
164
+ const val: JsonValue = [prim, recordId];
165
+ void [entries, exported, val, MAX_HISTORY_LIMIT];
166
+ ```
167
+
168
+ ### Querying history and application events (`audit.query`)
169
+
170
+ Use `audit.query()` for filtered, keyset-paginated queries across both database trigger rows (`source: "db"`) and application events written by `audit.log()` (`source: "app"`, where `table_name` is `null`).
171
+
172
+ > **Backend-only API:** `audit.query()` returns raw `HistoryEntry` rows including internal database metadata (`db_user`, `xact_id`, `table_oid`, `actor_source`) and raw `before`/`after` payloads. Always enforce authentication and tenant authorization on the server, and project each entry to an allowlisted client DTO before sending data to browsers. Note that `actor.tenant` is self-asserted actor metadata (absent when `actor` is `null`, `invalid`, or `jwt`); do not treat it as a replacement for row-level security. For high-QPS tenant feeds, add the opt-in partial expression indexes documented in [Opt-in tenant indexes](https://github.com/auditstream/auditstream/blob/main/docs/reference/cli/history.md#opt-in-tenant-indexes).
173
+
174
+ ```ts
175
+ import {
176
+ type AuditQuery,
177
+ type AuditQueryExecutor,
178
+ type AuditQueryPage,
179
+ type AuditQueryValues,
180
+ audit,
181
+ MAX_QUERY_OPS,
182
+ } from "@auditstream/node";
183
+
184
+ const exec: AuditQueryExecutor = async (_text: string, _values: AuditQueryValues) => ({
185
+ rows: [],
186
+ });
187
+
188
+ const query: AuditQuery = {
189
+ tenant: "org_acme",
190
+ source: "app",
191
+ opPrefix: "invoice.",
192
+ since: "2026-11-01T00:00:00Z",
193
+ limit: 25,
194
+ };
195
+
196
+ const page: AuditQueryPage = await audit.query(exec, query);
197
+ void [page.entries, page.nextCursor, page.hasMore, MAX_QUERY_OPS];
198
+ ```
199
+
200
+ ### Transport codec helpers
201
+
202
+ ORM adapters use `encodeScope()`, `decodeScope()`, `isTagged()`, `tagSql()`, and `setConfigValue()` directly.
203
+
204
+ ```ts
205
+ import {
206
+ type AuditScope,
207
+ type DecodedTransport,
208
+ decodeScope,
209
+ encodeScope,
210
+ isTagged,
211
+ MAX_ENCODED_COMMENT_CHARS,
212
+ setConfigValue,
213
+ tagSql,
214
+ } from "@auditstream/node";
215
+
216
+ const scope: AuditScope = { actor: { type: "user", id: "usr_42" } };
217
+ const encoded: string = encodeScope(scope);
218
+ const tagged: string = tagSql("UPDATE invoice SET status = 'paid' WHERE id = 1", scope);
219
+ const alreadyTagged: boolean = isTagged(tagged);
220
+ const decoded: DecodedTransport = decodeScope(tagged);
221
+ const settingJson: string = setConfigValue(scope);
222
+
223
+ void [encoded, alreadyTagged, decoded, settingJson, MAX_ENCODED_COMMENT_CHARS];
224
+ ```
225
+
226
+ ### Framework integrations
227
+
228
+ > **Security:** Always resolve `actor.id` and `actor.tenant` from a verified session, signed cookie, or validated JWT — never directly from unverified client headers such as `x-user-id`. If a reverse proxy or Next.js `proxy` forwards identity in a request header, it must strip or overwrite that header on every incoming request to prevent actor spoofing.
229
+
230
+ #### Express middleware (`@auditstream/node/express`)
231
+
232
+ ```ts
233
+ import {
234
+ auditstream,
235
+ type ExpressAuditOptions,
236
+ } from "@auditstream/node/express";
237
+ import express, { type Request } from "express";
238
+
239
+ interface AuthenticatedRequest extends Request {
240
+ user?: { id: string; tenantId?: string };
241
+ }
242
+
243
+ const options: ExpressAuditOptions = {
244
+ actor: (req) => {
245
+ const user = (req as AuthenticatedRequest).user;
246
+ if (!user) return undefined;
247
+ return user.tenantId
248
+ ? { type: "user", id: user.id, tenant: user.tenantId }
249
+ : { type: "user", id: user.id };
250
+ },
251
+ context: (req) => ({ requestId: req.header("x-request-id") ?? "req_unknown" }),
252
+ };
253
+
254
+ const app = express();
255
+ // Mount after your authentication middleware populates `req.user` from a verified session or JWT.
256
+ app.use(auditstream(options));
257
+ ```
258
+
259
+ #### Hono middleware (`@auditstream/node/hono`)
260
+
261
+ ```ts
262
+ import {
263
+ auditstream,
264
+ type HonoAuditOptions,
265
+ } from "@auditstream/node/hono";
266
+ import { Hono } from "hono";
267
+
268
+ declare function verifySession(
269
+ authorization: string | undefined,
270
+ ): Promise<{ id: string; tenantId?: string } | null>;
271
+
272
+ const options: HonoAuditOptions = {
273
+ actor: async (c) => {
274
+ const session = await verifySession(c.req.header("authorization"));
275
+ if (!session) return undefined;
276
+ return session.tenantId
277
+ ? { type: "user", id: session.id, tenant: session.tenantId }
278
+ : { type: "user", id: session.id };
279
+ },
280
+ };
281
+
282
+ const app = new Hono();
283
+ app.use("*", auditstream(options));
284
+ ```
285
+
286
+ #### Next.js Route Handlers and Server Actions (`@auditstream/node/next`)
287
+
288
+ ```ts
289
+ import {
290
+ auditAction,
291
+ type NextActionAuditOptions,
292
+ type NextAuditOptions,
293
+ withAudit,
294
+ } from "@auditstream/node/next";
295
+
296
+ declare function getVerifiedSession(
297
+ request?: Request,
298
+ ): Promise<{ userId: string; tenantId?: string } | null>;
299
+
300
+ const routeOptions: NextAuditOptions = {
301
+ actor: async (request) => {
302
+ const session = await getVerifiedSession(request);
303
+ if (!session) return undefined;
304
+ return session.tenantId
305
+ ? { type: "user", id: session.userId, tenant: session.tenantId }
306
+ : { type: "user", id: session.userId };
307
+ },
308
+ };
309
+
310
+ export const POST = withAudit(async (_request: Request) => new Response("ok"), routeOptions);
311
+
312
+ const actionOptions: NextActionAuditOptions<[invoiceId: number]> = {
313
+ actor: async () => {
314
+ const session = await getVerifiedSession();
315
+ return session ? { type: "user", id: session.userId } : undefined;
316
+ },
317
+ };
318
+
319
+ export const approveInvoice = auditAction(async (invoiceId: number) => invoiceId, actionOptions);
320
+ ```
321
+
322
+ ## Context and limits
323
+
324
+ ```mermaid
325
+ flowchart LR
326
+ Request["HTTP request or job"] --> Scope["audit.as() AsyncLocalStorage"]
327
+ Scope --> Adapter["ORM or driver adapter"]
328
+ Adapter --> Transport["Trailing comment or set_config"]
329
+ Transport --> Trigger["PostgreSQL capture trigger"]
330
+ Trigger --> History["auditstream.changes row"]
331
+ ```
332
+
333
+ Where context propagation stops:
334
+
335
+ - **Unawaited lazy queries:** Returning a lazy query without awaiting it exits the scope early. `audit.as()` awaits its callback inside the scope to prevent this.
336
+ - **Next.js `proxy`:** `proxy` cannot carry `AsyncLocalStorage` into Route Handlers or Server Actions. Pass identity via headers, cookies, rewrites, redirects, or URLs, and wrap handlers with `withAudit()` or `auditAction()`.
337
+ - **Background jobs:** Work outside a request has no ambient scope. Open a fresh `audit.as()` scope with a `service` or `system` actor.
338
+ - **Prisma Accelerate:** SQL comment plugins do not see queries under Accelerate. Wrap writes in `auditTransaction()` from `@auditstream/prisma`.
339
+ - **AWS RDS Proxy:** Trailing SQL comments are the default transport because `set_config(..., true)` pins server sessions on RDS Proxy.
340
+ - **Cloudflare Workers:** Enable the `nodejs_als` flag, or use a compatibility date of `2026-08-04` or later. `@auditstream/node` uses `AsyncLocalStorage.run()` only.
341
+
342
+ ## Links
343
+
344
+ - [Auditstream engine repository](https://github.com/auditstream/auditstream)
345
+ - [Engineering handbook](https://github.com/auditstream/auditstream/tree/main/docs/handbook)
346
+ - [Adapters design](https://github.com/auditstream/auditstream/blob/main/docs/handbook/adapters.md)
347
+ - [Transport specification](https://github.com/auditstream/auditstream/blob/main/spec/transport.md)
348
+ - [Supported versions](https://github.com/auditstream/auditstream/blob/main/docs/handbook/releases.md#supported-versions)
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Allowed actor categories defined by Auditstream Specification 0.1.0.
3
+ */
4
+ type ActorType = "user" | "api_key" | "ai_agent" | "service" | "system";
5
+ /**
6
+ * Maximum UTF-8 byte length of the compact serialized actor + context JSON payload.
7
+ */
8
+ declare const MAX_PAYLOAD_BYTES: 512;
9
+ /**
10
+ * A nested actor inside `Actor.onBehalfOf` (strictly one level deep; cannot carry `onBehalfOf`).
11
+ */
12
+ interface NestedActor {
13
+ /** Category of the nested actor. */
14
+ readonly type: ActorType;
15
+ /** Non-empty opaque identifier for the nested actor. */
16
+ readonly id: string;
17
+ /** Optional non-empty opaque tenant or organization identifier. */
18
+ readonly tenant?: string;
19
+ /** Disallowed: `onBehalfOf` nesting is strictly limited to one level. */
20
+ readonly onBehalfOf?: never;
21
+ }
22
+ /**
23
+ * Actor payload defined by Auditstream Specification 0.1.0.
24
+ */
25
+ interface Actor {
26
+ /** Actor category (`user`, `api_key`, `ai_agent`, `service`, or `system`). */
27
+ readonly type: ActorType;
28
+ /** Non-empty opaque identifier for the actor. */
29
+ readonly id: string;
30
+ /** Optional nested actor on whose behalf this actor acted (max depth 1). */
31
+ readonly onBehalfOf?: NestedActor;
32
+ /** Optional non-empty opaque tenant or organization identifier. */
33
+ readonly tenant?: string;
34
+ }
35
+ /**
36
+ * Optional execution context carried alongside an actor.
37
+ *
38
+ * `ip` and `userAgent` are opt-in only and should not be sent unless explicitly enabled.
39
+ */
40
+ interface AuditContext {
41
+ /** Optional non-empty correlation identifier for the request or job. */
42
+ readonly requestId?: string;
43
+ /** Optional non-empty entry surface label (for example `web`, `api`, `cli`, `worker`). */
44
+ readonly source?: string;
45
+ /** Optional opt-in client IP address. */
46
+ readonly ip?: string;
47
+ /** Optional opt-in client user-agent string. */
48
+ readonly userAgent?: string;
49
+ }
50
+ /**
51
+ * Active actor and optional context stored in the current `AsyncLocalStorage` scope.
52
+ */
53
+ interface AuditScope {
54
+ /** Validated actor for the current scope. */
55
+ readonly actor: Actor;
56
+ /** Optional validated context for the current scope. */
57
+ readonly context?: AuditContext;
58
+ }
59
+ /**
60
+ * Options accepted by {@link AuditNamespace.as}.
61
+ */
62
+ interface AuditAsOptions {
63
+ /** Optional execution context attached to the actor scope. */
64
+ readonly context?: AuditContext;
65
+ }
66
+ /**
67
+ * Machine-readable error codes emitted by {@link AuditstreamError}.
68
+ */
69
+ type AuditstreamErrorCode = "INVALID_ACTOR" | "INVALID_CONTEXT" | "PAYLOAD_TOO_LARGE" | "INVALID_EVENT" | "INVALID_RECORD" | "INVALID_QUERY";
70
+ /**
71
+ * Error thrown by Auditstream when an actor or context payload violates Specification 0.1.0.
72
+ */
73
+ declare class AuditstreamError extends Error {
74
+ /** Machine-readable error category. */
75
+ readonly code: AuditstreamErrorCode;
76
+ /** Creates a new {@link AuditstreamError} with a machine-readable `code` and message. */
77
+ constructor(code: AuditstreamErrorCode, message: string);
78
+ }
79
+ export { AuditScope as a, MAX_PAYLOAD_BYTES as c, AuditContext as i, NestedActor as l, ActorType as n, AuditstreamError as o, AuditAsOptions as r, AuditstreamErrorCode as s, Actor as t };
@@ -0,0 +1,141 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ // src/context.ts
3
+ const VALID_ACTOR_TYPES = /* @__PURE__ */ new Set([
4
+ "user",
5
+ "api_key",
6
+ "ai_agent",
7
+ "service",
8
+ "system"
9
+ ]);
10
+ /**
11
+ * Maximum UTF-8 byte length of the compact serialized actor + context JSON payload.
12
+ */
13
+ const MAX_PAYLOAD_BYTES = 512;
14
+ /**
15
+ * Error thrown by Auditstream when an actor or context payload violates Specification 0.1.0.
16
+ */
17
+ var AuditstreamError = class extends Error {
18
+ /** Machine-readable error category. */
19
+ code;
20
+ /** Creates a new {@link AuditstreamError} with a machine-readable `code` and message. */
21
+ constructor(code, message) {
22
+ super(message);
23
+ this.name = "AuditstreamError";
24
+ this.code = code;
25
+ }
26
+ };
27
+ const textEncoder = new TextEncoder();
28
+ const SCOPE_STORAGE_SYMBOL = Symbol.for("auditstream.node.scopeStorage.v1");
29
+ const SCOPE_CACHE_SYMBOL = Symbol.for("auditstream.node.scopeCache.v1");
30
+ function getSharedScopeStorage() {
31
+ const globalStore = globalThis;
32
+ const existing = globalStore[SCOPE_STORAGE_SYMBOL];
33
+ if (existing instanceof AsyncLocalStorage) return existing;
34
+ const created = new AsyncLocalStorage();
35
+ globalStore[SCOPE_STORAGE_SYMBOL] = created;
36
+ return created;
37
+ }
38
+ function getSharedScopeCache() {
39
+ const globalStore = globalThis;
40
+ const existing = globalStore[SCOPE_CACHE_SYMBOL];
41
+ if (existing instanceof WeakMap) return existing;
42
+ const created = /* @__PURE__ */ new WeakMap();
43
+ globalStore[SCOPE_CACHE_SYMBOL] = created;
44
+ return created;
45
+ }
46
+ const scopeStorage = getSharedScopeStorage();
47
+ const scopeCache = getSharedScopeCache();
48
+ /**
49
+ * Internal lookup used by `transport.ts` to reuse canonical JSON, UTF-8 bytes, and encoded tags
50
+ * for deeply frozen scopes created by `audit.as()`.
51
+ */
52
+ function getCachedScopePayload(scope) {
53
+ return scopeCache.get(scope);
54
+ }
55
+ function isPlainObject(value) {
56
+ return typeof value === "object" && value !== null && !Array.isArray(value);
57
+ }
58
+ function assertNonEmptyString(value, field, code) {
59
+ if (typeof value !== "string" || value.length === 0) throw new AuditstreamError(code, `${field} must be a non-empty string`);
60
+ }
61
+ function validateNestedActor(raw) {
62
+ if (!isPlainObject(raw)) throw new AuditstreamError("INVALID_ACTOR", "actor.onBehalfOf must be a JSON object");
63
+ if (typeof raw.type !== "string" || !VALID_ACTOR_TYPES.has(raw.type)) throw new AuditstreamError("INVALID_ACTOR", `actor.onBehalfOf.type must be one of user, api_key, ai_agent, service, system`);
64
+ assertNonEmptyString(raw.id, "actor.onBehalfOf.id", "INVALID_ACTOR");
65
+ if (raw.tenant !== void 0) assertNonEmptyString(raw.tenant, "actor.onBehalfOf.tenant", "INVALID_ACTOR");
66
+ if ("onBehalfOf" in raw && raw.onBehalfOf !== void 0) throw new AuditstreamError("INVALID_ACTOR", "actor.onBehalfOf must not contain a nested onBehalfOf (max depth is 1)");
67
+ const nested = {
68
+ type: raw.type,
69
+ id: raw.id
70
+ };
71
+ if (raw.tenant !== void 0) nested.tenant = raw.tenant;
72
+ return Object.freeze(nested);
73
+ }
74
+ function validateActor(raw) {
75
+ if (!isPlainObject(raw)) throw new AuditstreamError("INVALID_ACTOR", "actor must be a JSON object");
76
+ if (typeof raw.type !== "string" || !VALID_ACTOR_TYPES.has(raw.type)) throw new AuditstreamError("INVALID_ACTOR", `actor.type must be one of user, api_key, ai_agent, service, system`);
77
+ assertNonEmptyString(raw.id, "actor.id", "INVALID_ACTOR");
78
+ let onBehalfOf;
79
+ if (raw.onBehalfOf !== void 0) onBehalfOf = validateNestedActor(raw.onBehalfOf);
80
+ if (raw.tenant !== void 0) assertNonEmptyString(raw.tenant, "actor.tenant", "INVALID_ACTOR");
81
+ const actor = {
82
+ type: raw.type,
83
+ id: raw.id
84
+ };
85
+ if (onBehalfOf !== void 0) actor.onBehalfOf = onBehalfOf;
86
+ if (raw.tenant !== void 0) actor.tenant = raw.tenant;
87
+ return Object.freeze(actor);
88
+ }
89
+ function validateContext(raw) {
90
+ if (!isPlainObject(raw)) throw new AuditstreamError("INVALID_CONTEXT", "context must be a JSON object");
91
+ const context = {};
92
+ if (raw.requestId !== void 0) {
93
+ assertNonEmptyString(raw.requestId, "context.requestId", "INVALID_CONTEXT");
94
+ context.requestId = raw.requestId;
95
+ }
96
+ if (raw.source !== void 0) {
97
+ assertNonEmptyString(raw.source, "context.source", "INVALID_CONTEXT");
98
+ context.source = raw.source;
99
+ }
100
+ if (raw.ip !== void 0) {
101
+ assertNonEmptyString(raw.ip, "context.ip", "INVALID_CONTEXT");
102
+ context.ip = raw.ip;
103
+ }
104
+ if (raw.userAgent !== void 0) {
105
+ assertNonEmptyString(raw.userAgent, "context.userAgent", "INVALID_CONTEXT");
106
+ context.userAgent = raw.userAgent;
107
+ }
108
+ return Object.freeze(context);
109
+ }
110
+ function buildValidatedScope(rawActor, rawContext) {
111
+ const actor = validateActor(rawActor);
112
+ const context = rawContext === void 0 ? void 0 : validateContext(rawContext);
113
+ const payload = context === void 0 ? actor : {
114
+ ...actor,
115
+ context
116
+ };
117
+ const serialized = JSON.stringify(payload);
118
+ const bytes = textEncoder.encode(serialized);
119
+ if (bytes.byteLength > 512) throw new AuditstreamError("PAYLOAD_TOO_LARGE", `serialized actor payload is ${bytes.byteLength} UTF-8 bytes, exceeding the 512-byte limit`);
120
+ const scope = { actor };
121
+ if (context !== void 0) scope.context = context;
122
+ const frozenScope = Object.freeze(scope);
123
+ scopeCache.set(frozenScope, {
124
+ json: serialized,
125
+ bytes
126
+ });
127
+ return frozenScope;
128
+ }
129
+ /**
130
+ * Shared Auditstream runtime entry point providing `audit.as()` and `audit.current()`.
131
+ */
132
+ const audit = {
133
+ async as(actor, fn, options) {
134
+ const scope = buildValidatedScope(actor, options?.context);
135
+ return await scopeStorage.run(scope, async () => await fn());
136
+ },
137
+ current() {
138
+ return scopeStorage.getStore();
139
+ }
140
+ };
141
+ export { getCachedScopePayload as i, MAX_PAYLOAD_BYTES as n, audit as r, AuditstreamError as t };
@@ -1,2 +1,32 @@
1
- /** Subpath identifier exported by the workspace skeleton. */
2
- export declare const SUBPATH: "@auditstream/node/express";
1
+ import { Request, RequestHandler } from "express";
2
+ import { i as AuditContext, l as NestedActor, n as ActorType, t as Actor } from "./context-DOOKYTIY.mjs";
3
+ /**
4
+ * Options for the Express {@link auditstream} middleware.
5
+ *
6
+ * Auditstream never parses sessions, cookies, or JWTs on its own; pass an `actor`
7
+ * resolver that maps the incoming Express request to an {@link Actor} or `undefined`.
8
+ */
9
+ export interface ExpressAuditOptions {
10
+ /**
11
+ * Resolves the actor for the incoming request.
12
+ *
13
+ * Return `undefined` to run downstream handlers with no active Auditstream scope.
14
+ * Any thrown error or rejected promise is forwarded to Express via `next(err)` and
15
+ * prevents downstream route handlers from running.
16
+ */
17
+ readonly actor: (req: Request) => Actor | undefined | PromiseLike<Actor | undefined>;
18
+ /**
19
+ * Optional execution context resolver for the request (for example `requestId` or `source`).
20
+ * Only called when `actor` resolves to an {@link Actor}.
21
+ */
22
+ readonly context?: (req: Request) => AuditContext | undefined | PromiseLike<AuditContext | undefined>;
23
+ }
24
+ /**
25
+ * Creates Express middleware that opens one `audit.as()` actor scope per request.
26
+ *
27
+ * Uses `AsyncLocalStorage.run()` exclusively via `@auditstream/node` (no `enterWith()`).
28
+ * Resolver errors and invalid actor payloads (`AuditstreamError`) are forwarded to
29
+ * Express's error handler via `next(err)` without invoking downstream route handlers.
30
+ */
31
+ export declare function auditstream(options: ExpressAuditOptions): RequestHandler;
32
+ export type { Actor, ActorType, AuditContext, NestedActor };
package/dist/express.mjs CHANGED
@@ -1,4 +1,56 @@
1
+ import { r as audit } from "./context-pPVY39Lw.mjs";
1
2
  // src/express.ts
2
- /** Subpath identifier exported by the workspace skeleton. */
3
- const SUBPATH = "@auditstream/node/express";
4
- export { SUBPATH };
3
+ function isPromiseLike(value) {
4
+ return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
5
+ }
6
+ /**
7
+ * Creates Express middleware that opens one `audit.as()` actor scope per request.
8
+ *
9
+ * Uses `AsyncLocalStorage.run()` exclusively via `@auditstream/node` (no `enterWith()`).
10
+ * Resolver errors and invalid actor payloads (`AuditstreamError`) are forwarded to
11
+ * Express's error handler via `next(err)` without invoking downstream route handlers.
12
+ */
13
+ function auditstream(options) {
14
+ return (req, _res, next) => {
15
+ const enterScope = (actor, context) => {
16
+ if (actor === void 0) {
17
+ next();
18
+ return;
19
+ }
20
+ audit.as(actor, () => {
21
+ next();
22
+ }, context === void 0 ? void 0 : { context }).catch(next);
23
+ };
24
+ try {
25
+ const actorOrPromise = options.actor(req);
26
+ if (isPromiseLike(actorOrPromise)) {
27
+ Promise.resolve(actorOrPromise).then(async (actor) => {
28
+ if (actor === void 0) {
29
+ next();
30
+ return;
31
+ }
32
+ const context = options.context ? await options.context(req) : void 0;
33
+ await audit.as(actor, () => {
34
+ next();
35
+ }, context === void 0 ? void 0 : { context });
36
+ }).catch(next);
37
+ return;
38
+ }
39
+ if (actorOrPromise === void 0) {
40
+ next();
41
+ return;
42
+ }
43
+ const contextOrPromise = options.context?.(req);
44
+ if (contextOrPromise !== void 0 && isPromiseLike(contextOrPromise)) {
45
+ Promise.resolve(contextOrPromise).then((context) => audit.as(actorOrPromise, () => {
46
+ next();
47
+ }, context === void 0 ? void 0 : { context })).catch(next);
48
+ return;
49
+ }
50
+ enterScope(actorOrPromise, contextOrPromise);
51
+ } catch (error) {
52
+ next(error);
53
+ }
54
+ };
55
+ }
56
+ export { auditstream };