@krizaka/privacy 0.2.2 → 0.2.4

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
@@ -1,6 +1,6 @@
1
1
  # @krizaka/privacy
2
2
 
3
- Privacy for every Krizaka product (Loi 25): **consents by purpose**, the person's data **exported** from every module that holds it, **erased** from every module in one transaction, and **retention** per purpose set by the admin. Six products had a partial copy (Yomizaka's consents, export and delete; Akinaza's `recordConsent` and `eraseClient`; the asynchronous export and the admin exports the products carried; the consent columns). This is the one version.
3
+ Privacy for every Krizaka product (Loi 25): **consents by purpose**, the person's data **exported** from every module that holds it, **erased** from every module in one transaction, and **retention** per purpose set by the admin. Six products had a partial copy (Verikora's consents, export and delete; Folioviv's `recordConsent` and `eraseClient`; the asynchronous export and the admin exports the products carried; the consent columns). This is the one version.
4
4
 
5
5
  ```ts
6
6
  import { transaction } from "@krizaka/db";
@@ -11,22 +11,29 @@ emitMigration(privacySchema, 1, { tables: {} }); // commit the SQL once, in your
11
11
 
12
12
  const privacy = createPrivacy({
13
13
  clock: { now: () => new Date() },
14
- purposes: ["marketing", "screening"], // the purposes the product declares
14
+ purposes: ["marketing", "screening"], // the purposes the product declares
15
15
  contributors: [auditContributor(audit), ordersContributor, filesContributor], // every module that holds personal data
16
16
  transaction: (work) => transaction(connect, work),
17
17
  retentionDays: retentionFromSettings((key) => settings.get(key)), // privacy.retention.<purpose>Days
18
- audit, outbox, // optional: the erasure is recorded; a large export goes through the outbox
18
+ audit,
19
+ outbox, // optional: the erasure is recorded; a large export goes through the outbox
19
20
  });
20
21
 
21
- const eric = { kind: "account", id: account.id }; // a subject is a kind and an id: an account, a client file, an application
22
- await privacy.recordConsent(query, { subject: eric, purpose: "marketing", version: "2026-10-01", granted: true, means: "checkbox" });
23
- await privacy.hasConsent(query, eric, "marketing"); // the consent with the last word; never having said anything is a no
22
+ const eric = { kind: "account", id: account.id }; // a subject is a kind and an id: an account, a client file, an application
23
+ await privacy.recordConsent(query, {
24
+ subject: eric,
25
+ purpose: "marketing",
26
+ version: "2026-10-01",
27
+ granted: true,
28
+ means: "checkbox",
29
+ });
30
+ await privacy.hasConsent(query, eric, "marketing"); // the consent with the last word; never having said anything is a no
24
31
  const document = await privacy.exportSubject(query, eric); // { format: 1, subject, generatedAt, modules: { audit, orders, files } }
25
- await privacy.eraseSubject(eric); // every contributor, one transaction, consents withdrawn, a record without personal data
26
- await privacy.purge(query); // from the product's job: what is past each purpose's retention
32
+ await privacy.eraseSubject(eric); // every contributor, one transaction, consents withdrawn, a record without personal data
33
+ await privacy.purge(query); // from the product's job: what is past each purpose's retention
27
34
  ```
28
35
 
29
- - **A subject is a kind and an id**, not necessarily an account: Akinaza's data subject is a client file, Yomizaka's a tenant on an application.
36
+ - **A subject is a kind and an id**, not necessarily an account: Folioviv's data subject is a client file, Verikora's a tenant on an application.
30
37
  - **`privacy.consent` is written once**: a trigger refuses every update; a withdrawal is a new row; the row with the last `seq` wins. Each consent holds the **version of the notice shown**, the means and the instant: the proof of what the person agreed to.
