@krizaka/privacy 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,3 +33,28 @@ await privacy.purge(query); // from the product's
33
33
  - **Erasure** runs every contributor's `eraseFor` in ONE transaction, withdraws the live consents (a new row each, version `erasure` or the one you pass), records the request and an audit entry `privacy.erasure_completed` that names the request and the modules and **no one**. If a contributor fails, nothing is erased, the request is recorded as `failed` with a code, and the error is thrown (if recording the failure fails too, an `AggregateError` with the original first).
34
34
  - **Retention:** `privacySettings({ screening: { retentionDays: 365 } })` (`@krizaka/privacy/settings`, needs `@krizaka/settings` and `zod`) declares `privacy.retention.screeningDays` (`payment-history` → `paymentHistoryDays`). `purge` calls every contributor's `purgeExpired` for each purpose that has a retention.
35
35
  - The request table holds an id of the subject and no other personal data, so it can outlive the erasure it proves. `privacyStoreContract` (from `@krizaka/privacy/testkit`) is the contract every store runs.
36
+
37
+ ## Confidentiality incident register
38
+
39
+ The register that the Act respecting the protection of personal information in the private sector ([CQLR c. P-39.1](https://www.legisquebec.gouv.qc.ca/en/document/cs/P-39.1), ss. 3.5 to 3.8) asks every enterprise to keep, with the content and retention set by the [Regulation respecting confidentiality incidents](https://www.legisquebec.gouv.qc.ca/en/document/cr/P-39.1,%20r.%203.1). In short, as we read it (not legal advice): on reason to believe an incident occurred, reduce the risk and prevent a new one; assess the risk of serious injury from the sensitivity of the information, the anticipated consequences and the likelihood of misuse; if the risk is serious, notify the Commission d'accès à l'information and the people concerned promptly; and keep a register of every incident, serious or not, for at least five years after becoming aware of it, handed to the Commission on request.
40
+
41
+ ```ts
42
+ import { createIncidentRegister, registerToCsv, suggestSeriousInjury } from "@krizaka/privacy";
43
+
44
+ emitMigration(privacySchema, 2, { tables: {} }); // privacy.incident (after version 1)
45
+ const incidents = createIncidentRegister({ clock: { now: () => new Date() }, audit });
46
+ const admin = { id: account.id, label: account.name };
47
+
48
+ const { id } = await incidents.open(query, { scope: tenantId, kind: "access", description: "…", information: ["lease"], personsConcerned: 3 }, admin);
49
+ await incidents.recordMeasure(query, tenantId, id, "Session revoked", admin);
50
+ await incidents.assess(query, tenantId, id, { sensitivity: "high", consequences: "high", likelihood: "medium", seriousInjury: suggestSeriousInjury(factors), rationale: "…" }, admin);
51
+ await incidents.recordNotice(query, tenantId, id, "cai", { channel: "form" }, admin); // and "persons"
52
+ await incidents.close(query, tenantId, id, admin); // a serious injury closes once both notices are recorded
53
+ registerToCsv((await incidents.exportRegister(query, tenantId)).entries);
54
+ ```
55
+
56
+ - **Every call is by `scope`** (the tenant): an entry of another scope is never found, edited or exported. The store is the `IncidentStore` port (`memoryIncidentStore`, `dbIncidentStore`; `incidentStoreContract` from `@krizaka/privacy/testkit`); the clock is injected.
57
+ - **The register holds no personal data of the people concerned**: how many, and the categories of information, never the information.
58
+ - **Kept five years**: `retainUntil` is five years after `awareAt`; the database refuses to delete an entry before it, and refuses to edit a closed one. A drill is marked (`drill`) and stays in the register.
59
+ - `suggestSeriousInjury` is a guide for the person in charge; the decision (`seriousInjury`) is theirs and is recorded with its rationale. An incident without serious injury owes no notice (`recordNotice` refuses).
60
+ - With `audit`, each step is traced as `privacy.incident_*` without the description or any person.
@@ -0,0 +1,321 @@
1
+ import { Query, Clock } from '@krizaka/db';
2
+
3
+ /**
4
+ * The ports of « privacy » (Loi 25): consents by purpose, the person's data exported from every module that holds it, and erased
5
+ * from every module in one transaction. Generic: no product import, no database client (a `Query` comes in), no wall clock (a
6
+ * `Clock` comes in). What a module holds, and what erasing it means (blanking a row, deleting a file, keeping an invoice for six
7
+ * years), is the module's: it implements `PrivacyContributor`.
8
+ */
9
+
10
+ /**
11
+ * Whose data it is. Usually an account (`{ kind: "account", id }`), but a product's data subject is not always an account: Akinaza's
12
+ * is a client file, Yomizaka's a tenant on an application. The `kind` says which.
13
+ */
14
+ interface Subject {
15
+ /** What the id identifies: `account`, `client`, `application`. Lower-case letters, digits and `_`. */
16
+ kind: string;
17
+ /** The product's id for it (a UUID, a slug). */
18
+ id: string;
19
+ }
20
+ /** What a product records when a person agrees, or withdraws. */
21
+ interface ConsentInput {
22
+ subject: Subject;
23
+ /** What the person agreed to (`marketing`, `screening`, `reminders`): one of the product's declared purposes. */
24
+ purpose: string;
25
+ /** The version of the notice shown to them: the proof of WHAT they agreed to. */
26
+ version: string;
27
+ granted: boolean;
28
+ /** How they said it (`checkbox`, `link`, `verbal`, `erasure`). */
29
+ means?: string | undefined;
30
+ }
31
+ /** A consent as written. It is never edited: a withdrawal is a new row. */
32
+ interface ConsentRecord {
33
+ id: string;
34
+ subject: Subject;
35
+ purpose: string;
36
+ version: string;
37
+ granted: boolean;
38
+ means: string | null;
39
+ at: Date;
40
+ }
41
+ declare const REQUEST_KIND: {
42
+ readonly export: "export";
43
+ readonly erasure: "erasure";
44
+ };
45
+ type RequestKind = (typeof REQUEST_KIND)[keyof typeof REQUEST_KIND];
46
+ declare const REQUEST_STATUS: {
47
+ readonly requested: "requested";
48
+ readonly completed: "completed";
49
+ readonly failed: "failed";
50
+ };
51
+ type RequestStatus = (typeof REQUEST_STATUS)[keyof typeof REQUEST_STATUS];
52
+ /** An export or an erasure asked for, and where it stands. It holds an id of the subject and no other personal data. */
53
+ interface PrivacyRequest {
54
+ id: string;
55
+ subject: Subject;
56
+ kind: RequestKind;
57
+ status: RequestStatus;
58
+ requestedAt: Date;
59
+ completedAt: Date | null;
60
+ /** A code, never a message that could carry data. */
61
+ failure: string | null;
62
+ }
63
+ /**
64
+ * A module that holds personal data. The product registers one per module and one for its own tables.
65
+ *
66
+ * - `exportFor` returns what the module holds about the subject, as JSON-able data.
67
+ * - `eraseFor` erases or anonymises it, through the transaction it is given, so the whole erasure commits or rolls back together.
68
+ * A side effect outside the database (a file in storage) is not done here: append it to the outbox in the same transaction.
69
+ * - `purgeExpired` (optional) removes what the retention of a purpose says is past, for everyone.
70
+ */
71
+ interface PrivacyContributor {
72
+ /** A stable name, the key of its part in the export (`audit`, `orders`). */
73
+ name: string;
74
+ exportFor(query: Query, subject: Subject): Promise<unknown>;
75
+ eraseFor(tx: Query, subject: Subject): Promise<void>;
76
+ purgeExpired?(tx: Query, input: {
77
+ purpose: string;
78
+ before: Date;
79
+ }): Promise<number>;
80
+ }
81
+ /** The whole export of a subject: one document, a part per contributor. */
82
+ interface ExportDocument {
83
+ format: 1;
84
+ subject: Subject;
85
+ generatedAt: string;
86
+ modules: Record<string, unknown>;
87
+ }
88
+ /** Where consents and requests live. Every adapter runs `privacyStoreContract` (`@krizaka/privacy/testkit`). */
89
+ interface PrivacyStore {
90
+ insertConsent(consent: ConsentRecord): Promise<void>;
91
+ /** The consent with the last word for this purpose, or null when the person never said anything. */
92
+ latestConsent(subject: Subject, purpose: string): Promise<ConsentRecord | null>;
93
+ /** Every consent of the subject, oldest first. */
94
+ consentHistory(subject: Subject): Promise<ConsentRecord[]>;
95
+ insertRequest(request: PrivacyRequest): Promise<void>;
96
+ getRequest(id: string): Promise<PrivacyRequest | null>;
97
+ finishRequest(id: string, outcome: {
98
+ status: "completed" | "failed";
99
+ at: Date;
100
+ failure?: string;
101
+ }): Promise<void>;
102
+ requestsOf(subject: Subject): Promise<PrivacyRequest[]>;
103
+ }
104
+ /** The structural slice of `@krizaka/audit` this package writes through, so it adds no dependency. */
105
+ interface AuditPort {
106
+ record(query: Query, entry: {
107
+ actorId: string | null;
108
+ actorLabel: string;
109
+ action: string;
110
+ target?: {
111
+ type: string;
112
+ id: string;
113
+ } | null;
114
+ detail?: Record<string, unknown>;
115
+ }): Promise<unknown>;
116
+ }
117
+ /** The structural slice of `@krizaka/outbox` used for a large export. */
118
+ interface OutboxPort {
119
+ append(tx: Query, message: {
120
+ topic: string;
121
+ type: string;
122
+ payload: unknown;
123
+ id?: string;
124
+ }): Promise<unknown>;
125
+ }
126
+ declare const PRIVACY_CODE: {
127
+ readonly badSubject: "PRIVACY_BAD_SUBJECT";
128
+ readonly badPurpose: "PRIVACY_BAD_PURPOSE";
129
+ readonly badConsent: "PRIVACY_BAD_CONSENT";
130
+ readonly unknownRequest: "PRIVACY_UNKNOWN_REQUEST";
131
+ readonly notAnExport: "PRIVACY_NOT_AN_EXPORT";
132
+ readonly alreadyDone: "PRIVACY_ALREADY_DONE";
133
+ readonly contributorFailed: "PRIVACY_CONTRIBUTOR_FAILED";
134
+ readonly noOutbox: "PRIVACY_NO_OUTBOX";
135
+ };
136
+ type PrivacyCode = (typeof PRIVACY_CODE)[keyof typeof PRIVACY_CODE];
137
+ declare class PrivacyError extends Error {
138
+ readonly code: PrivacyCode;
139
+ constructor(code: PrivacyCode, message: string, options?: {
140
+ cause?: unknown;
141
+ });
142
+ }
143
+
144
+ /**
145
+ * The confidentiality incident register (Loi 25). Act respecting the protection of personal information in the private sector
146
+ * (CQLR c. P-39.1), ss. 3.5 to 3.8, and the Regulation respecting confidentiality incidents (CQLR c. P-39.1, r. 3.1): see the README
147
+ * for the links. The register holds the facts of an incident and NO personal data of the people concerned (only how many, and which
148
+ * categories of information).
149
+ */
150
+ /** What happened to the information (the Act speaks of unauthorised access, use, communication and loss). */
151
+ declare const INCIDENT_KIND: {
152
+ readonly access: "access";
153
+ readonly use: "use";
154
+ readonly communication: "communication";
155
+ readonly loss: "loss";
156
+ };
157
+ type IncidentKind = (typeof INCIDENT_KIND)[keyof typeof INCIDENT_KIND];
158
+ declare const INCIDENT_STATUS: {
159
+ readonly open: "open";
160
+ readonly assessed: "assessed";
161
+ readonly closed: "closed";
162
+ };
163
+ type IncidentStatus = (typeof INCIDENT_STATUS)[keyof typeof INCIDENT_STATUS];
164
+ declare const LEVEL: {
165
+ readonly low: "low";
166
+ readonly medium: "medium";
167
+ readonly high: "high";
168
+ };
169
+ type Level = (typeof LEVEL)[keyof typeof LEVEL];
170
+ declare const NOTICE_TARGET: {
171
+ readonly cai: "cai";
172
+ readonly persons: "persons";
173
+ };
174
+ type NoticeTarget = (typeof NOTICE_TARGET)[keyof typeof NOTICE_TARGET];
175
+ /** The three factors of the risk assessment (s. 3.6) and the decision of the person in charge. */
176
+ interface IncidentAssessment {
177
+ /** How sensitive the information is. */
178
+ sensitivity: Level;
179
+ /** How serious the anticipated consequences of its use are. */
180
+ consequences: Level;
181
+ /** How likely it is to be misused. */
182
+ likelihood: Level;
183
+ /** The decision: a risk of serious injury means notifying the Commission d'accès à l'information and the people concerned. */
184
+ seriousInjury: boolean;
185
+ rationale: string;
186
+ assessedAt: Date;
187
+ assessedBy: string;
188
+ }
189
+ /** A notice sent, to the Commission or to the people concerned. */
190
+ interface IncidentNotice {
191
+ sentAt: Date;
192
+ /** How it was sent (`form`, `email`, `letter`, `public`). */
193
+ channel: string;
194
+ /** The Commission's acknowledgement, if any. */
195
+ reference: string | null;
196
+ }
197
+ interface IncidentMeasure {
198
+ at: Date;
199
+ text: string;
200
+ }
201
+ /** One register entry: an incident, from the day the enterprise became aware of it. */
202
+ interface Incident {
203
+ id: string;
204
+ /** Whose register it is: a tenant, an organisation. Entries of another scope are never read. */
205
+ scope: string;
206
+ kind: IncidentKind;
207
+ /** When the enterprise became aware of it: the start of the retention. */
208
+ awareAt: Date;
209
+ occurredAt: Date | null;
210
+ description: string;
211
+ /** The categories of information concerned (`lease`, `pay stub`), never the information. */
212
+ information: string[];
213
+ /** How many people are concerned, null while unknown. */
214
+ personsConcerned: number | null;
215
+ measures: IncidentMeasure[];
216
+ status: IncidentStatus;
217
+ assessment: IncidentAssessment | null;
218
+ caiNotice: IncidentNotice | null;
219
+ personsNotice: IncidentNotice | null;
220
+ /** A fictitious incident, run to prove the procedure. It stays in the register, marked. */
221
+ drill: boolean;
222
+ openedBy: string;
223
+ openedAt: Date;
224
+ closedAt: Date | null;
225
+ /** The register entry cannot be deleted before this date: five years after `awareAt`. */
226
+ retainUntil: Date;
227
+ }
228
+ interface IncidentInput {
229
+ scope: string;
230
+ kind: IncidentKind;
231
+ awareAt?: Date | undefined;
232
+ occurredAt?: Date | undefined;
233
+ description: string;
234
+ information: readonly string[];
235
+ personsConcerned?: number | undefined;
236
+ drill?: boolean | undefined;
237
+ }
238
+ interface AssessmentInput {
239
+ sensitivity: Level;
240
+ consequences: Level;
241
+ likelihood: Level;
242
+ seriousInjury: boolean;
243
+ rationale: string;
244
+ }
245
+ /** Where the register lives. Every adapter runs `incidentStoreContract` (`@krizaka/privacy/testkit`). Every read is by scope. */
246
+ interface IncidentStore {
247
+ insert(incident: Incident): Promise<void>;
248
+ /** Replaces an incident that is not closed. */
249
+ save(incident: Incident): Promise<void>;
250
+ /** `lock`: for the read-then-write of one incident (`FOR UPDATE`). */
251
+ get(scope: string, id: string, options?: {
252
+ lock?: boolean;
253
+ }): Promise<Incident | null>;
254
+ /** The whole register of the scope, oldest awareness first. */
255
+ list(scope: string): Promise<Incident[]>;
256
+ }
257
+ interface IncidentActor {
258
+ /** An opaque id (an admin account). */
259
+ id: string | null;
260
+ label: string;
261
+ }
262
+ interface IncidentDeps {
263
+ clock: Clock;
264
+ audit?: AuditPort;
265
+ storeFor?: (query: Query) => IncidentStore;
266
+ /** The Postgres schema, when the product renamed the module's. */
267
+ schema?: string;
268
+ }
269
+ /** The register as handed to the Commission on request: one document, the entries oldest first. */
270
+ interface RegisterDocument {
271
+ format: 1;
272
+ scope: string;
273
+ generatedAt: string;
274
+ entries: Incident[];
275
+ }
276
+ interface IncidentRegister {
277
+ /** Opens an incident (s. 3.5: as soon as there is reason to believe one occurred). */
278
+ open(query: Query, input: IncidentInput, actor: IncidentActor): Promise<Incident>;
279
+ /** Writes the risk assessment (s. 3.6); it can be redone until the incident is closed. */
280
+ assess(query: Query, scope: string, id: string, input: AssessmentInput, actor: IncidentActor): Promise<Incident>;
281
+ /** Records a measure taken to reduce the risk and prevent a new incident (s. 3.5). */
282
+ recordMeasure(query: Query, scope: string, id: string, text: string, actor: IncidentActor): Promise<Incident>;
283
+ /** Records a notice sent. Only an incident assessed as a risk of serious injury is notified. */
284
+ recordNotice(query: Query, scope: string, id: string, target: NoticeTarget, notice: {
285
+ channel: string;
286
+ reference?: string | undefined;
287
+ }, actor: IncidentActor): Promise<Incident>;
288
+ /** Marks the incident as a drill (or not). */
289
+ markDrill(query: Query, scope: string, id: string, drill: boolean, actor: IncidentActor): Promise<Incident>;
290
+ /** Closes it: assessed, and both notices sent when the risk is serious. A closed entry is never edited again. */
291
+ close(query: Query, scope: string, id: string, actor: IncidentActor): Promise<Incident>;
292
+ get(query: Query, scope: string, id: string): Promise<Incident | null>;
293
+ /** The register of the scope. */
294
+ list(query: Query, scope: string): Promise<Incident[]>;
295
+ exportRegister(query: Query, scope: string): Promise<RegisterDocument>;
296
+ }
297
+ declare const INCIDENT_CODE: {
298
+ readonly badInput: "INCIDENT_BAD_INPUT";
299
+ readonly unknown: "INCIDENT_UNKNOWN";
300
+ readonly closed: "INCIDENT_CLOSED";
301
+ readonly notAssessed: "INCIDENT_NOT_ASSESSED";
302
+ readonly noNoticeDue: "INCIDENT_NO_NOTICE_DUE";
303
+ readonly noticesMissing: "INCIDENT_NOTICES_MISSING";
304
+ };
305
+ type IncidentCode = (typeof INCIDENT_CODE)[keyof typeof INCIDENT_CODE];
306
+ declare class IncidentError extends Error {
307
+ readonly code: IncidentCode;
308
+ constructor(code: IncidentCode, message: string);
309
+ }
310
+ /**
311
+ * A guide for the person in charge, never the decision: the injury is serious when the information is sensitive and misuse is not
312
+ * unlikely, when the consequences are severe and misuse is likely, or when everything is at least medium and misuse is likely.
313
+ */
314
+ declare function suggestSeriousInjury(factors: Pick<AssessmentInput, "sensitivity" | "consequences" | "likelihood">): boolean;
315
+ /** Five years after the enterprise became aware of the incident (the Regulation's minimum for keeping the register). */
316
+ declare function retainUntil(awareAt: Date): Date;
317
+ declare const REGISTER_CSV_COLUMNS: readonly ["id", "kind", "aware_at", "occurred_at", "description", "information", "persons_concerned", "serious_injury", "assessed_at", "cai_notice_at", "persons_notice_at", "measures", "status", "drill", "closed_at", "retain_until"];
318
+ /** The register as CSV (RFC 4180), cells that a spreadsheet would read as a formula are quoted with a leading apostrophe. */
319
+ declare function registerToCsv(entries: readonly Incident[]): string;
320
+
321
+ export { type AuditPort as A, type RegisterDocument as B, type ConsentInput as C, type RequestKind as D, type ExportDocument as E, type RequestStatus as F, registerToCsv as G, retainUntil as H, type IncidentStore as I, suggestSeriousInjury as J, LEVEL as L, NOTICE_TARGET as N, type OutboxPort as O, type PrivacyContributor as P, REGISTER_CSV_COLUMNS as R, type Subject as S, type IncidentDeps as a, type IncidentRegister as b, type PrivacyStore as c, type ConsentRecord as d, type PrivacyRequest as e, type AssessmentInput as f, INCIDENT_CODE as g, INCIDENT_KIND as h, INCIDENT_STATUS as i, type Incident as j, type IncidentActor as k, type IncidentAssessment as l, type IncidentCode as m, IncidentError as n, type IncidentInput as o, type IncidentKind as p, type IncidentMeasure as q, type IncidentNotice as r, type IncidentStatus as s, type Level as t, type NoticeTarget as u, PRIVACY_CODE as v, type PrivacyCode as w, PrivacyError as x, REQUEST_KIND as y, REQUEST_STATUS as z };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import * as _krizaka_db from '@krizaka/db';
2
2
  import { Query, Clock } from '@krizaka/db';
3
3
  export { Clock, Query } from '@krizaka/db';
4
- import { P as PrivacyContributor, a as PrivacyStore, C as ConsentInput, b as ConsentRecord, S as Subject, E as ExportDocument, c as PrivacyRequest, A as AuditPort, O as OutboxPort } from './port-Ds9VVyC2.js';
5
- export { d as PRIVACY_CODE, e as PrivacyCode, f as PrivacyError, R as REQUEST_KIND, g as REQUEST_STATUS, h as RequestKind, i as RequestStatus } from './port-Ds9VVyC2.js';
4
+ import { P as PrivacyContributor, I as IncidentStore, a as IncidentDeps, b as IncidentRegister, c as PrivacyStore, C as ConsentInput, d as ConsentRecord, S as Subject, E as ExportDocument, e as PrivacyRequest, A as AuditPort, O as OutboxPort } from './incident-DLXCVzpW.js';
5
+ export { f as AssessmentInput, g as INCIDENT_CODE, h as INCIDENT_KIND, i as INCIDENT_STATUS, j as Incident, k as IncidentActor, l as IncidentAssessment, m as IncidentCode, n as IncidentError, o as IncidentInput, p as IncidentKind, q as IncidentMeasure, r as IncidentNotice, s as IncidentStatus, L as LEVEL, t as Level, N as NOTICE_TARGET, u as NoticeTarget, v as PRIVACY_CODE, w as PrivacyCode, x as PrivacyError, R as REGISTER_CSV_COLUMNS, y as REQUEST_KIND, z as REQUEST_STATUS, B as RegisterDocument, D as RequestKind, F as RequestStatus, G as registerToCsv, H as retainUntil, J as suggestSeriousInjury } from './incident-DLXCVzpW.js';
6
6
 
7
7
  /** The structural slice of `@krizaka/audit` that contributes: what the trail holds about an actor, and detaching them from it. */
8
8
  interface AuditTrail {
@@ -18,6 +18,18 @@ declare function auditContributor(audit: AuditTrail, options?: {
18
18
  kind?: string;
19
19
  }): PrivacyContributor;
20
20
 
21
+ /** An in-memory incident store, for unit tests and demos (the contract kit runs on it and on the database's). */
22
+ declare function memoryIncidentStore(): IncidentStore;
23
+
24
+ /** The PostgreSQL incident store, over the `Query` it is given (the caller's transaction). `schema`: default `privacy`. */
25
+ declare function dbIncidentStore(query: Query, schema?: string): IncidentStore;
26
+
27
+ /**
28
+ * The confidentiality incident register of a product (Loi 25, ss. 3.5 to 3.8). Every call is by scope (the tenant), and a closed
29
+ * entry is never edited again; the database refuses to delete an entry before its retention ends.
30
+ */
31
+ declare function createIncidentRegister(deps: IncidentDeps): IncidentRegister;
32
+
21
33
  /** An in-memory store, for unit tests and demos (the same behaviour as the database's: the contract kit runs on both). */
22
34
  declare function memoryPrivacyStore(): PrivacyStore;
23
35
 
@@ -102,4 +114,4 @@ declare function checkPurpose(purpose: string): void;
102
114
  */
103
115
  declare const privacySchema: _krizaka_db.ModuleSchema;
104
116
 
105
- export { AuditPort, type AuditTrail, ConsentInput, ConsentRecord, ExportDocument, OutboxPort, type Privacy, PrivacyContributor, type PrivacyDeps, PrivacyRequest, PrivacyStore, Subject, type Transaction, auditContributor, checkPurpose, checkSubject, createPrivacy, dbPrivacyStore, memoryPrivacyStore, privacySchema };
117
+ export { AuditPort, type AuditTrail, ConsentInput, ConsentRecord, ExportDocument, IncidentDeps, IncidentRegister, IncidentStore, OutboxPort, type Privacy, PrivacyContributor, type PrivacyDeps, PrivacyRequest, PrivacyStore, Subject, type Transaction, auditContributor, checkPurpose, checkSubject, createIncidentRegister, createPrivacy, dbIncidentStore, dbPrivacyStore, memoryIncidentStore, memoryPrivacyStore, privacySchema };
package/dist/index.js CHANGED
@@ -21,6 +21,245 @@ function auditContributor(audit, options = {}) {
21
21
  };
22
22
  }
23
23
 
24
+ // src/incident.ts
25
+ var INCIDENT_KIND = { access: "access", use: "use", communication: "communication", loss: "loss" };
26
+ var INCIDENT_STATUS = { open: "open", assessed: "assessed", closed: "closed" };
27
+ var LEVEL = { low: "low", medium: "medium", high: "high" };
28
+ var NOTICE_TARGET = { cai: "cai", persons: "persons" };
29
+ var INCIDENT_CODE = {
30
+ badInput: "INCIDENT_BAD_INPUT",
31
+ unknown: "INCIDENT_UNKNOWN",
32
+ closed: "INCIDENT_CLOSED",
33
+ notAssessed: "INCIDENT_NOT_ASSESSED",
34
+ noNoticeDue: "INCIDENT_NO_NOTICE_DUE",
35
+ noticesMissing: "INCIDENT_NOTICES_MISSING"
36
+ };
37
+ var IncidentError = class extends Error {
38
+ constructor(code, message) {
39
+ super(message);
40
+ this.code = code;
41
+ this.name = "IncidentError";
42
+ }
43
+ code;
44
+ };
45
+ var RANK = { low: 0, medium: 1, high: 2 };
46
+ function suggestSeriousInjury(factors) {
47
+ const { sensitivity, consequences, likelihood } = { sensitivity: RANK[factors.sensitivity], consequences: RANK[factors.consequences], likelihood: RANK[factors.likelihood] };
48
+ if (sensitivity === RANK.high && likelihood >= RANK.medium) return true;
49
+ if (consequences === RANK.high && likelihood === RANK.high) return true;
50
+ return sensitivity >= RANK.medium && consequences >= RANK.medium && likelihood === RANK.high;
51
+ }
52
+ function retainUntil(awareAt) {
53
+ const until = new Date(awareAt);
54
+ until.setUTCFullYear(until.getUTCFullYear() + 5);
55
+ return until;
56
+ }
57
+ var FORMULA = /^[=+\-@\t\r]/;
58
+ var cell = (value) => {
59
+ const text = value === null || value === void 0 ? "" : value instanceof Date ? value.toISOString() : String(value);
60
+ const safe = FORMULA.test(text) ? `'${text}` : text;
61
+ return /[",\n\r]/.test(safe) ? `"${safe.replaceAll('"', '""')}"` : safe;
62
+ };
63
+ var REGISTER_CSV_COLUMNS = ["id", "kind", "aware_at", "occurred_at", "description", "information", "persons_concerned", "serious_injury", "assessed_at", "cai_notice_at", "persons_notice_at", "measures", "status", "drill", "closed_at", "retain_until"];
64
+ function registerToCsv(entries) {
65
+ const rows = entries.map(
66
+ (e) => [e.id, e.kind, e.awareAt, e.occurredAt, e.description, e.information.join("; "), e.personsConcerned, e.assessment?.seriousInjury ?? "", e.assessment?.assessedAt ?? "", e.caiNotice?.sentAt ?? "", e.personsNotice?.sentAt ?? "", e.measures.map((m) => m.text).join("; "), e.status, e.drill, e.closedAt, e.retainUntil].map(cell).join(",")
67
+ );
68
+ return [REGISTER_CSV_COLUMNS.join(","), ...rows].join("\r\n") + "\r\n";
69
+ }
70
+
71
+ // src/incident-memory.ts
72
+ function memoryIncidentStore() {
73
+ const rows = /* @__PURE__ */ new Map();
74
+ const key = (scope, id) => `${scope}\0${id}`;
75
+ return {
76
+ async insert(incident) {
77
+ rows.set(key(incident.scope, incident.id), structuredClone(incident));
78
+ },
79
+ async save(incident) {
80
+ const k = key(incident.scope, incident.id);
81
+ const current = rows.get(k);
82
+ if (!current) return;
83
+ if (current.status === INCIDENT_STATUS.closed) throw new Error("a closed incident is never edited");
84
+ rows.set(k, structuredClone(incident));
85
+ },
86
+ async get(scope, id) {
87
+ const found = rows.get(key(scope, id));
88
+ return found ? structuredClone(found) : null;
89
+ },
90
+ async list(scope) {
91
+ return [...rows.values()].filter((i) => i.scope === scope).sort((a, b) => a.awareAt.valueOf() - b.awareAt.valueOf() || a.id.localeCompare(b.id)).map((i) => structuredClone(i));
92
+ }
93
+ };
94
+ }
95
+
96
+ // src/incident-persistence.ts
97
+ import { ident } from "@krizaka/db";
98
+ var COLUMNS = "id, scope, kind, aware_at, occurred_at, description, information, persons_concerned, measures, status, assessment, cai_notice, persons_notice, drill, opened_by, opened_at, closed_at, retain_until";
99
+ var optional = (stamp) => stamp === null ? null : new Date(stamp);
100
+ var toNotice = (n) => n ? { sentAt: new Date(n.sentAt), channel: n.channel, reference: n.reference } : null;
101
+ var toAssessment = (a) => a ? { ...a, assessedAt: new Date(a.assessedAt) } : null;
102
+ var toIncident = (r) => ({
103
+ id: r.id,
104
+ scope: r.scope,
105
+ kind: r.kind,
106
+ awareAt: new Date(r.aware_at),
107
+ occurredAt: optional(r.occurred_at),
108
+ description: r.description,
109
+ information: r.information,
110
+ personsConcerned: r.persons_concerned,
111
+ measures: r.measures.map((m) => ({ at: new Date(m.at), text: m.text })),
112
+ status: r.status,
113
+ assessment: toAssessment(r.assessment),
114
+ caiNotice: toNotice(r.cai_notice),
115
+ personsNotice: toNotice(r.persons_notice),
116
+ drill: r.drill,
117
+ openedBy: r.opened_by,
118
+ openedAt: new Date(r.opened_at),
119
+ closedAt: optional(r.closed_at),
120
+ retainUntil: new Date(r.retain_until)
121
+ });
122
+ var json = (value) => value === null ? null : JSON.stringify(value);
123
+ function dbIncidentStore(query, schema = "privacy") {
124
+ const table = `${ident(schema)}.incident`;
125
+ const values = (i) => [i.id, i.scope, i.kind, i.awareAt, i.occurredAt, i.description, i.information, i.personsConcerned, JSON.stringify(i.measures), i.status, json(i.assessment), json(i.caiNotice), json(i.personsNotice), i.drill, i.openedBy, i.openedAt, i.closedAt, i.retainUntil];
126
+ return {
127
+ async insert(i) {
128
+ await query(`INSERT INTO ${table} (${COLUMNS}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11::jsonb, $12::jsonb, $13::jsonb, $14, $15, $16, $17, $18)`, values(i));
129
+ },
130
+ async save(i) {
131
+ await query(
132
+ `UPDATE ${table} SET kind = $3, aware_at = $4, occurred_at = $5, description = $6, information = $7, persons_concerned = $8, measures = $9::jsonb, status = $10, assessment = $11::jsonb, cai_notice = $12::jsonb, persons_notice = $13::jsonb, drill = $14, opened_by = $15, opened_at = $16, closed_at = $17, retain_until = $18 WHERE scope = $2 AND id = $1`,
133
+ values(i)
134
+ );
135
+ },
136
+ async get(scope, id, options) {
137
+ const [row] = await query(`SELECT ${COLUMNS} FROM ${table} WHERE scope = $1 AND id = $2${options?.lock ? " FOR UPDATE" : ""}`, [scope, id]);
138
+ return row ? toIncident(row) : null;
139
+ },
140
+ async list(scope) {
141
+ return (await query(`SELECT ${COLUMNS} FROM ${table} WHERE scope = $1 ORDER BY aware_at, id`, [scope])).map(toIncident);
142
+ }
143
+ };
144
+ }
145
+
146
+ // src/incidents.ts
147
+ import { randomUUID } from "crypto";
148
+ import { ident as ident2 } from "@krizaka/db";
149
+ var bad = (message) => new IncidentError(INCIDENT_CODE.badInput, message);
150
+ var within = (value, max, what) => {
151
+ if (value.trim().length < 1 || value.length > max) throw bad(`${what}: 1 to ${max} characters`);
152
+ };
153
+ var KINDS = Object.values(INCIDENT_KIND);
154
+ var LEVELS = Object.values(LEVEL);
155
+ function checkScope(scope) {
156
+ within(scope, 100, "scope");
157
+ }
158
+ function createIncidentRegister(deps) {
159
+ const schema = ident2(deps.schema ?? "privacy");
160
+ const storeFor = deps.storeFor ?? ((query) => dbIncidentStore(query, schema));
161
+ async function trace(query, actor, action, incident) {
162
+ await deps.audit?.record(query, { actorId: actor.id, actorLabel: actor.label, action: `privacy.incident_${action}`, target: { type: "incident", id: incident.id }, detail: { scope: incident.scope, drill: incident.drill } });
163
+ }
164
+ async function update(query, scope, id, action, actor, change) {
165
+ checkScope(scope);
166
+ const store = storeFor(query);
167
+ const incident = await store.get(scope, id, { lock: true });
168
+ if (!incident) throw new IncidentError(INCIDENT_CODE.unknown, "no such incident in this register");
169
+ if (incident.status === INCIDENT_STATUS.closed) throw new IncidentError(INCIDENT_CODE.closed, "a closed entry of the register is never edited");
170
+ change(incident);
171
+ await store.save(incident);
172
+ await trace(query, actor, action, incident);
173
+ return incident;
174
+ }
175
+ return {
176
+ async open(query, input, actor) {
177
+ checkScope(input.scope);
178
+ if (!KINDS.includes(input.kind)) throw bad(`kind \xAB ${input.kind} \xBB is not one of ${KINDS.join(", ")}`);
179
+ within(input.description, 2e3, "description");
180
+ if (input.information.length < 1 || input.information.length > 30) throw bad("information: 1 to 30 categories");
181
+ for (const category of input.information) within(category, 80, "information category");
182
+ if (input.personsConcerned !== void 0 && (!Number.isInteger(input.personsConcerned) || input.personsConcerned < 0)) throw bad("personsConcerned: a whole number, 0 or more");
183
+ const now = deps.clock.now();
184
+ const awareAt = input.awareAt ?? now;
185
+ if (awareAt.valueOf() > now.valueOf()) throw bad("awareAt cannot be in the future");
186
+ if (input.occurredAt && input.occurredAt.valueOf() > now.valueOf()) throw bad("occurredAt cannot be in the future");
187
+ const incident = {
188
+ id: randomUUID(),
189
+ scope: input.scope,
190
+ kind: input.kind,
191
+ awareAt,
192
+ occurredAt: input.occurredAt ?? null,
193
+ description: input.description,
194
+ information: [...input.information],
195
+ personsConcerned: input.personsConcerned ?? null,
196
+ measures: [],
197
+ status: INCIDENT_STATUS.open,
198
+ assessment: null,
199
+ caiNotice: null,
200
+ personsNotice: null,
201
+ drill: input.drill ?? false,
202
+ openedBy: actor.label,
203
+ openedAt: now,
204
+ closedAt: null,
205
+ retainUntil: retainUntil(awareAt)
206
+ };
207
+ await storeFor(query).insert(incident);
208
+ await trace(query, actor, "opened", incident);
209
+ return incident;
210
+ },
211
+ assess(query, scope, id, input, actor) {
212
+ for (const level of [input.sensitivity, input.consequences, input.likelihood]) if (!LEVELS.includes(level)) throw bad(`level \xAB ${level} \xBB is not one of ${LEVELS.join(", ")}`);
213
+ within(input.rationale, 2e3, "rationale");
214
+ return update(query, scope, id, "assessed", actor, (incident) => {
215
+ incident.assessment = { ...input, assessedAt: deps.clock.now(), assessedBy: actor.label };
216
+ incident.status = INCIDENT_STATUS.assessed;
217
+ });
218
+ },
219
+ recordMeasure(query, scope, id, text, actor) {
220
+ within(text, 1e3, "measure");
221
+ return update(query, scope, id, "measure_recorded", actor, (incident) => {
222
+ incident.measures.push({ at: deps.clock.now(), text });
223
+ });
224
+ },
225
+ recordNotice(query, scope, id, target, notice, actor) {
226
+ within(notice.channel, 40, "channel");
227
+ return update(query, scope, id, `notice_${target}`, actor, (incident) => {
228
+ if (!incident.assessment) throw new IncidentError(INCIDENT_CODE.notAssessed, "assess the risk before notifying");
229
+ if (!incident.assessment.seriousInjury) throw new IncidentError(INCIDENT_CODE.noNoticeDue, "no notice is due: the assessment found no risk of serious injury");
230
+ const sent = { sentAt: deps.clock.now(), channel: notice.channel, reference: notice.reference ?? null };
231
+ if (target === NOTICE_TARGET.cai) incident.caiNotice = sent;
232
+ else incident.personsNotice = sent;
233
+ });
234
+ },
235
+ markDrill(query, scope, id, drill, actor) {
236
+ return update(query, scope, id, "drill_marked", actor, (incident) => {
237
+ incident.drill = drill;
238
+ });
239
+ },
240
+ close(query, scope, id, actor) {
241
+ return update(query, scope, id, "closed", actor, (incident) => {
242
+ if (!incident.assessment) throw new IncidentError(INCIDENT_CODE.notAssessed, "assess the risk before closing");
243
+ if (incident.assessment.seriousInjury && (!incident.caiNotice || !incident.personsNotice)) throw new IncidentError(INCIDENT_CODE.noticesMissing, "a risk of serious injury is closed once the Commission and the people concerned are notified");
244
+ incident.status = INCIDENT_STATUS.closed;
245
+ incident.closedAt = deps.clock.now();
246
+ });
247
+ },
248
+ async get(query, scope, id) {
249
+ checkScope(scope);
250
+ return storeFor(query).get(scope, id);
251
+ },
252
+ async list(query, scope) {
253
+ checkScope(scope);
254
+ return storeFor(query).list(scope);
255
+ },
256
+ async exportRegister(query, scope) {
257
+ checkScope(scope);
258
+ return { format: 1, scope, generatedAt: deps.clock.now().toISOString(), entries: await storeFor(query).list(scope) };
259
+ }
260
+ };
261
+ }
262
+
24
263
  // src/memory.ts
25
264
  var sameSubject = (a, b) => a.kind === b.kind && a.id === b.id;
26
265
  function memoryPrivacyStore() {
@@ -55,14 +294,14 @@ function memoryPrivacyStore() {
55
294
  }
56
295
 
57
296
  // src/persistence.ts
58
- import { ident } from "@krizaka/db";
297
+ import { ident as ident3 } from "@krizaka/db";
59
298
  var toConsent = (r) => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, purpose: r.purpose, version: r.version, granted: r.granted, means: r.means, at: new Date(r.at) });
60
299
  var toRequest = (r) => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, kind: r.kind, status: r.status, requestedAt: new Date(r.requested_at), completedAt: r.completed_at === null ? null : new Date(r.completed_at), failure: r.failure });
