@krizaka/audit 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # @krizaka/audit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Who did what, for every Krizaka product.** The trail is append-only and lives in the product's database, in the Postgres schema `audit`.
4
+ - **Two ways to write:** inside the caller's transaction (it commits or rolls back with the work), or quietly beside it (a failure is logged, never thrown).
5
+ - **For the admin:** filtered and paginated.
6
+ - **For Loi 25:** exported and redacted.
7
+ - **Retention:** purged after a retention the admin sets.
8
+
9
+ There is no database client and no wall clock: you pass a `Query` and a `Clock`.
10
+
11
+ ```bash
12
+ pnpm add @krizaka/audit @krizaka/db
13
+ ```
14
+
15
+ ## Add its schema to your migrations
16
+
17
+ The schema is embedded through `@krizaka/db`, in your own sequence:
18
+
19
+ ```ts
20
+ import { emitMigration } from "@krizaka/db";
21
+ import { auditSchema } from "@krizaka/audit";
22
+
23
+ // commit the output as one of your migrations (drizzle-kit `generate --custom`, or your list)
24
+ emitMigration(auditSchema, 1, { tables: { owner: "accounts" } });
25
+ ```
26
+
27
+ The table is `audit.entry`. It holds the time, the actor (references your `accounts`, `ON DELETE SET NULL`), a readable label, the dotted action (`billing.checkout_started`), an optional target, the detail (jsonb) and the IP.
28
+
29
+ ## Use
30
+
31
+ ```ts
32
+ import { createAudit } from "@krizaka/audit";
33
+ import { transaction } from "@krizaka/db";
34
+
35
+ const audit = createAudit({ clock: { now: () => new Date() }, onError: (e) => logger.warn(e) });
36
+
37
+ // Inside a unit of work: the entry exists only if the work commits.
38
+ await transaction(connect, async (tx) => {
39
+ await suspendUser(tx, userId);
40
+ await audit.record(tx, { actorId: admin.id, actorLabel: admin.name, action: "admin.user_suspended", target: { type: "account", id: userId } });
41
+ });
42
+
43
+ // Beside it: never fails the request.
44
+ await audit.recordQuietly(query, { actorId: null, actorLabel: "stripe webhook", action: "billing.event_ignored", detail: { type } });
45
+
46
+ // The admin's view: newest first, filtered, paged by cursor.
47
+ const page = await audit.list(query, { actionPrefix: "admin.", limit: 50 });
48
+ const next = await audit.list(query, { actionPrefix: "admin.", limit: 50, before: page.at(-1)?.id });
49
+ ```
50
+
51
+ - **Loi 25:**
52
+ - `exportFor(query, accountId)` gives the person's entries;
53
+ - `redactActor(tx, accountId)` keeps the facts and removes the person: the id and IP become null, and the label becomes « erased ».
54
+
55
+ Put as little personal data in `detail` as the action needs.
56
+ - **Retention:** register `auditSettings` in your `@krizaka/settings` registry (`audit.retentionDays`: default 1095, 30–3650 days). Your job then calls `audit.purge(tx, { retentionDays })`.
57
+ - **Input from a request is checked the same way for every store:** a page size must be a positive integer (capped at 200), a cursor must be an entry id, an IP must be an address, and a retention must be within the setting's bounds (30–3650 days), so a bad value never purges the whole trail. Each refusal is an `AuditError` with a stable code (`AUDIT_BAD_FILTER`, `AUDIT_BAD_IP`, `AUDIT_BAD_RETENTION`…).
58
+ - **A fixed list of actions:** `createAudit({ allowedActions: [...] })` refuses anything else (`AUDIT_UNKNOWN_ACTION`).
59
+ - **Another store** runs the contract kit: `auditStoreContract` from `@krizaka/audit/testkit`. `memoryAuditStore()` is the reference.
@@ -0,0 +1,104 @@
1
+ import { A as AuditEntryInput, a as AuditFilters, b as AuditEntry, c as AuditStore, d as AuditInsert } from './port-B2kkvTQu.js';
2
+ export { e as AUDIT_CODE, f as AuditCode, g as AuditError } from './port-B2kkvTQu.js';
3
+ import * as _krizaka_db from '@krizaka/db';
4
+ import { Query, Clock } from '@krizaka/db';
5
+ export { Clock, Query } from '@krizaka/db';
6
+ import * as _krizaka_settings from '@krizaka/settings';
7
+
8
+ interface AuditDeps {
9
+ clock: Clock;
10
+ /** The store over a query (a pool or a transaction). Default: the PostgreSQL store on schema `audit`. */
11
+ storeFor?: (query: Query) => AuditStore;
12
+ /** The Postgres schema, when the product renamed the module's (used by the default store). */
13
+ schema?: string;
14
+ /** The product's fixed list of actions, when it keeps one (refused otherwise). */
15
+ allowedActions?: readonly string[];
16
+ /** Where a quiet write's failure goes (the product's logger). */
17
+ onError?: (error: unknown, entry: AuditEntryInput) => void | Promise<void>;
18
+ }
19
+ /** The trail as a product uses it. Every function takes the `Query` it writes through: pass `tx` to join a unit of work. */
20
+ interface Audit {
21
+ /** Records an entry; throws on failure, so it can join the caller's transaction (it commits or rolls back with it). */
22
+ record(query: Query, entry: AuditEntryInput): Promise<void>;
23
+ /** Records an entry beside the work: a failure goes to `onError`, never to the caller. */
24
+ recordQuietly(query: Query, entry: AuditEntryInput): Promise<void>;
25
+ list(query: Query, filters: AuditFilters): Promise<AuditEntry[]>;
26
+ /** One actor's entries, for the Loi 25 export. */
27
+ exportFor(query: Query, actorId: string): Promise<AuditEntry[]>;
28
+ /** Detaches one actor from the trail (Loi 25 erasure): the facts stay, the person does not. */
29
+ redactActor(query: Query, actorId: string): Promise<number>;
30
+ /** Removes what is older than `retentionDays` (the `audit.retentionDays` setting). */
31
+ purge(query: Query, options: {
32
+ retentionDays: number;
33
+ }): Promise<number>;
34
+ }
35
+ /**
36
+ * The audit trail of a product.
37
+ * @param deps the clock, the store, the product's action list and error sink
38
+ * @returns the trail's functions
39
+ */
40
+ declare function createAudit(deps: AuditDeps): Audit;
41
+
42
+ /** Whether an entry passes the admin's filters (the same semantics as the database store). */
43
+ declare function matches(entry: AuditEntry, filters: AuditFilters): boolean;
44
+ /**
45
+ * An in-memory trail, for unit tests and demos. Ids grow like the table's `bigserial`.
46
+ * @returns a store that passes `auditStoreContract`
47
+ */
48
+ declare function memoryAuditStore(): AuditStore;
49
+
50
+ /**
51
+ * The PostgreSQL store, on `<schema>.entry` (`auditSchema`), over the product's query: a pool, or an open transaction.
52
+ * @param query the product's SQL runner
53
+ * @param schema the Postgres schema, when the product renamed it (default `audit`)
54
+ * @returns a store that passes `auditStoreContract`
55
+ * @throws DbError `DB_UNSAFE_IDENTIFIER` for a schema that is not an identifier
56
+ */
57
+ declare function dbAuditStore(query: Query, schema?: string): AuditStore;
58
+
59
+ /** The size of a page of the trail, for the admin. */
60
+ declare const PAGE: {
61
+ readonly default: 50;
62
+ readonly max: 200;
63
+ };
64
+ /**
65
+ * Checks an entry against the trail's rules and the product's list of actions, and flattens it for a store.
66
+ * @param input what the product records
67
+ * @param at when (the injected clock)
68
+ * @param allowedActions the product's actions, when it keeps a fixed list
69
+ * @returns the row to write
70
+ * @throws AuditError `AUDIT_BAD_ACTION`, `AUDIT_UNKNOWN_ACTION`, `AUDIT_BAD_LABEL`, `AUDIT_BAD_IP`
71
+ */
72
+ declare function toInsert(input: AuditEntryInput, at: Date, allowedActions?: readonly string[]): AuditInsert;
73
+ /**
74
+ * The page size a store uses: the caller's, capped at `PAGE.max`, or `PAGE.default`.
75
+ * @param limit the requested size (already checked by `checkFilters`)
76
+ */
77
+ declare const pageSize: (limit: number | undefined) => number;
78
+ /**
79
+ * Checks filters that may come from a request: a page size that is a positive integer, a cursor that is an entry id.
80
+ * @throws AuditError `AUDIT_BAD_FILTER`
81
+ */
82
+ declare function checkFilters(filters: AuditFilters): void;
83
+ /**
84
+ * Checks a retention against the setting's bounds, so a wrong value can never purge the whole trail.
85
+ * @throws AuditError `AUDIT_BAD_RETENTION`
86
+ */
87
+ declare function checkRetention(days: number): void;
88
+
89
+ /**
90
+ * The tables of « audit », in their own Postgres schema (ADR-001 §3). The one product table referenced is the owner (the
91
+ * account table), declared by the product; deleting an account keeps its entries with the actor detached.
92
+ * Version 1 is frozen once released: a change is version 2.
93
+ */
94
+ declare const auditSchema: _krizaka_db.ModuleSchema;
95
+
96
+ /**
97
+ * The settings of « audit », a fragment the product adds to its registry: the admin sets how long the trail is kept, and
98
+ * the product's job calls `purge` with it. Global scope only.
99
+ */
100
+ declare const auditSettings: {
101
+ readonly "audit.retentionDays": _krizaka_settings.Def<number>;
102
+ };
103
+
104
+ export { type Audit, type AuditDeps, AuditEntry, AuditEntryInput, AuditFilters, AuditInsert, AuditStore, PAGE, auditSchema, auditSettings, checkFilters, checkRetention, createAudit, dbAuditStore, matches, memoryAuditStore, pageSize, toInsert };
package/dist/index.js ADDED
@@ -0,0 +1,226 @@
1
+ // src/audit.ts
2
+ import { ident as ident2 } from "@krizaka/db";
3
+ import { subDays } from "date-fns";
4
+
5
+ // src/persistence.ts
6
+ import { ident } from "@krizaka/db";
7
+
8
+ // src/rules.ts
9
+ import { isIP } from "net";
10
+
11
+ // src/port.ts
12
+ var AUDIT_CODE = {
13
+ badAction: "AUDIT_BAD_ACTION",
14
+ unknownAction: "AUDIT_UNKNOWN_ACTION",
15
+ badLabel: "AUDIT_BAD_LABEL",
16
+ badIp: "AUDIT_BAD_IP",
17
+ badFilter: "AUDIT_BAD_FILTER",
18
+ badRetention: "AUDIT_BAD_RETENTION"
19
+ };
20
+ var AuditError = class extends Error {
21
+ constructor(code, value) {
22
+ super(`${code}: ${value}`);
23
+ this.code = code;
24
+ this.value = value;
25
+ this.name = "AuditError";
26
+ }
27
+ code;
28
+ value;
29
+ };
30
+
31
+ // src/settings.ts
32
+ import { integer } from "@krizaka/settings";
33
+ var auditSettings = {
34
+ // @fixed: three years by default; the admin chooses between one month and ten years.
35
+ "audit.retentionDays": integer("audit", 1095, { min: 30, max: 3650, unit: "days" })
36
+ };
37
+
38
+ // src/rules.ts
39
+ var PAGE = {
40
+ // @fixed: a page the admin reads at once; beyond it, the cursor.
41
+ default: 50,
42
+ // @fixed: the most one request may return, whatever the caller asks.
43
+ max: 200
44
+ };
45
+ var ACTION = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+)*$/;
46
+ function toInsert(input, at, allowedActions) {
47
+ if (!ACTION.test(input.action) || input.action.length > 80) throw new AuditError(AUDIT_CODE.badAction, input.action);
48
+ if (allowedActions && !allowedActions.includes(input.action)) throw new AuditError(AUDIT_CODE.unknownAction, input.action);
49
+ if (input.ip != null && isIP(input.ip) === 0) throw new AuditError(AUDIT_CODE.badIp, input.ip);
50
+ const label = input.actorLabel.trim();
51
+ if (label.length < 1 || label.length > 120) throw new AuditError(AUDIT_CODE.badLabel, input.actorLabel);
52
+ return {
53
+ at,
54
+ actorId: input.actorId,
55
+ actorLabel: label,
56
+ action: input.action,
57
+ targetType: input.target?.type ?? null,
58
+ targetId: input.target?.id ?? null,
59
+ detail: input.detail ?? {},
60
+ ip: input.ip ?? null
61
+ };
62
+ }
63
+ var pageSize = (limit) => Math.min(limit ?? PAGE.default, PAGE.max);
64
+ var CURSOR = /^[1-9][0-9]{0,18}$/;
65
+ var BIGINT_MAX = 9223372036854775807n;
66
+ function checkFilters(filters) {
67
+ if (filters.limit !== void 0 && !(Number.isInteger(filters.limit) && filters.limit > 0)) throw new AuditError(AUDIT_CODE.badFilter, `limit ${String(filters.limit)}`);
68
+ if (filters.before !== void 0 && !(CURSOR.test(filters.before) && BigInt(filters.before) <= BIGINT_MAX)) throw new AuditError(AUDIT_CODE.badFilter, `before ${filters.before}`);
69
+ }
70
+ function checkRetention(days) {
71
+ const { min = 1, max = Number.MAX_SAFE_INTEGER } = auditSettings["audit.retentionDays"];
72
+ if (!Number.isInteger(days) || days < min || days > max) throw new AuditError(AUDIT_CODE.badRetention, String(days));
73
+ }
74
+
75
+ // src/persistence.ts
76
+ var COLUMNS = "id::text AS id, at, actor_id, actor_label, action, target_type, target_id, detail, host(ip) AS ip";
77
+ var toEntry = (r) => ({ id: r.id, at: r.at, actorId: r.actor_id, actorLabel: r.actor_label, action: r.action, targetType: r.target_type, targetId: r.target_id, detail: r.detail, ip: r.ip });
78
+ function where(filters) {
79
+ const parts = [];
80
+ const params = [];
81
+ const add = (clause, value) => {
82
+ params.push(value);
83
+ parts.push(clause(params.length));
84
+ };
85
+ if (filters.actorId !== void 0) add((n) => `actor_id = $${n}`, filters.actorId);
86
+ if (filters.actionPrefix !== void 0) add((n) => `starts_with(action, $${n})`, filters.actionPrefix);
87
+ if (filters.target !== void 0) {
88
+ add((n) => `target_type = $${n}`, filters.target.type);
89
+ add((n) => `target_id = $${n}`, filters.target.id);
90
+ }
91
+ if (filters.from !== void 0) add((n) => `at >= $${n}`, filters.from);
92
+ if (filters.to !== void 0) add((n) => `at < $${n}`, filters.to);
93
+ if (filters.before !== void 0) add((n) => `id < $${n}::bigint`, filters.before);
94
+ return { sql: parts.length > 0 ? `WHERE ${parts.join(" AND ")}` : "", params };
95
+ }
96
+ function dbAuditStore(query, schema = "audit") {
97
+ const table = `${ident(schema)}.entry`;
98
+ const rows = async (sql, params) => (await query(sql, params)).map(toEntry);
99
+ return {
100
+ async insert(e) {
101
+ await query(`INSERT INTO ${table} (at, actor_id, actor_label, action, target_type, target_id, detail, ip) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [e.at, e.actorId, e.actorLabel, e.action, e.targetType, e.targetId, JSON.stringify(e.detail), e.ip]);
102
+ },
103
+ async list(filters) {
104
+ const { sql, params } = where(filters);
105
+ return rows(`SELECT ${COLUMNS} FROM ${table} ${sql} ORDER BY id DESC LIMIT $${params.length + 1}`, [...params, pageSize(filters.limit)]);
106
+ },
107
+ forActor: (actorId) => rows(`SELECT ${COLUMNS} FROM ${table} WHERE actor_id = $1 ORDER BY id DESC`, [actorId]),
108
+ async redactActor(actorId) {
109
+ return (await query(`UPDATE ${table} SET actor_id = NULL, actor_label = 'erased', ip = NULL WHERE actor_id = $1 RETURNING id`, [actorId])).length;
110
+ },
111
+ async purgeBefore(before) {
112
+ return (await query(`DELETE FROM ${table} WHERE at < $1 RETURNING id`, [before])).length;
113
+ }
114
+ };
115
+ }
116
+
117
+ // src/audit.ts
118
+ async function report(onError, error, entry) {
119
+ try {
120
+ await onError?.(error, entry);
121
+ } catch {
122
+ }
123
+ }
124
+ function createAudit(deps) {
125
+ const schema = ident2(deps.schema ?? "audit");
126
+ const storeFor = deps.storeFor ?? ((query) => dbAuditStore(query, schema));
127
+ const record = async (query, entry) => storeFor(query).insert(toInsert(entry, deps.clock.now(), deps.allowedActions));
128
+ return {
129
+ record,
130
+ async recordQuietly(query, entry) {
131
+ try {
132
+ await record(query, entry);
133
+ } catch (error) {
134
+ await report(deps.onError, error, entry);
135
+ }
136
+ },
137
+ async list(query, filters) {
138
+ checkFilters(filters);
139
+ return storeFor(query).list(filters);
140
+ },
141
+ exportFor: (query, actorId) => storeFor(query).forActor(actorId),
142
+ redactActor: (query, actorId) => storeFor(query).redactActor(actorId),
143
+ async purge(query, { retentionDays }) {
144
+ checkRetention(retentionDays);
145
+ return storeFor(query).purgeBefore(subDays(deps.clock.now(), retentionDays));
146
+ }
147
+ };
148
+ }
149
+
150
+ // src/memory.ts
151
+ function matches(entry, filters) {
152
+ return (filters.actorId === void 0 || entry.actorId === filters.actorId) && (filters.actionPrefix === void 0 || entry.action.startsWith(filters.actionPrefix)) && (filters.target === void 0 || entry.targetType === filters.target.type && entry.targetId === filters.target.id) && (filters.from === void 0 || entry.at >= filters.from) && (filters.to === void 0 || entry.at < filters.to) && (filters.before === void 0 || BigInt(entry.id) < BigInt(filters.before));
153
+ }
154
+ function memoryAuditStore() {
155
+ const rows = [];
156
+ let lastId = 0n;
157
+ const copy = (e) => structuredClone(e);
158
+ const newestFirst = () => [...rows].sort((a, b) => Number(BigInt(b.id) - BigInt(a.id)));
159
+ return {
160
+ async insert(entry) {
161
+ lastId += 1n;
162
+ rows.push(copy({ ...entry, id: String(lastId) }));
163
+ },
164
+ async list(filters) {
165
+ return newestFirst().filter((e) => matches(e, filters)).slice(0, pageSize(filters.limit)).map(copy);
166
+ },
167
+ async forActor(actorId) {
168
+ return newestFirst().filter((e) => e.actorId === actorId).map(copy);
169
+ },
170
+ async redactActor(actorId) {
171
+ const mine = rows.filter((e) => e.actorId === actorId);
172
+ for (const e of mine) Object.assign(e, { actorId: null, actorLabel: "erased", ip: null });
173
+ return mine.length;
174
+ },
175
+ async purgeBefore(before) {
176
+ const old = rows.filter((e) => e.at < before);
177
+ for (const e of old) rows.splice(rows.indexOf(e), 1);
178
+ return old.length;
179
+ }
180
+ };
181
+ }
182
+
183
+ // src/schema.ts
184
+ import { defineModule } from "@krizaka/db";
185
+ var auditSchema = defineModule({
186
+ module: "audit",
187
+ tables: ["owner"],
188
+ migrations: [
189
+ {
190
+ version: 1,
191
+ name: "entries",
192
+ sql: (c) => `
193
+ CREATE TABLE ${c.schema}.entry (
194
+ id bigserial PRIMARY KEY,
195
+ at timestamptz NOT NULL,
196
+ actor_id uuid REFERENCES ${c.tables.owner}(id) ON DELETE SET NULL,
197
+ actor_label text NOT NULL CHECK (char_length(actor_label) BETWEEN 1 AND 120),
198
+ action text NOT NULL CHECK (action ~ '^[a-z][a-z0-9_]*(\\.[a-z0-9_]+)*$' AND char_length(action) <= 80),
199
+ target_type text CHECK (target_type IS NULL OR char_length(target_type) <= 40),
200
+ target_id text CHECK (target_id IS NULL OR char_length(target_id) <= 200),
201
+ detail jsonb NOT NULL DEFAULT '{}'::jsonb,
202
+ ip inet
203
+ );
204
+ CREATE INDEX entry_at ON ${c.schema}.entry (at DESC);
205
+ CREATE INDEX entry_action ON ${c.schema}.entry (action, at DESC);
206
+ CREATE INDEX entry_target ON ${c.schema}.entry (target_type, target_id, at DESC);
207
+ CREATE INDEX entry_actor ON ${c.schema}.entry (actor_id) WHERE actor_id IS NOT NULL;`
208
+ }
209
+ ]
210
+ });
211
+ export {
212
+ AUDIT_CODE,
213
+ AuditError,
214
+ PAGE,
215
+ auditSchema,
216
+ auditSettings,
217
+ checkFilters,
218
+ checkRetention,
219
+ createAudit,
220
+ dbAuditStore,
221
+ matches,
222
+ memoryAuditStore,
223
+ pageSize,
224
+ toInsert
225
+ };
226
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/audit.ts","../src/persistence.ts","../src/rules.ts","../src/port.ts","../src/settings.ts","../src/memory.ts","../src/schema.ts"],"sourcesContent":["import { ident } from \"@krizaka/db\";\nimport { subDays } from \"date-fns\";\n\nimport { dbAuditStore } from \"./persistence\";\nimport type { AuditEntry, AuditEntryInput, AuditFilters, AuditStore, Clock, Query } from \"./port\";\nimport { checkFilters, checkRetention, toInsert } from \"./rules\";\n\nexport interface AuditDeps {\n clock: Clock;\n /** The store over a query (a pool or a transaction). Default: the PostgreSQL store on schema `audit`. */\n storeFor?: (query: Query) => AuditStore;\n /** The Postgres schema, when the product renamed the module's (used by the default store). */\n schema?: string;\n /** The product's fixed list of actions, when it keeps one (refused otherwise). */\n allowedActions?: readonly string[];\n /** Where a quiet write's failure goes (the product's logger). */\n onError?: (error: unknown, entry: AuditEntryInput) => void | Promise<void>;\n}\n\n/** The trail as a product uses it. Every function takes the `Query` it writes through: pass `tx` to join a unit of work. */\nexport interface Audit {\n /** Records an entry; throws on failure, so it can join the caller's transaction (it commits or rolls back with it). */\n record(query: Query, entry: AuditEntryInput): Promise<void>;\n /** Records an entry beside the work: a failure goes to `onError`, never to the caller. */\n recordQuietly(query: Query, entry: AuditEntryInput): Promise<void>;\n list(query: Query, filters: AuditFilters): Promise<AuditEntry[]>;\n /** One actor's entries, for the Loi 25 export. */\n exportFor(query: Query, actorId: string): Promise<AuditEntry[]>;\n /** Detaches one actor from the trail (Loi 25 erasure): the facts stay, the person does not. */\n redactActor(query: Query, actorId: string): Promise<number>;\n /** Removes what is older than `retentionDays` (the `audit.retentionDays` setting). */\n purge(query: Query, options: { retentionDays: number }): Promise<number>;\n}\n\n/** Hands a quiet write's failure to the sink; a sink that throws or rejects is swallowed too: `recordQuietly` never throws. */\nasync function report(onError: AuditDeps[\"onError\"], error: unknown, entry: AuditEntryInput): Promise<void> {\n try {\n await onError?.(error, entry);\n } catch {\n // The sink is the product's logger; a failing logger must not fail the request it was only meant to observe.\n }\n}\n\n/**\n * The audit trail of a product.\n * @param deps the clock, the store, the product's action list and error sink\n * @returns the trail's functions\n */\nexport function createAudit(deps: AuditDeps): Audit {\n const schema = ident(deps.schema ?? \"audit\");\n const storeFor = deps.storeFor ?? ((query: Query) => dbAuditStore(query, schema));\n const record = async (query: Query, entry: AuditEntryInput) => storeFor(query).insert(toInsert(entry, deps.clock.now(), deps.allowedActions));\n return {\n record,\n async recordQuietly(query, entry) {\n try {\n await record(query, entry);\n } catch (error) {\n await report(deps.onError, error, entry);\n }\n },\n async list(query, filters) {\n checkFilters(filters);\n return storeFor(query).list(filters);\n },\n exportFor: (query, actorId) => storeFor(query).forActor(actorId),\n redactActor: (query, actorId) => storeFor(query).redactActor(actorId),\n async purge(query, { retentionDays }) {\n checkRetention(retentionDays);\n return storeFor(query).purgeBefore(subDays(deps.clock.now(), retentionDays));\n },\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { AuditEntry, AuditFilters, AuditStore } from \"./port\";\nimport { pageSize } from \"./rules\";\n\ninterface Row {\n id: string;\n at: Date;\n actor_id: string | null;\n actor_label: string;\n action: string;\n target_type: string | null;\n target_id: string | null;\n detail: Record<string, unknown>;\n ip: string | null;\n}\n\nconst COLUMNS = \"id::text AS id, at, actor_id, actor_label, action, target_type, target_id, detail, host(ip) AS ip\";\nconst toEntry = (r: Row): AuditEntry => ({ id: r.id, at: r.at, actorId: r.actor_id, actorLabel: r.actor_label, action: r.action, targetType: r.target_type, targetId: r.target_id, detail: r.detail, ip: r.ip });\n\n/** The WHERE clause of the admin's filters, with its parameters ($1, $2… in order). */\nfunction where(filters: AuditFilters): { sql: string; params: unknown[] } {\n const parts: string[] = [];\n const params: unknown[] = [];\n const add = (clause: (n: number) => string, value: unknown) => { params.push(value); parts.push(clause(params.length)); };\n if (filters.actorId !== undefined) add((n) => `actor_id = $${n}`, filters.actorId);\n if (filters.actionPrefix !== undefined) add((n) => `starts_with(action, $${n})`, filters.actionPrefix);\n if (filters.target !== undefined) { add((n) => `target_type = $${n}`, filters.target.type); add((n) => `target_id = $${n}`, filters.target.id); }\n if (filters.from !== undefined) add((n) => `at >= $${n}`, filters.from);\n if (filters.to !== undefined) add((n) => `at < $${n}`, filters.to);\n if (filters.before !== undefined) add((n) => `id < $${n}::bigint`, filters.before);\n return { sql: parts.length > 0 ? `WHERE ${parts.join(\" AND \")}` : \"\", params };\n}\n\n/**\n * The PostgreSQL store, on `<schema>.entry` (`auditSchema`), over the product's query: a pool, or an open transaction.\n * @param query the product's SQL runner\n * @param schema the Postgres schema, when the product renamed it (default `audit`)\n * @returns a store that passes `auditStoreContract`\n * @throws DbError `DB_UNSAFE_IDENTIFIER` for a schema that is not an identifier\n */\nexport function dbAuditStore(query: Query, schema = \"audit\"): AuditStore {\n const table = `${ident(schema)}.entry`;\n const rows = async (sql: string, params?: unknown[]) => (await query<Row>(sql, params)).map(toEntry);\n return {\n async insert(e) {\n await query(`INSERT INTO ${table} (at, actor_id, actor_label, action, target_type, target_id, detail, ip) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [e.at, e.actorId, e.actorLabel, e.action, e.targetType, e.targetId, JSON.stringify(e.detail), e.ip]);\n },\n async list(filters) {\n const { sql, params } = where(filters);\n return rows(`SELECT ${COLUMNS} FROM ${table} ${sql} ORDER BY id DESC LIMIT $${params.length + 1}`, [...params, pageSize(filters.limit)]);\n },\n forActor: (actorId) => rows(`SELECT ${COLUMNS} FROM ${table} WHERE actor_id = $1 ORDER BY id DESC`, [actorId]),\n async redactActor(actorId) {\n return (await query(`UPDATE ${table} SET actor_id = NULL, actor_label = 'erased', ip = NULL WHERE actor_id = $1 RETURNING id`, [actorId])).length;\n },\n async purgeBefore(before) {\n return (await query(`DELETE FROM ${table} WHERE at < $1 RETURNING id`, [before])).length;\n },\n };\n}\n","import { isIP } from \"node:net\";\n\nimport { AUDIT_CODE, type AuditEntryInput, AuditError, type AuditFilters, type AuditInsert } from \"./port\";\nimport { auditSettings } from \"./settings\";\n\n/** The size of a page of the trail, for the admin. */\nexport const PAGE = {\n // @fixed: a page the admin reads at once; beyond it, the cursor.\n default: 50,\n // @fixed: the most one request may return, whatever the caller asks.\n max: 200,\n} as const;\n\nconst ACTION = /^[a-z][a-z0-9_]*(\\.[a-z0-9_]+)*$/;\n\n/**\n * Checks an entry against the trail's rules and the product's list of actions, and flattens it for a store.\n * @param input what the product records\n * @param at when (the injected clock)\n * @param allowedActions the product's actions, when it keeps a fixed list\n * @returns the row to write\n * @throws AuditError `AUDIT_BAD_ACTION`, `AUDIT_UNKNOWN_ACTION`, `AUDIT_BAD_LABEL`, `AUDIT_BAD_IP`\n */\nexport function toInsert(input: AuditEntryInput, at: Date, allowedActions?: readonly string[]): AuditInsert {\n if (!ACTION.test(input.action) || input.action.length > 80) throw new AuditError(AUDIT_CODE.badAction, input.action);\n if (allowedActions && !allowedActions.includes(input.action)) throw new AuditError(AUDIT_CODE.unknownAction, input.action);\n if (input.ip != null && isIP(input.ip) === 0) throw new AuditError(AUDIT_CODE.badIp, input.ip);\n const label = input.actorLabel.trim();\n if (label.length < 1 || label.length > 120) throw new AuditError(AUDIT_CODE.badLabel, input.actorLabel);\n return {\n at,\n actorId: input.actorId,\n actorLabel: label,\n action: input.action,\n targetType: input.target?.type ?? null,\n targetId: input.target?.id ?? null,\n detail: input.detail ?? {},\n ip: input.ip ?? null,\n };\n}\n\n/**\n * The page size a store uses: the caller's, capped at `PAGE.max`, or `PAGE.default`.\n * @param limit the requested size (already checked by `checkFilters`)\n */\nexport const pageSize = (limit: number | undefined): number => Math.min(limit ?? PAGE.default, PAGE.max);\n\nconst CURSOR = /^[1-9][0-9]{0,18}$/;\n/** PostgreSQL's largest `bigint`: an entry id, and so a cursor, is never above it. */\nconst BIGINT_MAX = 9_223_372_036_854_775_807n;\n\n/**\n * Checks filters that may come from a request: a page size that is a positive integer, a cursor that is an entry id.\n * @throws AuditError `AUDIT_BAD_FILTER`\n */\nexport function checkFilters(filters: AuditFilters): void {\n if (filters.limit !== undefined && !(Number.isInteger(filters.limit) && filters.limit > 0)) throw new AuditError(AUDIT_CODE.badFilter, `limit ${String(filters.limit)}`);\n if (filters.before !== undefined && !(CURSOR.test(filters.before) && BigInt(filters.before) <= BIGINT_MAX)) throw new AuditError(AUDIT_CODE.badFilter, `before ${filters.before}`);\n}\n\n/**\n * Checks a retention against the setting's bounds, so a wrong value can never purge the whole trail.\n * @throws AuditError `AUDIT_BAD_RETENTION`\n */\nexport function checkRetention(days: number): void {\n const { min = 1, max = Number.MAX_SAFE_INTEGER } = auditSettings[\"audit.retentionDays\"];\n if (!Number.isInteger(days) || days < min || days > max) throw new AuditError(AUDIT_CODE.badRetention, String(days));\n}\n","/**\n * The ports of « audit »: who did what, when, to what. Generic: no product import, no database client (a `Query` comes in),\n * no wall clock (a `Clock` comes in). What an action means is the product's; the package keeps the trail.\n */\nexport type { Clock, Query } from \"@krizaka/db\";\n\n/** What a product records. `actorId` is null for the system or a deleted account; the label stays readable. */\nexport interface AuditEntryInput {\n actorId: string | null;\n /** A readable name of who acted (« Eric », « system », « stripe webhook »). */\n actorLabel: string;\n /** The product's action, dotted (`billing.checkout_started`, `admin.user_suspended`). */\n action: string;\n target?: { type: string; id: string } | null;\n /** Facts about the action. Never a secret, and as little personal data as the action needs. */\n detail?: Record<string, unknown>;\n ip?: string | null;\n}\n\n/** What a store writes: the input, flattened, with its time. */\nexport interface AuditInsert {\n at: Date;\n actorId: string | null;\n actorLabel: string;\n action: string;\n targetType: string | null;\n targetId: string | null;\n detail: Record<string, unknown>;\n ip: string | null;\n}\n\n/** An entry as read back: its id (a cursor too) and everything written. */\nexport interface AuditEntry extends AuditInsert {\n id: string;\n}\n\n/** How the admin filters the trail. Newest first; `before` is the last id of the previous page. */\nexport interface AuditFilters {\n actorId?: string;\n actionPrefix?: string;\n target?: { type: string; id: string };\n from?: Date;\n to?: Date;\n limit?: number;\n before?: string;\n}\n\n/** Where the trail lives. Every adapter runs `auditStoreContract` (`@krizaka/audit/testkit`). */\nexport interface AuditStore {\n insert(entry: AuditInsert): Promise<void>;\n list(filters: AuditFilters): Promise<AuditEntry[]>;\n /** Every entry of one actor (Loi 25 export). */\n forActor(actorId: string): Promise<AuditEntry[]>;\n /** Detaches one actor from the trail: id and IP removed, label « erased »; the facts stay. Returns how many entries changed. */\n redactActor(actorId: string): Promise<number>;\n /** Removes the entries older than `before`. Returns how many. */\n purgeBefore(before: Date): Promise<number>;\n}\n\nexport const AUDIT_CODE = {\n badAction: \"AUDIT_BAD_ACTION\",\n unknownAction: \"AUDIT_UNKNOWN_ACTION\",\n badLabel: \"AUDIT_BAD_LABEL\",\n badIp: \"AUDIT_BAD_IP\",\n badFilter: \"AUDIT_BAD_FILTER\",\n badRetention: \"AUDIT_BAD_RETENTION\",\n} as const;\nexport type AuditCode = (typeof AUDIT_CODE)[keyof typeof AUDIT_CODE];\n\nexport class AuditError extends Error {\n constructor(\n readonly code: AuditCode,\n readonly value: string,\n ) {\n super(`${code}: ${value}`);\n this.name = \"AuditError\";\n }\n}\n","import { integer, type Registry } from \"@krizaka/settings\";\n\n/**\n * The settings of « audit », a fragment the product adds to its registry: the admin sets how long the trail is kept, and\n * the product's job calls `purge` with it. Global scope only.\n */\nexport const auditSettings = {\n // @fixed: three years by default; the admin chooses between one month and ten years.\n \"audit.retentionDays\": integer(\"audit\", 1095, { min: 30, max: 3650, unit: \"days\" }),\n} as const satisfies Registry;\n","import type { AuditEntry, AuditFilters, AuditStore } from \"./port\";\nimport { pageSize } from \"./rules\";\n\n/** Whether an entry passes the admin's filters (the same semantics as the database store). */\nexport function matches(entry: AuditEntry, filters: AuditFilters): boolean {\n return (\n (filters.actorId === undefined || entry.actorId === filters.actorId) &&\n (filters.actionPrefix === undefined || entry.action.startsWith(filters.actionPrefix)) &&\n (filters.target === undefined || (entry.targetType === filters.target.type && entry.targetId === filters.target.id)) &&\n (filters.from === undefined || entry.at >= filters.from) &&\n (filters.to === undefined || entry.at < filters.to) &&\n (filters.before === undefined || BigInt(entry.id) < BigInt(filters.before))\n );\n}\n\n/**\n * An in-memory trail, for unit tests and demos. Ids grow like the table's `bigserial`.\n * @returns a store that passes `auditStoreContract`\n */\nexport function memoryAuditStore(): AuditStore {\n const rows: AuditEntry[] = [];\n let lastId = 0n; // like the table's sequence: never reused, even after a purge\n /** An independent copy: nothing given or read can change the stored trail. */\n const copy = (e: AuditEntry): AuditEntry => structuredClone(e);\n const newestFirst = () => [...rows].sort((a, b) => Number(BigInt(b.id) - BigInt(a.id)));\n return {\n async insert(entry) {\n lastId += 1n;\n rows.push(copy({ ...entry, id: String(lastId) }));\n },\n async list(filters) { return newestFirst().filter((e) => matches(e, filters)).slice(0, pageSize(filters.limit)).map(copy); },\n async forActor(actorId) { return newestFirst().filter((e) => e.actorId === actorId).map(copy); },\n async redactActor(actorId) {\n const mine = rows.filter((e) => e.actorId === actorId);\n for (const e of mine) Object.assign(e, { actorId: null, actorLabel: \"erased\", ip: null });\n return mine.length;\n },\n async purgeBefore(before) {\n const old = rows.filter((e) => e.at < before);\n for (const e of old) rows.splice(rows.indexOf(e), 1);\n return old.length;\n },\n };\n}\n","import { defineModule } from \"@krizaka/db\";\n\n/**\n * The tables of « audit », in their own Postgres schema (ADR-001 §3). The one product table referenced is the owner (the\n * account table), declared by the product; deleting an account keeps its entries with the actor detached.\n * Version 1 is frozen once released: a change is version 2.\n */\nexport const auditSchema = defineModule({\n module: \"audit\",\n tables: [\"owner\"],\n migrations: [\n {\n version: 1,\n name: \"entries\",\n sql: (c) => `\nCREATE TABLE ${c.schema}.entry (\n id bigserial PRIMARY KEY,\n at timestamptz NOT NULL,\n actor_id uuid REFERENCES ${c.tables.owner}(id) ON DELETE SET NULL,\n actor_label text NOT NULL CHECK (char_length(actor_label) BETWEEN 1 AND 120),\n action text NOT NULL CHECK (action ~ '^[a-z][a-z0-9_]*(\\\\.[a-z0-9_]+)*$' AND char_length(action) <= 80),\n target_type text CHECK (target_type IS NULL OR char_length(target_type) <= 40),\n target_id text CHECK (target_id IS NULL OR char_length(target_id) <= 200),\n detail jsonb NOT NULL DEFAULT '{}'::jsonb,\n ip inet\n);\nCREATE INDEX entry_at ON ${c.schema}.entry (at DESC);\nCREATE INDEX entry_action ON ${c.schema}.entry (action, at DESC);\nCREATE INDEX entry_target ON ${c.schema}.entry (target_type, target_id, at DESC);\nCREATE INDEX entry_actor ON ${c.schema}.entry (actor_id) WHERE actor_id IS NOT NULL;`,\n },\n ],\n});\n"],"mappings":";AAAA,SAAS,SAAAA,cAAa;AACtB,SAAS,eAAe;;;ACDxB,SAAS,aAAyB;;;ACAlC,SAAS,YAAY;;;AC2Dd,IAAM,aAAa;AAAA,EACxB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,UAAU;AAAA,EACV,OAAO;AAAA,EACP,WAAW;AAAA,EACX,cAAc;AAChB;AAGO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YACW,MACA,OACT;AACA,UAAM,GAAG,IAAI,KAAK,KAAK,EAAE;AAHhB;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EALW;AAAA,EACA;AAKb;;;AC7EA,SAAS,eAA8B;AAMhC,IAAM,gBAAgB;AAAA;AAAA,EAE3B,uBAAuB,QAAQ,SAAS,MAAM,EAAE,KAAK,IAAI,KAAK,MAAM,MAAM,OAAO,CAAC;AACpF;;;AFHO,IAAM,OAAO;AAAA;AAAA,EAElB,SAAS;AAAA;AAAA,EAET,KAAK;AACP;AAEA,IAAM,SAAS;AAUR,SAAS,SAAS,OAAwB,IAAU,gBAAiD;AAC1G,MAAI,CAAC,OAAO,KAAK,MAAM,MAAM,KAAK,MAAM,OAAO,SAAS,GAAI,OAAM,IAAI,WAAW,WAAW,WAAW,MAAM,MAAM;AACnH,MAAI,kBAAkB,CAAC,eAAe,SAAS,MAAM,MAAM,EAAG,OAAM,IAAI,WAAW,WAAW,eAAe,MAAM,MAAM;AACzH,MAAI,MAAM,MAAM,QAAQ,KAAK,MAAM,EAAE,MAAM,EAAG,OAAM,IAAI,WAAW,WAAW,OAAO,MAAM,EAAE;AAC7F,QAAM,QAAQ,MAAM,WAAW,KAAK;AACpC,MAAI,MAAM,SAAS,KAAK,MAAM,SAAS,IAAK,OAAM,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MAAM,SAAS,SAAS;AAAE,aAAO,YAAY,EAAE,OAAO,CAAC,MAAM,EAAE,YAAY,OAAO,EAAE,IAAI,IAAI;AAAA,IAAG;AAAA,IAC/F,MAAM,YAAY,SAAS;AACzB,YAAM,OAAO,KAAK,OAAO,CAAC,MAAM,EAAE,YAAY,OAAO;AACrD,iBAAW,KAAK,KAAM,QAAO,OAAO,GAAG,EAAE,SAAS,MAAM,YAAY,UAAU,IAAI,KAAK,CAAC;AACxF,aAAO,KAAK;AAAA,IACd;AAAA,IACA,MAAM,YAAY,QAAQ;AACxB,YAAM,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,KAAK,MAAM;AAC5C,iBAAW,KAAK,IAAK,MAAK,OAAO,KAAK,QAAQ,CAAC,GAAG,CAAC;AACnD,aAAO,IAAI;AAAA,IACb;AAAA,EACF;AACF;;;AC3CA,SAAS,oBAAoB;AAOtB,IAAM,cAAc,aAAa;AAAA,EACtC,QAAQ;AAAA,EACR,QAAQ,CAAC,OAAO;AAAA,EAChB,YAAY;AAAA,IACV;AAAA,MACE,SAAS;AAAA,MACT,MAAM;AAAA,MACN,KAAK,CAAC,MAAM;AAAA,eACH,EAAE,MAAM;AAAA;AAAA;AAAA,gCAGS,EAAE,OAAO,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAQnB,EAAE,MAAM;AAAA,+BACJ,EAAE,MAAM;AAAA,+BACR,EAAE,MAAM;AAAA,8BACT,EAAE,MAAM;AAAA,IAClC;AAAA,EACF;AACF,CAAC;","names":["ident","ident"]}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The ports of « audit »: who did what, when, to what. Generic: no product import, no database client (a `Query` comes in),
3
+ * no wall clock (a `Clock` comes in). What an action means is the product's; the package keeps the trail.
4
+ */
5
+
6
+ /** What a product records. `actorId` is null for the system or a deleted account; the label stays readable. */
7
+ interface AuditEntryInput {
8
+ actorId: string | null;
9
+ /** A readable name of who acted (« Eric », « system », « stripe webhook »). */
10
+ actorLabel: string;
11
+ /** The product's action, dotted (`billing.checkout_started`, `admin.user_suspended`). */
12
+ action: string;
13
+ target?: {
14
+ type: string;
15
+ id: string;
16
+ } | null;
17
+ /** Facts about the action. Never a secret, and as little personal data as the action needs. */
18
+ detail?: Record<string, unknown>;
19
+ ip?: string | null;
20
+ }
21
+ /** What a store writes: the input, flattened, with its time. */
22
+ interface AuditInsert {
23
+ at: Date;
24
+ actorId: string | null;
25
+ actorLabel: string;
26
+ action: string;
27
+ targetType: string | null;
28
+ targetId: string | null;
29
+ detail: Record<string, unknown>;
30
+ ip: string | null;
31
+ }
32
+ /** An entry as read back: its id (a cursor too) and everything written. */
33
+ interface AuditEntry extends AuditInsert {
34
+ id: string;
35
+ }
36
+ /** How the admin filters the trail. Newest first; `before` is the last id of the previous page. */
37
+ interface AuditFilters {
38
+ actorId?: string;
39
+ actionPrefix?: string;
40
+ target?: {
41
+ type: string;
42
+ id: string;
43
+ };
44
+ from?: Date;
45
+ to?: Date;
46
+ limit?: number;
47
+ before?: string;
48
+ }
49
+ /** Where the trail lives. Every adapter runs `auditStoreContract` (`@krizaka/audit/testkit`). */
50
+ interface AuditStore {
51
+ insert(entry: AuditInsert): Promise<void>;
52
+ list(filters: AuditFilters): Promise<AuditEntry[]>;
53
+ /** Every entry of one actor (Loi 25 export). */
54
+ forActor(actorId: string): Promise<AuditEntry[]>;
55
+ /** Detaches one actor from the trail: id and IP removed, label « erased »; the facts stay. Returns how many entries changed. */
56
+ redactActor(actorId: string): Promise<number>;
57
+ /** Removes the entries older than `before`. Returns how many. */
58
+ purgeBefore(before: Date): Promise<number>;
59
+ }
60
+ declare const AUDIT_CODE: {
61
+ readonly badAction: "AUDIT_BAD_ACTION";
62
+ readonly unknownAction: "AUDIT_UNKNOWN_ACTION";
63
+ readonly badLabel: "AUDIT_BAD_LABEL";
64
+ readonly badIp: "AUDIT_BAD_IP";
65
+ readonly badFilter: "AUDIT_BAD_FILTER";
66
+ readonly badRetention: "AUDIT_BAD_RETENTION";
67
+ };
68
+ type AuditCode = (typeof AUDIT_CODE)[keyof typeof AUDIT_CODE];
69
+ declare class AuditError extends Error {
70
+ readonly code: AuditCode;
71
+ readonly value: string;
72
+ constructor(code: AuditCode, value: string);
73
+ }
74
+
75
+ export { type AuditEntryInput as A, type AuditFilters as a, type AuditEntry as b, type AuditStore as c, type AuditInsert as d, AUDIT_CODE as e, type AuditCode as f, AuditError as g };
@@ -0,0 +1,12 @@
1
+ import { c as AuditStore } from './port-B2kkvTQu.js';
2
+
3
+ /**
4
+ * What every AuditStore adapter must do: the same behaviour behind the same port. `owner(n)` gives an actor id the adapter
5
+ * accepts (an account of the product). Each case writes under its own action prefix, so the cases share one database.
6
+ * @param name the adapter's name, shown in the test titles
7
+ * @param make builds the store
8
+ * @param owner the n-th actor id
9
+ */
10
+ declare function auditStoreContract(name: string, make: () => AuditStore | Promise<AuditStore>, owner: (n: number) => string | Promise<string>): void;
11
+
12
+ export { auditStoreContract };
@@ -0,0 +1,103 @@
1
+ // src/testkit.ts
2
+ import { expect, it } from "vitest";
3
+ function auditStoreContract(name, make, owner) {
4
+ const tag = () => `t${Math.random().toString(36).slice(2, 10)}`;
5
+ const entry = (prefix, over = {}) => ({
6
+ at: /* @__PURE__ */ new Date("2026-10-23T10:00:00Z"),
7
+ actorId: null,
8
+ actorLabel: "system",
9
+ action: `${prefix}.done`,
10
+ targetType: null,
11
+ targetId: null,
12
+ detail: {},
13
+ ip: null,
14
+ ...over
15
+ });
16
+ it(`${name}: keeps every field and lists the newest first`, async () => {
17
+ const store = await make();
18
+ const p = tag();
19
+ const actor = await owner(1);
20
+ await store.insert(entry(p, { at: /* @__PURE__ */ new Date("2026-10-23T09:00:00Z"), action: `${p}.first` }));
21
+ await store.insert(entry(p, { actorId: actor, actorLabel: "Eric", action: `${p}.second`, targetType: "shop", targetId: "s1", detail: { n: 2, tags: ["a"] }, ip: "203.0.113.9" }));
22
+ const listed = await store.list({ actionPrefix: `${p}.` });
23
+ expect(listed.map((e) => e.action)).toEqual([`${p}.second`, `${p}.first`]);
24
+ expect(listed[0]).toMatchObject({ actorId: actor, actorLabel: "Eric", targetType: "shop", targetId: "s1", detail: { n: 2, tags: ["a"] }, ip: "203.0.113.9" });
25
+ expect(listed[0].at.toISOString()).toBe("2026-10-23T10:00:00.000Z");
26
+ expect(typeof listed[0].id).toBe("string");
27
+ });
28
+ it(`${name}: filters by actor, target and time window`, async () => {
29
+ const store = await make();
30
+ const p = tag();
31
+ const [a, b] = [await owner(2), await owner(3)];
32
+ await store.insert(entry(p, { actorId: a, targetType: "shop", targetId: "x", at: /* @__PURE__ */ new Date("2026-10-01T00:00:00Z") }));
33
+ await store.insert(entry(p, { actorId: b, targetType: "shop", targetId: "y", at: /* @__PURE__ */ new Date("2026-10-10T00:00:00Z") }));
34
+ expect(await store.list({ actionPrefix: p, actorId: a })).toHaveLength(1);
35
+ expect((await store.list({ actionPrefix: p, target: { type: "shop", id: "y" } }))[0].actorId).toBe(b);
36
+ expect(await store.list({ actionPrefix: p, from: /* @__PURE__ */ new Date("2026-10-05T00:00:00Z") })).toHaveLength(1);
37
+ expect(await store.list({ actionPrefix: p, to: /* @__PURE__ */ new Date("2026-10-05T00:00:00Z") })).toHaveLength(1);
38
+ });
39
+ it(`${name}: pages with a limit and a cursor (the last id seen)`, async () => {
40
+ const store = await make();
41
+ const p = tag();
42
+ for (let i = 0; i < 5; i++) await store.insert(entry(p, { action: `${p}.n${i}` }));
43
+ const page1 = await store.list({ actionPrefix: p, limit: 2 });
44
+ const page2 = await store.list({ actionPrefix: p, limit: 2, before: page1.at(-1).id });
45
+ expect(page1.map((e) => e.action)).toEqual([`${p}.n4`, `${p}.n3`]);
46
+ expect(page2.map((e) => e.action)).toEqual([`${p}.n2`, `${p}.n1`]);
47
+ });
48
+ it(`${name}: exports one actor's entries and redacts them (Loi 25), leaving the others`, async () => {
49
+ const store = await make();
50
+ const p = tag();
51
+ const [gone, stays] = [await owner(4), await owner(5)];
52
+ await store.insert(entry(p, { actorId: gone, actorLabel: "Gone", ip: "198.51.100.1" }));
53
+ await store.insert(entry(p, { actorId: stays, actorLabel: "Stays" }));
54
+ expect((await store.forActor(gone)).filter((e) => e.action.startsWith(p))).toHaveLength(1);
55
+ expect(await store.redactActor(gone)).toBeGreaterThanOrEqual(1);
56
+ const after = await store.list({ actionPrefix: p });
57
+ expect(after.find((e) => e.actorLabel === "Stays").actorId).toBe(stays);
58
+ expect(after.find((e) => e.actorLabel !== "Stays")).toMatchObject({ actorId: null, actorLabel: "erased", ip: null });
59
+ expect((await store.forActor(gone)).filter((e) => e.action.startsWith(p))).toEqual([]);
60
+ });
61
+ it(`${name}: ids never repeat after a purge, so a cursor never skips an entry`, async () => {
62
+ const store = await make();
63
+ const p = tag();
64
+ await store.insert(entry(p, { action: `${p}.old`, at: /* @__PURE__ */ new Date("2020-01-01T00:00:00Z") }));
65
+ await store.insert(entry(p, { action: `${p}.kept`, at: /* @__PURE__ */ new Date("2026-10-01T00:00:00Z") }));
66
+ await store.purgeBefore(/* @__PURE__ */ new Date("2021-01-01T00:00:00Z"));
67
+ await store.insert(entry(p, { action: `${p}.after`, at: /* @__PURE__ */ new Date("2026-10-02T00:00:00Z") }));
68
+ const all = await store.list({ actionPrefix: p });
69
+ expect(new Set(all.map((e) => e.id)).size).toBe(all.length);
70
+ const first = await store.list({ actionPrefix: p, limit: 1 });
71
+ const rest = await store.list({ actionPrefix: p, before: first[0].id });
72
+ expect([...first, ...rest].map((e) => e.action)).toEqual([`${p}.after`, `${p}.kept`]);
73
+ });
74
+ it(`${name}: the trail cannot be changed by mutating what was given or what was read`, async () => {
75
+ const store = await make();
76
+ const p = tag();
77
+ const input = entry(p, { detail: { nested: { n: 1 } } });
78
+ await store.insert(input);
79
+ input.at.setUTCFullYear(1999);
80
+ input.detail.nested.n = 99;
81
+ const [read] = await store.list({ actionPrefix: p });
82
+ read.at.setUTCFullYear(1999);
83
+ read.detail.nested.n = 42;
84
+ read.actorLabel = "forged";
85
+ const [again] = await store.list({ actionPrefix: p });
86
+ expect(again).toMatchObject({ actorLabel: "system", detail: { nested: { n: 1 } } });
87
+ expect(again.at.toISOString()).toBe("2026-10-23T10:00:00.000Z");
88
+ const [exported] = await store.forActor("00000000-0000-4000-8000-000000000000");
89
+ expect(exported).toBeUndefined();
90
+ });
91
+ it(`${name}: purges only what is older than the given time, and counts it`, async () => {
92
+ const store = await make();
93
+ const p = tag();
94
+ await store.insert(entry(p, { action: `${p}.old`, at: /* @__PURE__ */ new Date("2020-01-01T00:00:00Z") }));
95
+ await store.insert(entry(p, { action: `${p}.new`, at: /* @__PURE__ */ new Date("2026-10-01T00:00:00Z") }));
96
+ expect(await store.purgeBefore(/* @__PURE__ */ new Date("2021-01-01T00:00:00Z"))).toBeGreaterThanOrEqual(1);
97
+ expect((await store.list({ actionPrefix: p })).map((e) => e.action)).toEqual([`${p}.new`]);
98
+ });
99
+ }
100
+ export {
101
+ auditStoreContract
102
+ };
103
+ //# sourceMappingURL=testkit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testkit.ts"],"sourcesContent":["import { expect, it } from \"vitest\";\n\nimport type { AuditInsert, AuditStore } from \"./port\";\n\n/**\n * What every AuditStore adapter must do: the same behaviour behind the same port. `owner(n)` gives an actor id the adapter\n * accepts (an account of the product). Each case writes under its own action prefix, so the cases share one database.\n * @param name the adapter's name, shown in the test titles\n * @param make builds the store\n * @param owner the n-th actor id\n */\nexport function auditStoreContract(name: string, make: () => AuditStore | Promise<AuditStore>, owner: (n: number) => string | Promise<string>) {\n const tag = () => `t${Math.random().toString(36).slice(2, 10)}`;\n const entry = (prefix: string, over: Partial<AuditInsert> = {}): AuditInsert => ({\n at: new Date(\"2026-10-23T10:00:00Z\"),\n actorId: null,\n actorLabel: \"system\",\n action: `${prefix}.done`,\n targetType: null,\n targetId: null,\n detail: {},\n ip: null,\n ...over,\n });\n\n it(`${name}: keeps every field and lists the newest first`, async () => {\n const store = await make();\n const p = tag();\n const actor = await owner(1);\n await store.insert(entry(p, { at: new Date(\"2026-10-23T09:00:00Z\"), action: `${p}.first` }));\n await store.insert(entry(p, { actorId: actor, actorLabel: \"Eric\", action: `${p}.second`, targetType: \"shop\", targetId: \"s1\", detail: { n: 2, tags: [\"a\"] }, ip: \"203.0.113.9\" }));\n const listed = await store.list({ actionPrefix: `${p}.` });\n expect(listed.map((e) => e.action)).toEqual([`${p}.second`, `${p}.first`]);\n expect(listed[0]).toMatchObject({ actorId: actor, actorLabel: \"Eric\", targetType: \"shop\", targetId: \"s1\", detail: { n: 2, tags: [\"a\"] }, ip: \"203.0.113.9\" });\n expect(listed[0]!.at.toISOString()).toBe(\"2026-10-23T10:00:00.000Z\");\n expect(typeof listed[0]!.id).toBe(\"string\");\n });\n\n it(`${name}: filters by actor, target and time window`, async () => {\n const store = await make();\n const p = tag();\n const [a, b] = [await owner(2), await owner(3)];\n await store.insert(entry(p, { actorId: a, targetType: \"shop\", targetId: \"x\", at: new Date(\"2026-10-01T00:00:00Z\") }));\n await store.insert(entry(p, { actorId: b, targetType: \"shop\", targetId: \"y\", at: new Date(\"2026-10-10T00:00:00Z\") }));\n expect(await store.list({ actionPrefix: p, actorId: a })).toHaveLength(1);\n expect((await store.list({ actionPrefix: p, target: { type: \"shop\", id: \"y\" } }))[0]!.actorId).toBe(b);\n expect(await store.list({ actionPrefix: p, from: new Date(\"2026-10-05T00:00:00Z\") })).toHaveLength(1);\n expect(await store.list({ actionPrefix: p, to: new Date(\"2026-10-05T00:00:00Z\") })).toHaveLength(1);\n });\n\n it(`${name}: pages with a limit and a cursor (the last id seen)`, async () => {\n const store = await make();\n const p = tag();\n for (let i = 0; i < 5; i++) await store.insert(entry(p, { action: `${p}.n${i}` }));\n const page1 = await store.list({ actionPrefix: p, limit: 2 });\n const page2 = await store.list({ actionPrefix: p, limit: 2, before: page1.at(-1)!.id });\n expect(page1.map((e) => e.action)).toEqual([`${p}.n4`, `${p}.n3`]);\n expect(page2.map((e) => e.action)).toEqual([`${p}.n2`, `${p}.n1`]);\n });\n\n it(`${name}: exports one actor's entries and redacts them (Loi 25), leaving the others`, async () => {\n const store = await make();\n const p = tag();\n const [gone, stays] = [await owner(4), await owner(5)];\n await store.insert(entry(p, { actorId: gone, actorLabel: \"Gone\", ip: \"198.51.100.1\" }));\n await store.insert(entry(p, { actorId: stays, actorLabel: \"Stays\" }));\n expect((await store.forActor(gone)).filter((e) => e.action.startsWith(p))).toHaveLength(1);\n expect(await store.redactActor(gone)).toBeGreaterThanOrEqual(1);\n const after = await store.list({ actionPrefix: p });\n expect(after.find((e) => e.actorLabel === \"Stays\")!.actorId).toBe(stays);\n expect(after.find((e) => e.actorLabel !== \"Stays\")).toMatchObject({ actorId: null, actorLabel: \"erased\", ip: null });\n expect((await store.forActor(gone)).filter((e) => e.action.startsWith(p))).toEqual([]);\n });\n\n it(`${name}: ids never repeat after a purge, so a cursor never skips an entry`, async () => {\n const store = await make();\n const p = tag();\n await store.insert(entry(p, { action: `${p}.old`, at: new Date(\"2020-01-01T00:00:00Z\") }));\n await store.insert(entry(p, { action: `${p}.kept`, at: new Date(\"2026-10-01T00:00:00Z\") }));\n await store.purgeBefore(new Date(\"2021-01-01T00:00:00Z\"));\n await store.insert(entry(p, { action: `${p}.after`, at: new Date(\"2026-10-02T00:00:00Z\") }));\n const all = await store.list({ actionPrefix: p });\n expect(new Set(all.map((e) => e.id)).size).toBe(all.length);\n const first = await store.list({ actionPrefix: p, limit: 1 });\n const rest = await store.list({ actionPrefix: p, before: first[0]!.id });\n expect([...first, ...rest].map((e) => e.action)).toEqual([`${p}.after`, `${p}.kept`]);\n });\n\n it(`${name}: the trail cannot be changed by mutating what was given or what was read`, async () => {\n const store = await make();\n const p = tag();\n const input = entry(p, { detail: { nested: { n: 1 } } });\n await store.insert(input);\n input.at.setUTCFullYear(1999);\n (input.detail.nested as { n: number }).n = 99;\n const [read] = await store.list({ actionPrefix: p });\n read!.at.setUTCFullYear(1999);\n (read!.detail.nested as { n: number }).n = 42;\n read!.actorLabel = \"forged\";\n const [again] = await store.list({ actionPrefix: p });\n expect(again).toMatchObject({ actorLabel: \"system\", detail: { nested: { n: 1 } } });\n expect(again!.at.toISOString()).toBe(\"2026-10-23T10:00:00.000Z\");\n const [exported] = await store.forActor(\"00000000-0000-4000-8000-000000000000\");\n expect(exported).toBeUndefined();\n });\n\n it(`${name}: purges only what is older than the given time, and counts it`, async () => {\n const store = await make();\n const p = tag();\n await store.insert(entry(p, { action: `${p}.old`, at: new Date(\"2020-01-01T00:00:00Z\") }));\n await store.insert(entry(p, { action: `${p}.new`, at: new Date(\"2026-10-01T00:00:00Z\") }));\n expect(await store.purgeBefore(new Date(\"2021-01-01T00:00:00Z\"))).toBeGreaterThanOrEqual(1);\n expect((await store.list({ actionPrefix: p })).map((e) => e.action)).toEqual([`${p}.new`]);\n });\n}\n"],"mappings":";AAAA,SAAS,QAAQ,UAAU;AAWpB,SAAS,mBAAmB,MAAc,MAA8C,OAAgD;AAC7I,QAAM,MAAM,MAAM,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AAC7D,QAAM,QAAQ,CAAC,QAAgB,OAA6B,CAAC,OAAoB;AAAA,IAC/E,IAAI,oBAAI,KAAK,sBAAsB;AAAA,IACnC,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,QAAQ,GAAG,MAAM;AAAA,IACjB,YAAY;AAAA,IACZ,UAAU;AAAA,IACV,QAAQ,CAAC;AAAA,IACT,IAAI;AAAA,IACJ,GAAG;AAAA,EACL;AAEA,KAAG,GAAG,IAAI,kDAAkD,YAAY;AACtE,UAAM,QAAQ,MAAM,KAAK;AACzB,UAAM,IAAI,IAAI;AACd,UAAM,QAAQ,MAAM,MAAM,CAAC;AAC3B,UAAM,MAAM,OAAO,MAAM,GAAG,EAAE,IAAI,oBAAI,KAAK,sBAAsB,GAAG,QAAQ,GAAG,CAAC,SAAS,CAAC,CAAC;AAC3F,UAAM,MAAM,OAAO,MAAM,GAAG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A,EACjC,CAAC;AAED,KAAG,GAAG,IAAI,kEAAkE,YAAY;AACtF,UAAM,QAAQ,MAAM,KAAK;AACzB,UAAM,IAAI,IAAI;AACd,UAAM,MAAM,OAAO,MAAM,GAAG,EAAE,QAAQ,GAAG,CAAC,QAAQ,IAAI,oBAAI,KAAK,sBAAsB,EAAE,CAAC,CAAC;AACzF,UAAM,MAAM,OAAO,MAAM,GAAG,EAAE,QAAQ,GAAG,CAAC,QAAQ,IAAI,oBAAI,KAAK,sBAAsB,EAAE,CAAC,CAAC;AACzF,WAAO,MAAM,MAAM,YAAY,oBAAI,KAAK,sBAAsB,CAAC,CAAC,EAAE,uBAAuB,CAAC;AAC1F,YAAQ,MAAM,MAAM,KAAK,EAAE,cAAc,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC;AAAA,EAC3F,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "@krizaka/audit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Who did what, for every Krizaka product: an append-only audit trail in its own schema, written inside the caller's transaction or quietly beside it, filtered for the admin, exported and redacted for Loi 25, purged after a retention set by the admin. No database client, no wall clock.",
5
+ "keywords": [
6
+ "krizaka",
7
+ "audit",
8
+ "audit-log",
9
+ "loi-25",
10
+ "postgresql"
11
+ ],
12
+ "homepage": "https://github.com/krizaka/krizaka-ts/tree/main/packages/audit",
13
+ "bugs": "https://github.com/krizaka/krizaka-ts/issues",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/krizaka/krizaka-ts.git",
17
+ "directory": "packages/audit"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": "Krizaka (https://www.krizaka.com)",
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ },
30
+ "./testkit": {
31
+ "types": "./dist/testkit.d.ts",
32
+ "import": "./dist/testkit.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "sideEffects": false,
42
+ "engines": {
43
+ "node": ">=22"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^22.10.0",
47
+ "@types/pg": "^8.23.1",
48
+ "eslint": "^9.39.0",
49
+ "pg": "^8.23.1",
50
+ "tsup": "^8.5.0",
51
+ "typescript": "^5.9.3",
52
+ "vitest": "^4.1.11",
53
+ "zod": "^4.6.7",
54
+ "@krizaka/config": "^0.8.0"
55
+ },
56
+ "dependencies": {
57
+ "date-fns": "^4.4.0",
58
+ "@krizaka/settings": "^0.1.0",
59
+ "@krizaka/db": "^0.1.0"
60
+ },
61
+ "peerDependencies": {
62
+ "vitest": ">=4",
63
+ "zod": ">=3.23"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "vitest": {
67
+ "optional": true
68
+ }
69
+ },
70
+ "scripts": {
71
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
72
+ "lint": "eslint . --max-warnings 0 && tsc --noEmit",
73
+ "typecheck": "tsc --noEmit",
74
+ "test": "vitest run",
75
+ "check": "pnpm run lint && pnpm run test && pnpm run build"
76
+ }
6
77
  }