31
38
  - **`PrivacyContributor`** is the port every module implements: `exportFor(query, subject)`, `eraseFor(tx, subject)` (erase or anonymise through the transaction it is given: a module that keeps an invoice for six years blanks the name and keeps the row), and optionally `purgeExpired(tx, { purpose, before })`. The product registers one for its own tables. `auditContributor(audit)` is provided for `@krizaka/audit` (the export lists the actor's entries; the erasure detaches them and keeps the facts). A side effect outside the database (a file in storage) is not done in `eraseFor`: append it to the outbox in the same transaction.
32
39
  - **Export** assembles one JSON document with a part per contributor; a contributor that fails fails the export, naming it (a silent omission would be a lie). **A large export** is asked in the caller's transaction with `requestExport(tx, subject)` (it appends `evt.privacy.export_requested.v1` to the outbox, holding the request id only) and a worker calls `fulfilExport(query, requestId, deliver)`: the asynchronous mode.
@@ -41,15 +48,31 @@ The register that the Act respecting the protection of personal information in t
41
48
  ```ts
42
49
  import { createIncidentRegister, registerToCsv, suggestSeriousInjury } from "@krizaka/privacy";
43
50
 
44
- emitMigration(privacySchema, 2, { tables: {} }); // privacy.incident (after version 1)
51
+ emitMigration(privacySchema, 2, { tables: {} }); // privacy.incident (after version 1)
45
52
  const incidents = createIncidentRegister({ clock: { now: () => new Date() }, audit });
46
53
  const admin = { id: account.id, label: account.name };
47
54
 
48
- const { id } = await incidents.open(query, { scope: tenantId, kind: "access", description: "…", information: ["lease"], personsConcerned: 3 }, admin);
55
+ const { id } = await incidents.open(
56
+ query,
57
+ { scope: tenantId, kind: "access", description: "…", information: ["lease"], personsConcerned: 3 },
58
+ admin,
59
+ );
49
60
  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
61
+ await incidents.assess(
62
+ query,
63
+ tenantId,
64
+ id,
65
+ {
66
+ sensitivity: "high",
67
+ consequences: "high",
68
+ likelihood: "medium",
69
+ seriousInjury: suggestSeriousInjury(factors),
70
+ rationale: "…",
71
+ },
72
+ admin,
73
+ );
74
+ await incidents.recordNotice(query, tenantId, id, "cai", { channel: "form" }, admin); // and "persons"
75
+ await incidents.close(query, tenantId, id, admin); // a serious injury closes once both notices are recorded
53
76
  registerToCsv((await incidents.exportRegister(query, tenantId)).entries);
54
77
  ```
55
78
 
@@ -25,11 +25,20 @@ var KIND = /^[a-z][a-z0-9_]{0,39}$/;
25
25
  var PURPOSE = /^[a-z][a-z0-9_-]{0,39}$/;
26
26
  var MAX_ID = 200;
27
27
  function checkSubject(subject) {
28
- if (!KIND.test(subject.kind)) throw new PrivacyError(PRIVACY_CODE.badSubject, `subject kind \xAB ${subject.kind} \xBB: lower-case letters, digits and _, starting with a letter`);
29
- if (subject.id.length < 1 || subject.id.length > MAX_ID) throw new PrivacyError(PRIVACY_CODE.badSubject, `subject id: 1 to ${MAX_ID} characters`);
28
+ if (!KIND.test(subject.kind))
29
+ throw new PrivacyError(
30
+ PRIVACY_CODE.badSubject,
31
+ `subject kind \xAB ${subject.kind} \xBB: lower-case letters, digits and _, starting with a letter`
32
+ );
33
+ if (subject.id.length < 1 || subject.id.length > MAX_ID)
34
+ throw new PrivacyError(PRIVACY_CODE.badSubject, `subject id: 1 to ${MAX_ID} characters`);
30
35
  }
31
36
  function checkPurpose(purpose) {
32
- if (!PURPOSE.test(purpose)) throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose \xAB ${purpose} \xBB: lower-case letters, digits, _ and -, starting with a letter, at most 40 characters`);
37
+ if (!PURPOSE.test(purpose))
38
+ throw new PrivacyError(
39
+ PRIVACY_CODE.badPurpose,
40
+ `purpose \xAB ${purpose} \xBB: lower-case letters, digits, _ and -, starting with a letter, at most 40 characters`
41
+ );
33
42
  }
34
43
 
35
44
  export {
@@ -40,4 +49,4 @@ export {
40
49
  checkSubject,
41
50
  checkPurpose
42
51
  };
43
- //# sourceMappingURL=chunk-PMXEX2LW.js.map
52
+ //# sourceMappingURL=chunk-DVWHUJHQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/port.ts","../src/rules.ts"],"sourcesContent":["/**\n * The ports of « privacy » (Loi 25): consents by purpose, the person's data exported from every module that holds it, and erased\n * from every module in one transaction. Generic: no product import, no database client (a `Query` comes in), no wall clock (a\n * `Clock` comes in). What a module holds, and what erasing it means (blanking a row, deleting a file, keeping an invoice for six\n * years), is the module's: it implements `PrivacyContributor`.\n */\nexport type { Clock, Query } from \"@krizaka/db\";\nimport type { Query } from \"@krizaka/db\";\n\n/**\n * Whose data it is. Usually an account (`{ kind: \"account\", id }`), but a product's data subject is not always an account: Folioviv's\n * is a client file, Verikora's a tenant on an application. The `kind` says which.\n */\nexport interface Subject {\n /** What the id identifies: `account`, `client`, `application`. Lower-case letters, digits and `_`. */\n kind: string;\n /** The product's id for it (a UUID, a slug). */\n id: string;\n}\n\n/** What a product records when a person agrees, or withdraws. */\nexport interface ConsentInput {\n subject: Subject;\n /** What the person agreed to (`marketing`, `screening`, `reminders`): one of the product's declared purposes. */\n purpose: string;\n /** The version of the notice shown to them: the proof of WHAT they agreed to. */\n version: string;\n granted: boolean;\n /** How they said it (`checkbox`, `link`, `verbal`, `erasure`). */\n means?: string | undefined;\n}\n\n/** A consent as written. It is never edited: a withdrawal is a new row. */\nexport interface ConsentRecord {\n id: string;\n subject: Subject;\n purpose: string;\n version: string;\n granted: boolean;\n means: string | null;\n at: Date;\n}\n\nexport const REQUEST_KIND = { export: \"export\", erasure: \"erasure\" } as const;\nexport type RequestKind = (typeof REQUEST_KIND)[keyof typeof REQUEST_KIND];\nexport const REQUEST_STATUS = { requested: \"requested\", completed: \"completed\", failed: \"failed\" } as const;\nexport type RequestStatus = (typeof REQUEST_STATUS)[keyof typeof REQUEST_STATUS];\n\n/** An export or an erasure asked for, and where it stands. It holds an id of the subject and no other personal data. */\nexport interface PrivacyRequest {\n id: string;\n subject: Subject;\n kind: RequestKind;\n status: RequestStatus;\n requestedAt: Date;\n completedAt: Date | null;\n /** A code, never a message that could carry data. */\n failure: string | null;\n}\n\n/**\n * A module that holds personal data. The product registers one per module and one for its own tables.\n *\n * - `exportFor` returns what the module holds about the subject, as JSON-able data.\n * - `eraseFor` erases or anonymises it, through the transaction it is given, so the whole erasure commits or rolls back together.\n * A side effect outside the database (a file in storage) is not done here: append it to the outbox in the same transaction.\n * - `purgeExpired` (optional) removes what the retention of a purpose says is past, for everyone.\n */\nexport interface PrivacyContributor {\n /** A stable name, the key of its part in the export (`audit`, `orders`). */\n name: string;\n exportFor(query: Query, subject: Subject): Promise<unknown>;\n eraseFor(tx: Query, subject: Subject): Promise<void>;\n purgeExpired?(tx: Query, input: { purpose: string; before: Date }): Promise<number>;\n}\n\n/** The whole export of a subject: one document, a part per contributor. */\nexport interface ExportDocument {\n format: 1;\n subject: Subject;\n generatedAt: string;\n modules: Record<string, unknown>;\n}\n\n/** Where consents and requests live. Every adapter runs `privacyStoreContract` (`@krizaka/privacy/testkit`). */\nexport interface PrivacyStore {\n insertConsent(consent: ConsentRecord): Promise<void>;\n /** The consent with the last word for this purpose, or null when the person never said anything. */\n latestConsent(subject: Subject, purpose: string): Promise<ConsentRecord | null>;\n /** Every consent of the subject, oldest first. */\n consentHistory(subject: Subject): Promise<ConsentRecord[]>;\n insertRequest(request: PrivacyRequest): Promise<void>;\n getRequest(id: string): Promise<PrivacyRequest | null>;\n finishRequest(id: string, outcome: { status: \"completed\" | \"failed\"; at: Date; failure?: string }): Promise<void>;\n requestsOf(subject: Subject): Promise<PrivacyRequest[]>;\n}\n\n/** The structural slice of `@krizaka/audit` this package writes through, so it adds no dependency. */\nexport interface AuditPort {\n record(\n query: Query,\n entry: {\n actorId: string | null;\n actorLabel: string;\n action: string;\n target?: { type: string; id: string } | null;\n detail?: Record<string, unknown>;\n },\n ): Promise<unknown>;\n}\n\n/** The structural slice of `@krizaka/outbox` used for a large export. */\nexport interface OutboxPort {\n append(tx: Query, message: { topic: string; type: string; payload: unknown; id?: string }): Promise<unknown>;\n}\n\nexport const PRIVACY_CODE = {\n badSubject: \"PRIVACY_BAD_SUBJECT\",\n badPurpose: \"PRIVACY_BAD_PURPOSE\",\n badConsent: \"PRIVACY_BAD_CONSENT\",\n unknownRequest: \"PRIVACY_UNKNOWN_REQUEST\",\n notAnExport: \"PRIVACY_NOT_AN_EXPORT\",\n alreadyDone: \"PRIVACY_ALREADY_DONE\",\n contributorFailed: \"PRIVACY_CONTRIBUTOR_FAILED\",\n noOutbox: \"PRIVACY_NO_OUTBOX\",\n} as const;\nexport type PrivacyCode = (typeof PRIVACY_CODE)[keyof typeof PRIVACY_CODE];\n\nexport class PrivacyError extends Error {\n constructor(\n readonly code: PrivacyCode,\n message: string,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = \"PrivacyError\";\n }\n}\n","import { PRIVACY_CODE, PrivacyError, type Subject } from \"./port\";\n\nconst KIND = /^[a-z][a-z0-9_]{0,39}$/;\nconst PURPOSE = /^[a-z][a-z0-9_-]{0,39}$/;\nconst MAX_ID = 200;\n\n/** @throws PrivacyError for a subject whose kind or id is not well formed */\nexport function checkSubject(subject: Subject): void {\n if (!KIND.test(subject.kind))\n throw new PrivacyError(\n PRIVACY_CODE.badSubject,\n `subject kind « ${subject.kind} »: lower-case letters, digits and _, starting with a letter`,\n );\n if (subject.id.length < 1 || subject.id.length > MAX_ID)\n throw new PrivacyError(PRIVACY_CODE.badSubject, `subject id: 1 to ${MAX_ID} characters`);\n}\n\n/** @throws PrivacyError for a purpose that is not lower-case letters, digits, `_` and `-`, starting with a letter */\nexport function checkPurpose(purpose: string): void {\n if (!PURPOSE.test(purpose))\n throw new PrivacyError(\n PRIVACY_CODE.badPurpose,\n `purpose « ${purpose} »: lower-case letters, digits, _ and -, starting with a letter, at most 40 characters`,\n );\n}\n"],"mappings":";AA2CO,IAAM,eAAe,EAAE,QAAQ,UAAU,SAAS,UAAU;AAE5D,IAAM,iBAAiB,EAAE,WAAW,aAAa,WAAW,aAAa,QAAQ,SAAS;AAuE1F,IAAM,eAAe;AAAA,EAC1B,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,UAAU;AACZ;AAGO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YACW,MACT,SACA,SACA;AACA,UAAM,SAAS,OAAO;AAJb;AAKT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAOb;;;ACvIA,IAAM,OAAO;AACb,IAAM,UAAU;AAChB,IAAM,SAAS;AAGR,SAAS,aAAa,SAAwB;AACnD,MAAI,CAAC,KAAK,KAAK,QAAQ,IAAI;AACzB,UAAM,IAAI;AAAA,MACR,aAAa;AAAA,MACb,qBAAkB,QAAQ,IAAI;AAAA,IAChC;AACF,MAAI,QAAQ,GAAG,SAAS,KAAK,QAAQ,GAAG,SAAS;AAC/C,UAAM,IAAI,aAAa,aAAa,YAAY,oBAAoB,MAAM,aAAa;AAC3F;AAGO,SAAS,aAAa,SAAuB;AAClD,MAAI,CAAC,QAAQ,KAAK,OAAO;AACvB,UAAM,IAAI;AAAA,MACR,aAAa;AAAA,MACb,gBAAa,OAAO;AAAA,IACtB;AACJ;","names":[]}
@@ -8,8 +8,8 @@ import { Query, Clock } from '@krizaka/db';
8
8
  */
9
9
 
10
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.
11
+ * Whose data it is. Usually an account (`{ kind: "account", id }`), but a product's data subject is not always an account: Folioviv's
12
+ * is a client file, Verikora's a tenant on an application. The `kind` says which.
13
13
  */
14
14
  interface Subject {
15
15
  /** What the id identifies: `account`, `client`, `application`. Lower-case letters, digits and `_`. */
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, 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';
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-B4bxcEgY.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-B4bxcEgY.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 {
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  REQUEST_STATUS,
6
6
  checkPurpose,
7
7
  checkSubject
8
- } from "./chunk-PMXEX2LW.js";
8
+ } from "./chunk-DVWHUJHQ.js";
9
9
 
10
10
  // src/contributors.ts
11
11
  function auditContributor(audit, options = {}) {
@@ -44,7 +44,11 @@ var IncidentError = class extends Error {
44
44
  };
45
45
  var RANK = { low: 0, medium: 1, high: 2 };
46
46
  function suggestSeriousInjury(factors) {
47
- const { sensitivity, consequences, likelihood } = { sensitivity: RANK[factors.sensitivity], consequences: RANK[factors.consequences], likelihood: RANK[factors.likelihood] };
47
+ const { sensitivity, consequences, likelihood } = {
48
+ sensitivity: RANK[factors.sensitivity],
49
+ consequences: RANK[factors.consequences],
50
+ likelihood: RANK[factors.likelihood]
51
+ };
48
52
  if (sensitivity === RANK.high && likelihood >= RANK.medium) return true;
49
53
  if (consequences === RANK.high && likelihood === RANK.high) return true;
50
54
  return sensitivity >= RANK.medium && consequences >= RANK.medium && likelihood === RANK.high;
@@ -60,10 +64,44 @@ var cell = (value) => {
60
64
  const safe = FORMULA.test(text) ? `'${text}` : text;
61
65
  return /[",\n\r]/.test(safe) ? `"${safe.replaceAll('"', '""')}"` : safe;
62
66
  };
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"];
67
+ var REGISTER_CSV_COLUMNS = [
68
+ "id",
69
+ "kind",
70
+ "aware_at",
71
+ "occurred_at",
72
+ "description",
73
+ "information",
74
+ "persons_concerned",
75
+ "serious_injury",
76
+ "assessed_at",
77
+ "cai_notice_at",
78
+ "persons_notice_at",
79
+ "measures",
80
+ "status",
81
+ "drill",
82
+ "closed_at",
83
+ "retain_until"
84
+ ];
64
85
  function registerToCsv(entries) {
65
86
  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(",")
87
+ (e) => [
88
+ e.id,
89
+ e.kind,
90
+ e.awareAt,
91
+ e.occurredAt,
92
+ e.description,
93
+ e.information.join("; "),
94
+ e.personsConcerned,
95
+ e.assessment?.seriousInjury ?? "",
96
+ e.assessment?.assessedAt ?? "",
97
+ e.caiNotice?.sentAt ?? "",
98
+ e.personsNotice?.sentAt ?? "",
99
+ e.measures.map((m) => m.text).join("; "),
100
+ e.status,
101
+ e.drill,
102
+ e.closedAt,
103
+ e.retainUntil
104
+ ].map(cell).join(",")
67
105
  );
68
106
  return [REGISTER_CSV_COLUMNS.join(","), ...rows].join("\r\n") + "\r\n";
69
107
  }
@@ -122,10 +160,32 @@ var toIncident = (r) => ({
122
160
  var json = (value) => value === null ? null : JSON.stringify(value);
123
161
  function dbIncidentStore(query, schema = "privacy") {
124
162
  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];
163
+ const values = (i) => [
164
+ i.id,
165
+ i.scope,
166
+ i.kind,
167
+ i.awareAt,
168
+ i.occurredAt,
169
+ i.description,
170
+ i.information,
171
+ i.personsConcerned,
172
+ JSON.stringify(i.measures),
173
+ i.status,
174
+ json(i.assessment),
175
+ json(i.caiNotice),
176
+ json(i.personsNotice),
177
+ i.drill,
178
+ i.openedBy,
179
+ i.openedAt,
180
+ i.closedAt,
181
+ i.retainUntil
182
+ ];
126
183
  return {
127
184
  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));
185
+ await query(
186
+ `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)`,
187
+ values(i)
188
+ );
129
189
  },
130
190
  async save(i) {
131
191
  await query(
@@ -134,7 +194,10 @@ function dbIncidentStore(query, schema = "privacy") {
134
194
  );
135
195
  },
136
196
  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]);
197
+ const [row] = await query(
198
+ `SELECT ${COLUMNS} FROM ${table} WHERE scope = $1 AND id = $2${options?.lock ? " FOR UPDATE" : ""}`,
199
+ [scope, id]
200
+ );
138
201
  return row ? toIncident(row) : null;
139
202
  },
140
203
  async list(scope) {
@@ -159,14 +222,21 @@ function createIncidentRegister(deps) {
159
222
  const schema = ident2(deps.schema ?? "privacy");
160
223
  const storeFor = deps.storeFor ?? ((query) => dbIncidentStore(query, schema));
161
224
  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 } });