61
300
  var CONSENT_COLUMNS = "id, subject_kind, subject_id, purpose, version, granted, means, at";
62
301
  var REQUEST_COLUMNS = "id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure";
63
302
  function dbPrivacyStore(query, schema = "privacy") {
64
- const consent = `${ident(schema)}.consent`;
65
- const request = `${ident(schema)}.request`;
303
+ const consent = `${ident3(schema)}.consent`;
304
+ const request = `${ident3(schema)}.request`;
66
305
  const same = (subject) => [subject.kind, subject.id];
67
306
  return {
68
307
  async insertConsent(c) {
@@ -92,13 +331,13 @@ function dbPrivacyStore(query, schema = "privacy") {
92
331
  }
93
332
 
94
333
  // src/privacy.ts
95
- import { randomUUID } from "crypto";
96
- import { ident as ident2 } from "@krizaka/db";
334
+ import { randomUUID as randomUUID2 } from "crypto";
335
+ import { ident as ident4 } from "@krizaka/db";
97
336
  import { subHours } from "@krizaka/time";
98
337
  var FAILURE_CODE = "CONTRIBUTOR_FAILED";
99
338
  var ERASURE_VERSION = "erasure";
100
339
  function createPrivacy(deps) {
101
- const schema = ident2(deps.schema ?? "privacy");
340
+ const schema = ident4(deps.schema ?? "privacy");
102
341
  const storeFor = deps.storeFor ?? ((query) => dbPrivacyStore(query, schema));
103
342
  for (const purpose of deps.purposes) checkPurpose(purpose);
104
343
  const names = deps.contributors.map((c) => c.name);
@@ -115,13 +354,13 @@ function createPrivacy(deps) {
115
354
  }
116
355
  return { format: 1, subject, generatedAt: deps.clock.now().toISOString(), modules };
117
356
  }
118
- const newRequest = (subject, kind) => ({ id: randomUUID(), subject, kind, status: REQUEST_STATUS.requested, requestedAt: deps.clock.now(), completedAt: null, failure: null });
357
+ const newRequest = (subject, kind) => ({ id: randomUUID2(), subject, kind, status: REQUEST_STATUS.requested, requestedAt: deps.clock.now(), completedAt: null, failure: null });
119
358
  async function recordConsent(query, input) {
120
359
  checkSubject(input.subject);
121
360
  checkPurpose(input.purpose);
122
361
  if (!known.has(input.purpose)) throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose \xAB ${input.purpose} \xBB is not one the product declared`);
123
362
  if (input.version.length < 1 || input.version.length > 100) throw new PrivacyError(PRIVACY_CODE.badConsent, "the notice version is 1 to 100 characters");
124
- const record = { id: randomUUID(), subject: input.subject, purpose: input.purpose, version: input.version, granted: input.granted, means: input.means ?? null, at: deps.clock.now() };
363
+ const record = { id: randomUUID2(), subject: input.subject, purpose: input.purpose, version: input.version, granted: input.granted, means: input.means ?? null, at: deps.clock.now() };
125
364
  await storeFor(query).insertConsent(record);
126
365
  return record;
127
366
  }
@@ -261,20 +500,77 @@ CREATE TABLE ${c.schema}.request (
261
500
  failure text CHECK (failure IS NULL OR char_length(failure) <= 100)
262
501
  );
263
502
  CREATE INDEX request_subject ON ${c.schema}.request (subject_kind, subject_id, requested_at DESC);`
503
+ },
504
+ {
505
+ version: 2,
506
+ name: "confidentiality incident register",
507
+ sql: (c) => `
508
+ CREATE TABLE ${c.schema}.incident (
509
+ id uuid PRIMARY KEY,
510
+ scope text NOT NULL CHECK (char_length(scope) BETWEEN 1 AND 100),
511
+ kind text NOT NULL CHECK (kind IN ('access', 'use', 'communication', 'loss')),
512
+ aware_at timestamptz NOT NULL,
513
+ occurred_at timestamptz,
514
+ description text NOT NULL CHECK (char_length(description) BETWEEN 1 AND 2000),
515
+ information text[] NOT NULL CHECK (cardinality(information) BETWEEN 1 AND 30),
516
+ persons_concerned integer CHECK (persons_concerned IS NULL OR persons_concerned >= 0),
517
+ measures jsonb NOT NULL DEFAULT '[]',
518
+ status text NOT NULL CHECK (status IN ('open', 'assessed', 'closed')),
519
+ assessment jsonb,
520
+ cai_notice jsonb,
521
+ persons_notice jsonb,
522
+ drill boolean NOT NULL DEFAULT false,
523
+ opened_by text NOT NULL,
524
+ opened_at timestamptz NOT NULL,
525
+ closed_at timestamptz,
526
+ retain_until timestamptz NOT NULL
527
+ );
528
+ CREATE INDEX incident_scope ON ${c.schema}.incident (scope, aware_at, id);
529
+ CREATE FUNCTION ${c.schema}.incident_guard() RETURNS trigger LANGUAGE plpgsql AS $fn$
530
+ BEGIN
531
+ IF TG_OP = 'DELETE' THEN
532
+ IF OLD.retain_until > now() THEN
533
+ RAISE EXCEPTION 'an incident stays in the register until its retention ends' USING ERRCODE = 'restrict_violation';
534
+ END IF;
535
+ RETURN OLD;
536
+ END IF;
537
+ IF OLD.status = 'closed' THEN
538
+ RAISE EXCEPTION 'a closed entry of the register is never edited' USING ERRCODE = 'restrict_violation';
539
+ END IF;
540
+ IF NEW.id <> OLD.id OR NEW.scope <> OLD.scope THEN
541
+ RAISE EXCEPTION 'an incident never changes register' USING ERRCODE = 'restrict_violation';
542
+ END IF;
543
+ RETURN NEW;
544
+ END;
545
+ $fn$;
546
+ CREATE TRIGGER incident_guard BEFORE UPDATE OR DELETE ON ${c.schema}.incident FOR EACH ROW EXECUTE FUNCTION ${c.schema}.incident_guard();`
264
547
  }
265
548
  ]
266
549
  });
