@agentlaw/audit 0.1.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,20 @@
1
+ # @agentlaw/audit
2
+
3
+ Tamper-evident audit log for AI agent actions, part of [AgentLaw](https://github.com/Mounaji-Webs/agentlaw). Hash-chained JSONL: every decision the policy engine takes lands as an entry whose hash covers its content plus the previous entry — an edit or deletion anywhere breaks the chain.
4
+
5
+ ```ts
6
+ import { AuditWriter, verifyAuditDir } from "@agentlaw/audit";
7
+
8
+ const audit = await AuditWriter.open({ dir: ".agentlaw/audit", policyHash });
9
+ audit.append("decision", { tool: "shell", decision: "deny", ruleId: "no-rm" });
10
+
11
+ const report = await verifyAuditDir(".agentlaw/audit");
12
+ // the report flags the exact entry the moment anything was altered
13
+ ```
14
+
15
+ - **Writer** — append-only JSONL, one chain per environment, secret redaction before anything is persisted.
16
+ - **Verifier** — recomputes the whole chain from canonical content; used by `agentlaw audit verify`.
17
+
18
+ Spec: [RFC-0002 — audit log](https://github.com/Mounaji-Webs/agentlaw/blob/main/spec/rfc-0002-audit-log.md).
19
+
20
+ Apache-2.0.
@@ -0,0 +1,5 @@
1
+ export { redactArgs, type RedactedArgs } from "./redact.js";
2
+ export type { AuditEntry, AuditEvent } from "./types.js";
3
+ export { verifyAuditDir, type AuditVerifyError, type AuditVerifyReport, type VerifyAuditOptions, } from "./verify.js";
4
+ export { auditFileName, AuditWriter, listAuditFiles, type AuditWriterOptions } from "./writer.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAC5D,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,EACL,cAAc,EACd,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,cAAc,EAAE,KAAK,kBAAkB,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { redactArgs } from "./redact.js";
2
+ export { verifyAuditDir, } from "./verify.js";
3
+ export { auditFileName, AuditWriter, listAuditFiles } from "./writer.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAqB,MAAM,aAAa,CAAC;AAE5D,OAAO,EACL,cAAc,GAIf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,cAAc,EAA2B,MAAM,aAAa,CAAC"}
@@ -0,0 +1,12 @@
1
+ export interface RedactedArgs {
2
+ /** Deep copy with sensitive values replaced by "[REDACTED]". */
3
+ redacted: unknown;
4
+ /** Hash of the ORIGINAL args — integrity is provable without storing secrets. */
5
+ argsHash: string;
6
+ }
7
+ /**
8
+ * Redact any object property whose key contains one of `keys`
9
+ * (case-insensitive), at any depth.
10
+ */
11
+ export declare function redactArgs(args: unknown, keys: string[]): RedactedArgs;
12
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../src/redact.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,YAAY;IAC3B,gEAAgE;IAChE,QAAQ,EAAE,OAAO,CAAC;IAClB,iFAAiF;IACjF,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,YAAY,CAuBtE"}
package/dist/redact.js ADDED
@@ -0,0 +1,29 @@
1
+ import { canonicalize, sha256Hex } from "@agentlaw/core";
2
+ /**
3
+ * Redact any object property whose key contains one of `keys`
4
+ * (case-insensitive), at any depth.
5
+ */
6
+ export function redactArgs(args, keys) {
7
+ const needles = keys.map((key) => key.toLowerCase());
8
+ const isSensitive = (key) => {
9
+ const lower = key.toLowerCase();
10
+ return needles.some((needle) => lower.includes(needle));
11
+ };
12
+ const walk = (value) => {
13
+ if (Array.isArray(value))
14
+ return value.map(walk);
15
+ if (value !== null && typeof value === "object") {
16
+ const out = {};
17
+ for (const [key, inner] of Object.entries(value)) {
18
+ out[key] = isSensitive(key) ? "[REDACTED]" : walk(inner);
19
+ }
20
+ return out;
21
+ }
22
+ return value;
23
+ };
24
+ return {
25
+ redacted: walk(args),
26
+ argsHash: "sha256:" + sha256Hex(canonicalize(args ?? null)),
27
+ };
28
+ }
29
+ //# sourceMappingURL=redact.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.js","sourceRoot":"","sources":["../src/redact.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AASzD;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,IAAa,EAAE,IAAc;IACtD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC;IACrD,MAAM,WAAW,GAAG,CAAC,GAAW,EAAW,EAAE;QAC3C,MAAM,KAAK,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QAChC,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAC1D,CAAC,CAAC;IAEF,MAAM,IAAI,GAAG,CAAC,KAAc,EAAW,EAAE;QACvC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACjD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAChD,MAAM,GAAG,GAA4B,EAAE,CAAC;YACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAgC,CAAC,EAAE,CAAC;gBAC5E,GAAG,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAC3D,CAAC;YACD,OAAO,GAAG,CAAC;QACb,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IAEF,OAAO;QACL,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC;QACpB,QAAQ,EAAE,SAAS,GAAG,SAAS,CAAC,YAAY,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC;KAC5D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * One line of the audit log. `hash` covers the JCS canonical form of the
3
+ * entry without `hash`/`sig`; `prev` is the hash of the previous entry —
4
+ * across file rotations too — forming a single tamper-evident chain.
5
+ */
6
+ export interface AuditEntry {
7
+ seq: number;
8
+ ts: string;
9
+ event: string;
10
+ policyHash: string;
11
+ prev: string | null;
12
+ hash: string;
13
+ sig?: string;
14
+ [field: string]: unknown;
15
+ }
16
+ export type AuditEvent = "chain_start" | "tool_call" | "resource_read" | "approval_requested" | "approval_resolved" | "policy_loaded" | "server_down" | "rotate";
17
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B;AAED,MAAM,MAAM,UAAU,GAClB,aAAa,GACb,WAAW,GACX,eAAe,GACf,oBAAoB,GACpB,mBAAmB,GACnB,eAAe,GACf,aAAa,GACb,QAAQ,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,23 @@
1
+ export interface AuditVerifyError {
2
+ file: string;
3
+ line: number;
4
+ seq?: number;
5
+ reason: string;
6
+ }
7
+ export interface AuditVerifyReport {
8
+ ok: boolean;
9
+ files: string[];
10
+ entries: number;
11
+ error?: AuditVerifyError;
12
+ }
13
+ export interface VerifyAuditOptions {
14
+ /** Optional per-entry signature check: (entryHash, sig) => valid. */
15
+ verifySig?: (entryHash: string, sig: string) => boolean;
16
+ }
17
+ /**
18
+ * Recompute the whole chain: every entry's hash from its canonical content,
19
+ * every `prev` link (across files, in name order) and seq monotonicity.
20
+ * Reports the exact first broken link.
21
+ */
22
+ export declare function verifyAuditDir(dir: string, options?: VerifyAuditOptions): Promise<AuditVerifyReport>;
23
+ //# sourceMappingURL=verify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,gBAAgB,CAAC;CAC1B;AAED,MAAM,WAAW,kBAAkB;IACjC,qEAAqE;IACrE,SAAS,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC;CACzD;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,iBAAiB,CAAC,CA6C5B"}
package/dist/verify.js ADDED
@@ -0,0 +1,52 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { canonicalize, sha256Hex } from "@agentlaw/core";
4
+ import { listAuditFiles } from "./writer.js";
5
+ /**
6
+ * Recompute the whole chain: every entry's hash from its canonical content,
7
+ * every `prev` link (across files, in name order) and seq monotonicity.
8
+ * Reports the exact first broken link.
9
+ */
10
+ export async function verifyAuditDir(dir, options = {}) {
11
+ const files = await listAuditFiles(dir);
12
+ let entries = 0;
13
+ let prevHash = null;
14
+ let prevSeq = null;
15
+ const fail = (error) => ({ ok: false, files, entries, error });
16
+ for (const file of files) {
17
+ const text = await readFile(join(dir, file), "utf8");
18
+ const lines = text.split("\n");
19
+ for (let i = 0; i < lines.length; i++) {
20
+ const raw = lines[i];
21
+ if (raw.trim() === "")
22
+ continue;
23
+ const lineNo = i + 1;
24
+ let entry;
25
+ try {
26
+ entry = JSON.parse(raw);
27
+ }
28
+ catch {
29
+ return fail({ file, line: lineNo, reason: "line is not valid JSON" });
30
+ }
31
+ const { hash, sig, ...content } = entry;
32
+ const expected = "sha256:" + sha256Hex(canonicalize(content));
33
+ if (hash !== expected) {
34
+ return fail({ file, line: lineNo, seq: entry.seq, reason: "entry hash does not match content" });
35
+ }
36
+ if (entry.prev !== prevHash) {
37
+ return fail({ file, line: lineNo, seq: entry.seq, reason: "prev link broken (entry removed, reordered or inserted)" });
38
+ }
39
+ if (prevSeq !== null && entry.seq !== prevSeq + 1) {
40
+ return fail({ file, line: lineNo, seq: entry.seq, reason: `seq jumped from ${prevSeq} to ${entry.seq}` });
41
+ }
42
+ if (sig !== undefined && options.verifySig && !options.verifySig(hash, sig)) {
43
+ return fail({ file, line: lineNo, seq: entry.seq, reason: "entry signature invalid" });
44
+ }
45
+ prevHash = hash;
46
+ prevSeq = entry.seq;
47
+ entries += 1;
48
+ }
49
+ }
50
+ return { ok: true, files, entries };
51
+ }
52
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.js","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAqB7C;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,GAAW,EACX,UAA8B,EAAE;IAEhC,MAAM,KAAK,GAAG,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;IACxC,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,QAAQ,GAAkB,IAAI,CAAC;IACnC,IAAI,OAAO,GAAkB,IAAI,CAAC;IAElC,MAAM,IAAI,GAAG,CAAC,KAAuB,EAAqB,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;IAEpG,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC;QACrD,MAAM,KAAK,GAAG,IA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AI,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,mBAAmB,OAAO,OAAO,KAAK,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAC5G,CAAC;YACD,IAAI,GAAG,KAAK,SAAS,IAAI,OAAO,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;gBAC5E,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC,CAAC;YACzF,CAAC;YAED,QAAQ,GAAG,IAAI,CAAC;YAChB,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC;YACpB,OAAO,IAAI,CAAC,CAAC;QACf,CAAC;IACH,CAAC;IAED,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AACtC,CAAC"}
@@ -0,0 +1,36 @@
1
+ import type { AuditEntry } from "./types.js";
2
+ export interface AuditWriterOptions {
3
+ dir: string;
4
+ policyHash: string;
5
+ /** Rotate to a new file once the current one exceeds this size. */
6
+ maxBytes?: number;
7
+ /** Optional per-entry signature over the entry hash (base64). */
8
+ sign?: (entryHash: string) => string;
9
+ now?: () => Date;
10
+ }
11
+ export declare function auditFileName(index: number): string;
12
+ export declare function listAuditFiles(dir: string): Promise<string[]>;
13
+ /**
14
+ * Hash-chained JSONL writer. Writes are async but strictly serialized (the
15
+ * chain requires total order); `append` never blocks the caller's hot path.
16
+ *
17
+ * Each writer session opens a NEW file whose first entry is `chain_start`
18
+ * with `prev` pointing at the last entry of the previous file — one chain
19
+ * across sessions and rotations.
20
+ */
21
+ export declare class AuditWriter {
22
+ private readonly options;
23
+ private seq;
24
+ private prevHash;
25
+ private fileIndex;
26
+ private bytesInFile;
27
+ private queue;
28
+ private failure;
29
+ private constructor();
30
+ static open(options: AuditWriterOptions): Promise<AuditWriter>;
31
+ /** Enqueue an entry. Throws only if a previous disk write already failed. */
32
+ append(event: string, fields: Record<string, unknown>): AuditEntry;
33
+ /** Wait for every enqueued entry to reach disk; surfaces write failures. */
34
+ flush(): Promise<void>;
35
+ }
36
+ //# sourceMappingURL=writer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writer.d.ts","sourceRoot":"","sources":["../src/writer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAK7C,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,mEAAmE;IACnE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,CAAC;IACrC,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAQnE;AAuBD;;;;;;;GAOG;AACH,qBAAa,WAAW;IASpB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAR1B,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,KAAK,CAAoC;IACjD,OAAO,CAAC,OAAO,CAAsB;IAErC,OAAO;WAUM,IAAI,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,WAAW,CAAC;IAiBpE,6EAA6E;IAC7E,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU;IAiClE,4EAA4E;IACtE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAI7B"}
package/dist/writer.js ADDED
@@ -0,0 +1,108 @@
1
+ import { appendFile, mkdir, readdir, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { canonicalize, sha256Hex } from "@agentlaw/core";
4
+ const FILE_PATTERN = /^audit-(\d{6})\.jsonl$/;
5
+ const DEFAULT_MAX_BYTES = 50 * 1024 * 1024;
6
+ export function auditFileName(index) {
7
+ return `audit-${String(index).padStart(6, "0")}.jsonl`;
8
+ }
9
+ export async function listAuditFiles(dir) {
10
+ let names;
11
+ try {
12
+ names = await readdir(dir);
13
+ }
14
+ catch {
15
+ return [];
16
+ }
17
+ return names.filter((name) => FILE_PATTERN.test(name)).sort();
18
+ }
19
+ async function recoverChainState(dir) {
20
+ const files = await listAuditFiles(dir);
21
+ const last = files.at(-1);
22
+ if (!last)
23
+ return { seq: 0, prevHash: null, lastIndex: 0 };
24
+ const text = await readFile(join(dir, last), "utf8");
25
+ const lines = text.split("\n").filter((line) => line.trim() !== "");
26
+ const lastLine = lines.at(-1);
27
+ const index = Number(FILE_PATTERN.exec(last)[1]);
28
+ if (!lastLine)
29
+ return { seq: 0, prevHash: null, lastIndex: index };
30
+ const entry = JSON.parse(lastLine);
31
+ return { seq: entry.seq, prevHash: entry.hash, lastIndex: index };
32
+ }
33
+ /**
34
+ * Hash-chained JSONL writer. Writes are async but strictly serialized (the
35
+ * chain requires total order); `append` never blocks the caller's hot path.
36
+ *
37
+ * Each writer session opens a NEW file whose first entry is `chain_start`
38
+ * with `prev` pointing at the last entry of the previous file — one chain
39
+ * across sessions and rotations.
40
+ */
41
+ export class AuditWriter {
42
+ options;
43
+ seq;
44
+ prevHash;
45
+ fileIndex;
46
+ bytesInFile = 0;
47
+ queue = Promise.resolve();
48
+ failure = null;
49
+ constructor(options, state) {
50
+ this.options = options;
51
+ this.seq = state.seq;
52
+ this.prevHash = state.prevHash;
53
+ this.fileIndex = state.lastIndex + 1;
54
+ }
55
+ static async open(options) {
56
+ await mkdir(options.dir, { recursive: true });
57
+ const state = await recoverChainState(options.dir);
58
+ const writer = new AuditWriter({
59
+ dir: options.dir,
60
+ policyHash: options.policyHash,
61
+ maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
62
+ ...(options.sign ? { sign: options.sign } : {}),
63
+ ...(options.now ? { now: options.now } : {}),
64
+ }, state);
65
+ writer.append("chain_start", {});
66
+ return writer;
67
+ }
68
+ /** Enqueue an entry. Throws only if a previous disk write already failed. */
69
+ append(event, fields) {
70
+ if (this.failure) {
71
+ throw this.failure;
72
+ }
73
+ const partial = {
74
+ seq: ++this.seq,
75
+ ts: (this.options.now?.() ?? new Date()).toISOString(),
76
+ event,
77
+ ...fields,
78
+ policyHash: this.options.policyHash,
79
+ prev: this.prevHash,
80
+ };
81
+ const hash = "sha256:" + sha256Hex(canonicalize(partial));
82
+ const entry = { ...partial, hash };
83
+ if (this.options.sign)
84
+ entry.sig = this.options.sign(hash);
85
+ this.prevHash = hash;
86
+ const line = JSON.stringify(entry) + "\n";
87
+ this.queue = this.queue.then(async () => {
88
+ if (this.bytesInFile > 0 && this.bytesInFile + line.length > this.options.maxBytes) {
89
+ this.fileIndex += 1;
90
+ this.bytesInFile = 0;
91
+ }
92
+ const path = join(this.options.dir, auditFileName(this.fileIndex));
93
+ await appendFile(path, line, "utf8");
94
+ this.bytesInFile += Buffer.byteLength(line);
95
+ });
96
+ this.queue = this.queue.catch((err) => {
97
+ this.failure = err instanceof Error ? err : new Error(String(err));
98
+ });
99
+ return entry;
100
+ }
101
+ /** Wait for every enqueued entry to reach disk; surfaces write failures. */
102
+ async flush() {
103
+ await this.queue;
104
+ if (this.failure)
105
+ throw this.failure;
106
+ }
107
+ }
108
+ //# sourceMappingURL=writer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writer.js","sourceRoot":"","sources":["../src/writer.ts"],"names":[],"mappings":"AAAA,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O;YAAE,MAAM,IAAI,CAAC,OAAO,CAAC;IACvC,CAAC;CACF"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@agentlaw/audit",
3
+ "version": "0.1.0",
4
+ "description": "Tamper-evident audit log for AI agent actions: hash-chained JSONL writer and verifier.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "src"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -b",
24
+ "typecheck": "tsc -b",
25
+ "pretest": "tsc -b",
26
+ "test": "node --import tsx --test \"test/**/*.test.ts\""
27
+ },
28
+ "dependencies": {
29
+ "@agentlaw/core": "0.1.0"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org/"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/Mounaji-Webs/agentlaw.git",
38
+ "directory": "packages/audit"
39
+ },
40
+ "homepage": "https://agentlaw.dev",
41
+ "bugs": "https://github.com/Mounaji-Webs/agentlaw/issues",
42
+ "keywords": [
43
+ "ai-agents",
44
+ "security",
45
+ "policy",
46
+ "mcp",
47
+ "governance",
48
+ "agentlaw",
49
+ "audit-log",
50
+ "hash-chain",
51
+ "tamper-evident"
52
+ ]
53
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ export { redactArgs, type RedactedArgs } from "./redact.js";
2
+ export type { AuditEntry, AuditEvent } from "./types.js";
3
+ export {
4
+ verifyAuditDir,
5
+ type AuditVerifyError,
6
+ type AuditVerifyReport,
7
+ type VerifyAuditOptions,
8
+ } from "./verify.js";
9
+ export { auditFileName, AuditWriter, listAuditFiles, type AuditWriterOptions } from "./writer.js";
package/src/redact.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { canonicalize, sha256Hex } from "@agentlaw/core";
2
+
3
+ export interface RedactedArgs {
4
+ /** Deep copy with sensitive values replaced by "[REDACTED]". */
5
+ redacted: unknown;
6
+ /** Hash of the ORIGINAL args — integrity is provable without storing secrets. */
7
+ argsHash: string;
8
+ }
9
+
10
+ /**
11
+ * Redact any object property whose key contains one of `keys`
12
+ * (case-insensitive), at any depth.
13
+ */
14
+ export function redactArgs(args: unknown, keys: string[]): RedactedArgs {
15
+ const needles = keys.map((key) => key.toLowerCase());
16
+ const isSensitive = (key: string): boolean => {
17
+ const lower = key.toLowerCase();
18
+ return needles.some((needle) => lower.includes(needle));
19
+ };
20
+
21
+ const walk = (value: unknown): unknown => {
22
+ if (Array.isArray(value)) return value.map(walk);
23
+ if (value !== null && typeof value === "object") {
24
+ const out: Record<string, unknown> = {};
25
+ for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {
26
+ out[key] = isSensitive(key) ? "[REDACTED]" : walk(inner);
27
+ }
28
+ return out;
29
+ }
30
+ return value;
31
+ };
32
+
33
+ return {
34
+ redacted: walk(args),
35
+ argsHash: "sha256:" + sha256Hex(canonicalize(args ?? null)),
36
+ };
37
+ }
package/src/types.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * One line of the audit log. `hash` covers the JCS canonical form of the
3
+ * entry without `hash`/`sig`; `prev` is the hash of the previous entry —
4
+ * across file rotations too — forming a single tamper-evident chain.
5
+ */
6
+ export interface AuditEntry {
7
+ seq: number;
8
+ ts: string;
9
+ event: string;
10
+ policyHash: string;
11
+ prev: string | null;
12
+ hash: string;
13
+ sig?: string;
14
+ [field: string]: unknown;
15
+ }
16
+
17
+ export type AuditEvent =
18
+ | "chain_start"
19
+ | "tool_call"
20
+ | "resource_read"
21
+ | "approval_requested"
22
+ | "approval_resolved"
23
+ | "policy_loaded"
24
+ | "server_down"
25
+ | "rotate";
package/src/verify.ts ADDED
@@ -0,0 +1,79 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { canonicalize, sha256Hex } from "@agentlaw/core";
4
+ import type { AuditEntry } from "./types.js";
5
+ import { listAuditFiles } from "./writer.js";
6
+
7
+ export interface AuditVerifyError {
8
+ file: string;
9
+ line: number;
10
+ seq?: number;
11
+ reason: string;
12
+ }
13
+
14
+ export interface AuditVerifyReport {
15
+ ok: boolean;
16
+ files: string[];
17
+ entries: number;
18
+ error?: AuditVerifyError;
19
+ }
20
+
21
+ export interface VerifyAuditOptions {
22
+ /** Optional per-entry signature check: (entryHash, sig) => valid. */
23
+ verifySig?: (entryHash: string, sig: string) => boolean;
24
+ }
25
+
26
+ /**
27
+ * Recompute the whole chain: every entry's hash from its canonical content,
28
+ * every `prev` link (across files, in name order) and seq monotonicity.
29
+ * Reports the exact first broken link.
30
+ */
31
+ export async function verifyAuditDir(
32
+ dir: string,
33
+ options: VerifyAuditOptions = {},
34
+ ): Promise<AuditVerifyReport> {
35
+ const files = await listAuditFiles(dir);
36
+ let entries = 0;
37
+ let prevHash: string | null = null;
38
+ let prevSeq: number | null = null;
39
+
40
+ const fail = (error: AuditVerifyError): AuditVerifyReport => ({ ok: false, files, entries, error });
41
+
42
+ for (const file of files) {
43
+ const text = await readFile(join(dir, file), "utf8");
44
+ const lines = text.split("\n");
45
+ for (let i = 0; i < lines.length; i++) {
46
+ const raw = lines[i]!;
47
+ if (raw.trim() === "") continue;
48
+ const lineNo = i + 1;
49
+
50
+ let entry: AuditEntry;
51
+ try {
52
+ entry = JSON.parse(raw) as AuditEntry;
53
+ } catch {
54
+ return fail({ file, line: lineNo, reason: "line is not valid JSON" });
55
+ }
56
+
57
+ const { hash, sig, ...content } = entry;
58
+ const expected = "sha256:" + sha256Hex(canonicalize(content));
59
+ if (hash !== expected) {
60
+ return fail({ file, line: lineNo, seq: entry.seq, reason: "entry hash does not match content" });
61
+ }
62
+ if (entry.prev !== prevHash) {
63
+ return fail({ file, line: lineNo, seq: entry.seq, reason: "prev link broken (entry removed, reordered or inserted)" });
64
+ }
65
+ if (prevSeq !== null && entry.seq !== prevSeq + 1) {
66
+ return fail({ file, line: lineNo, seq: entry.seq, reason: `seq jumped from ${prevSeq} to ${entry.seq}` });
67
+ }
68
+ if (sig !== undefined && options.verifySig && !options.verifySig(hash, sig)) {
69
+ return fail({ file, line: lineNo, seq: entry.seq, reason: "entry signature invalid" });
70
+ }
71
+
72
+ prevHash = hash;
73
+ prevSeq = entry.seq;
74
+ entries += 1;
75
+ }
76
+ }
77
+
78
+ return { ok: true, files, entries };
79
+ }
package/src/writer.ts ADDED
@@ -0,0 +1,136 @@
1
+ import { appendFile, mkdir, readdir, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { canonicalize, sha256Hex } from "@agentlaw/core";
4
+ import type { AuditEntry } from "./types.js";
5
+
6
+ const FILE_PATTERN = /^audit-(\d{6})\.jsonl$/;
7
+ const DEFAULT_MAX_BYTES = 50 * 1024 * 1024;
8
+
9
+ export interface AuditWriterOptions {
10
+ dir: string;
11
+ policyHash: string;
12
+ /** Rotate to a new file once the current one exceeds this size. */
13
+ maxBytes?: number;
14
+ /** Optional per-entry signature over the entry hash (base64). */
15
+ sign?: (entryHash: string) => string;
16
+ now?: () => Date;
17
+ }
18
+
19
+ export function auditFileName(index: number): string {
20
+ return `audit-${String(index).padStart(6, "0")}.jsonl`;
21
+ }
22
+
23
+ export async function listAuditFiles(dir: string): Promise<string[]> {
24
+ let names: string[];
25
+ try {
26
+ names = await readdir(dir);
27
+ } catch {
28
+ return [];
29
+ }
30
+ return names.filter((name) => FILE_PATTERN.test(name)).sort();
31
+ }
32
+
33
+ interface ChainState {
34
+ seq: number;
35
+ prevHash: string | null;
36
+ lastIndex: number;
37
+ }
38
+
39
+ async function recoverChainState(dir: string): Promise<ChainState> {
40
+ const files = await listAuditFiles(dir);
41
+ const last = files.at(-1);
42
+ if (!last) return { seq: 0, prevHash: null, lastIndex: 0 };
43
+
44
+ const text = await readFile(join(dir, last), "utf8");
45
+ const lines = text.split("\n").filter((line) => line.trim() !== "");
46
+ const lastLine = lines.at(-1);
47
+ const index = Number(FILE_PATTERN.exec(last)![1]);
48
+ if (!lastLine) return { seq: 0, prevHash: null, lastIndex: index };
49
+
50
+ const entry = JSON.parse(lastLine) as AuditEntry;
51
+ return { seq: entry.seq, prevHash: entry.hash, lastIndex: index };
52
+ }
53
+
54
+ /**
55
+ * Hash-chained JSONL writer. Writes are async but strictly serialized (the
56
+ * chain requires total order); `append` never blocks the caller's hot path.
57
+ *
58
+ * Each writer session opens a NEW file whose first entry is `chain_start`
59
+ * with `prev` pointing at the last entry of the previous file — one chain
60
+ * across sessions and rotations.
61
+ */
62
+ export class AuditWriter {
63
+ private seq: number;
64
+ private prevHash: string | null;
65
+ private fileIndex: number;
66
+ private bytesInFile = 0;
67
+ private queue: Promise<void> = Promise.resolve();
68
+ private failure: Error | null = null;
69
+
70
+ private constructor(
71
+ private readonly options: Required<Pick<AuditWriterOptions, "dir" | "policyHash" | "maxBytes">> &
72
+ Pick<AuditWriterOptions, "sign" | "now">,
73
+ state: ChainState,
74
+ ) {
75
+ this.seq = state.seq;
76
+ this.prevHash = state.prevHash;
77
+ this.fileIndex = state.lastIndex + 1;
78
+ }
79
+
80
+ static async open(options: AuditWriterOptions): Promise<AuditWriter> {
81
+ await mkdir(options.dir, { recursive: true });
82
+ const state = await recoverChainState(options.dir);
83
+ const writer = new AuditWriter(
84
+ {
85
+ dir: options.dir,
86
+ policyHash: options.policyHash,
87
+ maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
88
+ ...(options.sign ? { sign: options.sign } : {}),
89
+ ...(options.now ? { now: options.now } : {}),
90
+ },
91
+ state,
92
+ );
93
+ writer.append("chain_start", {});
94
+ return writer;
95
+ }
96
+
97
+ /** Enqueue an entry. Throws only if a previous disk write already failed. */
98
+ append(event: string, fields: Record<string, unknown>): AuditEntry {
99
+ if (this.failure) {
100
+ throw this.failure;
101
+ }
102
+ const partial: Omit<AuditEntry, "hash"> = {
103
+ seq: ++this.seq,
104
+ ts: (this.options.now?.() ?? new Date()).toISOString(),
105
+ event,
106
+ ...fields,
107
+ policyHash: this.options.policyHash,
108
+ prev: this.prevHash,
109
+ };
110
+ const hash = "sha256:" + sha256Hex(canonicalize(partial));
111
+ const entry = { ...partial, hash } as AuditEntry;
112
+ if (this.options.sign) entry.sig = this.options.sign(hash);
113
+ this.prevHash = hash;
114
+
115
+ const line = JSON.stringify(entry) + "\n";
116
+ this.queue = this.queue.then(async () => {
117
+ if (this.bytesInFile > 0 && this.bytesInFile + line.length > this.options.maxBytes) {
118
+ this.fileIndex += 1;
119
+ this.bytesInFile = 0;
120
+ }
121
+ const path = join(this.options.dir, auditFileName(this.fileIndex));
122
+ await appendFile(path, line, "utf8");
123
+ this.bytesInFile += Buffer.byteLength(line);
124
+ });
125
+ this.queue = this.queue.catch((err) => {
126
+ this.failure = err instanceof Error ? err : new Error(String(err));
127
+ });
128
+ return entry;
129
+ }
130
+
131
+ /** Wait for every enqueued entry to reach disk; surfaces write failures. */
132
+ async flush(): Promise<void> {
133
+ await this.queue;
134
+ if (this.failure) throw this.failure;
135
+ }
136
+ }