225
+ await deps.audit?.record(query, {
226
+ actorId: actor.id,
227
+ actorLabel: actor.label,
228
+ action: `privacy.incident_${action}`,
229
+ target: { type: "incident", id: incident.id },
230
+ detail: { scope: incident.scope, drill: incident.drill }
231
+ });
163
232
  }
164
233
  async function update(query, scope, id, action, actor, change) {
165
234
  checkScope(scope);
166
235
  const store = storeFor(query);
167
236
  const incident = await store.get(scope, id, { lock: true });
168
237
  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");
238
+ if (incident.status === INCIDENT_STATUS.closed)
239
+ throw new IncidentError(INCIDENT_CODE.closed, "a closed entry of the register is never edited");
170
240
  change(incident);
171
241
  await store.save(incident);
172
242
  await trace(query, actor, action, incident);
@@ -179,11 +249,13 @@ function createIncidentRegister(deps) {
179
249
  within(input.description, 2e3, "description");
180
250
  if (input.information.length < 1 || input.information.length > 30) throw bad("information: 1 to 30 categories");
181
251
  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");
252
+ if (input.personsConcerned !== void 0 && (!Number.isInteger(input.personsConcerned) || input.personsConcerned < 0))
253
+ throw bad("personsConcerned: a whole number, 0 or more");
183
254
  const now = deps.clock.now();
184
255
  const awareAt = input.awareAt ?? now;
185
256
  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");
257
+ if (input.occurredAt && input.occurredAt.valueOf() > now.valueOf())
258
+ throw bad("occurredAt cannot be in the future");
187
259
  const incident = {
188
260
  id: randomUUID(),
189
261
  scope: input.scope,
@@ -209,7 +281,8 @@ function createIncidentRegister(deps) {
209
281
  return incident;
210
282
  },
211
283
  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(", ")}`);
284
+ for (const level of [input.sensitivity, input.consequences, input.likelihood])
285
+ if (!LEVELS.includes(level)) throw bad(`level \xAB ${level} \xBB is not one of ${LEVELS.join(", ")}`);
213
286
  within(input.rationale, 2e3, "rationale");
214
287
  return update(query, scope, id, "assessed", actor, (incident) => {
215
288
  incident.assessment = { ...input, assessedAt: deps.clock.now(), assessedBy: actor.label };
@@ -225,8 +298,13 @@ function createIncidentRegister(deps) {
225
298
  recordNotice(query, scope, id, target, notice, actor) {
226
299
  within(notice.channel, 40, "channel");
227
300
  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");
301
+ if (!incident.assessment)
302
+ throw new IncidentError(INCIDENT_CODE.notAssessed, "assess the risk before notifying");
303
+ if (!incident.assessment.seriousInjury)
304
+ throw new IncidentError(
305
+ INCIDENT_CODE.noNoticeDue,
306
+ "no notice is due: the assessment found no risk of serious injury"
307
+ );
230
308
  const sent = { sentAt: deps.clock.now(), channel: notice.channel, reference: notice.reference ?? null };
231
309
  if (target === NOTICE_TARGET.cai) incident.caiNotice = sent;
232
310
  else incident.personsNotice = sent;
@@ -240,7 +318,11 @@ function createIncidentRegister(deps) {
240
318
  close(query, scope, id, actor) {
241
319
  return update(query, scope, id, "closed", actor, (incident) => {
242
320
  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");
321
+ if (incident.assessment.seriousInjury && (!incident.caiNotice || !incident.personsNotice))
322
+ throw new IncidentError(
323
+ INCIDENT_CODE.noticesMissing,
324
+ "a risk of serious injury is closed once the Commission and the people concerned are notified"
325
+ );
244
326
  incident.status = INCIDENT_STATUS.closed;
245
327
  incident.closedAt = deps.clock.now();
246
328
  });
@@ -255,7 +337,12 @@ function createIncidentRegister(deps) {
255
337
  },
256
338
  async exportRegister(query, scope) {
257
339
  checkScope(scope);
258
- return { format: 1, scope, generatedAt: deps.clock.now().toISOString(), entries: await storeFor(query).list(scope) };
340
+ return {
341
+ format: 1,
342
+ scope,
343
+ generatedAt: deps.clock.now().toISOString(),
344
+ entries: await storeFor(query).list(scope)
345
+ };
259
346
  }
260
347
  };
261
348
  }
@@ -285,7 +372,8 @@ function memoryPrivacyStore() {
285
372
  },
286
373
  async finishRequest(id, outcome) {
287
374
  const found = requests.get(id);
288
- if (found) Object.assign(found, { status: outcome.status, completedAt: outcome.at, failure: outcome.failure ?? null });
375
+ if (found)
376
+ Object.assign(found, { status: outcome.status, completedAt: outcome.at, failure: outcome.failure ?? null });
289
377
  },
290
378
  async requestsOf(subject) {
291
379
  return [...requests.values()].filter((r) => sameSubject(r.subject, subject)).sort((a, b) => b.requestedAt.valueOf() - a.requestedAt.valueOf()).map((r) => structuredClone(r));
@@ -295,8 +383,24 @@ function memoryPrivacyStore() {
295
383
 
296
384
  // src/persistence.ts
297
385
  import { ident as ident3 } from "@krizaka/db";
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) });
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 });
386
+ var toConsent = (r) => ({
387
+ id: r.id,
388
+ subject: { kind: r.subject_kind, id: r.subject_id },
389
+ purpose: r.purpose,
390
+ version: r.version,
391
+ granted: r.granted,
392
+ means: r.means,
393
+ at: new Date(r.at)
394
+ });
395
+ var toRequest = (r) => ({
396
+ id: r.id,
397
+ subject: { kind: r.subject_kind, id: r.subject_id },
398
+ kind: r.kind,
399
+ status: r.status,
400
+ requestedAt: new Date(r.requested_at),
401
+ completedAt: r.completed_at === null ? null : new Date(r.completed_at),
402
+ failure: r.failure
403
+ });
300
404
  var CONSENT_COLUMNS = "id, subject_kind, subject_id, purpose, version, granted, means, at";
301
405
  var REQUEST_COLUMNS = "id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure";
302
406
  function dbPrivacyStore(query, schema = "privacy") {
@@ -305,27 +409,47 @@ function dbPrivacyStore(query, schema = "privacy") {
305
409
  const same = (subject) => [subject.kind, subject.id];
306
410
  return {
307
411
  async insertConsent(c) {
308
- 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]);
412
+ await query(
413
+ `INSERT INTO ${consent} (id, subject_kind, subject_id, purpose, version, granted, means, at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
414
+ [c.id, c.subject.kind, c.subject.id, c.purpose, c.version, c.granted, c.means, c.at]
415
+ );
309
416
  },
310
417
  async latestConsent(subject, purpose) {
311
- const [row] = await query(`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]);
418
+ const [row] = await query(
419
+ `SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 AND purpose = $3 ORDER BY seq DESC LIMIT 1`,
420
+ [...same(subject), purpose]
421
+ );
312
422
  return row ? toConsent(row) : null;
313
423
  },
314
424
  async consentHistory(subject) {
315
- return (await query(`SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY seq`, same(subject))).map(toConsent);
425
+ return (await query(
426
+ `SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY seq`,
427
+ same(subject)
428
+ )).map(toConsent);
316
429
  },
317
430
  async insertRequest(r) {
318
- 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]);
431
+ await query(
432
+ `INSERT INTO ${request} (id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
433
+ [r.id, r.subject.kind, r.subject.id, r.kind, r.status, r.requestedAt, r.completedAt, r.failure]
434
+ );
319
435
  },
320
436
  async getRequest(id) {
321
437
  const [row] = await query(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE id = $1`, [id]);
322
438
  return row ? toRequest(row) : null;
323
439
  },
324
440
  async finishRequest(id, outcome) {
325
- await query(`UPDATE ${request} SET status = $2, completed_at = $3, failure = $4 WHERE id = $1`, [id, outcome.status, outcome.at, outcome.failure ?? null]);
441
+ await query(`UPDATE ${request} SET status = $2, completed_at = $3, failure = $4 WHERE id = $1`, [
442
+ id,
443
+ outcome.status,
444
+ outcome.at,
445
+ outcome.failure ?? null
446
+ ]);
326
447
  },
327
448
  async requestsOf(subject) {
328
- return (await query(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY requested_at DESC, id`, same(subject))).map(toRequest);
449
+ return (await query(
450
+ `SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY requested_at DESC, id`,
451
+ same(subject)
452
+ )).map(toRequest);
329
453
  }
330
454
  };