267
550
  export {
551
+ INCIDENT_CODE,
552
+ INCIDENT_KIND,
553
+ INCIDENT_STATUS,
554
+ IncidentError,
555
+ LEVEL,
556
+ NOTICE_TARGET,
268
557
  PRIVACY_CODE,
269
558
  PrivacyError,
559
+ REGISTER_CSV_COLUMNS,
270
560
  REQUEST_KIND,
271
561
  REQUEST_STATUS,
272
562
  auditContributor,
273
563
  checkPurpose,
274
564
  checkSubject,
565
+ createIncidentRegister,
275
566
  createPrivacy,
567
+ dbIncidentStore,
276
568
  dbPrivacyStore,
569
+ memoryIncidentStore,
277
570
  memoryPrivacyStore,
278
- privacySchema
571
+ privacySchema,
572
+ registerToCsv,
573
+ retainUntil,
574
+ suggestSeriousInjury
279
575
  };
280
576
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contributors.ts","../src/memory.ts","../src/persistence.ts","../src/privacy.ts","../src/schema.ts"],"sourcesContent":["import type { Query } from \"@krizaka/db\";\n\nimport type { PrivacyContributor } from \"./port\";\n\n/** The structural slice of `@krizaka/audit` that contributes: what the trail holds about an actor, and detaching them from it. */\nexport interface AuditTrail {\n exportFor(query: Query, actorId: string): Promise<unknown>;\n redactActor(query: Query, actorId: string): Promise<number>;\n}\n\n/**\n * `@krizaka/audit` as a contributor: an export lists the actor's entries; an erasure detaches the person (id and address removed, the\n * label « erased ») and keeps the facts. It applies to a subject of the kind the product's actors are (default `account`).\n * @param audit the product's audit (`createAudit(...)`)\n */\nexport function auditContributor(audit: AuditTrail, options: { kind?: string } = {}): PrivacyContributor {\n const kind = options.kind ?? \"account\";\n return {\n name: \"audit\",\n async exportFor(query, subject) {\n return subject.kind === kind ? audit.exportFor(query, subject.id) : [];\n },\n async eraseFor(tx, subject) {\n if (subject.kind === kind) await audit.redactActor(tx, subject.id);\n },\n };\n}\n","import type { ConsentRecord, PrivacyRequest, PrivacyStore, Subject } from \"./port\";\n\nconst sameSubject = (a: Subject, b: Subject) => a.kind === b.kind && a.id === b.id;\n\n/** An in-memory store, for unit tests and demos (the same behaviour as the database's: the contract kit runs on both). */\nexport function memoryPrivacyStore(): PrivacyStore {\n const consents: ConsentRecord[] = [];\n const requests = new Map<string, PrivacyRequest>();\n return {\n async insertConsent(c) {\n consents.push(structuredClone(c));\n },\n async latestConsent(subject, purpose) {\n const found = consents.filter((c) => sameSubject(c.subject, subject) && c.purpose === purpose).at(-1);\n return found ? structuredClone(found) : null;\n },\n async consentHistory(subject) {\n return consents.filter((c) => sameSubject(c.subject, subject)).map((c) => structuredClone(c));\n },\n async insertRequest(r) {\n requests.set(r.id, structuredClone(r));\n },\n async getRequest(id) {\n const found = requests.get(id);\n return found ? structuredClone(found) : null;\n },\n async finishRequest(id, outcome) {\n const found = requests.get(id);\n if (found) Object.assign(found, { status: outcome.status, completedAt: outcome.at, failure: outcome.failure ?? null });\n },\n async requestsOf(subject) {\n return [...requests.values()].filter((r) => sameSubject(r.subject, subject)).sort((a, b) => b.requestedAt.valueOf() - a.requestedAt.valueOf()).map((r) => structuredClone(r));\n },\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { ConsentRecord, PrivacyRequest, PrivacyStore, RequestKind, RequestStatus, Subject } from \"./port\";\n\ninterface ConsentRow {\n id: string;\n subject_kind: string;\n subject_id: string;\n purpose: string;\n version: string;\n granted: boolean;\n means: string | null;\n at: Date | string;\n}\ninterface RequestRow {\n id: string;\n subject_kind: string;\n subject_id: string;\n kind: RequestKind;\n status: RequestStatus;\n requested_at: Date | string;\n completed_at: Date | string | null;\n failure: string | null;\n}\n\nconst toConsent = (r: ConsentRow): ConsentRecord => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, purpose: r.purpose, version: r.version, granted: r.granted, means: r.means, at: new Date(r.at) });\nconst toRequest = (r: RequestRow): PrivacyRequest => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, kind: r.kind, status: r.status, requestedAt: new Date(r.requested_at), completedAt: r.completed_at === null ? null : new Date(r.completed_at), failure: r.failure });\n\nconst CONSENT_COLUMNS = \"id, subject_kind, subject_id, purpose, version, granted, means, at\";\nconst REQUEST_COLUMNS = \"id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure\";\n\n/**\n * The PostgreSQL store of « privacy », over the `Query` it is given (the caller's transaction, to join its unit of work).\n * @param schema the Postgres schema of the module, default `privacy`\n */\nexport function dbPrivacyStore(query: Query, schema = \"privacy\"): PrivacyStore {\n const consent = `${ident(schema)}.consent`;\n const request = `${ident(schema)}.request`;\n const same = (subject: Subject) => [subject.kind, subject.id];\n return {\n async insertConsent(c) {\n await query(`INSERT INTO ${consent} (id, subject_kind, subject_id, purpose, version, granted, means, at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [c.id, c.subject.kind, c.subject.id, c.purpose, c.version, c.granted, c.means, c.at]);\n },\n async latestConsent(subject, purpose) {\n const [row] = await query<ConsentRow>(`SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 AND purpose = $3 ORDER BY seq DESC LIMIT 1`, [...same(subject), purpose]);\n return row ? toConsent(row) : null;\n },\n async consentHistory(subject) {\n return (await query<ConsentRow>(`SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY seq`, same(subject))).map(toConsent);\n },\n async insertRequest(r) {\n await query(`INSERT INTO ${request} (id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [r.id, r.subject.kind, r.subject.id, r.kind, r.status, r.requestedAt, r.completedAt, r.failure]);\n },\n async getRequest(id) {\n const [row] = await query<RequestRow>(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE id = $1`, [id]);\n return row ? toRequest(row) : null;\n },\n async finishRequest(id, outcome) {\n await query(`UPDATE ${request} SET status = $2, completed_at = $3, failure = $4 WHERE id = $1`, [id, outcome.status, outcome.at, outcome.failure ?? null]);\n },\n async requestsOf(subject) {\n return (await query<RequestRow>(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY requested_at DESC, id`, same(subject))).map(toRequest);\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { ident } from \"@krizaka/db\";\nimport { subHours } from \"@krizaka/time\";\n\nimport { dbPrivacyStore } from \"./persistence\";\nimport {\n type AuditPort,\n type Clock,\n type ConsentInput,\n type ConsentRecord,\n type ExportDocument,\n type OutboxPort,\n PRIVACY_CODE,\n type PrivacyContributor,\n PrivacyError,\n type PrivacyRequest,\n type PrivacyStore,\n type Query,\n REQUEST_KIND,\n REQUEST_STATUS,\n type Subject,\n} from \"./port\";\nimport { checkPurpose, checkSubject } from \"./rules\";\n\n/** The product's unit of work: runs `work` on one connection, commits when it resolves, rolls back when it throws (`transaction` of `@krizaka/db`). */\nexport type Transaction = <T>(work: (tx: Query) => Promise<T>) => Promise<T>;\n\nexport interface PrivacyDeps {\n clock: Clock;\n /** Every module that holds personal data, and the product's own. Their names are the keys of the export. */\n contributors: readonly PrivacyContributor[];\n /** The purposes the product declares (`screening`, `marketing`). A consent for another is refused. */\n purposes: readonly string[];\n /** The product's transaction, for the erasure. */\n transaction: Transaction;\n /** How many days a purpose is kept: the settings `privacy.retention.<purpose>Days` (`retentionFromSettings`). `undefined` = no retention for it. */\n retentionDays?: (purpose: string) => number | undefined | Promise<number | undefined>;\n /** The audit trail: an erasure is recorded there without personal data. */\n audit?: AuditPort;\n /** The outbox: required for the asynchronous export of a large account (`requestExport`). */\n outbox?: OutboxPort;\n /** The store over a query. Default: the PostgreSQL store on schema `privacy`. */\n storeFor?: (query: Query) => PrivacyStore;\n /** The Postgres schema, when the product renamed the module's (used by the default store). */\n schema?: string;\n}\n\nexport interface Privacy {\n /** Writes a consent or a withdrawal. Never edits one. */\n recordConsent(query: Query, input: ConsentInput): Promise<ConsentRecord>;\n /** Whether the consent with the last word for this purpose is a yes. A person who never said anything has not consented. */\n hasConsent(query: Query, subject: Subject, purpose: string): Promise<boolean>;\n /** Every consent and withdrawal of the subject, oldest first. */\n consentHistory(query: Query, subject: Subject): Promise<ConsentRecord[]>;\n /** The export, at once: one document with a part per contributor. The request is recorded. */\n exportSubject(query: Query, subject: Subject): Promise<ExportDocument>;\n /**\n * The export of a large account, asynchronously: records the request and appends a message to the outbox IN THE CALLER'S\n * TRANSACTION (`tx`). A worker then calls `fulfilExport(requestId, deliver)`. The message holds the request id only.\n */\n requestExport(tx: Query, subject: Subject): Promise<{ requestId: string }>;\n /** Assembles the export of a recorded request and hands it to `deliver` (store the file, mail a link); the request is completed after `deliver` returns. */\n fulfilExport(query: Query, requestId: string, deliver: (document: ExportDocument, request: PrivacyRequest) => Promise<void>): Promise<void>;\n /**\n * Erases the subject from every contributor in ONE transaction, withdraws their live consents, and records the request and an\n * audit entry that names no one. If a contributor fails nothing is erased, the request is recorded as failed, and the error is thrown.\n */\n eraseSubject(subject: Subject, options?: { noticeVersion?: string }): Promise<PrivacyRequest>;\n /** Removes, for each purpose with a retention, what the contributors hold past it. Returns how many rows each purpose removed. */\n purge(query: Query): Promise<Record<string, number>>;\n /** The subject's requests, newest first. */\n requests(query: Query, subject: Subject): Promise<PrivacyRequest[]>;\n}\n\nconst FAILURE_CODE = \"CONTRIBUTOR_FAILED\";\nconst ERASURE_VERSION = \"erasure\";\n\n/**\n * Privacy for a product (Loi 25).\n * @param deps the contributors, the purposes, the product's transaction and the clock\n * @throws PrivacyError for a purpose or a contributor name that is not well formed or appears twice\n */\nexport function createPrivacy(deps: PrivacyDeps): Privacy {\n const schema = ident(deps.schema ?? \"privacy\");\n const storeFor = deps.storeFor ?? ((query: Query) => dbPrivacyStore(query, schema));\n for (const purpose of deps.purposes) checkPurpose(purpose);\n const names = deps.contributors.map((c) => c.name);\n if (new Set(names).size !== names.length) throw new PrivacyError(PRIVACY_CODE.contributorFailed, `two contributors have the same name: ${names.join(\", \")}`);\n const known = new Set(deps.purposes);\n\n async function assemble(query: Query, subject: Subject): Promise<ExportDocument> {\n const modules: Record<string, unknown> = {};\n for (const contributor of deps.contributors) {\n try {\n modules[contributor.name] = await contributor.exportFor(query, subject);\n } catch (cause) {\n throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the export of « ${contributor.name} » failed`, { cause });\n }\n }\n return { format: 1, subject, generatedAt: deps.clock.now().toISOString(), modules };\n }\n\n const newRequest = (subject: Subject, kind: PrivacyRequest[\"kind\"]): PrivacyRequest => ({ id: randomUUID(), subject, kind, status: REQUEST_STATUS.requested, requestedAt: deps.clock.now(), completedAt: null, failure: null });\n\n async function recordConsent(query: Query, input: ConsentInput): Promise<ConsentRecord> {\n checkSubject(input.subject);\n checkPurpose(input.purpose);\n if (!known.has(input.purpose)) throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose « ${input.purpose} » is not one the product declared`);\n if (input.version.length < 1 || input.version.length > 100) throw new PrivacyError(PRIVACY_CODE.badConsent, \"the notice version is 1 to 100 characters\");\n const record: ConsentRecord = { id: randomUUID(), subject: input.subject, purpose: input.purpose, version: input.version, granted: input.granted, means: input.means ?? null, at: deps.clock.now() };\n await storeFor(query).insertConsent(record);\n return record;\n }\n\n return {\n recordConsent,\n async hasConsent(query, subject, purpose) {\n checkSubject(subject);\n checkPurpose(purpose);\n return (await storeFor(query).latestConsent(subject, purpose))?.granted === true;\n },\n async consentHistory(query, subject) {\n checkSubject(subject);\n return storeFor(query).consentHistory(subject);\n },\n async exportSubject(query, subject) {\n checkSubject(subject);\n const store = storeFor(query);\n const request = newRequest(subject, REQUEST_KIND.export);\n await store.insertRequest(request);\n try {\n const document = await assemble(query, subject);\n await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: deps.clock.now() });\n return document;\n } catch (error) {\n await store.finishRequest(request.id, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });\n throw error;\n }\n },\n async requestExport(tx, subject) {\n checkSubject(subject);\n if (!deps.outbox) throw new PrivacyError(PRIVACY_CODE.noOutbox, \"an asynchronous export needs the outbox\");\n const request = newRequest(subject, REQUEST_KIND.export);\n await storeFor(tx).insertRequest(request);\n await deps.outbox.append(tx, { topic: \"privacy\", type: \"evt.privacy.export_requested.v1\", payload: { requestId: request.id }, id: request.id });\n return { requestId: request.id };\n },\n async fulfilExport(query, requestId, deliver) {\n const store = storeFor(query);\n const request = await store.getRequest(requestId);\n if (!request) throw new PrivacyError(PRIVACY_CODE.unknownRequest, `no request ${requestId}`);\n if (request.kind !== REQUEST_KIND.export) throw new PrivacyError(PRIVACY_CODE.notAnExport, `request ${requestId} is not an export`);\n if (request.status === REQUEST_STATUS.completed) throw new PrivacyError(PRIVACY_CODE.alreadyDone, `request ${requestId} is already completed`);\n try {\n await deliver(await assemble(query, request.subject), request);\n } catch (error) {\n await store.finishRequest(requestId, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });\n throw error;\n }\n await store.finishRequest(requestId, { status: REQUEST_STATUS.completed, at: deps.clock.now() });\n },\n async eraseSubject(subject, options = {}) {\n checkSubject(subject);\n const request = newRequest(subject, REQUEST_KIND.erasure);\n try {\n return await deps.transaction(async (tx) => {\n const store = storeFor(tx);\n await store.insertRequest(request);\n for (const contributor of deps.contributors) {\n try {\n await contributor.eraseFor(tx, subject);\n } catch (cause) {\n throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the erasure of « ${contributor.name} » failed`, { cause });\n }\n }\n for (const purpose of deps.purposes) {\n if ((await store.latestConsent(subject, purpose))?.granted) await recordConsent(tx, { subject, purpose, version: options.noticeVersion ?? ERASURE_VERSION, granted: false, means: ERASURE_VERSION });\n }\n const completedAt = deps.clock.now();\n await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: completedAt });\n // the entry names the request and the modules, never the person\n await deps.audit?.record(tx, { actorId: null, actorLabel: \"privacy\", action: \"privacy.erasure_completed\", target: { type: \"privacy_request\", id: request.id }, detail: { contributors: names } });\n return { ...request, status: REQUEST_STATUS.completed, completedAt };\n });\n } catch (error) {\n // the transaction rolled back, request row included: record the failure beside it, and never mask the original error\n try {\n await deps.transaction((tx) => storeFor(tx).insertRequest({ ...request, status: REQUEST_STATUS.failed, completedAt: deps.clock.now(), failure: FAILURE_CODE }));\n } catch (recordFailure) {\n throw new AggregateError([error, recordFailure], \"the erasure failed, and so did recording its failure\", { cause: recordFailure });\n }\n throw error;\n }\n },\n async purge(query) {\n const removed: Record<string, number> = {};\n for (const purpose of deps.purposes) {\n const days = await deps.retentionDays?.(purpose);\n if (days === undefined) continue;\n if (!Number.isInteger(days) || days < 1) throw new RangeError(`the retention of « ${purpose} » must be a whole number of days from 1, got ${days}`);\n const before = subHours(deps.clock.now(), days * 24);\n let total = 0;\n for (const contributor of deps.contributors) total += (await contributor.purgeExpired?.(query, { purpose, before })) ?? 0;\n removed[purpose] = total;\n }\n return removed;\n },\n async requests(query, subject) {\n checkSubject(subject);\n return storeFor(query).requestsOf(subject);\n },\n };\n}\n","import { defineModule } from \"@krizaka/db\";\n\n/**\n * The tables of « privacy », in their own Postgres schema (ADR-001 §3). They reference no product table: a subject is a kind and an\n * id the product chooses (an account, a client file, an application).\n *\n * - `consent` is WRITTEN ONCE: a trigger refuses any update. A withdrawal is a new row; the consent with the last word (highest `seq`) wins.\n * - `request` is the record of an export or an erasure: when, of what kind, how it ended. It holds an id and no other personal data,\n * so it can outlive the erasure it proves.\n *\n * Version 1 is frozen once released: a change is version 2.\n */\nexport const privacySchema = defineModule({\n module: \"privacy\",\n migrations: [\n {\n version: 1,\n name: \"consents and requests\",\n sql: (c) => `\nCREATE TABLE ${c.schema}.consent (\n seq bigserial UNIQUE,\n id uuid PRIMARY KEY,\n subject_kind text NOT NULL CHECK (subject_kind ~ '^[a-z][a-z0-9_]{0,39}$'),\n subject_id text NOT NULL CHECK (char_length(subject_id) BETWEEN 1 AND 200),\n purpose text NOT NULL CHECK (purpose ~ '^[a-z][a-z0-9_-]{0,39}$'),\n version text NOT NULL CHECK (char_length(version) BETWEEN 1 AND 100),\n granted boolean NOT NULL,\n means text CHECK (means IS NULL OR char_length(means) <= 40),\n at timestamptz NOT NULL\n);\nCREATE INDEX consent_subject ON ${c.schema}.consent (subject_kind, subject_id, purpose, seq DESC);\nCREATE FUNCTION ${c.schema}.consent_written_once() RETURNS trigger LANGUAGE plpgsql AS $fn$\nBEGIN\n RAISE EXCEPTION 'a consent is written once: a withdrawal is a new row' USING ERRCODE = 'restrict_violation';\nEND;\n$fn$;\nCREATE TRIGGER consent_written_once BEFORE UPDATE ON ${c.schema}.consent FOR EACH ROW EXECUTE FUNCTION ${c.schema}.consent_written_once();\nCREATE TABLE ${c.schema}.request (\n id uuid PRIMARY KEY,\n subject_kind text NOT NULL CHECK (subject_kind ~ '^[a-z][a-z0-9_]{0,39}$'),\n subject_id text NOT NULL CHECK (char_length(subject_id) BETWEEN 1 AND 200),\n kind text NOT NULL CHECK (kind IN ('export', 'erasure')),\n status text NOT NULL CHECK (status IN ('requested', 'completed', 'failed')),\n requested_at timestamptz NOT NULL,\n completed_at timestamptz,\n failure text CHECK (failure IS NULL OR char_length(failure) <= 100)\n);\nCREATE INDEX request_subject ON ${c.schema}.request (subject_kind, subject_id, requested_at DESC);`,\n },\n ],\n});\n"],"mappings":";;;;;;;;;;AAeO,SAAS,iBAAiB,OAAmB,UAA6B,CAAC,GAAuB;AACvG,QAAM,OAAO,QAAQ,QAAQ;AAC7B,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,UAAU,OAAO,SAAS;AAC9B,aAAO,QAAQ,SAAS,OAAO,MAAM,UAAU,OAAO,QAAQ,EAAE,IAAI,CAAC;AAAA,IACvE;AAAA,IACA,MAAM,SAAS,IAAI,SAAS;AAC1B,UAAI,QAAQ,SAAS,KAAM,OAAM,MAAM,YAAY,IAAI,QAAQ,EAAE;AAAA,IACnE;AAAA,EACF;AACF;;;ACxBA,IAAM,cAAc,CAAC,GAAY,MAAe,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE;AAGzE,SAAS,qBAAmC;AACjD,QAAM,WAA4B,CAAC;AACnC,QAAM,WAAW,oBAAI,IAA4B;AACjD,SAAO;AAAA,IACL,MAAM,cAAc,GAAG;AACrB,eAAS,KAAK,gBAAgB,CAAC,CAAC;AAAA,IAClC;AAAA,IACA,MAAM,cAAc,SAAS,SAAS;AACpC,YAAM,QAAQ,SAAS,OAAO,CAAC,MAAM,YAAY,EAAE,SAAS,OAAO,KAAK,EAAE,YAAY,OAAO,EAAE,GAAG,EAAE;AACpG,aAAO,QA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0CAA0C,EAAE,MAAM;AAAA,eAClG,EAAE,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kCAUW,EAAE,MAAM;AAAA,IACtC;AAAA,EACF;AACF,CAAC;","names":["ident","ident"]}
1
+ {"version":3,"sources":["../src/contributors.ts","../src/incident.ts","../src/incident-memory.ts","../src/incident-persistence.ts","../src/incidents.ts","../src/memory.ts","../src/persistence.ts","../src/privacy.ts","../src/schema.ts"],"sourcesContent":["import type { Query } from \"@krizaka/db\";\n\nimport type { PrivacyContributor } from \"./port\";\n\n/** The structural slice of `@krizaka/audit` that contributes: what the trail holds about an actor, and detaching them from it. */\nexport interface AuditTrail {\n exportFor(query: Query, actorId: string): Promise<unknown>;\n redactActor(query: Query, actorId: string): Promise<number>;\n}\n\n/**\n * `@krizaka/audit` as a contributor: an export lists the actor's entries; an erasure detaches the person (id and address removed, the\n * label « erased ») and keeps the facts. It applies to a subject of the kind the product's actors are (default `account`).\n * @param audit the product's audit (`createAudit(...)`)\n */\nexport function auditContributor(audit: AuditTrail, options: { kind?: string } = {}): PrivacyContributor {\n const kind = options.kind ?? \"account\";\n return {\n name: \"audit\",\n async exportFor(query, subject) {\n return subject.kind === kind ? audit.exportFor(query, subject.id) : [];\n },\n async eraseFor(tx, subject) {\n if (subject.kind === kind) await audit.redactActor(tx, subject.id);\n },\n };\n}\n","import type { AuditPort, Clock, Query } from \"./port\";\n\n/**\n * The confidentiality incident register (Loi 25). Act respecting the protection of personal information in the private sector\n * (CQLR c. P-39.1), ss. 3.5 to 3.8, and the Regulation respecting confidentiality incidents (CQLR c. P-39.1, r. 3.1): see the README\n * for the links. The register holds the facts of an incident and NO personal data of the people concerned (only how many, and which\n * categories of information).\n */\n\n/** What happened to the information (the Act speaks of unauthorised access, use, communication and loss). */\nexport const INCIDENT_KIND = { access: \"access\", use: \"use\", communication: \"communication\", loss: \"loss\" } as const;\nexport type IncidentKind = (typeof INCIDENT_KIND)[keyof typeof INCIDENT_KIND];\n\nexport const INCIDENT_STATUS = { open: \"open\", assessed: \"assessed\", closed: \"closed\" } as const;\nexport type IncidentStatus = (typeof INCIDENT_STATUS)[keyof typeof INCIDENT_STATUS];\n\nexport const LEVEL = { low: \"low\", medium: \"medium\", high: \"high\" } as const;\nexport type Level = (typeof LEVEL)[keyof typeof LEVEL];\n\nexport const NOTICE_TARGET = { cai: \"cai\", persons: \"persons\" } as const;\nexport type NoticeTarget = (typeof NOTICE_TARGET)[keyof typeof NOTICE_TARGET];\n\n/** The three factors of the risk assessment (s. 3.6) and the decision of the person in charge. */\nexport interface IncidentAssessment {\n /** How sensitive the information is. */\n sensitivity: Level;\n /** How serious the anticipated consequences of its use are. */\n consequences: Level;\n /** How likely it is to be misused. */\n likelihood: Level;\n /** The decision: a risk of serious injury means notifying the Commission d'accès à l'information and the people concerned. */\n seriousInjury: boolean;\n rationale: string;\n assessedAt: Date;\n assessedBy: string;\n}\n\n/** A notice sent, to the Commission or to the people concerned. */\nexport interface IncidentNotice {\n sentAt: Date;\n /** How it was sent (`form`, `email`, `letter`, `public`). */\n channel: string;\n /** The Commission's acknowledgement, if any. */\n reference: string | null;\n}\n\nexport interface IncidentMeasure {\n at: Date;\n text: string;\n}\n\n/** One register entry: an incident, from the day the enterprise became aware of it. */\nexport interface Incident {\n id: string;\n /** Whose register it is: a tenant, an organisation. Entries of another scope are never read. */\n scope: string;\n kind: IncidentKind;\n /** When the enterprise became aware of it: the start of the retention. */\n awareAt: Date;\n occurredAt: Date | null;\n description: string;\n /** The categories of information concerned (`lease`, `pay stub`), never the information. */\n information: string[];\n /** How many people are concerned, null while unknown. */\n personsConcerned: number | null;\n measures: IncidentMeasure[];\n status: IncidentStatus;\n assessment: IncidentAssessment | null;\n caiNotice: IncidentNotice | null;\n personsNotice: IncidentNotice | null;\n /** A fictitious incident, run to prove the procedure. It stays in the register, marked. */\n drill: boolean;\n openedBy: string;\n openedAt: Date;\n closedAt: Date | null;\n /** The register entry cannot be deleted before this date: five years after `awareAt`. */\n retainUntil: Date;\n}\n\nexport interface IncidentInput {\n scope: string;\n kind: IncidentKind;\n awareAt?: Date | undefined;\n occurredAt?: Date | undefined;\n description: string;\n information: readonly string[];\n personsConcerned?: number | undefined;\n drill?: boolean | undefined;\n}\n\nexport interface AssessmentInput {\n sensitivity: Level;\n consequences: Level;\n likelihood: Level;\n seriousInjury: boolean;\n rationale: string;\n}\n\n/** Where the register lives. Every adapter runs `incidentStoreContract` (`@krizaka/privacy/testkit`). Every read is by scope. */\nexport interface IncidentStore {\n insert(incident: Incident): Promise<void>;\n /** Replaces an incident that is not closed. */\n save(incident: Incident): Promise<void>;\n /** `lock`: for the read-then-write of one incident (`FOR UPDATE`). */\n get(scope: string, id: string, options?: { lock?: boolean }): Promise<Incident | null>;\n /** The whole register of the scope, oldest awareness first. */\n list(scope: string): Promise<Incident[]>;\n}\n\nexport interface IncidentActor {\n /** An opaque id (an admin account). */\n id: string | null;\n label: string;\n}\n\nexport interface IncidentDeps {\n clock: Clock;\n audit?: AuditPort;\n storeFor?: (query: Query) => IncidentStore;\n /** The Postgres schema, when the product renamed the module's. */\n schema?: string;\n}\n\n/** The register as handed to the Commission on request: one document, the entries oldest first. */\nexport interface RegisterDocument {\n format: 1;\n scope: string;\n generatedAt: string;\n entries: Incident[];\n}\n\nexport interface IncidentRegister {\n /** Opens an incident (s. 3.5: as soon as there is reason to believe one occurred). */\n open(query: Query, input: IncidentInput, actor: IncidentActor): Promise<Incident>;\n /** Writes the risk assessment (s. 3.6); it can be redone until the incident is closed. */\n assess(query: Query, scope: string, id: string, input: AssessmentInput, actor: IncidentActor): Promise<Incident>;\n /** Records a measure taken to reduce the risk and prevent a new incident (s. 3.5). */\n recordMeasure(query: Query, scope: string, id: string, text: string, actor: IncidentActor): Promise<Incident>;\n /** Records a notice sent. Only an incident assessed as a risk of serious injury is notified. */\n recordNotice(query: Query, scope: string, id: string, target: NoticeTarget, notice: { channel: string; reference?: string | undefined }, actor: IncidentActor): Promise<Incident>;\n /** Marks the incident as a drill (or not). */\n markDrill(query: Query, scope: string, id: string, drill: boolean, actor: IncidentActor): Promise<Incident>;\n /** Closes it: assessed, and both notices sent when the risk is serious. A closed entry is never edited again. */\n close(query: Query, scope: string, id: string, actor: IncidentActor): Promise<Incident>;\n get(query: Query, scope: string, id: string): Promise<Incident | null>;\n /** The register of the scope. */\n list(query: Query, scope: string): Promise<Incident[]>;\n exportRegister(query: Query, scope: string): Promise<RegisterDocument>;\n}\n\nexport const INCIDENT_CODE = {\n badInput: \"INCIDENT_BAD_INPUT\",\n unknown: \"INCIDENT_UNKNOWN\",\n closed: \"INCIDENT_CLOSED\",\n notAssessed: \"INCIDENT_NOT_ASSESSED\",\n noNoticeDue: \"INCIDENT_NO_NOTICE_DUE\",\n noticesMissing: \"INCIDENT_NOTICES_MISSING\",\n} as const;\nexport type IncidentCode = (typeof INCIDENT_CODE)[keyof typeof INCIDENT_CODE];\n\nexport class IncidentError extends Error {\n constructor(\n readonly code: IncidentCode,\n message: string,\n ) {\n super(message);\n this.name = \"IncidentError\";\n }\n}\n\nconst RANK: Record<Level, number> = { low: 0, medium: 1, high: 2 };\n\n/**\n * A guide for the person in charge, never the decision: the injury is serious when the information is sensitive and misuse is not\n * unlikely, when the consequences are severe and misuse is likely, or when everything is at least medium and misuse is likely.\n */\nexport function suggestSeriousInjury(factors: Pick<AssessmentInput, \"sensitivity\" | \"consequences\" | \"likelihood\">): boolean {\n const { sensitivity, consequences, likelihood } = { sensitivity: RANK[factors.sensitivity], consequences: RANK[factors.consequences], likelihood: RANK[factors.likelihood] };\n if (sensitivity === RANK.high && likelihood >= RANK.medium) return true;\n if (consequences === RANK.high && likelihood === RANK.high) return true;\n return sensitivity >= RANK.medium && consequences >= RANK.medium && likelihood === RANK.high;\n}\n\n/** Five years after the enterprise became aware of the incident (the Regulation's minimum for keeping the register). */\nexport function retainUntil(awareAt: Date): Date {\n const until = new Date(awareAt);\n until.setUTCFullYear(until.getUTCFullYear() + 5);\n return until;\n}\n\nconst FORMULA = /^[=+\\-@\\t\\r]/;\nconst cell = (value: unknown): string => {\n const text = value === null || value === undefined ? \"\" : value instanceof Date ? value.toISOString() : String(value);\n const safe = FORMULA.test(text) ? `'${text}` : text;\n return /[\",\\n\\r]/.test(safe) ? `\"${safe.replaceAll('\"', '\"\"')}\"` : safe;\n};\nexport const REGISTER_CSV_COLUMNS = [\"id\", \"kind\", \"aware_at\", \"occurred_at\", \"description\", \"information\", \"persons_concerned\", \"serious_injury\", \"assessed_at\", \"cai_notice_at\", \"persons_notice_at\", \"measures\", \"status\", \"drill\", \"closed_at\", \"retain_until\"] as const;\n\n/** The register as CSV (RFC 4180), cells that a spreadsheet would read as a formula are quoted with a leading apostrophe. */\nexport function registerToCsv(entries: readonly Incident[]): string {\n const rows = entries.map((e) =>\n [e.id, e.kind, e.awareAt, e.occurredAt, e.description, e.information.join(\"; \"), e.personsConcerned, e.assessment?.seriousInjury ?? \"\", e.assessment?.assessedAt ?? \"\", e.caiNotice?.sentAt ?? \"\", e.personsNotice?.sentAt ?? \"\", e.measures.map((m) => m.text).join(\"; \"), e.status, e.drill, e.closedAt, e.retainUntil].map(cell).join(\",\"),\n );\n return [REGISTER_CSV_COLUMNS.join(\",\"), ...rows].join(\"\\r\\n\") + \"\\r\\n\";\n}\n","import { type Incident, INCIDENT_STATUS, type IncidentStore } from \"./incident\";\n\n/** An in-memory incident store, for unit tests and demos (the contract kit runs on it and on the database's). */\nexport function memoryIncidentStore(): IncidentStore {\n const rows = new Map<string, Incident>();\n const key = (scope: string, id: string) => `${scope}\\u0000${id}`;\n return {\n async insert(incident) {\n rows.set(key(incident.scope, incident.id), structuredClone(incident));\n },\n async save(incident) {\n const k = key(incident.scope, incident.id);\n const current = rows.get(k);\n if (!current) return; // like an UPDATE that matches nothing\n if (current.status === INCIDENT_STATUS.closed) throw new Error(\"a closed incident is never edited\");\n rows.set(k, structuredClone(incident));\n },\n async get(scope, id) {\n const found = rows.get(key(scope, id));\n return found ? structuredClone(found) : null;\n },\n async list(scope) {\n return [...rows.values()].filter((i) => i.scope === scope).sort((a, b) => a.awareAt.valueOf() - b.awareAt.valueOf() || a.id.localeCompare(b.id)).map((i) => structuredClone(i));\n },\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { Incident, IncidentAssessment, IncidentKind, IncidentMeasure, IncidentNotice, IncidentStatus, IncidentStore, Level } from \"./incident\";\n\ntype Stamp = Date | string;\ninterface IncidentRow {\n id: string;\n scope: string;\n kind: IncidentKind;\n aware_at: Stamp;\n occurred_at: Stamp | null;\n description: string;\n information: string[];\n persons_concerned: number | null;\n measures: { at: string; text: string }[];\n status: IncidentStatus;\n assessment: { sensitivity: Level; consequences: Level; likelihood: Level; seriousInjury: boolean; rationale: string; assessedAt: string; assessedBy: string } | null;\n cai_notice: { sentAt: string; channel: string; reference: string | null } | null;\n persons_notice: { sentAt: string; channel: string; reference: string | null } | null;\n drill: boolean;\n opened_by: string;\n opened_at: Stamp;\n closed_at: Stamp | null;\n retain_until: Stamp;\n}\n\nconst COLUMNS = \"id, scope, kind, aware_at, occurred_at, description, information, persons_concerned, measures, status, assessment, cai_notice, persons_notice, drill, opened_by, opened_at, closed_at, retain_until\";\nconst optional = (stamp: Stamp | null) => (stamp === null ? null : new Date(stamp));\nconst toNotice = (n: IncidentRow[\"cai_notice\"]): IncidentNotice | null => (n ? { sentAt: new Date(n.sentAt), channel: n.channel, reference: n.reference } : null);\nconst toAssessment = (a: IncidentRow[\"assessment\"]): IncidentAssessment | null => (a ? { ...a, assessedAt: new Date(a.assessedAt) } : null);\n\nconst toIncident = (r: IncidentRow): Incident => ({\n id: r.id,\n scope: r.scope,\n kind: r.kind,\n awareAt: new Date(r.aware_at),\n occurredAt: optional(r.occurred_at),\n description: r.description,\n information: r.information,\n personsConcerned: r.persons_concerned,\n measures: r.measures.map((m): IncidentMeasure => ({ at: new Date(m.at), text: m.text })),\n status: r.status,\n assessment: toAssessment(r.assessment),\n caiNotice: toNotice(r.cai_notice),\n personsNotice: toNotice(r.persons_notice),\n drill: r.drill,\n openedBy: r.opened_by,\n openedAt: new Date(r.opened_at),\n closedAt: optional(r.closed_at),\n retainUntil: new Date(r.retain_until),\n});\n\nconst json = (value: unknown) => (value === null ? null : JSON.stringify(value));\n\n/** The PostgreSQL incident store, over the `Query` it is given (the caller's transaction). `schema`: default `privacy`. */\nexport function dbIncidentStore(query: Query, schema = \"privacy\"): IncidentStore {\n const table = `${ident(schema)}.incident`;\n const values = (i: Incident) => [i.id, i.scope, i.kind, i.awareAt, i.occurredAt, i.description, i.information, i.personsConcerned, JSON.stringify(i.measures), i.status, json(i.assessment), json(i.caiNotice), json(i.personsNotice), i.drill, i.openedBy, i.openedAt, i.closedAt, i.retainUntil];\n return {\n async insert(i) {\n await query(`INSERT INTO ${table} (${COLUMNS}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11::jsonb, $12::jsonb, $13::jsonb, $14, $15, $16, $17, $18)`, values(i));\n },\n async save(i) {\n await query(\n `UPDATE ${table} SET kind = $3, aware_at = $4, occurred_at = $5, description = $6, information = $7, persons_concerned = $8, measures = $9::jsonb, status = $10, assessment = $11::jsonb, cai_notice = $12::jsonb, persons_notice = $13::jsonb, drill = $14, opened_by = $15, opened_at = $16, closed_at = $17, retain_until = $18 WHERE scope = $2 AND id = $1`,\n values(i),\n );\n },\n async get(scope, id, options) {\n const [row] = await query<IncidentRow>(`SELECT ${COLUMNS} FROM ${table} WHERE scope = $1 AND id = $2${options?.lock ? \" FOR UPDATE\" : \"\"}`, [scope, id]);\n return row ? toIncident(row) : null;\n },\n async list(scope) {\n return (await query<IncidentRow>(`SELECT ${COLUMNS} FROM ${table} WHERE scope = $1 ORDER BY aware_at, id`, [scope])).map(toIncident);\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { ident } from \"@krizaka/db\";\n\nimport {\n type AssessmentInput,\n type Incident,\n INCIDENT_CODE,\n INCIDENT_KIND,\n INCIDENT_STATUS,\n type IncidentActor,\n type IncidentDeps,\n IncidentError,\n type IncidentInput,\n type IncidentRegister,\n LEVEL,\n NOTICE_TARGET,\n retainUntil,\n} from \"./incident\";\nimport { dbIncidentStore } from \"./incident-persistence\";\nimport type { Query } from \"./port\";\n\nconst bad = (message: string) => new IncidentError(INCIDENT_CODE.badInput, message);\nconst within = (value: string, max: number, what: string) => {\n if (value.trim().length < 1 || value.length > max) throw bad(`${what}: 1 to ${max} characters`);\n};\nconst KINDS: readonly string[] = Object.values(INCIDENT_KIND);\nconst LEVELS: readonly string[] = Object.values(LEVEL);\n\nfunction checkScope(scope: string) {\n within(scope, 100, \"scope\");\n}\n\n/**\n * The confidentiality incident register of a product (Loi 25, ss. 3.5 to 3.8). Every call is by scope (the tenant), and a closed\n * entry is never edited again; the database refuses to delete an entry before its retention ends.\n */\nexport function createIncidentRegister(deps: IncidentDeps): IncidentRegister {\n const schema = ident(deps.schema ?? \"privacy\");\n const storeFor = deps.storeFor ?? ((query: Query) => dbIncidentStore(query, schema));\n\n async function trace(query: Query, actor: IncidentActor, action: string, incident: Incident) {\n await deps.audit?.record(query, { actorId: actor.id, actorLabel: actor.label, action: `privacy.incident_${action}`, target: { type: \"incident\", id: incident.id }, detail: { scope: incident.scope, drill: incident.drill } });\n }\n\n /** Reads the incident under lock, applies `change` to a copy, saves it, traces it. */\n async function update(query: Query, scope: string, id: string, action: string, actor: IncidentActor, change: (incident: Incident) => void): Promise<Incident> {\n checkScope(scope);\n const store = storeFor(query);\n const incident = await store.get(scope, id, { lock: true });\n if (!incident) throw new IncidentError(INCIDENT_CODE.unknown, \"no such incident in this register\");\n if (incident.status === INCIDENT_STATUS.closed) throw new IncidentError(INCIDENT_CODE.closed, \"a closed entry of the register is never edited\");\n change(incident);\n await store.save(incident);\n await trace(query, actor, action, incident);\n return incident;\n }\n\n return {\n async open(query, input: IncidentInput, actor) {\n checkScope(input.scope);\n if (!KINDS.includes(input.kind)) throw bad(`kind « ${input.kind} » is not one of ${KINDS.join(\", \")}`);\n within(input.description, 2000, \"description\");\n if (input.information.length < 1 || input.information.length > 30) throw bad(\"information: 1 to 30 categories\");\n for (const category of input.information) within(category, 80, \"information category\");\n if (input.personsConcerned !== undefined && (!Number.isInteger(input.personsConcerned) || input.personsConcerned < 0)) throw bad(\"personsConcerned: a whole number, 0 or more\");\n const now = deps.clock.now();\n const awareAt = input.awareAt ?? now;\n if (awareAt.valueOf() > now.valueOf()) throw bad(\"awareAt cannot be in the future\");\n if (input.occurredAt && input.occurredAt.valueOf() > now.valueOf()) throw bad(\"occurredAt cannot be in the future\");\n const incident: Incident = {\n id: randomUUID(),\n scope: input.scope,\n kind: input.kind,\n awareAt,\n occurredAt: input.occurredAt ?? null,\n description: input.description,\n information: [...input.information],\n personsConcerned: input.personsConcerned ?? null,\n measures: [],\n status: INCIDENT_STATUS.open,\n assessment: null,\n caiNotice: null,\n personsNotice: null,\n drill: input.drill ?? false,\n openedBy: actor.label,\n openedAt: now,\n closedAt: null,\n retainUntil: retainUntil(awareAt),\n };\n await storeFor(query).insert(incident);\n await trace(query, actor, \"opened\", incident);\n return incident;\n },\n assess(query, scope, id, input: AssessmentInput, actor) {\n for (const level of [input.sensitivity, input.consequences, input.likelihood]) if (!LEVELS.includes(level)) throw bad(`level « ${level} » is not one of ${LEVELS.join(\", \")}`);\n within(input.rationale, 2000, \"rationale\");\n return update(query, scope, id, \"assessed\", actor, (incident) => {\n incident.assessment = { ...input, assessedAt: deps.clock.now(), assessedBy: actor.label };\n incident.status = INCIDENT_STATUS.assessed;\n });\n },\n recordMeasure(query, scope, id, text, actor) {\n within(text, 1000, \"measure\");\n return update(query, scope, id, \"measure_recorded\", actor, (incident) => {\n incident.measures.push({ at: deps.clock.now(), text });\n });\n },\n recordNotice(query, scope, id, target, notice, actor) {\n within(notice.channel, 40, \"channel\");\n return update(query, scope, id, `notice_${target}`, actor, (incident) => {\n if (!incident.assessment) throw new IncidentError(INCIDENT_CODE.notAssessed, \"assess the risk before notifying\");\n if (!incident.assessment.seriousInjury) throw new IncidentError(INCIDENT_CODE.noNoticeDue, \"no notice is due: the assessment found no risk of serious injury\");\n const sent = { sentAt: deps.clock.now(), channel: notice.channel, reference: notice.reference ?? null };\n if (target === NOTICE_TARGET.cai) incident.caiNotice = sent;\n else incident.personsNotice = sent;\n });\n },\n markDrill(query, scope, id, drill, actor) {\n return update(query, scope, id, \"drill_marked\", actor, (incident) => {\n incident.drill = drill;\n });\n },\n close(query, scope, id, actor) {\n return update(query, scope, id, \"closed\", actor, (incident) => {\n if (!incident.assessment) throw new IncidentError(INCIDENT_CODE.notAssessed, \"assess the risk before closing\");\n if (incident.assessment.seriousInjury && (!incident.caiNotice || !incident.personsNotice)) throw new IncidentError(INCIDENT_CODE.noticesMissing, \"a risk of serious injury is closed once the Commission and the people concerned are notified\");\n incident.status = INCIDENT_STATUS.closed;\n incident.closedAt = deps.clock.now();\n });\n },\n async get(query, scope, id) {\n checkScope(scope);\n return storeFor(query).get(scope, id);\n },\n async list(query, scope) {\n checkScope(scope);\n return storeFor(query).list(scope);\n },\n async exportRegister(query, scope) {\n checkScope(scope);\n return { format: 1, scope, generatedAt: deps.clock.now().toISOString(), entries: await storeFor(query).list(scope) };\n },\n };\n}\n","import type { ConsentRecord, PrivacyRequest, PrivacyStore, Subject } from \"./port\";\n\nconst sameSubject = (a: Subject, b: Subject) => a.kind === b.kind && a.id === b.id;\n\n/** An in-memory store, for unit tests and demos (the same behaviour as the database's: the contract kit runs on both). */\nexport function memoryPrivacyStore(): PrivacyStore {\n const consents: ConsentRecord[] = [];\n const requests = new Map<string, PrivacyRequest>();\n return {\n async insertConsent(c) {\n consents.push(structuredClone(c));\n },\n async latestConsent(subject, purpose) {\n const found = consents.filter((c) => sameSubject(c.subject, subject) && c.purpose === purpose).at(-1);\n return found ? structuredClone(found) : null;\n },\n async consentHistory(subject) {\n return consents.filter((c) => sameSubject(c.subject, subject)).map((c) => structuredClone(c));\n },\n async insertRequest(r) {\n requests.set(r.id, structuredClone(r));\n },\n async getRequest(id) {\n const found = requests.get(id);\n return found ? structuredClone(found) : null;\n },\n async finishRequest(id, outcome) {\n const found = requests.get(id);\n if (found) Object.assign(found, { status: outcome.status, completedAt: outcome.at, failure: outcome.failure ?? null });\n },\n async requestsOf(subject) {\n return [...requests.values()].filter((r) => sameSubject(r.subject, subject)).sort((a, b) => b.requestedAt.valueOf() - a.requestedAt.valueOf()).map((r) => structuredClone(r));\n },\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { ConsentRecord, PrivacyRequest, PrivacyStore, RequestKind, RequestStatus, Subject } from \"./port\";\n\ninterface ConsentRow {\n id: string;\n subject_kind: string;\n subject_id: string;\n purpose: string;\n version: string;\n granted: boolean;\n means: string | null;\n at: Date | string;\n}\ninterface RequestRow {\n id: string;\n subject_kind: string;\n subject_id: string;\n kind: RequestKind;\n status: RequestStatus;\n requested_at: Date | string;\n completed_at: Date | string | null;\n failure: string | null;\n}\n\nconst toConsent = (r: ConsentRow): ConsentRecord => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, purpose: r.purpose, version: r.version, granted: r.granted, means: r.means, at: new Date(r.at) });\nconst toRequest = (r: RequestRow): PrivacyRequest => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, kind: r.kind, status: r.status, requestedAt: new Date(r.requested_at), completedAt: r.completed_at === null ? null : new Date(r.completed_at), failure: r.failure });\n\nconst CONSENT_COLUMNS = \"id, subject_kind, subject_id, purpose, version, granted, means, at\";\nconst REQUEST_COLUMNS = \"id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure\";\n\n/**\n * The PostgreSQL store of « privacy », over the `Query` it is given (the caller's transaction, to join its unit of work).\n * @param schema the Postgres schema of the module, default `privacy`\n */\nexport function dbPrivacyStore(query: Query, schema = \"privacy\"): PrivacyStore {\n const consent = `${ident(schema)}.consent`;\n const request = `${ident(schema)}.request`;\n const same = (subject: Subject) => [subject.kind, subject.id];\n return {\n async insertConsent(c) {\n await query(`INSERT INTO ${consent} (id, subject_kind, subject_id, purpose, version, granted, means, at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [c.id, c.subject.kind, c.subject.id, c.purpose, c.version, c.granted, c.means, c.at]);\n },\n async latestConsent(subject, purpose) {\n const [row] = await query<ConsentRow>(`SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 AND purpose = $3 ORDER BY seq DESC LIMIT 1`, [...same(subject), purpose]);\n return row ? toConsent(row) : null;\n },\n async consentHistory(subject) {\n return (await query<ConsentRow>(`SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY seq`, same(subject))).map(toConsent);\n },\n async insertRequest(r) {\n await query(`INSERT INTO ${request} (id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [r.id, r.subject.kind, r.subject.id, r.kind, r.status, r.requestedAt, r.completedAt, r.failure]);\n },\n async getRequest(id) {\n const [row] = await query<RequestRow>(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE id = $1`, [id]);\n return row ? toRequest(row) : null;\n },\n async finishRequest(id, outcome) {\n await query(`UPDATE ${request} SET status = $2, completed_at = $3, failure = $4 WHERE id = $1`, [id, outcome.status, outcome.at, outcome.failure ?? null]);\n },\n async requestsOf(subject) {\n return (await query<RequestRow>(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY requested_at DESC, id`, same(subject))).map(toRequest);\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { ident } from \"@krizaka/db\";\nimport { subHours } from \"@krizaka/time\";\n\nimport { dbPrivacyStore } from \"./persistence\";\nimport {\n type AuditPort,\n type Clock,\n type ConsentInput,\n type ConsentRecord,\n type ExportDocument,\n type OutboxPort,\n PRIVACY_CODE,\n type PrivacyContributor,\n PrivacyError,\n type PrivacyRequest,\n type PrivacyStore,\n type Query,\n REQUEST_KIND,\n REQUEST_STATUS,\n type Subject,\n} from \"./port\";\nimport { checkPurpose, checkSubject } from \"./rules\";\n\n/** The product's unit of work: runs `work` on one connection, commits when it resolves, rolls back when it throws (`transaction` of `@krizaka/db`). */\nexport type Transaction = <T>(work: (tx: Query) => Promise<T>) => Promise<T>;\n\nexport interface PrivacyDeps {\n clock: Clock;\n /** Every module that holds personal data, and the product's own. Their names are the keys of the export. */\n contributors: readonly PrivacyContributor[];\n /** The purposes the product declares (`screening`, `marketing`). A consent for another is refused. */\n purposes: readonly string[];\n /** The product's transaction, for the erasure. */\n transaction: Transaction;\n /** How many days a purpose is kept: the settings `privacy.retention.<purpose>Days` (`retentionFromSettings`). `undefined` = no retention for it. */\n retentionDays?: (purpose: string) => number | undefined | Promise<number | undefined>;\n /** The audit trail: an erasure is recorded there without personal data. */\n audit?: AuditPort;\n /** The outbox: required for the asynchronous export of a large account (`requestExport`). */\n outbox?: OutboxPort;\n /** The store over a query. Default: the PostgreSQL store on schema `privacy`. */\n storeFor?: (query: Query) => PrivacyStore;\n /** The Postgres schema, when the product renamed the module's (used by the default store). */\n schema?: string;\n}\n\nexport interface Privacy {\n /** Writes a consent or a withdrawal. Never edits one. */\n recordConsent(query: Query, input: ConsentInput): Promise<ConsentRecord>;\n /** Whether the consent with the last word for this purpose is a yes. A person who never said anything has not consented. */\n hasConsent(query: Query, subject: Subject, purpose: string): Promise<boolean>;\n /** Every consent and withdrawal of the subject, oldest first. */\n consentHistory(query: Query, subject: Subject): Promise<ConsentRecord[]>;\n /** The export, at once: one document with a part per contributor. The request is recorded. */\n exportSubject(query: Query, subject: Subject): Promise<ExportDocument>;\n /**\n * The export of a large account, asynchronously: records the request and appends a message to the outbox IN THE CALLER'S\n * TRANSACTION (`tx`). A worker then calls `fulfilExport(requestId, deliver)`. The message holds the request id only.\n */\n requestExport(tx: Query, subject: Subject): Promise<{ requestId: string }>;\n /** Assembles the export of a recorded request and hands it to `deliver` (store the file, mail a link); the request is completed after `deliver` returns. */\n fulfilExport(query: Query, requestId: string, deliver: (document: ExportDocument, request: PrivacyRequest) => Promise<void>): Promise<void>;\n /**\n * Erases the subject from every contributor in ONE transaction, withdraws their live consents, and records the request and an\n * audit entry that names no one. If a contributor fails nothing is erased, the request is recorded as failed, and the error is thrown.\n */\n eraseSubject(subject: Subject, options?: { noticeVersion?: string }): Promise<PrivacyRequest>;\n /** Removes, for each purpose with a retention, what the contributors hold past it. Returns how many rows each purpose removed. */\n purge(query: Query): Promise<Record<string, number>>;\n /** The subject's requests, newest first. */\n requests(query: Query, subject: Subject): Promise<PrivacyRequest[]>;\n}\n\nconst FAILURE_CODE = \"CONTRIBUTOR_FAILED\";\nconst ERASURE_VERSION = \"erasure\";\n\n/**\n * Privacy for a product (Loi 25).\n * @param deps the contributors, the purposes, the product's transaction and the clock\n * @throws PrivacyError for a purpose or a contributor name that is not well formed or appears twice\n */\nexport function createPrivacy(deps: PrivacyDeps): Privacy {\n const schema = ident(deps.schema ?? \"privacy\");\n const storeFor = deps.storeFor ?? ((query: Query) => dbPrivacyStore(query, schema));\n for (const purpose of deps.purposes) checkPurpose(purpose);\n const names = deps.contributors.map((c) => c.name);\n if (new Set(names).size !== names.length) throw new PrivacyError(PRIVACY_CODE.contributorFailed, `two contributors have the same name: ${names.join(\", \")}`);\n const known = new Set(deps.purposes);\n\n async function assemble(query: Query, subject: Subject): Promise<ExportDocument> {\n const modules: Record<string, unknown> = {};\n for (const contributor of deps.contributors) {\n try {\n modules[contributor.name] = await contributor.exportFor(query, subject);\n } catch (cause) {\n throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the export of « ${contributor.name} » failed`, { cause });\n }\n }\n return { format: 1, subject, generatedAt: deps.clock.now().toISOString(), modules };\n }\n\n const newRequest = (subject: Subject, kind: PrivacyRequest[\"kind\"]): PrivacyRequest => ({ id: randomUUID(), subject, kind, status: REQUEST_STATUS.requested, requestedAt: deps.clock.now(), completedAt: null, failure: null });\n\n async function recordConsent(query: Query, input: ConsentInput): Promise<ConsentRecord> {\n checkSubject(input.subject);\n checkPurpose(input.purpose);\n if (!known.has(input.purpose)) throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose « ${input.purpose} » is not one the product declared`);\n if (input.version.length < 1 || input.version.length > 100) throw new PrivacyError(PRIVACY_CODE.badConsent, \"the notice version is 1 to 100 characters\");\n const record: ConsentRecord = { id: randomUUID(), subject: input.subject, purpose: input.purpose, version: input.version, granted: input.granted, means: input.means ?? null, at: deps.clock.now() };\n await storeFor(query).insertConsent(record);\n return record;\n }\n\n return {\n recordConsent,\n async hasConsent(query, subject, purpose) {\n checkSubject(subject);\n checkPurpose(purpose);\n return (await storeFor(query).latestConsent(subject, purpose))?.granted === true;\n },\n async consentHistory(query, subject) {\n checkSubject(subject);\n return storeFor(query).consentHistory(subject);\n },\n async exportSubject(query, subject) {\n checkSubject(subject);\n const store = storeFor(query);\n const request = newRequest(subject, REQUEST_KIND.export);\n await store.insertRequest(request);\n try {\n const document = await assemble(query, subject);\n await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: deps.clock.now() });\n return document;\n } catch (error) {\n await store.finishRequest(request.id, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });\n throw error;\n }\n },\n async requestExport(tx, subject) {\n checkSubject(subject);\n if (!deps.outbox) throw new PrivacyError(PRIVACY_CODE.noOutbox, \"an asynchronous export needs the outbox\");\n const request = newRequest(subject, REQUEST_KIND.export);\n await storeFor(tx).insertRequest(request);\n await deps.outbox.append(tx, { topic: \"privacy\", type: \"evt.privacy.export_requested.v1\", payload: { requestId: request.id }, id: request.id });\n return { requestId: request.id };\n },\n async fulfilExport(query, requestId, deliver) {\n const store = storeFor(query);\n const request = await store.getRequest(requestId);\n if (!request) throw new PrivacyError(PRIVACY_CODE.unknownRequest, `no request ${requestId}`);\n if (request.kind !== REQUEST_KIND.export) throw new PrivacyError(PRIVACY_CODE.notAnExport, `request ${requestId} is not an export`);\n if (request.status === REQUEST_STATUS.completed) throw new PrivacyError(PRIVACY_CODE.alreadyDone, `request ${requestId} is already completed`);\n try {\n await deliver(await assemble(query, request.subject), request);\n } catch (error) {\n await store.finishRequest(requestId, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });\n throw error;\n }\n await store.finishRequest(requestId, { status: REQUEST_STATUS.completed, at: deps.clock.now() });\n },\n async eraseSubject(subject, options = {}) {\n checkSubject(subject);\n const request = newRequest(subject, REQUEST_KIND.erasure);\n try {\n return await deps.transaction(async (tx) => {\n const store = storeFor(tx);\n await store.insertRequest(request);\n for (const contributor of deps.contributors) {\n try {\n await contributor.eraseFor(tx, subject);\n } catch (cause) {\n throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the erasure of « ${contributor.name} » failed`, { cause });\n }\n }\n for (const purpose of deps.purposes) {\n if ((await store.latestConsent(subject, purpose))?.granted) await recordConsent(tx, { subject, purpose, version: options.noticeVersion ?? ERASURE_VERSION, granted: false, means: ERASURE_VERSION });\n }\n const completedAt = deps.clock.now();\n await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: completedAt });\n // the entry names the request and the modules, never the person\n await deps.audit?.record(tx, { actorId: null, actorLabel: \"privacy\", action: \"privacy.erasure_completed\", target: { type: \"privacy_request\", id: request.id }, detail: { contributors: names } });\n return { ...request, status: REQUEST_STATUS.completed, completedAt };\n });\n } catch (error) {\n // the transaction rolled back, request row included: record the failure beside it, and never mask the original error\n try {\n await deps.transaction((tx) => storeFor(tx).insertRequest({ ...request, status: REQUEST_STATUS.failed, completedAt: deps.clock.now(), failure: FAILURE_CODE }));\n } catch (recordFailure) {\n throw new AggregateError([error, recordFailure], \"the erasure failed, and so did recording its failure\", { cause: recordFailure });\n }\n throw error;\n }\n },\n async purge(query) {\n const removed: Record<string, number> = {};\n for (const purpose of deps.purposes) {\n const days = await deps.retentionDays?.(purpose);\n if (days === undefined) continue;\n if (!Number.isInteger(days) || days < 1) throw new RangeError(`the retention of « ${purpose} » must be a whole number of days from 1, got ${days}`);\n const before = subHours(deps.clock.now(), days * 24);\n let total = 0;\n for (const contributor of deps.contributors) total += (await contributor.purgeExpired?.(query, { purpose, before })) ?? 0;\n removed[purpose] = total;\n }\n return removed;\n },\n async requests(query, subject) {\n checkSubject(subject);\n return storeFor(query).requestsOf(subject);\n },\n };\n}\n","import { defineModule } from \"@krizaka/db\";\n\n/**\n * The tables of « privacy », in their own Postgres schema (ADR-001 §3). They reference no product table: a subject is a kind and an\n * id the product chooses (an account, a client file, an application).\n *\n * - `consent` is WRITTEN ONCE: a trigger refuses any update. A withdrawal is a new row; the consent with the last word (highest `seq`) wins.\n * - `request` is the record of an export or an erasure: when, of what kind, how it ended. It holds an id and no other personal data,\n * so it can outlive the erasure it proves.\n *\n * Version 1 is frozen once released: a change is version 2.\n */\nexport const privacySchema = defineModule({\n module: \"privacy\",\n migrations: [\n {\n version: 1,\n name: \"consents and requests\",\n sql: (c) => `\nCREATE TABLE ${c.schema}.consent (\n seq bigserial UNIQUE,\n id uuid PRIMARY KEY,\n subject_kind text NOT NULL CHECK (subject_kind ~ '^[a-z][a-z0-9_]{0,39}$'),\n subject_id text NOT NULL CHECK (char_length(subject_id) BETWEEN 1 AND 200),\n purpose text NOT NULL CHECK (purpose ~ '^[a-z][a-z0-9_-]{0,39}$'),\n version text NOT NULL CHECK (char_length(version) BETWEEN 1 AND 100),\n granted boolean NOT NULL,\n means text CHECK (means IS NULL OR char_length(means) <= 40),\n at timestamptz NOT NULL\n);\nCREATE INDEX consent_subject ON ${c.schema}.consent (subject_kind, subject_id, purpose, seq DESC);\nCREATE FUNCTION ${c.schema}.consent_written_once() RETURNS trigger LANGUAGE plpgsql AS $fn$\nBEGIN\n RAISE EXCEPTION 'a consent is written once: a withdrawal is a new row' USING ERRCODE = 'restrict_violation';\nEND;\n$fn$;\nCREATE TRIGGER consent_written_once BEFORE UPDATE ON ${c.schema}.consent FOR EACH ROW EXECUTE FUNCTION ${c.schema}.consent_written_once();\nCREATE TABLE ${c.schema}.request (\n id uuid PRIMARY KEY,\n subject_kind text NOT NULL CHECK (subject_kind ~ '^[a-z][a-z0-9_]{0,39}$'),\n subject_id text NOT NULL CHECK (char_length(subject_id) BETWEEN 1 AND 200),\n kind text NOT NULL CHECK (kind IN ('export', 'erasure')),\n status text NOT NULL CHECK (status IN ('requested', 'completed', 'failed')),\n requested_at timestamptz NOT NULL,\n completed_at timestamptz,\n failure text CHECK (failure IS NULL OR char_length(failure) <= 100)\n);\nCREATE INDEX request_subject ON ${c.schema}.request (subject_kind, subject_id, requested_at DESC);`,\n },\n {\n version: 2,\n name: \"confidentiality incident register\",\n sql: (c) => `\nCREATE TABLE ${c.schema}.incident (\n id uuid PRIMARY KEY,\n scope text NOT NULL CHECK (char_length(scope) BETWEEN 1 AND 100),\n kind text NOT NULL CHECK (kind IN ('access', 'use', 'communication', 'loss')),\n aware_at timestamptz NOT NULL,\n occurred_at timestamptz,\n description text NOT NULL CHECK (char_length(description) BETWEEN 1 AND 2000),\n information text[] NOT NULL CHECK (cardinality(information) BETWEEN 1 AND 30),\n persons_concerned integer CHECK (persons_concerned IS NULL OR persons_concerned >= 0),\n measures jsonb NOT NULL DEFAULT '[]',\n status text NOT NULL CHECK (status IN ('open', 'assessed', 'closed')),\n assessment jsonb,\n cai_notice jsonb,\n persons_notice jsonb,\n drill boolean NOT NULL DEFAULT false,\n opened_by text NOT NULL,\n opened_at timestamptz NOT NULL,\n closed_at timestamptz,\n retain_until timestamptz NOT NULL\n);\nCREATE INDEX incident_scope ON ${c.schema}.incident (scope, aware_at, id);\nCREATE FUNCTION ${c.schema}.incident_guard() RETURNS trigger LANGUAGE plpgsql AS $fn$\nBEGIN\n IF TG_OP = 'DELETE' THEN\n IF OLD.retain_until > now() THEN\n RAISE EXCEPTION 'an incident stays in the register until its retention ends' USING ERRCODE = 'restrict_violation';\n END IF;\n RETURN OLD;\n END IF;\n IF OLD.status = 'closed' THEN\n RAISE EXCEPTION 'a closed entry of the register is never edited' USING ERRCODE = 'restrict_violation';\n END IF;\n IF NEW.id <> OLD.id OR NEW.scope <> OLD.scope THEN\n RAISE EXCEPTION 'an incident never changes register' USING ERRCODE = 'restrict_violation';\n END IF;\n RETURN NEW;\nEND;\n$fn$;\nCREATE TRIGGER incident_guard BEFORE UPDATE OR DELETE ON ${c.schema}.incident FOR EACH ROW EXECUTE FUNCTION ${c.schema}.incident_guard();`,\n },\n ],\n});\n"],"mappings":";;;;;;;;;;AAeO,SAAS,iBAAiB,OAAmB,UAA6B,CAAC,GAAuB;AACvG,QAAM,OAAO,QAAQ,QAAQ;AAC7B,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,UAAU,OAAO,SAAS;AAC9B,aAAO,QAAQ,SAAS,OAAO,MAAM,UAAU,OAAO,QAAQ,EAAE,IAAI,CAAC;AAAA,IACvE;AAAA,IACA,MAAM,SAAS,IAAI,SAAS;AAC1B,UAAI,QAAQ,SAAS,KAAM,OAAM,MAAM,YAAY,IAAI,QAAQ,EAAE;AAAA,IACnE;AAAA,EACF;AACF;;;AChBO,IAAM,gBAAgB,EAAE,QAAQ,UAAU,KAAK,OAAO,eAAe,iBAAiB,MAAM,OAAO;AAGnG,IAAM,kBAAkB,EAAE,MAAM,QAAQ,UAAU,YAAY,QAAQ,SAAS;AAG/E,IAAM,QAAQ,EAAE,KAAK,OAAO,QAAQ,UAAU,MAAM,OAAO;AAG3D,IAAM,gBAAgB,EAAE,KAAK,OAAO,SAAS,UAAU;AAmIvD,IAAM,gBAAgB;AAAA,EAC3B,UAAU;AAAA,EACV,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,aAAa;AAAA,EACb,gBAAgB;AAClB;AAGO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACW,MACT,SACA;AACA,UAAM,OAAO;AAHJ;AAIT,SAAK,OAAO;AAAA,EACd;AAAA,EALW;AAMb;AAEA,IAAM,OAA8B,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,EAAE;AAM1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ACH,EAAE,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iCAoBU,EAAE,MAAM;AAAA,kBACvB,EAAE,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2DAiBiC,EAAE,MAAM,2CAA2C,EAAE,MAAM;AAAA,IAClH;AAAA,EACF;AACF,CAAC;","names":["ident","ident","ident","randomUUID","ident","ident","randomUUID"]}
package/dist/testkit.d.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { a as PrivacyStore } from './port-Ds9VVyC2.js';
1
+ import { I as IncidentStore, c as PrivacyStore } from './incident-DLXCVzpW.js';
2
2
  import '@krizaka/db';