331
455
  }
@@ -341,7 +465,8 @@ function createPrivacy(deps) {
341
465
  const storeFor = deps.storeFor ?? ((query) => dbPrivacyStore(query, schema));
342
466
  for (const purpose of deps.purposes) checkPurpose(purpose);
343
467
  const names = deps.contributors.map((c) => c.name);
344
- if (new Set(names).size !== names.length) throw new PrivacyError(PRIVACY_CODE.contributorFailed, `two contributors have the same name: ${names.join(", ")}`);
468
+ if (new Set(names).size !== names.length)
469
+ throw new PrivacyError(PRIVACY_CODE.contributorFailed, `two contributors have the same name: ${names.join(", ")}`);
345
470
  const known = new Set(deps.purposes);
346
471
  async function assemble(query, subject) {
347
472
  const modules = {};
@@ -349,18 +474,38 @@ function createPrivacy(deps) {
349
474
  try {
350
475
  modules[contributor.name] = await contributor.exportFor(query, subject);
351
476
  } catch (cause) {
352
- throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the export of \xAB ${contributor.name} \xBB failed`, { cause });
477
+ throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the export of \xAB ${contributor.name} \xBB failed`, {
478
+ cause
479
+ });
353
480
  }
354
481
  }
355
482
  return { format: 1, subject, generatedAt: deps.clock.now().toISOString(), modules };
356
483
  }
357
- const newRequest = (subject, kind) => ({ id: randomUUID2(), subject, kind, status: REQUEST_STATUS.requested, requestedAt: deps.clock.now(), completedAt: null, failure: null });
484
+ const newRequest = (subject, kind) => ({
485
+ id: randomUUID2(),
486
+ subject,
487
+ kind,
488
+ status: REQUEST_STATUS.requested,
489
+ requestedAt: deps.clock.now(),
490
+ completedAt: null,
491
+ failure: null
492
+ });
358
493
  async function recordConsent(query, input) {
359
494
  checkSubject(input.subject);
360
495
  checkPurpose(input.purpose);
361
- if (!known.has(input.purpose)) throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose \xAB ${input.purpose} \xBB is not one the product declared`);
362
- if (input.version.length < 1 || input.version.length > 100) throw new PrivacyError(PRIVACY_CODE.badConsent, "the notice version is 1 to 100 characters");
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() };
496
+ if (!known.has(input.purpose))
497
+ throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose \xAB ${input.purpose} \xBB is not one the product declared`);
498
+ if (input.version.length < 1 || input.version.length > 100)
499
+ throw new PrivacyError(PRIVACY_CODE.badConsent, "the notice version is 1 to 100 characters");
500
+ const record = {
501
+ id: randomUUID2(),
502
+ subject: input.subject,
503
+ purpose: input.purpose,
504
+ version: input.version,
505
+ granted: input.granted,
506
+ means: input.means ?? null,
507
+ at: deps.clock.now()
508
+ };
364
509
  await storeFor(query).insertConsent(record);
365
510
  return record;
366
511
  }
@@ -385,7 +530,11 @@ function createPrivacy(deps) {
385
530
  await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: deps.clock.now() });
386
531
  return document;
387
532
  } catch (error) {
388
- await store.finishRequest(request.id, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });
533
+ await store.finishRequest(request.id, {
534
+ status: REQUEST_STATUS.failed,
535
+ at: deps.clock.now(),
536
+ failure: FAILURE_CODE
537
+ });
389
538
  throw error;
390
539
  }
391
540
  },
@@ -394,19 +543,30 @@ function createPrivacy(deps) {
394
543
  if (!deps.outbox) throw new PrivacyError(PRIVACY_CODE.noOutbox, "an asynchronous export needs the outbox");
395
544
  const request = newRequest(subject, REQUEST_KIND.export);
396
545
  await storeFor(tx).insertRequest(request);
397
- await deps.outbox.append(tx, { topic: "privacy", type: "evt.privacy.export_requested.v1", payload: { requestId: request.id }, id: request.id });
546
+ await deps.outbox.append(tx, {
547
+ topic: "privacy",
548
+ type: "evt.privacy.export_requested.v1",
549
+ payload: { requestId: request.id },
550
+ id: request.id
551
+ });
398
552
  return { requestId: request.id };
399
553
  },
400
554
  async fulfilExport(query, requestId, deliver) {
401
555
  const store = storeFor(query);
402
556
  const request = await store.getRequest(requestId);
403
557
  if (!request) throw new PrivacyError(PRIVACY_CODE.unknownRequest, `no request ${requestId}`);
404
- if (request.kind !== REQUEST_KIND.export) throw new PrivacyError(PRIVACY_CODE.notAnExport, `request ${requestId} is not an export`);
405
- if (request.status === REQUEST_STATUS.completed) throw new PrivacyError(PRIVACY_CODE.alreadyDone, `request ${requestId} is already completed`);
558
+ if (request.kind !== REQUEST_KIND.export)
559
+ throw new PrivacyError(PRIVACY_CODE.notAnExport, `request ${requestId} is not an export`);
560
+ if (request.status === REQUEST_STATUS.completed)
561
+ throw new PrivacyError(PRIVACY_CODE.alreadyDone, `request ${requestId} is already completed`);
406
562
  try {
407
563
  await deliver(await assemble(query, request.subject), request);
408
564
  } catch (error) {
409
- await store.finishRequest(requestId, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });
565
+ await store.finishRequest(requestId, {
566
+ status: REQUEST_STATUS.failed,
567
+ at: deps.clock.now(),
568
+ failure: FAILURE_CODE
569
+ });
410
570
  throw error;
411
571
  }
412
572
  await store.finishRequest(requestId, { status: REQUEST_STATUS.completed, at: deps.clock.now() });
@@ -422,22 +582,46 @@ function createPrivacy(deps) {
422
582
  try {
423
583
  await contributor.eraseFor(tx, subject);
424
584
  } catch (cause) {
425
- throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the erasure of \xAB ${contributor.name} \xBB failed`, { cause });
585
+ throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the erasure of \xAB ${contributor.name} \xBB failed`, {
586
+ cause
587
+ });
426
588
  }
427
589
  }
428
590
  for (const purpose of deps.purposes) {
429
- if ((await store.latestConsent(subject, purpose))?.granted) await recordConsent(tx, { subject, purpose, version: options.noticeVersion ?? ERASURE_VERSION, granted: false, means: ERASURE_VERSION });
591
+ if ((await store.latestConsent(subject, purpose))?.granted)
592
+ await recordConsent(tx, {
593
+ subject,
594
+ purpose,
595
+ version: options.noticeVersion ?? ERASURE_VERSION,
596
+ granted: false,
597
+ means: ERASURE_VERSION
598
+ });
430
599
  }
431
600
  const completedAt = deps.clock.now();
432
601
  await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: completedAt });
433
- await deps.audit?.record(tx, { actorId: null, actorLabel: "privacy", action: "privacy.erasure_completed", target: { type: "privacy_request", id: request.id }, detail: { contributors: names } });
602
+ await deps.audit?.record(tx, {
603
+ actorId: null,
604
+ actorLabel: "privacy",
605
+ action: "privacy.erasure_completed",
606
+ target: { type: "privacy_request", id: request.id },
607
+ detail: { contributors: names }
608
+ });
434
609
  return { ...request, status: REQUEST_STATUS.completed, completedAt };
435
610
  });
436
611
  } catch (error) {
437
612
  try {
438
- await deps.transaction((tx) => storeFor(tx).insertRequest({ ...request, status: REQUEST_STATUS.failed, completedAt: deps.clock.now(), failure: FAILURE_CODE }));
613
+ await deps.transaction(
614
+ (tx) => storeFor(tx).insertRequest({
615
+ ...request,
616
+ status: REQUEST_STATUS.failed,
617
+ completedAt: deps.clock.now(),
618
+ failure: FAILURE_CODE
619
+ })
620
+ );
439
621
  } catch (recordFailure) {
440
- throw new AggregateError([error, recordFailure], "the erasure failed, and so did recording its failure", { cause: recordFailure });
622
+ throw new AggregateError([error, recordFailure], "the erasure failed, and so did recording its failure", {
623
+ cause: recordFailure
624
+ });
441
625
  }
442
626
  throw error;
443
627
  }
@@ -447,10 +631,12 @@ function createPrivacy(deps) {
447
631
  for (const purpose of deps.purposes) {
448
632
  const days = await deps.retentionDays?.(purpose);
449
633
  if (days === void 0) continue;
450
- if (!Number.isInteger(days) || days < 1) throw new RangeError(`the retention of \xAB ${purpose} \xBB must be a whole number of days from 1, got ${days}`);
634
+ if (!Number.isInteger(days) || days < 1)
635
+ throw new RangeError(`the retention of \xAB ${purpose} \xBB must be a whole number of days from 1, got ${days}`);
451
636
  const before = subHours(deps.clock.now(), days * 24);
452
637
  let total = 0;
453
- for (const contributor of deps.contributors) total += await contributor.purgeExpired?.(query, { purpose, before }) ?? 0;
638
+ for (const contributor of deps.contributors)
639
+ total += await contributor.purgeExpired?.(query, { purpose, before }) ?? 0;
454
640
  removed[purpose] = total;
455
641
  }
456
642
  return removed;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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;A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;AAAA,kCAUW,EAAE,MAAM;AAAA,IACtC;AAAA,IACA;AAAA,MACE,SAAS;AAAA,MACT,MAAM;AAAA,MACN,KAAK,CAAC,MAAM;AAAA,eACH,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"]}
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(\n query: Query,\n scope: string,\n id: string,\n target: NoticeTarget,\n notice: { channel: string; reference?: string | undefined },\n actor: IncidentActor,\n ): 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(\n factors: Pick<AssessmentInput, \"sensitivity\" | \"consequences\" | \"likelihood\">,\n): boolean {\n const { sensitivity, consequences, likelihood } = {\n sensitivity: RANK[factors.sensitivity],\n consequences: RANK[factors.consequences],\n likelihood: RANK[factors.likelihood],\n };\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 = [\n \"id\",\n \"kind\",\n \"aware_at\",\n \"occurred_at\",\n \"description\",\n \"information\",\n \"persons_concerned\",\n \"serious_injury\",\n \"assessed_at\",\n \"cai_notice_at\",\n \"persons_notice_at\",\n \"measures\",\n \"status\",\n \"drill\",\n \"closed_at\",\n \"retain_until\",\n] 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 [\n e.id,\n e.kind,\n e.awareAt,\n e.occurredAt,\n e.description,\n e.information.join(\"; \"),\n e.personsConcerned,\n e.assessment?.seriousInjury ?? \"\",\n e.assessment?.assessedAt ?? \"\",\n e.caiNotice?.sentAt ?? \"\",\n e.personsNotice?.sentAt ?? \"\",\n e.measures.map((m) => m.text).join(\"; \"),\n e.status,\n e.drill,\n e.closedAt,\n e.retainUntil,\n ]\n .map(cell)\n .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()]\n .filter((i) => i.scope === scope)\n .sort((a, b) => a.awareAt.valueOf() - b.awareAt.valueOf() || a.id.localeCompare(b.id))\n .map((i) => structuredClone(i));\n },\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type {\n Incident,\n IncidentAssessment,\n IncidentKind,\n IncidentMeasure,\n IncidentNotice,\n IncidentStatus,\n IncidentStore,\n Level,\n} 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: {\n sensitivity: Level;\n consequences: Level;\n likelihood: Level;\n seriousInjury: boolean;\n rationale: string;\n assessedAt: string;\n assessedBy: string;\n } | 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 =\n \"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 n ? { sentAt: new Date(n.sentAt), channel: n.channel, reference: n.reference } : null;\nconst toAssessment = (a: IncidentRow[\"assessment\"]): IncidentAssessment | null =>\n 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) => [\n i.id,\n i.scope,\n i.kind,\n i.awareAt,\n i.occurredAt,\n i.description,\n i.information,\n i.personsConcerned,\n JSON.stringify(i.measures),\n i.status,\n json(i.assessment),\n json(i.caiNotice),\n json(i.personsNotice),\n i.drill,\n i.openedBy,\n i.openedAt,\n i.closedAt,\n i.retainUntil,\n ];\n return {\n async insert(i) {\n await query(\n `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)`,\n values(i),\n );\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>(\n `SELECT ${COLUMNS} FROM ${table} WHERE scope = $1 AND id = $2${options?.lock ? \" FOR UPDATE\" : \"\"}`,\n [scope, id],\n );\n return row ? toIncident(row) : null;\n },\n async list(scope) {\n return (\n await query<IncidentRow>(`SELECT ${COLUMNS} FROM ${table} WHERE scope = $1 ORDER BY aware_at, id`, [scope])\n ).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, {\n actorId: actor.id,\n actorLabel: actor.label,\n action: `privacy.incident_${action}`,\n target: { type: \"incident\", id: incident.id },\n detail: { scope: incident.scope, drill: incident.drill },\n });\n }\n\n /** Reads the incident under lock, applies `change` to a copy, saves it, traces it. */\n async function update(\n query: Query,\n scope: string,\n id: string,\n action: string,\n actor: IncidentActor,\n change: (incident: Incident) => void,\n ): 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)\n 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 (\n input.personsConcerned !== undefined &&\n (!Number.isInteger(input.personsConcerned) || input.personsConcerned < 0)\n )\n 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())\n 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])\n 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)\n throw new IncidentError(INCIDENT_CODE.notAssessed, \"assess the risk before notifying\");\n if (!incident.assessment.seriousInjury)\n throw new IncidentError(\n INCIDENT_CODE.noNoticeDue,\n \"no notice is due: the assessment found no risk of serious injury\",\n );\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))\n throw new IncidentError(\n INCIDENT_CODE.noticesMissing,\n \"a risk of serious injury is closed once the Commission and the people concerned are notified\",\n );\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 {\n format: 1,\n scope,\n generatedAt: deps.clock.now().toISOString(),\n entries: await storeFor(query).list(scope),\n };\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)\n Object.assign(found, { status: outcome.status, completedAt: outcome.at, failure: outcome.failure ?? null });\n },\n async requestsOf(subject) {\n return [...requests.values()]\n .filter((r) => sameSubject(r.subject, subject))\n .sort((a, b) => b.requestedAt.valueOf() - a.requestedAt.valueOf())\n .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 => ({\n id: r.id,\n subject: { kind: r.subject_kind, id: r.subject_id },\n purpose: r.purpose,\n version: r.version,\n granted: r.granted,\n means: r.means,\n at: new Date(r.at),\n});\nconst toRequest = (r: RequestRow): PrivacyRequest => ({\n id: r.id,\n subject: { kind: r.subject_kind, id: r.subject_id },\n kind: r.kind,\n status: r.status,\n requestedAt: new Date(r.requested_at),\n completedAt: r.completed_at === null ? null : new Date(r.completed_at),\n failure: r.failure,\n});\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(\n `INSERT INTO ${consent} (id, subject_kind, subject_id, purpose, version, granted, means, at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,\n [c.id, c.subject.kind, c.subject.id, c.purpose, c.version, c.granted, c.means, c.at],\n );\n },\n async latestConsent(subject, purpose) {\n const [row] = await query<ConsentRow>(\n `SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 AND purpose = $3 ORDER BY seq DESC LIMIT 1`,\n [...same(subject), purpose],\n );\n return row ? toConsent(row) : null;\n },\n async consentHistory(subject) {\n return (\n await query<ConsentRow>(\n `SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY seq`,\n same(subject),\n )\n ).map(toConsent);\n },\n async insertRequest(r) {\n await query(\n `INSERT INTO ${request} (id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,\n [r.id, r.subject.kind, r.subject.id, r.kind, r.status, r.requestedAt, r.completedAt, r.failure],\n );\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`, [\n id,\n outcome.status,\n outcome.at,\n outcome.failure ?? null,\n ]);\n },\n async requestsOf(subject) {\n return (\n await query<RequestRow>(\n `SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY requested_at DESC, id`,\n same(subject),\n )\n ).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(\n query: Query,\n requestId: string,\n deliver: (document: ExportDocument, request: PrivacyRequest) => Promise<void>,\n ): 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)\n 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`, {\n cause,\n });\n }\n }\n return { format: 1, subject, generatedAt: deps.clock.now().toISOString(), modules };\n }\n\n const newRequest = (subject: Subject, kind: PrivacyRequest[\"kind\"]): PrivacyRequest => ({\n id: randomUUID(),\n subject,\n kind,\n status: REQUEST_STATUS.requested,\n requestedAt: deps.clock.now(),\n completedAt: null,\n failure: null,\n });\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))\n 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)\n throw new PrivacyError(PRIVACY_CODE.badConsent, \"the notice version is 1 to 100 characters\");\n const record: ConsentRecord = {\n id: randomUUID(),\n subject: input.subject,\n purpose: input.purpose,\n version: input.version,\n granted: input.granted,\n means: input.means ?? null,\n at: deps.clock.now(),\n };\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, {\n status: REQUEST_STATUS.failed,\n at: deps.clock.now(),\n failure: FAILURE_CODE,\n });\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, {\n topic: \"privacy\",\n type: \"evt.privacy.export_requested.v1\",\n payload: { requestId: request.id },\n id: request.id,\n });\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)\n throw new PrivacyError(PRIVACY_CODE.notAnExport, `request ${requestId} is not an export`);\n if (request.status === REQUEST_STATUS.completed)\n 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, {\n status: REQUEST_STATUS.failed,\n at: deps.clock.now(),\n failure: FAILURE_CODE,\n });\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`, {\n cause,\n });\n }\n }\n for (const purpose of deps.purposes) {\n if ((await store.latestConsent(subject, purpose))?.granted)\n await recordConsent(tx, {\n subject,\n purpose,\n version: options.noticeVersion ?? ERASURE_VERSION,\n granted: false,\n means: ERASURE_VERSION,\n });\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, {\n actorId: null,\n actorLabel: \"privacy\",\n action: \"privacy.erasure_completed\",\n target: { type: \"privacy_request\", id: request.id },\n detail: { contributors: names },\n });\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) =>\n storeFor(tx).insertRequest({\n ...request,\n status: REQUEST_STATUS.failed,\n completedAt: deps.clock.now(),\n failure: FAILURE_CODE,\n }),\n );\n } catch (recordFailure) {\n throw new AggregateError([error, recordFailure], \"the erasure failed, and so did recording its failure\", {\n cause: recordFailure,\n });\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)\n 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)\n 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":";;;;;;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B,aAAa;AAAA,EACxC,QAAQ;AAAA,EACR,YAAY;AAAA,IACV;AAAA,MACE,SAAS;AAAA,MACT,MAAM;AAAA,MACN,KAAK,CAAC,MAAM;AAAA,eACH,EAAE,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kCAWW,EAAE,MAAM;AAAA,kBACxB,EAAE,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,uDAK6B,EAAE,MAAM,0CAA0C,EAAE,MAAM;AAAA,eAClG,EAAE,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kCAUW,EAAE,MAAM;AAAA,IACtC;AAAA,IACA;AAAA,MACE,SAAS;AAAA,MACT,MAAM;AAAA,MACN,KAAK,CAAC,MAAM;AAAA,eACH,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/settings.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  checkPurpose
3
- } from "./chunk-PMXEX2LW.js";
3
+ } from "./chunk-DVWHUJHQ.js";
4
4
 