3
3
 
4
4
  /** What every `PrivacyStore` adapter must do: the same behaviour behind the same port. `make` gives an empty store. */
5
5
  declare function privacyStoreContract(name: string, make: () => PrivacyStore | Promise<PrivacyStore>): void;
6
+ /** What every `IncidentStore` adapter must do. `make` gives an empty store. */
7
+ declare function incidentStoreContract(name: string, make: () => IncidentStore | Promise<IncidentStore>): void;
6
8
 
7
- export { privacyStoreContract };
9
+ export { incidentStoreContract, privacyStoreContract };
package/dist/testkit.js CHANGED
@@ -57,7 +57,66 @@ function privacyStoreContract(name, make) {
57
57
  expect(await store.requestsOf(CLIENT)).toEqual([]);
58
58
  });
59
59
  }
60
+ var awareDay = /* @__PURE__ */ new Date("2026-10-20T09:00:00.000Z");
61
+ var incident = (scope, overrides = {}) => ({
62
+ id: randomUUID(),
63
+ scope,
64
+ kind: "access",
65
+ awareAt: awareDay,
66
+ occurredAt: null,
67
+ description: "A staff account opened a file it should not have.",
68
+ information: ["lease"],
69
+ personsConcerned: 3,
70
+ measures: [{ at: awareDay, text: "Session revoked." }],
71
+ status: "open",
72
+ assessment: null,
73
+ caiNotice: null,
74
+ personsNotice: null,
75
+ drill: false,
76
+ openedBy: "admin",
77
+ openedAt: awareDay,
78
+ closedAt: null,
79
+ retainUntil: /* @__PURE__ */ new Date("2031-10-20T09:00:00.000Z"),
80
+ ...overrides
81
+ });
82
+ function incidentStoreContract(name, make) {
83
+ it(`${name}: writes an entry and reads it back whole, dates included`, async () => {
84
+ const store = await make();
85
+ const assessed = incident("t1", { status: "assessed", assessment: { sensitivity: "high", consequences: "medium", likelihood: "high", seriousInjury: true, rationale: "Leases.", assessedAt: at(5), assessedBy: "dpo" }, caiNotice: { sentAt: at(9), channel: "form", reference: "CAI-1" } });
86
+ await store.insert(assessed);
87
+ expect(await store.get("t1", assessed.id)).toEqual(assessed);
88
+ });
89
+ it(`${name}: never shows an entry to another scope`, async () => {
90
+ const store = await make();
91
+ const mine = incident("t1");
92
+ await store.insert(mine);
93
+ await store.insert(incident("t2"));
94
+ expect(await store.get("t2", mine.id)).toBeNull();
95
+ expect((await store.list("t1")).map((i) => i.id)).toEqual([mine.id]);
96
+ await store.save({ ...mine, scope: "t2", description: "changed" });
97
+ expect((await store.get("t1", mine.id))?.description).toBe(mine.description);
98
+ expect(await store.get("t2", mine.id)).toBeNull();
99
+ });
100
+ it(`${name}: lists the register oldest awareness first, and replaces an open entry`, async () => {
101
+ const store = await make();
102
+ const later = incident("t1", { awareAt: at(100) });
103
+ const earlier = incident("t1", { awareAt: at(-100) });
104
+ await store.insert(later);
105
+ await store.insert(earlier);
106
+ expect((await store.list("t1")).map((i) => i.id)).toEqual([earlier.id, later.id]);
107
+ await store.save({ ...later, personsConcerned: 12 });
108
+ expect((await store.get("t1", later.id, { lock: true }))?.personsConcerned).toBe(12);
109
+ });
110
+ it(`${name}: refuses to edit a closed entry`, async () => {
111
+ const store = await make();
112
+ const closed = incident("t1", { status: "closed", closedAt: at(1) });
113
+ await store.insert(closed);
114
+ await expect(store.save({ ...closed, description: "rewritten" })).rejects.toThrow();
115
+ expect((await store.get("t1", closed.id))?.description).toBe(closed.description);
116
+ });
117
+ }
60
118
  export {
119
+ incidentStoreContract,
61
120
  privacyStoreContract
62
121
  };
63
122
  //# sourceMappingURL=testkit.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/testkit.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nimport { expect, it } from \"vitest\";\n\nimport type { ConsentRecord, PrivacyRequest, PrivacyStore, Subject } from \"./port\";\n\nconst T0 = new Date(\"2026-10-26T12:00:00.000Z\");\nconst at = (seconds: number) => new Date(T0.valueOf() + seconds * 1000);\nconst ERIC: Subject = { kind: \"account\", id: \"11111111-1111-4111-8111-111111111111\" };\nconst CLIENT: Subject = { kind: \"client\", id: \"c-42\" };\n\nconst consent = (subject: Subject, purpose: string, granted: boolean, seconds: number): ConsentRecord => ({ id: randomUUID(), subject, purpose, version: \"2026-10-01\", granted, means: \"checkbox\", at: at(seconds) });\nconst request = (subject: Subject, kind: PrivacyRequest[\"kind\"], seconds: number): PrivacyRequest => ({ id: randomUUID(), subject, kind, status: \"requested\", requestedAt: at(seconds), completedAt: null, failure: null });\n\n/** What every `PrivacyStore` adapter must do: the same behaviour behind the same port. `make` gives an empty store. */\nexport function privacyStoreContract(name: string, make: () => PrivacyStore | Promise<PrivacyStore>) {\n it(`${name}: knows nothing about a person who never said anything`, async () => {\n const store = await make();\n expect(await store.latestConsent(ERIC, \"marketing\")).toBeNull();\n expect(await store.consentHistory(ERIC)).toEqual([]);\n });\n\n it(`${name}: the consent with the last word wins, and the history keeps every one in order`, async () => {\n const store = await make();\n const first = consent(ERIC, \"marketing\", true, 0);\n const second = consent(ERIC, \"marketing\", false, 10);\n const third = consent(ERIC, \"marketing\", true, 20);\n for (const c of [first, second, third]) await store.insertConsent(c);\n expect(await store.latestConsent(ERIC, \"marketing\")).toEqual(third);\n expect((await store.consentHistory(ERIC)).map((c) => c.id)).toEqual([first.id, second.id, third.id]);\n });\n\n it(`${name}: keeps purposes and subjects apart, whatever the kind of subject`, async () => {\n const store = await make();\n await store.insertConsent(consent(ERIC, \"marketing\", true, 0));\n await store.insertConsent(consent(ERIC, \"screening\", false, 1));\n await store.insertConsent(consent(CLIENT, \"marketing\", false, 2));\n expect((await store.latestConsent(ERIC, \"marketing\"))?.granted).toBe(true);\n expect((await store.latestConsent(ERIC, \"screening\"))?.granted).toBe(false);\n expect((await store.latestConsent(CLIENT, \"marketing\"))?.granted).toBe(false);\n expect(await store.consentHistory(CLIENT)).toHaveLength(1);\n expect(await store.latestConsent({ kind: \"client\", id: ERIC.id }, \"marketing\")).toBeNull(); // same id, another kind\n });\n\n it(`${name}: records the proof: the notice version, the means and the instant`, async () => {\n const store = await make();\n const c = { ...consent(ERIC, \"marketing\", true, 5), version: \"v7\", means: \"link\" };\n await store.insertConsent(c);\n const found = await store.latestConsent(ERIC, \"marketing\");\n expect(found).toMatchObject({ version: \"v7\", means: \"link\", granted: true });\n expect(found!.at.toISOString()).toBe(at(5).toISOString());\n });\n\n it(`${name}: follows a request from asked to completed, or failed with a code`, async () => {\n const store = await make();\n const done = request(ERIC, \"export\", 0);\n const broke = request(ERIC, \"erasure\", 10);\n await store.insertRequest(done);\n await store.insertRequest(broke);\n await store.finishRequest(done.id, { status: \"completed\", at: at(3) });\n await store.finishRequest(broke.id, { status: \"failed\", at: at(11), failure: \"CONTRIBUTOR_FAILED\" });\n expect(await store.getRequest(done.id)).toMatchObject({ kind: \"export\", status: \"completed\", failure: null });\n expect((await store.getRequest(done.id))!.completedAt!.toISOString()).toBe(at(3).toISOString());\n expect(await store.getRequest(broke.id)).toMatchObject({ kind: \"erasure\", status: \"failed\", failure: \"CONTRIBUTOR_FAILED\" });\n expect(await store.getRequest(randomUUID())).toBeNull();\n expect((await store.requestsOf(ERIC)).map((r) => r.id)).toEqual([broke.id, done.id]); // newest first\n expect(await store.requestsOf(CLIENT)).toEqual([]);\n });\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,QAAQ,UAAU;AAI3B,IAAM,KAAK,oBAAI,KAAK,0BAA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,EAAE;AACzC,UAAM,MAAM,cAAc,IAAI;AAC9B,UAAM,MAAM,cAAc,KAAK;AAC/B,UAAM,MAAM,cAAc,KAAK,IAAI,EAAE,QAAQ,aAAa,IAAI,GAAG,CAAC,EAAE,CAAC;AACrE,UAAM,MAAM,cAAc,MAAM,IAAI,EAAE,QAAQ,UAAU,IAAI,GAAG,EAAE,GAAG,SAAS,qBAAqB,CAAC;AACnG,WAAO,MAAM,MAAM,WAAW,KAAK,EAAE,CAAC,EAAE,cAAc,EAAE,MAAM,UAAU,QAAQ,aAAa,SAAS,KAAK,CAAC;AAC5G,YAAQ,MAAM,MAAM,WAAW,KAAK,EAAE,GAAI,YAAa,YAAY,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,YAAY,CAAC;AAC9F,WAAO,MAAM,MAAM,WAAW,MAAM,EAAE,CAAC,EAAE,cAAc,EAAE,MAAM,WAAW,QAAQ,UAAU,SAAS,qBAAqB,CAAC;AAC3H,WAAO,MAAM,MAAM,WAAW,WAAW,CAAC,CAAC,EAAE,SAAS;AACtD,YAAQ,MAAM,MAAM,WAAW,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,QAAQ,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;AACnF,WAAO,MAAM,MAAM,WAAW,MAAM,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACnD,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/testkit.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nimport { expect, it } from \"vitest\";\n\nimport type { Incident, IncidentStore } from \"./incident\";\nimport type { ConsentRecord, PrivacyRequest, PrivacyStore, Subject } from \"./port\";\n\nconst T0 = new Date(\"2026-10-26T12:00:00.000Z\");\nconst at = (seconds: number) => new Date(T0.valueOf() + seconds * 1000);\nconst ERIC: Subject = { kind: \"account\", id: \"11111111-1111-4111-8111-111111111111\" };\nconst CLIENT: Subject = { kind: \"client\", id: \"c-42\" };\n\nconst consent = (subject: Subject, purpose: string, granted: boolean, seconds: number): ConsentRecord => ({ id: randomUUID(), subject, purpose, version: \"2026-10-01\", granted, means: \"checkbox\", at: at(seconds) });\nconst request = (subject: Subject, kind: PrivacyRequest[\"kind\"], seconds: number): PrivacyRequest => ({ id: randomUUID(), subject, kind, status: \"requested\", requestedAt: at(seconds), completedAt: null, failure: null });\n\n/** What every `PrivacyStore` adapter must do: the same behaviour behind the same port. `make` gives an empty store. */\nexport function privacyStoreContract(name: string, make: () => PrivacyStore | Promise<PrivacyStore>) {\n it(`${name}: knows nothing about a person who never said anything`, async () => {\n const store = await make();\n expect(await store.latestConsent(ERIC, \"marketing\")).toBeNull();\n expect(await store.consentHistory(ERIC)).toEqual([]);\n });\n\n it(`${name}: the consent with the last word wins, and the history keeps every one in order`, async () => {\n const store = await make();\n const first = consent(ERIC, \"marketing\", true, 0);\n const second = consent(ERIC, \"marketing\", false, 10);\n const third = consent(ERIC, \"marketing\", true, 20);\n for (const c of [first, second, third]) await store.insertConsent(c);\n expect(await store.latestConsent(ERIC, \"marketing\")).toEqual(third);\n expect((await store.consentHistory(ERIC)).map((c) => c.id)).toEqual([first.id, second.id, third.id]);\n });\n\n it(`${name}: keeps purposes and subjects apart, whatever the kind of subject`, async () => {\n const store = await make();\n await store.insertConsent(consent(ERIC, \"marketing\", true, 0));\n await store.insertConsent(consent(ERIC, \"screening\", false, 1));\n await store.insertConsent(consent(CLIENT, \"marketing\", false, 2));\n expect((await store.latestConsent(ERIC, \"marketing\"))?.granted).toBe(true);\n expect((await store.latestConsent(ERIC, \"screening\"))?.granted).toBe(false);\n expect((await store.latestConsent(CLIENT, \"marketing\"))?.granted).toBe(false);\n expect(await store.consentHistory(CLIENT)).toHaveLength(1);\n expect(await store.latestConsent({ kind: \"client\", id: ERIC.id }, \"marketing\")).toBeNull(); // same id, another kind\n });\n\n it(`${name}: records the proof: the notice version, the means and the instant`, async () => {\n const store = await make();\n const c = { ...consent(ERIC, \"marketing\", true, 5), version: \"v7\", means: \"link\" };\n await store.insertConsent(c);\n const found = await store.latestConsent(ERIC, \"marketing\");\n expect(found).toMatchObject({ version: \"v7\", means: \"link\", granted: true });\n expect(found!.at.toISOString()).toBe(at(5).toISOString());\n });\n\n it(`${name}: follows a request from asked to completed, or failed with a code`, async () => {\n const store = await make();\n const done = request(ERIC, \"export\", 0);\n const broke = request(ERIC, \"erasure\", 10);\n await store.insertRequest(done);\n await store.insertRequest(broke);\n await store.finishRequest(done.id, { status: \"completed\", at: at(3) });\n await store.finishRequest(broke.id, { status: \"failed\", at: at(11), failure: \"CONTRIBUTOR_FAILED\" });\n expect(await store.getRequest(done.id)).toMatchObject({ kind: \"export\", status: \"completed\", failure: null });\n expect((await store.getRequest(done.id))!.completedAt!.toISOString()).toBe(at(3).toISOString());\n expect(await store.getRequest(broke.id)).toMatchObject({ kind: \"erasure\", status: \"failed\", failure: \"CONTRIBUTOR_FAILED\" });\n expect(await store.getRequest(randomUUID())).toBeNull();\n expect((await store.requestsOf(ERIC)).map((r) => r.id)).toEqual([broke.id, done.id]); // newest first\n expect(await store.requestsOf(CLIENT)).toEqual([]);\n });\n}\n\nconst awareDay = new Date(\"2026-10-20T09:00:00.000Z\");\nconst incident = (scope: string, overrides: Partial<Incident> = {}): Incident => ({\n id: randomUUID(),\n scope,\n kind: \"access\",\n awareAt: awareDay,\n occurredAt: null,\n description: \"A staff account opened a file it should not have.\",\n information: [\"lease\"],\n personsConcerned: 3,\n measures: [{ at: awareDay, text: \"Session revoked.\" }],\n status: \"open\",\n assessment: null,\n caiNotice: null,\n personsNotice: null,\n drill: false,\n openedBy: \"admin\",\n openedAt: awareDay,\n closedAt: null,\n retainUntil: new Date(\"2031-10-20T09:00:00.000Z\"),\n ...overrides,\n});\n\n/** What every `IncidentStore` adapter must do. `make` gives an empty store. */\nexport function incidentStoreContract(name: string, make: () => IncidentStore | Promise<IncidentStore>) {\n it(`${name}: writes an entry and reads it back whole, dates included`, async () => {\n const store = await make();\n const assessed = incident(\"t1\", { status: \"assessed\", assessment: { sensitivity: \"high\", consequences: \"medium\", likelihood: \"high\", seriousInjury: true, rationale: \"Leases.\", assessedAt: at(5), assessedBy: \"dpo\" }, caiNotice: { sentAt: at(9), channel: \"form\", reference: \"CAI-1\" } });\n await store.insert(assessed);\n expect(await store.get(\"t1\", assessed.id)).toEqual(assessed);\n });\n\n it(`${name}: never shows an entry to another scope`, async () => {\n const store = await make();\n const mine = incident(\"t1\");\n await store.insert(mine);\n await store.insert(incident(\"t2\"));\n expect(await store.get(\"t2\", mine.id)).toBeNull();\n expect((await store.list(\"t1\")).map((i) => i.id)).toEqual([mine.id]);\n await store.save({ ...mine, scope: \"t2\", description: \"changed\" });\n expect((await store.get(\"t1\", mine.id))?.description).toBe(mine.description);\n expect(await store.get(\"t2\", mine.id)).toBeNull();\n });\n\n it(`${name}: lists the register oldest awareness first, and replaces an open entry`, async () => {\n const store = await make();\n const later = incident(\"t1\", { awareAt: at(100) });\n const earlier = incident(\"t1\", { awareAt: at(-100) });\n await store.insert(later);\n await store.insert(earlier);\n expect((await store.list(\"t1\")).map((i) => i.id)).toEqual([earlier.id, later.id]);\n await store.save({ ...later, personsConcerned: 12 });\n expect((await store.get(\"t1\", later.id, { lock: true }))?.personsConcerned).toBe(12);\n });\n\n it(`${name}: refuses to edit a closed entry`, async () => {\n const store = await make();\n const closed = incident(\"t1\", { status: \"closed\", closedAt: at(1) });\n await store.insert(closed);\n await expect(store.save({ ...closed, description: \"rewritten\" })).rejects.toThrow();\n expect((await store.get(\"t1\", closed.id))?.description).toBe(closed.description);\n });\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,QAAQ,UAAU;AAK3B,IAAM,KAAK,oBAAI,KAAK,0BAA0B;AAC9C,IAAM,KAAK,CAAC,YAAoB,IAAI,KAAK,GAAG,QAAQ,IAAI,UAAU,GAAI;AACtE,IAAM,OAAgB,EAAE,MAAM,WAAW,IAAI,uCAAuC;AACpF,IAAM,SAAkB,EAAE,MAA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,GAAG,IAAI,EAAE,CAAC;AACpD,UAAM,MAAM,OAAO,KAAK;AACxB,UAAM,MAAM,OAAO,OAAO;AAC1B,YAAQ,MAAM,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,QAAQ,CAAC,QAAQ,IAAI,MAAM,EAAE,CAAC;AAChF,UAAM,MAAM,KAAK,EAAE,GAAG,OAAO,kBAAkB,GAAG,CAAC;AACnD,YAAQ,MAAM,MAAM,IAAI,MAAM,MAAM,IAAI,EAAE,MAAM,KAAK,CAAC,IAAI,gBAAgB,EAAE,KAAK,EAAE;AAAA,EACrF,CAAC;AAED,KAAG,GAAG,IAAI,oCAAoC,YAAY;AACxD,UAAM,QAAQ,MAAM,KAAK;AACzB,UAAM,SAAS,SAAS,MAAM,EAAE,QAAQ,UAAU,UAAU,GAAG,CAAC,EAAE,CAAC;AACnE,UAAM,MAAM,OAAO,MAAM;AACzB,UAAM,OAAO,MAAM,KAAK,EAAE,GAAG,QAAQ,aAAa,YAAY,CAAC,CAAC,EAAE,QAAQ,QAAQ;AAClF,YAAQ,MAAM,MAAM,IAAI,MAAM,OAAO,EAAE,IAAI,WAAW,EAAE,KAAK,OAAO,WAAW;AAAA,EACjF,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krizaka/privacy",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Privacy for every Krizaka product (Loi 25): consents by purpose written once with the notice version shown, an export assembled from every module that holds the person's data, an erasure that runs in one transaction and leaves a record without personal data, and retention per purpose set by the admin. A port each module implements; no database client, no wall clock.",