5
5
  // src/settings.ts
6
6
  import { integer } from "@krizaka/settings";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/settings.ts"],"sourcesContent":["import { integer, type Registry } from \"@krizaka/settings\";\n\nimport { checkPurpose } from \"./rules\";\n\n/** The settings key of a purpose's retention: `payment-history` → `privacy.retention.paymentHistoryDays` (a key holds letters and digits only). */\nexport const retentionKey = (purpose: string): string => `privacy.retention.${purpose.replace(/[-_]([a-z0-9])/g, (_, c: string) => c.toUpperCase())}Days`;\n\n/**\n * The registry fragment of the retention: `privacy.retention.<purpose>Days` for each purpose the product declares, an integer with the\n * product's default. Global scope. The admin sets how long what a purpose collected is kept; the product's job calls `purge`.\n * @param purposes the product's purposes (`screening`, `payment-history`), with their default retention in days\n * @throws PrivacyError for a purpose id that is not well formed, or two that give the same key\n */\nexport function privacySettings(purposes: Readonly<Record<string, { retentionDays: number }>>): Registry {\n const fragment: Registry = {};\n for (const [purpose, { retentionDays }] of Object.entries(purposes)) {\n checkPurpose(purpose);\n const key = retentionKey(purpose);\n if (key in fragment) throw new RangeError(`privacy purposes give the same settings key: ${key}`);\n // @fixed: a purpose is kept from a day to ten years; the default is the product's\n fragment[key] = integer(\"privacy\", retentionDays, { min: 1, max: 3650, unit: \"days\" });\n }\n return fragment;\n}\n\n/** The retention of a purpose as `createPrivacy` takes it, from the product's accessor (`(key) => service.get(key, ctx)`). */\nexport function retentionFromSettings(read: (key: string) => number | undefined | Promise<number | undefined>): (purpose: string) => Promise<number | undefined> {\n return async (purpose) => read(retentionKey(purpose));\n}\n"],"mappings":";;;;;AAAA,SAAS,eAA8B;AAKhC,IAAM,eAAe,CAAC,YAA4B,qBAAqB,QAAQ,QAAQ,mBAAmB,CAAC,GAAG,MAAc,EAAE,YAAY,CAAC,CAAC;AAQ5I,SAAS,gBAAgB,UAAyE;AACvG,QAAM,WAAqB,CAAC;AAC5B,aAAW,CAAC,SAAS,EAAE,cAAc,CAAC,KAAK,OAAO,QAAQ,QAAQ,GAAG;AACnE,iBAAa,OAAO;AACpB,UAAM,MAAM,aAAa,OAAO;AAChC,QAAI,OAAO,SAAU,OAAM,IAAI,WAAW,gDAAgD,GAAG,EAAE;AAE/F,aAAS,GAAG,IAAI,QAAQ,WAAW,eAAe,EAAE,KAAK,GAAG,KAAK,MAAM,MAAM,OAAO,CAAC;AAAA,EACvF;AACA,SAAO;AACT;AAGO,SAAS,sBAAsB,MAA2H;AAC/J,SAAO,OAAO,YAAY,KAAK,aAAa,OAAO,CAAC;AACtD;","names":[]}
1
+ {"version":3,"sources":["../src/settings.ts"],"sourcesContent":["import { integer, type Registry } from \"@krizaka/settings\";\n\nimport { checkPurpose } from \"./rules\";\n\n/** The settings key of a purpose's retention: `payment-history` → `privacy.retention.paymentHistoryDays` (a key holds letters and digits only). */\nexport const retentionKey = (purpose: string): string =>\n `privacy.retention.${purpose.replace(/[-_]([a-z0-9])/g, (_, c: string) => c.toUpperCase())}Days`;\n\n/**\n * The registry fragment of the retention: `privacy.retention.<purpose>Days` for each purpose the product declares, an integer with the\n * product's default. Global scope. The admin sets how long what a purpose collected is kept; the product's job calls `purge`.\n * @param purposes the product's purposes (`screening`, `payment-history`), with their default retention in days\n * @throws PrivacyError for a purpose id that is not well formed, or two that give the same key\n */\nexport function privacySettings(purposes: Readonly<Record<string, { retentionDays: number }>>): Registry {\n const fragment: Registry = {};\n for (const [purpose, { retentionDays }] of Object.entries(purposes)) {\n checkPurpose(purpose);\n const key = retentionKey(purpose);\n if (key in fragment) throw new RangeError(`privacy purposes give the same settings key: ${key}`);\n // @fixed: a purpose is kept from a day to ten years; the default is the product's\n fragment[key] = integer(\"privacy\", retentionDays, { min: 1, max: 3650, unit: \"days\" });\n }\n return fragment;\n}\n\n/** The retention of a purpose as `createPrivacy` takes it, from the product's accessor (`(key) => service.get(key, ctx)`). */\nexport function retentionFromSettings(\n read: (key: string) => number | undefined | Promise<number | undefined>,\n): (purpose: string) => Promise<number | undefined> {\n return async (purpose) => read(retentionKey(purpose));\n}\n"],"mappings":";;;;;AAAA,SAAS,eAA8B;AAKhC,IAAM,eAAe,CAAC,YAC3B,qBAAqB,QAAQ,QAAQ,mBAAmB,CAAC,GAAG,MAAc,EAAE,YAAY,CAAC,CAAC;AAQrF,SAAS,gBAAgB,UAAyE;AACvG,QAAM,WAAqB,CAAC;AAC5B,aAAW,CAAC,SAAS,EAAE,cAAc,CAAC,KAAK,OAAO,QAAQ,QAAQ,GAAG;AACnE,iBAAa,OAAO;AACpB,UAAM,MAAM,aAAa,OAAO;AAChC,QAAI,OAAO,SAAU,OAAM,IAAI,WAAW,gDAAgD,GAAG,EAAE;AAE/F,aAAS,GAAG,IAAI,QAAQ,WAAW,eAAe,EAAE,KAAK,GAAG,KAAK,MAAM,MAAM,OAAO,CAAC;AAAA,EACvF;AACA,SAAO;AACT;AAGO,SAAS,sBACd,MACkD;AAClD,SAAO,OAAO,YAAY,KAAK,aAAa,OAAO,CAAC;AACtD;","names":[]}
package/dist/testkit.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { I as IncidentStore, c as PrivacyStore } from './incident-DLXCVzpW.js';
1
+ import { I as IncidentStore, c as PrivacyStore } from './incident-B4bxcEgY.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. */
package/dist/testkit.js CHANGED
@@ -5,8 +5,24 @@ var T0 = /* @__PURE__ */ new Date("2026-10-26T12:00:00.000Z");
5
5
  var at = (seconds) => new Date(T0.valueOf() + seconds * 1e3);