5
5
  "keywords": [
6
6
  "krizaka",
@@ -58,12 +58,12 @@
58
58
  "typescript": "^5.9.3",
59
59
  "vitest": "^4.1.11",
60
60
  "zod": "^4.6.7",
61
- "@krizaka/config": "^0.8.1"
61
+ "@krizaka/config": "^0.10.0"
62
62
  },
63
63
  "dependencies": {
64
64
  "@krizaka/db": "^0.2.0",
65
- "@krizaka/settings": "^0.4.0",
66
- "@krizaka/time": "^0.1.0"
65
+ "@krizaka/time": "^0.1.0",
66
+ "@krizaka/settings": "^0.5.0"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "vitest": ">=4",
@@ -1,144 +0,0 @@
1
- import { Query } from '@krizaka/db';
2
-
3
- /**
4
- * The ports of « privacy » (Loi 25): consents by purpose, the person's data exported from every module that holds it, and erased
5
- * from every module in one transaction. Generic: no product import, no database client (a `Query` comes in), no wall clock (a
6
- * `Clock` comes in). What a module holds, and what erasing it means (blanking a row, deleting a file, keeping an invoice for six
7
- * years), is the module's: it implements `PrivacyContributor`.
8
- */
9
-
10
- /**
11
- * Whose data it is. Usually an account (`{ kind: "account", id }`), but a product's data subject is not always an account: Akinaza's
12
- * is a client file, Yomizaka's a tenant on an application. The `kind` says which.
13
- */
14
- interface Subject {
15
- /** What the id identifies: `account`, `client`, `application`. Lower-case letters, digits and `_`. */
16
- kind: string;
17
- /** The product's id for it (a UUID, a slug). */
18
- id: string;
19
- }
20
- /** What a product records when a person agrees, or withdraws. */
21
- interface ConsentInput {
22
- subject: Subject;
23
- /** What the person agreed to (`marketing`, `screening`, `reminders`): one of the product's declared purposes. */
24
- purpose: string;
25
- /** The version of the notice shown to them: the proof of WHAT they agreed to. */
26
- version: string;
27
- granted: boolean;
28
- /** How they said it (`checkbox`, `link`, `verbal`, `erasure`). */
29
- means?: string | undefined;
30
- }
31
- /** A consent as written. It is never edited: a withdrawal is a new row. */
32
- interface ConsentRecord {
33
- id: string;
34
- subject: Subject;
35
- purpose: string;
36
- version: string;
37
- granted: boolean;
38
- means: string | null;
39
- at: Date;
40
- }
41
- declare const REQUEST_KIND: {
42
- readonly export: "export";
43
- readonly erasure: "erasure";
44
- };
45
- type RequestKind = (typeof REQUEST_KIND)[keyof typeof REQUEST_KIND];
46
- declare const REQUEST_STATUS: {
47
- readonly requested: "requested";
48
- readonly completed: "completed";
49
- readonly failed: "failed";
50
- };
51
- type RequestStatus = (typeof REQUEST_STATUS)[keyof typeof REQUEST_STATUS];
52
- /** An export or an erasure asked for, and where it stands. It holds an id of the subject and no other personal data. */
53
- interface PrivacyRequest {
54
- id: string;
55
- subject: Subject;
56
- kind: RequestKind;
57
- status: RequestStatus;
58
- requestedAt: Date;
59
- completedAt: Date | null;
60
- /** A code, never a message that could carry data. */
61
- failure: string | null;
62
- }
63
- /**
64
- * A module that holds personal data. The product registers one per module and one for its own tables.
65
- *
66
- * - `exportFor` returns what the module holds about the subject, as JSON-able data.
67
- * - `eraseFor` erases or anonymises it, through the transaction it is given, so the whole erasure commits or rolls back together.
68
- * A side effect outside the database (a file in storage) is not done here: append it to the outbox in the same transaction.
69
- * - `purgeExpired` (optional) removes what the retention of a purpose says is past, for everyone.
70
- */
71
- interface PrivacyContributor {
72
- /** A stable name, the key of its part in the export (`audit`, `orders`). */
73
- name: string;
74
- exportFor(query: Query, subject: Subject): Promise<unknown>;
75
- eraseFor(tx: Query, subject: Subject): Promise<void>;
76
- purgeExpired?(tx: Query, input: {
77
- purpose: string;
78
- before: Date;
79
- }): Promise<number>;
80
- }
81
- /** The whole export of a subject: one document, a part per contributor. */
82
- interface ExportDocument {
83
- format: 1;
84
- subject: Subject;
85
- generatedAt: string;
86
- modules: Record<string, unknown>;
87
- }
88
- /** Where consents and requests live. Every adapter runs `privacyStoreContract` (`@krizaka/privacy/testkit`). */
89
- interface PrivacyStore {
90
- insertConsent(consent: ConsentRecord): Promise<void>;
91
- /** The consent with the last word for this purpose, or null when the person never said anything. */
92
- latestConsent(subject: Subject, purpose: string): Promise<ConsentRecord | null>;
93
- /** Every consent of the subject, oldest first. */
94
- consentHistory(subject: Subject): Promise<ConsentRecord[]>;
95
- insertRequest(request: PrivacyRequest): Promise<void>;
96
- getRequest(id: string): Promise<PrivacyRequest | null>;
97
- finishRequest(id: string, outcome: {
98
- status: "completed" | "failed";
99
- at: Date;
100
- failure?: string;
101
- }): Promise<void>;
102
- requestsOf(subject: Subject): Promise<PrivacyRequest[]>;
103
- }
104
- /** The structural slice of `@krizaka/audit` this package writes through, so it adds no dependency. */
105
- interface AuditPort {
106
- record(query: Query, entry: {
107
- actorId: string | null;
108
- actorLabel: string;
109
- action: string;
110
- target?: {
111
- type: string;
112
- id: string;
113
- } | null;
114
- detail?: Record<string, unknown>;
115
- }): Promise<unknown>;
116
- }
117
- /** The structural slice of `@krizaka/outbox` used for a large export. */
118
- interface OutboxPort {
119
- append(tx: Query, message: {
120
- topic: string;
121
- type: string;
122
- payload: unknown;
123
- id?: string;
124
- }): Promise<unknown>;
125
- }
126
- declare const PRIVACY_CODE: {
127
- readonly badSubject: "PRIVACY_BAD_SUBJECT";
128
- readonly badPurpose: "PRIVACY_BAD_PURPOSE";
129
- readonly badConsent: "PRIVACY_BAD_CONSENT";
130
- readonly unknownRequest: "PRIVACY_UNKNOWN_REQUEST";
131
- readonly notAnExport: "PRIVACY_NOT_AN_EXPORT";
132
- readonly alreadyDone: "PRIVACY_ALREADY_DONE";
133
- readonly contributorFailed: "PRIVACY_CONTRIBUTOR_FAILED";
134
- readonly noOutbox: "PRIVACY_NO_OUTBOX";
135
- };
136
- type PrivacyCode = (typeof PRIVACY_CODE)[keyof typeof PRIVACY_CODE];
137
- declare class PrivacyError extends Error {
138
- readonly code: PrivacyCode;
139
- constructor(code: PrivacyCode, message: string, options?: {
140
- cause?: unknown;
141
- });
142
- }
143
-
144
- export { type AuditPort as A, type ConsentInput as C, type ExportDocument as E, type OutboxPort as O, type PrivacyContributor as P, REQUEST_KIND as R, type Subject as S, type PrivacyStore as a, type ConsentRecord as b, type PrivacyRequest as c, PRIVACY_CODE as d, type PrivacyCode as e, PrivacyError as f, REQUEST_STATUS as g, type RequestKind as h, type RequestStatus as i };