6
6
  var ERIC = { kind: "account", id: "11111111-1111-4111-8111-111111111111" };
7
7
  var CLIENT = { kind: "client", id: "c-42" };
8
- var consent = (subject, purpose, granted, seconds) => ({ id: randomUUID(), subject, purpose, version: "2026-10-01", granted, means: "checkbox", at: at(seconds) });
9
- var request = (subject, kind, seconds) => ({ id: randomUUID(), subject, kind, status: "requested", requestedAt: at(seconds), completedAt: null, failure: null });
8
+ var consent = (subject, purpose, granted, seconds) => ({
9
+ id: randomUUID(),
10
+ subject,
11
+ purpose,
12
+ version: "2026-10-01",
13
+ granted,
14
+ means: "checkbox",
15
+ at: at(seconds)
16
+ });
17
+ var request = (subject, kind, seconds) => ({
18
+ id: randomUUID(),
19
+ subject,
20
+ kind,
21
+ status: "requested",
22
+ requestedAt: at(seconds),
23
+ completedAt: null,
24
+ failure: null
25
+ });
10
26
  function privacyStoreContract(name, make) {
11
27
  it(`${name}: knows nothing about a person who never said anything`, async () => {
12
28
  const store = await make();
@@ -51,7 +67,11 @@ function privacyStoreContract(name, make) {
51
67
  await store.finishRequest(broke.id, { status: "failed", at: at(11), failure: "CONTRIBUTOR_FAILED" });
52
68
  expect(await store.getRequest(done.id)).toMatchObject({ kind: "export", status: "completed", failure: null });
53
69
  expect((await store.getRequest(done.id)).completedAt.toISOString()).toBe(at(3).toISOString());
54
- expect(await store.getRequest(broke.id)).toMatchObject({ kind: "erasure", status: "failed", failure: "CONTRIBUTOR_FAILED" });
70
+ expect(await store.getRequest(broke.id)).toMatchObject({
71
+ kind: "erasure",
72
+ status: "failed",
73
+ failure: "CONTRIBUTOR_FAILED"
74
+ });
55
75
  expect(await store.getRequest(randomUUID())).toBeNull();
56
76
  expect((await store.requestsOf(ERIC)).map((r) => r.id)).toEqual([broke.id, done.id]);
57
77
  expect(await store.requestsOf(CLIENT)).toEqual([]);
@@ -82,7 +102,19 @@ var incident = (scope, overrides = {}) => ({
82
102
  function incidentStoreContract(name, make) {
83
103
  it(`${name}: writes an entry and reads it back whole, dates included`, async () => {
84
104
  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" } });
105
+ const assessed = incident("t1", {
106
+ status: "assessed",
107
+ assessment: {
108
+ sensitivity: "high",
109
+ consequences: "medium",
110
+ likelihood: "high",
111
+ seriousInjury: true,
112
+ rationale: "Leases.",
113
+ assessedAt: at(5),
114
+ assessedBy: "dpo"
115
+ },
116
+ caiNotice: { sentAt: at(9), channel: "form", reference: "CAI-1" }
117
+ });
86
118
  await store.insert(assessed);
87
119
  expect(await store.get("t1", assessed.id)).toEqual(assessed);
88
120
  });
@@ -1 +1 @@
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,MAAM,UAAU,IAAI,OAAO;AAErD,IAAM,UAAU,CAAC,SAAkB,SAAiB,SAAkB,aAAoC,EAAE,IAAI,WAAW,GAAG,SAAS,SAAS,SAAS,cAAc,SAAS,OAAO,YAAY,IAAI,GAAG,OAAO,EAAE;AACnN,IAAM,UAAU,CAAC,SAAkB,MAA8B,aAAqC,EAAE,IAAI,WAAW,GAAG,SAAS,MAAM,QAAQ,aAAa,aAAa,GAAG,OAAO,GAAG,aAAa,MAAM,SAAS,KAAK;AAGlN,SAAS,qBAAqB,MAAc,MAAkD;AACnG,KAAG,GAAG,IAAI,0DAA0D,YAAY;AAC9E,UAAM,QAAQ,MAAM,KAAK;AACzB,WAAO,MAAM,MAAM,cAAc,MAAM,WAAW,CAAC,EAAE,SAAS;AAC9D,WAAO,MAAM,MAAM,eAAe,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACrD,CAAC;AAED,KAAG,GAAG,IAAI,mFAAmF,YAAY;AACvG,UAAM,QAAQ,MAAM,KAAK;AACzB,UAAM,QAAQ,QAAQ,MAAM,aAAa,MAAM,CAAC;AAChD,UAAM,SAAS,QAAQ,MAAM,aAAa,OAAO,EAAE;AACnD,UAAM,QAAQ,QAAQ,MAAM,aAAa,MAAM,EAAE;AACjD,eAAW,KAAK,CAAC,OAAO,QAAQ,KAAK,EAAG,OAAM,MAAM,cAAc,CAAC;AACnE,WAAO,MAAM,MAAM,cAA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\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 => ({\n id: randomUUID(),\n subject,\n purpose,\n version: \"2026-10-01\",\n granted,\n means: \"checkbox\",\n at: at(seconds),\n});\nconst request = (subject: Subject, kind: PrivacyRequest[\"kind\"], seconds: number): PrivacyRequest => ({\n id: randomUUID(),\n subject,\n kind,\n status: \"requested\",\n requestedAt: at(seconds),\n completedAt: null,\n failure: null,\n});\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({\n kind: \"erasure\",\n status: \"failed\",\n failure: \"CONTRIBUTOR_FAILED\",\n });\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\", {\n status: \"assessed\",\n assessment: {\n sensitivity: \"high\",\n consequences: \"medium\",\n likelihood: \"high\",\n seriousInjury: true,\n rationale: \"Leases.\",\n assessedAt: at(5),\n assessedBy: \"dpo\",\n },\n caiNotice: { sentAt: at(9), channel: \"form\", reference: \"CAI-1\" },\n });\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,MAAM,UAAU,IAAI,OAAO;AAErD,IAAM,UAAU,CAAC,SAAkB,SAAiB,SAAkB,aAAoC;AAAA,EACxG,IAAI,WAAW;AAAA,EACf;AAAA,EACA;AAAA,EACA,SAAS;AAAA,EACT;AAAA,EACA,OAAO;AAAA,EACP,IAAI,GAAG,OAAO;AAChB;AACA,IAAM,UAAU,CAAC,SAAkB,MAA8B,aAAqC;AAAA,EACpG,IAAI,WAAW;AAAA,EACf;AAAA,EACA;AAAA,EACA,QAAQ;AAAA,EACR,aAAa,GAAG,OAAO;AAAA,EACvB,aAAa;AAAA,EACb,SAAS;AACX;AAGO,SAAS,qBAAqB,MAAc,MAAkD;AACnG,KAAG,GAAG,IAAI,0DAA0D,YAAY;AAC9E,UAAM,QAAQ,MAAM,KAAK;AACzB,WAAO,MAAM,MAAM,cAAc,MAAM,WAAW,CAAC,EAAE,SAAS;AAC9D,WAAO,MAAM,MAAM,eAAe,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACrD,CAAC;AAED,KAAG,GAAG,IAAI,mFAAmF,YAAY;AACvG,UAAM,QAAQ,MAAM,KAAK;AACzB,UAAM,QAAQ,QAAQ,MAAM,aAAa,MAAM,CAAC;AAChD,UAAM,SAAS,QAAQ,MAAM,aAAa,OAAO,EAAE;AACnD,UAAM,QAAQ,QAAQ,MAAM,aAAa,MAAM,EAAE;AACjD,eAAW,KAAK,CAAC,OAAO,QAAQ,KAAK,EA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AAO,WAAW;AAAA,EACjF,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krizaka/privacy",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
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,11 +58,11 @@
58
58
  "typescript": "^5.9.3",
59
59
  "vitest": "^4.1.11",
60
60
  "zod": "^4.6.7",
61
- "@krizaka/config": "^0.17.0"
61
+ "@krizaka/config": "^0.21.0"
62
62
  },
63
63
  "dependencies": {
64
64
  "@krizaka/db": "^0.3.1",
65
- "@krizaka/settings": "^0.5.2",
65
+ "@krizaka/settings": "^0.7.0",
66
66
  "@krizaka/time": "^0.2.0"
67
67
  },
68
68
  "peerDependencies": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/port.ts","../src/rules.ts"],"sourcesContent":["/**\n * The ports of « privacy » (Loi 25): consents by purpose, the person's data exported from every module that holds it, and erased\n * from every module in one transaction. Generic: no product import, no database client (a `Query` comes in), no wall clock (a\n * `Clock` comes in). What a module holds, and what erasing it means (blanking a row, deleting a file, keeping an invoice for six\n * years), is the module's: it implements `PrivacyContributor`.\n */\nexport type { Clock, Query } from \"@krizaka/db\";\nimport type { Query } from \"@krizaka/db\";\n\n/**\n * Whose data it is. Usually an account (`{ kind: \"account\", id }`), but a product's data subject is not always an account: Akinaza's\n * is a client file, Yomizaka's a tenant on an application. The `kind` says which.\n */\nexport interface Subject {\n /** What the id identifies: `account`, `client`, `application`. Lower-case letters, digits and `_`. */\n kind: string;\n /** The product's id for it (a UUID, a slug). */\n id: string;\n}\n\n/** What a product records when a person agrees, or withdraws. */\nexport interface ConsentInput {\n subject: Subject;\n /** What the person agreed to (`marketing`, `screening`, `reminders`): one of the product's declared purposes. */\n purpose: string;\n /** The version of the notice shown to them: the proof of WHAT they agreed to. */\n version: string;\n granted: boolean;\n /** How they said it (`checkbox`, `link`, `verbal`, `erasure`). */\n means?: string | undefined;\n}\n\n/** A consent as written. It is never edited: a withdrawal is a new row. */\nexport interface ConsentRecord {\n id: string;\n subject: Subject;\n purpose: string;\n version: string;\n granted: boolean;\n means: string | null;\n at: Date;\n}\n\nexport const REQUEST_KIND = { export: \"export\", erasure: \"erasure\" } as const;\nexport type RequestKind = (typeof REQUEST_KIND)[keyof typeof REQUEST_KIND];\nexport const REQUEST_STATUS = { requested: \"requested\", completed: \"completed\", failed: \"failed\" } as const;\nexport type RequestStatus = (typeof REQUEST_STATUS)[keyof typeof REQUEST_STATUS];\n\n/** An export or an erasure asked for, and where it stands. It holds an id of the subject and no other personal data. */\nexport interface PrivacyRequest {\n id: string;\n subject: Subject;\n kind: RequestKind;\n status: RequestStatus;\n requestedAt: Date;\n completedAt: Date | null;\n /** A code, never a message that could carry data. */\n failure: string | null;\n}\n\n/**\n * A module that holds personal data. The product registers one per module and one for its own tables.\n *\n * - `exportFor` returns what the module holds about the subject, as JSON-able data.\n * - `eraseFor` erases or anonymises it, through the transaction it is given, so the whole erasure commits or rolls back together.\n * A side effect outside the database (a file in storage) is not done here: append it to the outbox in the same transaction.\n * - `purgeExpired` (optional) removes what the retention of a purpose says is past, for everyone.\n */\nexport interface PrivacyContributor {\n /** A stable name, the key of its part in the export (`audit`, `orders`). */\n name: string;\n exportFor(query: Query, subject: Subject): Promise<unknown>;\n eraseFor(tx: Query, subject: Subject): Promise<void>;\n purgeExpired?(tx: Query, input: { purpose: string; before: Date }): Promise<number>;\n}\n\n/** The whole export of a subject: one document, a part per contributor. */\nexport interface ExportDocument {\n format: 1;\n subject: Subject;\n generatedAt: string;\n modules: Record<string, unknown>;\n}\n\n/** Where consents and requests live. Every adapter runs `privacyStoreContract` (`@krizaka/privacy/testkit`). */\nexport interface PrivacyStore {\n insertConsent(consent: ConsentRecord): Promise<void>;\n /** The consent with the last word for this purpose, or null when the person never said anything. */\n latestConsent(subject: Subject, purpose: string): Promise<ConsentRecord | null>;\n /** Every consent of the subject, oldest first. */\n consentHistory(subject: Subject): Promise<ConsentRecord[]>;\n insertRequest(request: PrivacyRequest): Promise<void>;\n getRequest(id: string): Promise<PrivacyRequest | null>;\n finishRequest(id: string, outcome: { status: \"completed\" | \"failed\"; at: Date; failure?: string }): Promise<void>;\n requestsOf(subject: Subject): Promise<PrivacyRequest[]>;\n}\n\n/** The structural slice of `@krizaka/audit` this package writes through, so it adds no dependency. */\nexport interface AuditPort {\n record(query: Query, entry: { actorId: string | null; actorLabel: string; action: string; target?: { type: string; id: string } | null; detail?: Record<string, unknown> }): Promise<unknown>;\n}\n\n/** The structural slice of `@krizaka/outbox` used for a large export. */\nexport interface OutboxPort {\n append(tx: Query, message: { topic: string; type: string; payload: unknown; id?: string }): Promise<unknown>;\n}\n\nexport const PRIVACY_CODE = {\n badSubject: \"PRIVACY_BAD_SUBJECT\",\n badPurpose: \"PRIVACY_BAD_PURPOSE\",\n badConsent: \"PRIVACY_BAD_CONSENT\",\n unknownRequest: \"PRIVACY_UNKNOWN_REQUEST\",\n notAnExport: \"PRIVACY_NOT_AN_EXPORT\",\n alreadyDone: \"PRIVACY_ALREADY_DONE\",\n contributorFailed: \"PRIVACY_CONTRIBUTOR_FAILED\",\n noOutbox: \"PRIVACY_NO_OUTBOX\",\n} as const;\nexport type PrivacyCode = (typeof PRIVACY_CODE)[keyof typeof PRIVACY_CODE];\n\nexport class PrivacyError extends Error {\n constructor(\n readonly code: PrivacyCode,\n message: string,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = \"PrivacyError\";\n }\n}\n","import { PRIVACY_CODE, PrivacyError, type Subject } from \"./port\";\n\nconst KIND = /^[a-z][a-z0-9_]{0,39}$/;\nconst PURPOSE = /^[a-z][a-z0-9_-]{0,39}$/;\nconst MAX_ID = 200;\n\n/** @throws PrivacyError for a subject whose kind or id is not well formed */\nexport function checkSubject(subject: Subject): void {\n if (!KIND.test(subject.kind)) throw new PrivacyError(PRIVACY_CODE.badSubject, `subject kind « ${subject.kind} »: lower-case letters, digits and _, starting with a letter`);\n if (subject.id.length < 1 || subject.id.length > MAX_ID) throw new PrivacyError(PRIVACY_CODE.badSubject, `subject id: 1 to ${MAX_ID} characters`);\n}\n\n/** @throws PrivacyError for a purpose that is not lower-case letters, digits, `_` and `-`, starting with a letter */\nexport function checkPurpose(purpose: string): void {\n if (!PURPOSE.test(purpose)) throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose « ${purpose} »: lower-case letters, digits, _ and -, starting with a letter, at most 40 characters`);\n}\n"],"mappings":";AA2CO,IAAM,eAAe,EAAE,QAAQ,UAAU,SAAS,UAAU;AAE5D,IAAM,iBAAiB,EAAE,WAAW,aAAa,WAAW,aAAa,QAAQ,SAAS;AA8D1F,IAAM,eAAe;AAAA,EAC1B,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,UAAU;AACZ;AAGO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YACW,MACT,SACA,SACA;AACA,UAAM,SAAS,OAAO;AAJb;AAKT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAOb;;;AC9HA,IAAM,OAAO;AACb,IAAM,UAAU;AAChB,IAAM,SAAS;AAGR,SAAS,aAAa,SAAwB;AACnD,MAAI,CAAC,KAAK,KAAK,QAAQ,IAAI,EAAG,OAAM,IAAI,aAAa,aAAa,YAAY,qBAAkB,QAAQ,IAAI,iEAA8D;AAC1K,MAAI,QAAQ,GAAG,SAAS,KAAK,QAAQ,GAAG,SAAS,OAAQ,OAAM,IAAI,aAAa,aAAa,YAAY,oBAAoB,MAAM,aAAa;AAClJ;AAGO,SAAS,aAAa,SAAuB;AAClD,MAAI,CAAC,QAAQ,KAAK,OAAO,EAAG,OAAM,IAAI,aAAa,aAAa,YAAY,gBAAa,OAAO,2FAAwF;AAC1L;","names":[]}