@krizaka/privacy 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # @krizaka/privacy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 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`; Yasakia's async export; Orochia's and Kachizaka's admin exports; Yororis' consent columns). This is the one version.
4
+
5
+ ```ts
6
+ import { transaction } from "@krizaka/db";
7
+ import { auditContributor, createPrivacy, privacySchema } from "@krizaka/privacy";
8
+ import { privacySettings, retentionFromSettings } from "@krizaka/privacy/settings";
9
+
10
+ emitMigration(privacySchema, 1, { tables: {} }); // commit the SQL once, in your migrations: privacy.consent and privacy.request
11
+
12
+ const privacy = createPrivacy({
13
+ clock: { now: () => new Date() },
14
+ purposes: ["marketing", "screening"], // the purposes the product declares
15
+ contributors: [auditContributor(audit), ordersContributor, filesContributor], // every module that holds personal data
16
+ transaction: (work) => transaction(connect, work),
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
19
+ });
20
+
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
24
+ 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
27
+ ```
28
+
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.
30
+ - **`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
+ - **`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
+ - **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)`: Yasakia's asynchronous mode.
33
+ - **Erasure** runs every contributor's `eraseFor` in ONE transaction, withdraws the live consents (a new row each, version `erasure` or the one you pass), records the request and an audit entry `privacy.erasure_completed` that names the request and the modules and **no one**. If a contributor fails, nothing is erased, the request is recorded as `failed` with a code, and the error is thrown (if recording the failure fails too, an `AggregateError` with the original first).
34
+ - **Retention:** `privacySettings({ screening: { retentionDays: 365 } })` (`@krizaka/privacy/settings`, needs `@krizaka/settings` and `zod`) declares `privacy.retention.screeningDays` (`payment-history` → `paymentHistoryDays`). `purge` calls every contributor's `purgeExpired` for each purpose that has a retention.
35
+ - The request table holds an id of the subject and no other personal data, so it can outlive the erasure it proves. `privacyStoreContract` (from `@krizaka/privacy/testkit`) is the contract every store runs.
@@ -0,0 +1,43 @@
1
+ // src/port.ts
2
+ var REQUEST_KIND = { export: "export", erasure: "erasure" };
3
+ var REQUEST_STATUS = { requested: "requested", completed: "completed", failed: "failed" };
4
+ var PRIVACY_CODE = {
5
+ badSubject: "PRIVACY_BAD_SUBJECT",
6
+ badPurpose: "PRIVACY_BAD_PURPOSE",
7
+ badConsent: "PRIVACY_BAD_CONSENT",
8
+ unknownRequest: "PRIVACY_UNKNOWN_REQUEST",
9
+ notAnExport: "PRIVACY_NOT_AN_EXPORT",
10
+ alreadyDone: "PRIVACY_ALREADY_DONE",
11
+ contributorFailed: "PRIVACY_CONTRIBUTOR_FAILED",
12
+ noOutbox: "PRIVACY_NO_OUTBOX"
13
+ };
14
+ var PrivacyError = class extends Error {
15
+ constructor(code, message, options) {
16
+ super(message, options);
17
+ this.code = code;
18
+ this.name = "PrivacyError";
19
+ }
20
+ code;
21
+ };
22
+
23
+ // src/rules.ts
24
+ var KIND = /^[a-z][a-z0-9_]{0,39}$/;
25
+ var PURPOSE = /^[a-z][a-z0-9_-]{0,39}$/;
26
+ var MAX_ID = 200;
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`);
30
+ }
31
+ 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`);
33
+ }
34
+
35
+ export {
36
+ REQUEST_KIND,
37
+ REQUEST_STATUS,
38
+ PRIVACY_CODE,
39
+ PrivacyError,
40
+ checkSubject,
41
+ checkPurpose
42
+ };
43
+ //# sourceMappingURL=chunk-PMXEX2LW.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: 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":[]}
@@ -0,0 +1,105 @@
1
+ import * as _krizaka_db from '@krizaka/db';
2
+ import { Query, Clock } from '@krizaka/db';
3
+ export { Clock, Query } from '@krizaka/db';
4
+ import { P as PrivacyContributor, a as PrivacyStore, C as ConsentInput, b as ConsentRecord, S as Subject, E as ExportDocument, c as PrivacyRequest, A as AuditPort, O as OutboxPort } from './port-Ds9VVyC2.js';
5
+ export { d as PRIVACY_CODE, e as PrivacyCode, f as PrivacyError, R as REQUEST_KIND, g as REQUEST_STATUS, h as RequestKind, i as RequestStatus } from './port-Ds9VVyC2.js';
6
+
7
+ /** The structural slice of `@krizaka/audit` that contributes: what the trail holds about an actor, and detaching them from it. */
8
+ interface AuditTrail {
9
+ exportFor(query: Query, actorId: string): Promise<unknown>;
10
+ redactActor(query: Query, actorId: string): Promise<number>;
11
+ }
12
+ /**
13
+ * `@krizaka/audit` as a contributor: an export lists the actor's entries; an erasure detaches the person (id and address removed, the
14
+ * label « erased ») and keeps the facts. It applies to a subject of the kind the product's actors are (default `account`).
15
+ * @param audit the product's audit (`createAudit(...)`)
16
+ */
17
+ declare function auditContributor(audit: AuditTrail, options?: {
18
+ kind?: string;
19
+ }): PrivacyContributor;
20
+
21
+ /** An in-memory store, for unit tests and demos (the same behaviour as the database's: the contract kit runs on both). */
22
+ declare function memoryPrivacyStore(): PrivacyStore;
23
+
24
+ /**
25
+ * The PostgreSQL store of « privacy », over the `Query` it is given (the caller's transaction, to join its unit of work).
26
+ * @param schema the Postgres schema of the module, default `privacy`
27
+ */
28
+ declare function dbPrivacyStore(query: Query, schema?: string): PrivacyStore;
29
+
30
+ /** The product's unit of work: runs `work` on one connection, commits when it resolves, rolls back when it throws (`transaction` of `@krizaka/db`). */
31
+ type Transaction = <T>(work: (tx: Query) => Promise<T>) => Promise<T>;
32
+ interface PrivacyDeps {
33
+ clock: Clock;
34
+ /** Every module that holds personal data, and the product's own. Their names are the keys of the export. */
35
+ contributors: readonly PrivacyContributor[];
36
+ /** The purposes the product declares (`screening`, `marketing`). A consent for another is refused. */
37
+ purposes: readonly string[];
38
+ /** The product's transaction, for the erasure. */
39
+ transaction: Transaction;
40
+ /** How many days a purpose is kept: the settings `privacy.retention.<purpose>Days` (`retentionFromSettings`). `undefined` = no retention for it. */
41
+ retentionDays?: (purpose: string) => number | undefined | Promise<number | undefined>;
42
+ /** The audit trail: an erasure is recorded there without personal data. */
43
+ audit?: AuditPort;
44
+ /** The outbox: required for the asynchronous export of a large account (`requestExport`). */
45
+ outbox?: OutboxPort;
46
+ /** The store over a query. Default: the PostgreSQL store on schema `privacy`. */
47
+ storeFor?: (query: Query) => PrivacyStore;
48
+ /** The Postgres schema, when the product renamed the module's (used by the default store). */
49
+ schema?: string;
50
+ }
51
+ interface Privacy {
52
+ /** Writes a consent or a withdrawal. Never edits one. */
53
+ recordConsent(query: Query, input: ConsentInput): Promise<ConsentRecord>;
54
+ /** Whether the consent with the last word for this purpose is a yes. A person who never said anything has not consented. */
55
+ hasConsent(query: Query, subject: Subject, purpose: string): Promise<boolean>;
56
+ /** Every consent and withdrawal of the subject, oldest first. */
57
+ consentHistory(query: Query, subject: Subject): Promise<ConsentRecord[]>;
58
+ /** The export, at once: one document with a part per contributor. The request is recorded. */
59
+ exportSubject(query: Query, subject: Subject): Promise<ExportDocument>;
60
+ /**
61
+ * The export of a large account, asynchronously: records the request and appends a message to the outbox IN THE CALLER'S
62
+ * TRANSACTION (`tx`). A worker then calls `fulfilExport(requestId, deliver)`. The message holds the request id only.
63
+ */
64
+ requestExport(tx: Query, subject: Subject): Promise<{
65
+ requestId: string;
66
+ }>;
67
+ /** 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. */
68
+ fulfilExport(query: Query, requestId: string, deliver: (document: ExportDocument, request: PrivacyRequest) => Promise<void>): Promise<void>;
69
+ /**
70
+ * Erases the subject from every contributor in ONE transaction, withdraws their live consents, and records the request and an
71
+ * audit entry that names no one. If a contributor fails nothing is erased, the request is recorded as failed, and the error is thrown.
72
+ */
73
+ eraseSubject(subject: Subject, options?: {
74
+ noticeVersion?: string;
75
+ }): Promise<PrivacyRequest>;
76
+ /** Removes, for each purpose with a retention, what the contributors hold past it. Returns how many rows each purpose removed. */
77
+ purge(query: Query): Promise<Record<string, number>>;
78
+ /** The subject's requests, newest first. */
79
+ requests(query: Query, subject: Subject): Promise<PrivacyRequest[]>;
80
+ }
81
+ /**
82
+ * Privacy for a product (Loi 25).
83
+ * @param deps the contributors, the purposes, the product's transaction and the clock
84
+ * @throws PrivacyError for a purpose or a contributor name that is not well formed or appears twice
85
+ */
86
+ declare function createPrivacy(deps: PrivacyDeps): Privacy;
87
+
88
+ /** @throws PrivacyError for a subject whose kind or id is not well formed */
89
+ declare function checkSubject(subject: Subject): void;
90
+ /** @throws PrivacyError for a purpose that is not lower-case letters, digits, `_` and `-`, starting with a letter */
91
+ declare function checkPurpose(purpose: string): void;
92
+
93
+ /**
94
+ * The tables of « privacy », in their own Postgres schema (ADR-001 §3). They reference no product table: a subject is a kind and an
95
+ * id the product chooses (an account, a client file, an application).
96
+ *
97
+ * - `consent` is WRITTEN ONCE: a trigger refuses any update. A withdrawal is a new row; the consent with the last word (highest `seq`) wins.
98
+ * - `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,
99
+ * so it can outlive the erasure it proves.
100
+ *
101
+ * Version 1 is frozen once released: a change is version 2.
102
+ */
103
+ declare const privacySchema: _krizaka_db.ModuleSchema;
104
+
105
+ export { AuditPort, type AuditTrail, ConsentInput, ConsentRecord, ExportDocument, OutboxPort, type Privacy, PrivacyContributor, type PrivacyDeps, PrivacyRequest, PrivacyStore, Subject, type Transaction, auditContributor, checkPurpose, checkSubject, createPrivacy, dbPrivacyStore, memoryPrivacyStore, privacySchema };
package/dist/index.js ADDED
@@ -0,0 +1,280 @@
1
+ import {
2
+ PRIVACY_CODE,
3
+ PrivacyError,
4
+ REQUEST_KIND,
5
+ REQUEST_STATUS,
6
+ checkPurpose,
7
+ checkSubject
8
+ } from "./chunk-PMXEX2LW.js";
9
+
10
+ // src/contributors.ts
11
+ function auditContributor(audit, options = {}) {
12
+ const kind = options.kind ?? "account";
13
+ return {
14
+ name: "audit",
15
+ async exportFor(query, subject) {
16
+ return subject.kind === kind ? audit.exportFor(query, subject.id) : [];
17
+ },
18
+ async eraseFor(tx, subject) {
19
+ if (subject.kind === kind) await audit.redactActor(tx, subject.id);
20
+ }
21
+ };
22
+ }
23
+
24
+ // src/memory.ts
25
+ var sameSubject = (a, b) => a.kind === b.kind && a.id === b.id;
26
+ function memoryPrivacyStore() {
27
+ const consents = [];
28
+ const requests = /* @__PURE__ */ new Map();
29
+ return {
30
+ async insertConsent(c) {
31
+ consents.push(structuredClone(c));
32
+ },
33
+ async latestConsent(subject, purpose) {
34
+ const found = consents.filter((c) => sameSubject(c.subject, subject) && c.purpose === purpose).at(-1);
35
+ return found ? structuredClone(found) : null;
36
+ },
37
+ async consentHistory(subject) {
38
+ return consents.filter((c) => sameSubject(c.subject, subject)).map((c) => structuredClone(c));
39
+ },
40
+ async insertRequest(r) {
41
+ requests.set(r.id, structuredClone(r));
42
+ },
43
+ async getRequest(id) {
44
+ const found = requests.get(id);
45
+ return found ? structuredClone(found) : null;
46
+ },
47
+ async finishRequest(id, outcome) {
48
+ const found = requests.get(id);
49
+ if (found) Object.assign(found, { status: outcome.status, completedAt: outcome.at, failure: outcome.failure ?? null });
50
+ },
51
+ async requestsOf(subject) {
52
+ return [...requests.values()].filter((r) => sameSubject(r.subject, subject)).sort((a, b) => b.requestedAt.valueOf() - a.requestedAt.valueOf()).map((r) => structuredClone(r));
53
+ }
54
+ };
55
+ }
56
+
57
+ // src/persistence.ts
58
+ import { ident } from "@krizaka/db";
59
+ var toConsent = (r) => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, purpose: r.purpose, version: r.version, granted: r.granted, means: r.means, at: new Date(r.at) });
60
+ var toRequest = (r) => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, kind: r.kind, status: r.status, requestedAt: new Date(r.requested_at), completedAt: r.completed_at === null ? null : new Date(r.completed_at), failure: r.failure });
61
+ var CONSENT_COLUMNS = "id, subject_kind, subject_id, purpose, version, granted, means, at";
62
+ var REQUEST_COLUMNS = "id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure";
63
+ function dbPrivacyStore(query, schema = "privacy") {
64
+ const consent = `${ident(schema)}.consent`;
65
+ const request = `${ident(schema)}.request`;
66
+ const same = (subject) => [subject.kind, subject.id];
67
+ return {
68
+ async insertConsent(c) {
69
+ 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]);
70
+ },
71
+ async latestConsent(subject, purpose) {
72
+ 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]);
73
+ return row ? toConsent(row) : null;
74
+ },
75
+ async consentHistory(subject) {
76
+ return (await query(`SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY seq`, same(subject))).map(toConsent);
77
+ },
78
+ async insertRequest(r) {
79
+ 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]);
80
+ },
81
+ async getRequest(id) {
82
+ const [row] = await query(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE id = $1`, [id]);
83
+ return row ? toRequest(row) : null;
84
+ },
85
+ async finishRequest(id, outcome) {
86
+ await query(`UPDATE ${request} SET status = $2, completed_at = $3, failure = $4 WHERE id = $1`, [id, outcome.status, outcome.at, outcome.failure ?? null]);
87
+ },
88
+ async requestsOf(subject) {
89
+ 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);
90
+ }
91
+ };
92
+ }
93
+
94
+ // src/privacy.ts
95
+ import { randomUUID } from "crypto";
96
+ import { ident as ident2 } from "@krizaka/db";
97
+ import { subHours } from "@krizaka/time";
98
+ var FAILURE_CODE = "CONTRIBUTOR_FAILED";
99
+ var ERASURE_VERSION = "erasure";
100
+ function createPrivacy(deps) {
101
+ const schema = ident2(deps.schema ?? "privacy");
102
+ const storeFor = deps.storeFor ?? ((query) => dbPrivacyStore(query, schema));
103
+ for (const purpose of deps.purposes) checkPurpose(purpose);
104
+ const names = deps.contributors.map((c) => c.name);
105
+ if (new Set(names).size !== names.length) throw new PrivacyError(PRIVACY_CODE.contributorFailed, `two contributors have the same name: ${names.join(", ")}`);
106
+ const known = new Set(deps.purposes);
107
+ async function assemble(query, subject) {
108
+ const modules = {};
109
+ for (const contributor of deps.contributors) {
110
+ try {
111
+ modules[contributor.name] = await contributor.exportFor(query, subject);
112
+ } catch (cause) {
113
+ throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the export of \xAB ${contributor.name} \xBB failed`, { cause });
114
+ }
115
+ }
116
+ return { format: 1, subject, generatedAt: deps.clock.now().toISOString(), modules };
117
+ }
118
+ const newRequest = (subject, kind) => ({ id: randomUUID(), subject, kind, status: REQUEST_STATUS.requested, requestedAt: deps.clock.now(), completedAt: null, failure: null });
119
+ async function recordConsent(query, input) {
120
+ checkSubject(input.subject);
121
+ checkPurpose(input.purpose);
122
+ if (!known.has(input.purpose)) throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose \xAB ${input.purpose} \xBB is not one the product declared`);
123
+ if (input.version.length < 1 || input.version.length > 100) throw new PrivacyError(PRIVACY_CODE.badConsent, "the notice version is 1 to 100 characters");
124
+ const record = { id: randomUUID(), subject: input.subject, purpose: input.purpose, version: input.version, granted: input.granted, means: input.means ?? null, at: deps.clock.now() };
125
+ await storeFor(query).insertConsent(record);
126
+ return record;
127
+ }
128
+ return {
129
+ recordConsent,
130
+ async hasConsent(query, subject, purpose) {
131
+ checkSubject(subject);
132
+ checkPurpose(purpose);
133
+ return (await storeFor(query).latestConsent(subject, purpose))?.granted === true;
134
+ },
135
+ async consentHistory(query, subject) {
136
+ checkSubject(subject);
137
+ return storeFor(query).consentHistory(subject);
138
+ },
139
+ async exportSubject(query, subject) {
140
+ checkSubject(subject);
141
+ const store = storeFor(query);
142
+ const request = newRequest(subject, REQUEST_KIND.export);
143
+ await store.insertRequest(request);
144
+ try {
145
+ const document = await assemble(query, subject);
146
+ await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: deps.clock.now() });
147
+ return document;
148
+ } catch (error) {
149
+ await store.finishRequest(request.id, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });
150
+ throw error;
151
+ }
152
+ },
153
+ async requestExport(tx, subject) {
154
+ checkSubject(subject);
155
+ if (!deps.outbox) throw new PrivacyError(PRIVACY_CODE.noOutbox, "an asynchronous export needs the outbox");
156
+ const request = newRequest(subject, REQUEST_KIND.export);
157
+ await storeFor(tx).insertRequest(request);
158
+ await deps.outbox.append(tx, { topic: "privacy", type: "evt.privacy.export_requested.v1", payload: { requestId: request.id }, id: request.id });
159
+ return { requestId: request.id };
160
+ },
161
+ async fulfilExport(query, requestId, deliver) {
162
+ const store = storeFor(query);
163
+ const request = await store.getRequest(requestId);
164
+ if (!request) throw new PrivacyError(PRIVACY_CODE.unknownRequest, `no request ${requestId}`);
165
+ if (request.kind !== REQUEST_KIND.export) throw new PrivacyError(PRIVACY_CODE.notAnExport, `request ${requestId} is not an export`);
166
+ if (request.status === REQUEST_STATUS.completed) throw new PrivacyError(PRIVACY_CODE.alreadyDone, `request ${requestId} is already completed`);
167
+ try {
168
+ await deliver(await assemble(query, request.subject), request);
169
+ } catch (error) {
170
+ await store.finishRequest(requestId, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });
171
+ throw error;
172
+ }
173
+ await store.finishRequest(requestId, { status: REQUEST_STATUS.completed, at: deps.clock.now() });
174
+ },
175
+ async eraseSubject(subject, options = {}) {
176
+ checkSubject(subject);
177
+ const request = newRequest(subject, REQUEST_KIND.erasure);
178
+ try {
179
+ return await deps.transaction(async (tx) => {
180
+ const store = storeFor(tx);
181
+ await store.insertRequest(request);
182
+ for (const contributor of deps.contributors) {
183
+ try {
184
+ await contributor.eraseFor(tx, subject);
185
+ } catch (cause) {
186
+ throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the erasure of \xAB ${contributor.name} \xBB failed`, { cause });
187
+ }
188
+ }
189
+ for (const purpose of deps.purposes) {
190
+ if ((await store.latestConsent(subject, purpose))?.granted) await recordConsent(tx, { subject, purpose, version: options.noticeVersion ?? ERASURE_VERSION, granted: false, means: ERASURE_VERSION });
191
+ }
192
+ const completedAt = deps.clock.now();
193
+ await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: completedAt });
194
+ await deps.audit?.record(tx, { actorId: null, actorLabel: "privacy", action: "privacy.erasure_completed", target: { type: "privacy_request", id: request.id }, detail: { contributors: names } });
195
+ return { ...request, status: REQUEST_STATUS.completed, completedAt };
196
+ });
197
+ } catch (error) {
198
+ try {
199
+ await deps.transaction((tx) => storeFor(tx).insertRequest({ ...request, status: REQUEST_STATUS.failed, completedAt: deps.clock.now(), failure: FAILURE_CODE }));
200
+ } catch (recordFailure) {
201
+ throw new AggregateError([error, recordFailure], "the erasure failed, and so did recording its failure", { cause: recordFailure });
202
+ }
203
+ throw error;
204
+ }
205
+ },
206
+ async purge(query) {
207
+ const removed = {};
208
+ for (const purpose of deps.purposes) {
209
+ const days = await deps.retentionDays?.(purpose);
210
+ if (days === void 0) continue;
211
+ 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}`);
212
+ const before = subHours(deps.clock.now(), days * 24);
213
+ let total = 0;
214
+ for (const contributor of deps.contributors) total += await contributor.purgeExpired?.(query, { purpose, before }) ?? 0;
215
+ removed[purpose] = total;
216
+ }
217
+ return removed;
218
+ },
219
+ async requests(query, subject) {
220
+ checkSubject(subject);
221
+ return storeFor(query).requestsOf(subject);
222
+ }
223
+ };
224
+ }
225
+
226
+ // src/schema.ts
227
+ import { defineModule } from "@krizaka/db";
228
+ var privacySchema = defineModule({
229
+ module: "privacy",
230
+ migrations: [
231
+ {
232
+ version: 1,
233
+ name: "consents and requests",
234
+ sql: (c) => `
235
+ CREATE TABLE ${c.schema}.consent (
236
+ seq bigserial UNIQUE,
237
+ id uuid PRIMARY KEY,
238
+ subject_kind text NOT NULL CHECK (subject_kind ~ '^[a-z][a-z0-9_]{0,39}$'),
239
+ subject_id text NOT NULL CHECK (char_length(subject_id) BETWEEN 1 AND 200),
240
+ purpose text NOT NULL CHECK (purpose ~ '^[a-z][a-z0-9_-]{0,39}$'),
241
+ version text NOT NULL CHECK (char_length(version) BETWEEN 1 AND 100),
242
+ granted boolean NOT NULL,
243
+ means text CHECK (means IS NULL OR char_length(means) <= 40),
244
+ at timestamptz NOT NULL
245
+ );
246
+ CREATE INDEX consent_subject ON ${c.schema}.consent (subject_kind, subject_id, purpose, seq DESC);
247
+ CREATE FUNCTION ${c.schema}.consent_written_once() RETURNS trigger LANGUAGE plpgsql AS $fn$
248
+ BEGIN
249
+ RAISE EXCEPTION 'a consent is written once: a withdrawal is a new row' USING ERRCODE = 'restrict_violation';
250
+ END;
251
+ $fn$;
252
+ CREATE TRIGGER consent_written_once BEFORE UPDATE ON ${c.schema}.consent FOR EACH ROW EXECUTE FUNCTION ${c.schema}.consent_written_once();
253
+ CREATE TABLE ${c.schema}.request (
254
+ id uuid PRIMARY KEY,
255
+ subject_kind text NOT NULL CHECK (subject_kind ~ '^[a-z][a-z0-9_]{0,39}$'),
256
+ subject_id text NOT NULL CHECK (char_length(subject_id) BETWEEN 1 AND 200),
257
+ kind text NOT NULL CHECK (kind IN ('export', 'erasure')),
258
+ status text NOT NULL CHECK (status IN ('requested', 'completed', 'failed')),
259
+ requested_at timestamptz NOT NULL,
260
+ completed_at timestamptz,
261
+ failure text CHECK (failure IS NULL OR char_length(failure) <= 100)
262
+ );
263
+ CREATE INDEX request_subject ON ${c.schema}.request (subject_kind, subject_id, requested_at DESC);`
264
+ }
265
+ ]
266
+ });
267
+ export {
268
+ PRIVACY_CODE,
269
+ PrivacyError,
270
+ REQUEST_KIND,
271
+ REQUEST_STATUS,
272
+ auditContributor,
273
+ checkPurpose,
274
+ checkSubject,
275
+ createPrivacy,
276
+ dbPrivacyStore,
277
+ memoryPrivacyStore,
278
+ privacySchema
279
+ };
280
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/contributors.ts","../src/memory.ts","../src/persistence.ts","../src/privacy.ts","../src/schema.ts"],"sourcesContent":["import type { Query } from \"@krizaka/db\";\n\nimport type { PrivacyContributor } from \"./port\";\n\n/** The structural slice of `@krizaka/audit` that contributes: what the trail holds about an actor, and detaching them from it. */\nexport interface AuditTrail {\n exportFor(query: Query, actorId: string): Promise<unknown>;\n redactActor(query: Query, actorId: string): Promise<number>;\n}\n\n/**\n * `@krizaka/audit` as a contributor: an export lists the actor's entries; an erasure detaches the person (id and address removed, the\n * label « erased ») and keeps the facts. It applies to a subject of the kind the product's actors are (default `account`).\n * @param audit the product's audit (`createAudit(...)`)\n */\nexport function auditContributor(audit: AuditTrail, options: { kind?: string } = {}): PrivacyContributor {\n const kind = options.kind ?? \"account\";\n return {\n name: \"audit\",\n async exportFor(query, subject) {\n return subject.kind === kind ? audit.exportFor(query, subject.id) : [];\n },\n async eraseFor(tx, subject) {\n if (subject.kind === kind) await audit.redactActor(tx, subject.id);\n },\n };\n}\n","import type { ConsentRecord, PrivacyRequest, PrivacyStore, Subject } from \"./port\";\n\nconst sameSubject = (a: Subject, b: Subject) => a.kind === b.kind && a.id === b.id;\n\n/** An in-memory store, for unit tests and demos (the same behaviour as the database's: the contract kit runs on both). */\nexport function memoryPrivacyStore(): PrivacyStore {\n const consents: ConsentRecord[] = [];\n const requests = new Map<string, PrivacyRequest>();\n return {\n async insertConsent(c) {\n consents.push(structuredClone(c));\n },\n async latestConsent(subject, purpose) {\n const found = consents.filter((c) => sameSubject(c.subject, subject) && c.purpose === purpose).at(-1);\n return found ? structuredClone(found) : null;\n },\n async consentHistory(subject) {\n return consents.filter((c) => sameSubject(c.subject, subject)).map((c) => structuredClone(c));\n },\n async insertRequest(r) {\n requests.set(r.id, structuredClone(r));\n },\n async getRequest(id) {\n const found = requests.get(id);\n return found ? structuredClone(found) : null;\n },\n async finishRequest(id, outcome) {\n const found = requests.get(id);\n if (found) Object.assign(found, { status: outcome.status, completedAt: outcome.at, failure: outcome.failure ?? null });\n },\n async requestsOf(subject) {\n return [...requests.values()].filter((r) => sameSubject(r.subject, subject)).sort((a, b) => b.requestedAt.valueOf() - a.requestedAt.valueOf()).map((r) => structuredClone(r));\n },\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { ConsentRecord, PrivacyRequest, PrivacyStore, RequestKind, RequestStatus, Subject } from \"./port\";\n\ninterface ConsentRow {\n id: string;\n subject_kind: string;\n subject_id: string;\n purpose: string;\n version: string;\n granted: boolean;\n means: string | null;\n at: Date | string;\n}\ninterface RequestRow {\n id: string;\n subject_kind: string;\n subject_id: string;\n kind: RequestKind;\n status: RequestStatus;\n requested_at: Date | string;\n completed_at: Date | string | null;\n failure: string | null;\n}\n\nconst toConsent = (r: ConsentRow): ConsentRecord => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, purpose: r.purpose, version: r.version, granted: r.granted, means: r.means, at: new Date(r.at) });\nconst toRequest = (r: RequestRow): PrivacyRequest => ({ id: r.id, subject: { kind: r.subject_kind, id: r.subject_id }, kind: r.kind, status: r.status, requestedAt: new Date(r.requested_at), completedAt: r.completed_at === null ? null : new Date(r.completed_at), failure: r.failure });\n\nconst CONSENT_COLUMNS = \"id, subject_kind, subject_id, purpose, version, granted, means, at\";\nconst REQUEST_COLUMNS = \"id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure\";\n\n/**\n * The PostgreSQL store of « privacy », over the `Query` it is given (the caller's transaction, to join its unit of work).\n * @param schema the Postgres schema of the module, default `privacy`\n */\nexport function dbPrivacyStore(query: Query, schema = \"privacy\"): PrivacyStore {\n const consent = `${ident(schema)}.consent`;\n const request = `${ident(schema)}.request`;\n const same = (subject: Subject) => [subject.kind, subject.id];\n return {\n async insertConsent(c) {\n await query(`INSERT INTO ${consent} (id, subject_kind, subject_id, purpose, version, granted, means, at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [c.id, c.subject.kind, c.subject.id, c.purpose, c.version, c.granted, c.means, c.at]);\n },\n async latestConsent(subject, purpose) {\n const [row] = await query<ConsentRow>(`SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 AND purpose = $3 ORDER BY seq DESC LIMIT 1`, [...same(subject), purpose]);\n return row ? toConsent(row) : null;\n },\n async consentHistory(subject) {\n return (await query<ConsentRow>(`SELECT ${CONSENT_COLUMNS} FROM ${consent} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY seq`, same(subject))).map(toConsent);\n },\n async insertRequest(r) {\n await query(`INSERT INTO ${request} (id, subject_kind, subject_id, kind, status, requested_at, completed_at, failure) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [r.id, r.subject.kind, r.subject.id, r.kind, r.status, r.requestedAt, r.completedAt, r.failure]);\n },\n async getRequest(id) {\n const [row] = await query<RequestRow>(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE id = $1`, [id]);\n return row ? toRequest(row) : null;\n },\n async finishRequest(id, outcome) {\n await query(`UPDATE ${request} SET status = $2, completed_at = $3, failure = $4 WHERE id = $1`, [id, outcome.status, outcome.at, outcome.failure ?? null]);\n },\n async requestsOf(subject) {\n return (await query<RequestRow>(`SELECT ${REQUEST_COLUMNS} FROM ${request} WHERE subject_kind = $1 AND subject_id = $2 ORDER BY requested_at DESC, id`, same(subject))).map(toRequest);\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { ident } from \"@krizaka/db\";\nimport { subHours } from \"@krizaka/time\";\n\nimport { dbPrivacyStore } from \"./persistence\";\nimport {\n type AuditPort,\n type Clock,\n type ConsentInput,\n type ConsentRecord,\n type ExportDocument,\n type OutboxPort,\n PRIVACY_CODE,\n type PrivacyContributor,\n PrivacyError,\n type PrivacyRequest,\n type PrivacyStore,\n type Query,\n REQUEST_KIND,\n REQUEST_STATUS,\n type Subject,\n} from \"./port\";\nimport { checkPurpose, checkSubject } from \"./rules\";\n\n/** The product's unit of work: runs `work` on one connection, commits when it resolves, rolls back when it throws (`transaction` of `@krizaka/db`). */\nexport type Transaction = <T>(work: (tx: Query) => Promise<T>) => Promise<T>;\n\nexport interface PrivacyDeps {\n clock: Clock;\n /** Every module that holds personal data, and the product's own. Their names are the keys of the export. */\n contributors: readonly PrivacyContributor[];\n /** The purposes the product declares (`screening`, `marketing`). A consent for another is refused. */\n purposes: readonly string[];\n /** The product's transaction, for the erasure. */\n transaction: Transaction;\n /** How many days a purpose is kept: the settings `privacy.retention.<purpose>Days` (`retentionFromSettings`). `undefined` = no retention for it. */\n retentionDays?: (purpose: string) => number | undefined | Promise<number | undefined>;\n /** The audit trail: an erasure is recorded there without personal data. */\n audit?: AuditPort;\n /** The outbox: required for the asynchronous export of a large account (`requestExport`). */\n outbox?: OutboxPort;\n /** The store over a query. Default: the PostgreSQL store on schema `privacy`. */\n storeFor?: (query: Query) => PrivacyStore;\n /** The Postgres schema, when the product renamed the module's (used by the default store). */\n schema?: string;\n}\n\nexport interface Privacy {\n /** Writes a consent or a withdrawal. Never edits one. */\n recordConsent(query: Query, input: ConsentInput): Promise<ConsentRecord>;\n /** Whether the consent with the last word for this purpose is a yes. A person who never said anything has not consented. */\n hasConsent(query: Query, subject: Subject, purpose: string): Promise<boolean>;\n /** Every consent and withdrawal of the subject, oldest first. */\n consentHistory(query: Query, subject: Subject): Promise<ConsentRecord[]>;\n /** The export, at once: one document with a part per contributor. The request is recorded. */\n exportSubject(query: Query, subject: Subject): Promise<ExportDocument>;\n /**\n * The export of a large account, asynchronously: records the request and appends a message to the outbox IN THE CALLER'S\n * TRANSACTION (`tx`). A worker then calls `fulfilExport(requestId, deliver)`. The message holds the request id only.\n */\n requestExport(tx: Query, subject: Subject): Promise<{ requestId: string }>;\n /** Assembles the export of a recorded request and hands it to `deliver` (store the file, mail a link); the request is completed after `deliver` returns. */\n fulfilExport(query: Query, requestId: string, deliver: (document: ExportDocument, request: PrivacyRequest) => Promise<void>): Promise<void>;\n /**\n * Erases the subject from every contributor in ONE transaction, withdraws their live consents, and records the request and an\n * audit entry that names no one. If a contributor fails nothing is erased, the request is recorded as failed, and the error is thrown.\n */\n eraseSubject(subject: Subject, options?: { noticeVersion?: string }): Promise<PrivacyRequest>;\n /** Removes, for each purpose with a retention, what the contributors hold past it. Returns how many rows each purpose removed. */\n purge(query: Query): Promise<Record<string, number>>;\n /** The subject's requests, newest first. */\n requests(query: Query, subject: Subject): Promise<PrivacyRequest[]>;\n}\n\nconst FAILURE_CODE = \"CONTRIBUTOR_FAILED\";\nconst ERASURE_VERSION = \"erasure\";\n\n/**\n * Privacy for a product (Loi 25).\n * @param deps the contributors, the purposes, the product's transaction and the clock\n * @throws PrivacyError for a purpose or a contributor name that is not well formed or appears twice\n */\nexport function createPrivacy(deps: PrivacyDeps): Privacy {\n const schema = ident(deps.schema ?? \"privacy\");\n const storeFor = deps.storeFor ?? ((query: Query) => dbPrivacyStore(query, schema));\n for (const purpose of deps.purposes) checkPurpose(purpose);\n const names = deps.contributors.map((c) => c.name);\n if (new Set(names).size !== names.length) throw new PrivacyError(PRIVACY_CODE.contributorFailed, `two contributors have the same name: ${names.join(\", \")}`);\n const known = new Set(deps.purposes);\n\n async function assemble(query: Query, subject: Subject): Promise<ExportDocument> {\n const modules: Record<string, unknown> = {};\n for (const contributor of deps.contributors) {\n try {\n modules[contributor.name] = await contributor.exportFor(query, subject);\n } catch (cause) {\n throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the export of « ${contributor.name} » failed`, { cause });\n }\n }\n return { format: 1, subject, generatedAt: deps.clock.now().toISOString(), modules };\n }\n\n const newRequest = (subject: Subject, kind: PrivacyRequest[\"kind\"]): PrivacyRequest => ({ id: randomUUID(), subject, kind, status: REQUEST_STATUS.requested, requestedAt: deps.clock.now(), completedAt: null, failure: null });\n\n async function recordConsent(query: Query, input: ConsentInput): Promise<ConsentRecord> {\n checkSubject(input.subject);\n checkPurpose(input.purpose);\n if (!known.has(input.purpose)) throw new PrivacyError(PRIVACY_CODE.badPurpose, `purpose « ${input.purpose} » is not one the product declared`);\n if (input.version.length < 1 || input.version.length > 100) throw new PrivacyError(PRIVACY_CODE.badConsent, \"the notice version is 1 to 100 characters\");\n const record: ConsentRecord = { id: randomUUID(), subject: input.subject, purpose: input.purpose, version: input.version, granted: input.granted, means: input.means ?? null, at: deps.clock.now() };\n await storeFor(query).insertConsent(record);\n return record;\n }\n\n return {\n recordConsent,\n async hasConsent(query, subject, purpose) {\n checkSubject(subject);\n checkPurpose(purpose);\n return (await storeFor(query).latestConsent(subject, purpose))?.granted === true;\n },\n async consentHistory(query, subject) {\n checkSubject(subject);\n return storeFor(query).consentHistory(subject);\n },\n async exportSubject(query, subject) {\n checkSubject(subject);\n const store = storeFor(query);\n const request = newRequest(subject, REQUEST_KIND.export);\n await store.insertRequest(request);\n try {\n const document = await assemble(query, subject);\n await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: deps.clock.now() });\n return document;\n } catch (error) {\n await store.finishRequest(request.id, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });\n throw error;\n }\n },\n async requestExport(tx, subject) {\n checkSubject(subject);\n if (!deps.outbox) throw new PrivacyError(PRIVACY_CODE.noOutbox, \"an asynchronous export needs the outbox\");\n const request = newRequest(subject, REQUEST_KIND.export);\n await storeFor(tx).insertRequest(request);\n await deps.outbox.append(tx, { topic: \"privacy\", type: \"evt.privacy.export_requested.v1\", payload: { requestId: request.id }, id: request.id });\n return { requestId: request.id };\n },\n async fulfilExport(query, requestId, deliver) {\n const store = storeFor(query);\n const request = await store.getRequest(requestId);\n if (!request) throw new PrivacyError(PRIVACY_CODE.unknownRequest, `no request ${requestId}`);\n if (request.kind !== REQUEST_KIND.export) throw new PrivacyError(PRIVACY_CODE.notAnExport, `request ${requestId} is not an export`);\n if (request.status === REQUEST_STATUS.completed) throw new PrivacyError(PRIVACY_CODE.alreadyDone, `request ${requestId} is already completed`);\n try {\n await deliver(await assemble(query, request.subject), request);\n } catch (error) {\n await store.finishRequest(requestId, { status: REQUEST_STATUS.failed, at: deps.clock.now(), failure: FAILURE_CODE });\n throw error;\n }\n await store.finishRequest(requestId, { status: REQUEST_STATUS.completed, at: deps.clock.now() });\n },\n async eraseSubject(subject, options = {}) {\n checkSubject(subject);\n const request = newRequest(subject, REQUEST_KIND.erasure);\n try {\n return await deps.transaction(async (tx) => {\n const store = storeFor(tx);\n await store.insertRequest(request);\n for (const contributor of deps.contributors) {\n try {\n await contributor.eraseFor(tx, subject);\n } catch (cause) {\n throw new PrivacyError(PRIVACY_CODE.contributorFailed, `the erasure of « ${contributor.name} » failed`, { cause });\n }\n }\n for (const purpose of deps.purposes) {\n if ((await store.latestConsent(subject, purpose))?.granted) await recordConsent(tx, { subject, purpose, version: options.noticeVersion ?? ERASURE_VERSION, granted: false, means: ERASURE_VERSION });\n }\n const completedAt = deps.clock.now();\n await store.finishRequest(request.id, { status: REQUEST_STATUS.completed, at: completedAt });\n // the entry names the request and the modules, never the person\n await deps.audit?.record(tx, { actorId: null, actorLabel: \"privacy\", action: \"privacy.erasure_completed\", target: { type: \"privacy_request\", id: request.id }, detail: { contributors: names } });\n return { ...request, status: REQUEST_STATUS.completed, completedAt };\n });\n } catch (error) {\n // the transaction rolled back, request row included: record the failure beside it, and never mask the original error\n try {\n await deps.transaction((tx) => storeFor(tx).insertRequest({ ...request, status: REQUEST_STATUS.failed, completedAt: deps.clock.now(), failure: FAILURE_CODE }));\n } catch (recordFailure) {\n throw new AggregateError([error, recordFailure], \"the erasure failed, and so did recording its failure\", { cause: recordFailure });\n }\n throw error;\n }\n },\n async purge(query) {\n const removed: Record<string, number> = {};\n for (const purpose of deps.purposes) {\n const days = await deps.retentionDays?.(purpose);\n if (days === undefined) continue;\n if (!Number.isInteger(days) || days < 1) throw new RangeError(`the retention of « ${purpose} » must be a whole number of days from 1, got ${days}`);\n const before = subHours(deps.clock.now(), days * 24);\n let total = 0;\n for (const contributor of deps.contributors) total += (await contributor.purgeExpired?.(query, { purpose, before })) ?? 0;\n removed[purpose] = total;\n }\n return removed;\n },\n async requests(query, subject) {\n checkSubject(subject);\n return storeFor(query).requestsOf(subject);\n },\n };\n}\n","import { defineModule } from \"@krizaka/db\";\n\n/**\n * The tables of « privacy », in their own Postgres schema (ADR-001 §3). They reference no product table: a subject is a kind and an\n * id the product chooses (an account, a client file, an application).\n *\n * - `consent` is WRITTEN ONCE: a trigger refuses any update. A withdrawal is a new row; the consent with the last word (highest `seq`) wins.\n * - `request` is the record of an export or an erasure: when, of what kind, how it ended. It holds an id and no other personal data,\n * so it can outlive the erasure it proves.\n *\n * Version 1 is frozen once released: a change is version 2.\n */\nexport const privacySchema = defineModule({\n module: \"privacy\",\n migrations: [\n {\n version: 1,\n name: \"consents and requests\",\n sql: (c) => `\nCREATE TABLE ${c.schema}.consent (\n seq bigserial UNIQUE,\n id uuid PRIMARY KEY,\n subject_kind text NOT NULL CHECK (subject_kind ~ '^[a-z][a-z0-9_]{0,39}$'),\n subject_id text NOT NULL CHECK (char_length(subject_id) BETWEEN 1 AND 200),\n purpose text NOT NULL CHECK (purpose ~ '^[a-z][a-z0-9_-]{0,39}$'),\n version text NOT NULL CHECK (char_length(version) BETWEEN 1 AND 100),\n granted boolean NOT NULL,\n means text CHECK (means IS NULL OR char_length(means) <= 40),\n at timestamptz NOT NULL\n);\nCREATE INDEX consent_subject ON ${c.schema}.consent (subject_kind, subject_id, purpose, seq DESC);\nCREATE FUNCTION ${c.schema}.consent_written_once() RETURNS trigger LANGUAGE plpgsql AS $fn$\nBEGIN\n RAISE EXCEPTION 'a consent is written once: a withdrawal is a new row' USING ERRCODE = 'restrict_violation';\nEND;\n$fn$;\nCREATE TRIGGER consent_written_once BEFORE UPDATE ON ${c.schema}.consent FOR EACH ROW EXECUTE FUNCTION ${c.schema}.consent_written_once();\nCREATE TABLE ${c.schema}.request (\n id uuid PRIMARY KEY,\n subject_kind text NOT NULL CHECK (subject_kind ~ '^[a-z][a-z0-9_]{0,39}$'),\n subject_id text NOT NULL CHECK (char_length(subject_id) BETWEEN 1 AND 200),\n kind text NOT NULL CHECK (kind IN ('export', 'erasure')),\n status text NOT NULL CHECK (status IN ('requested', 'completed', 'failed')),\n requested_at timestamptz NOT NULL,\n completed_at timestamptz,\n failure text CHECK (failure IS NULL OR char_length(failure) <= 100)\n);\nCREATE INDEX request_subject ON ${c.schema}.request (subject_kind, subject_id, requested_at DESC);`,\n },\n ],\n});\n"],"mappings":";;;;;;;;;;AAeO,SAAS,iBAAiB,OAAmB,UAA6B,CAAC,GAAuB;AACvG,QAAM,OAAO,QAAQ,QAAQ;AAC7B,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,UAAU,OAAO,SAAS;AAC9B,aAAO,QAAQ,SAAS,OAAO,MAAM,UAAU,OAAO,QAAQ,EAAE,IAAI,CAAC;AAAA,IACvE;AAAA,IACA,MAAM,SAAS,IAAI,SAAS;AAC1B,UAAI,QAAQ,SAAS,KAAM,OAAM,MAAM,YAAY,IAAI,QAAQ,EAAE;AAAA,IACnE;AAAA,EACF;AACF;;;ACxBA,IAAM,cAAc,CAAC,GAAY,MAAe,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE;AAGzE,SAAS,qBAAmC;AACjD,QAAM,WAA4B,CAAC;AACnC,QAAM,WAAW,oBAAI,IAA4B;AACjD,SAAO;AAAA,IACL,MAAM,cAAc,GAAG;AACrB,eAAS,KAAK,gBAAgB,CAAC,CAAC;AAAA,IAClC;AAAA,IACA,MAAM,cAAc,SAAS,SAAS;AACpC,YAAM,QAAQ,SAAS,OAAO,CAAC,MAAM,YAAY,EAAE,SAAS,OAAO,KAAK,EAAE,YAAY,OAAO,EAAE,GAAG,EAAE;AACpG,aAAO,QAAQ,gBAAgB,KAAK,IAAI;AAAA,IAC1C;AAAA,IACA,MAAM,eAAe,SAAS;AAC5B,aAAO,SAAS,OAAO,CAAC,MAAM,YAAY,EAAE,SAAS,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,gBAAgB,CAAC,CAAC;AAAA,IAC9F;AAAA,IACA,MAAM,cAAc,GAAG;AACrB,eAAS,IAAI,EAAE,IAAI,gBAAgB,CAAC,CAAC;AAAA,IACvC;AAAA,IACA,MAAM,WAAW,IAAI;AACnB,Y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AACzC,iBAAW,WAAW,KAAK,UAAU;AACnC,cAAM,OAAO,MAAM,KAAK,gBAAgB,OAAO;AAC/C,YAAI,SAAS,OAAW;AACxB,YAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,EAAG,OAAM,IAAI,WAAW,yBAAsB,OAAO,oDAAiD,IAAI,EAAE;AAClJ,cAAM,SAAS,SAAS,KAAK,MAAM,IAAI,GAAG,OAAO,EAAE;AACnD,YAAI,QAAQ;AACZ,mBAAW,eAAe,KAAK,aAAc,UAAU,MAAM,YAAY,eAAe,OAAO,EAAE,SAAS,OAAO,CAAC,KAAM;AACxH,gBAAQ,OAAO,IAAI;AAAA,MACrB;AACA,aAAO;AAAA,IACT;AAAA,IACA,MAAM,SAAS,OAAO,SAAS;AAC7B,mBAAa,OAAO;AACpB,aAAO,SAAS,KAAK,EAAE,WAAW,OAAO;AAAA,IAC3C;AAAA,EACF;AACF;;;ACrNA,SAAS,oBAAoB;AAYtB,IAAM,gBAAgB,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,EACF;AACF,CAAC;","names":["ident","ident"]}
@@ -0,0 +1,144 @@
1
+ import { Query } from '@krizaka/db';
2
+
3
+ /**
4
+ * The ports of « privacy » (Loi 25): consents by purpose, the person's data exported from every module that holds it, and erased
5
+ * from every module in one transaction. Generic: no product import, no database client (a `Query` comes in), no wall clock (a
6
+ * `Clock` comes in). What a module holds, and what erasing it means (blanking a row, deleting a file, keeping an invoice for six
7
+ * years), is the module's: it implements `PrivacyContributor`.
8
+ */
9
+
10
+ /**
11
+ * Whose data it is. Usually an account (`{ kind: "account", id }`), but a product's data subject is not always an account: Akinaza's
12
+ * is a client file, Yomizaka's a tenant on an application. The `kind` says which.
13
+ */
14
+ interface Subject {
15
+ /** What the id identifies: `account`, `client`, `application`. Lower-case letters, digits and `_`. */
16
+ kind: string;
17
+ /** The product's id for it (a UUID, a slug). */
18
+ id: string;
19
+ }
20
+ /** What a product records when a person agrees, or withdraws. */
21
+ interface ConsentInput {
22
+ subject: Subject;
23
+ /** What the person agreed to (`marketing`, `screening`, `reminders`): one of the product's declared purposes. */
24
+ purpose: string;
25
+ /** The version of the notice shown to them: the proof of WHAT they agreed to. */
26
+ version: string;
27
+ granted: boolean;
28
+ /** How they said it (`checkbox`, `link`, `verbal`, `erasure`). */
29
+ means?: string | undefined;
30
+ }
31
+ /** A consent as written. It is never edited: a withdrawal is a new row. */
32
+ interface ConsentRecord {
33
+ id: string;
34
+ subject: Subject;
35
+ purpose: string;
36
+ version: string;
37
+ granted: boolean;
38
+ means: string | null;
39
+ at: Date;
40
+ }
41
+ declare const REQUEST_KIND: {
42
+ readonly export: "export";
43
+ readonly erasure: "erasure";
44
+ };
45
+ type RequestKind = (typeof REQUEST_KIND)[keyof typeof REQUEST_KIND];
46
+ declare const REQUEST_STATUS: {
47
+ readonly requested: "requested";
48
+ readonly completed: "completed";
49
+ readonly failed: "failed";
50
+ };
51
+ type RequestStatus = (typeof REQUEST_STATUS)[keyof typeof REQUEST_STATUS];
52
+ /** An export or an erasure asked for, and where it stands. It holds an id of the subject and no other personal data. */
53
+ interface PrivacyRequest {
54
+ id: string;
55
+ subject: Subject;
56
+ kind: RequestKind;
57
+ status: RequestStatus;
58
+ requestedAt: Date;
59
+ completedAt: Date | null;
60
+ /** A code, never a message that could carry data. */
61
+ failure: string | null;
62
+ }
63
+ /**
64
+ * A module that holds personal data. The product registers one per module and one for its own tables.
65
+ *
66
+ * - `exportFor` returns what the module holds about the subject, as JSON-able data.
67
+ * - `eraseFor` erases or anonymises it, through the transaction it is given, so the whole erasure commits or rolls back together.
68
+ * A side effect outside the database (a file in storage) is not done here: append it to the outbox in the same transaction.
69
+ * - `purgeExpired` (optional) removes what the retention of a purpose says is past, for everyone.
70
+ */
71
+ interface PrivacyContributor {
72
+ /** A stable name, the key of its part in the export (`audit`, `orders`). */
73
+ name: string;
74
+ exportFor(query: Query, subject: Subject): Promise<unknown>;
75
+ eraseFor(tx: Query, subject: Subject): Promise<void>;
76
+ purgeExpired?(tx: Query, input: {
77
+ purpose: string;
78
+ before: Date;
79
+ }): Promise<number>;
80
+ }
81
+ /** The whole export of a subject: one document, a part per contributor. */
82
+ interface ExportDocument {
83
+ format: 1;
84
+ subject: Subject;
85
+ generatedAt: string;
86
+ modules: Record<string, unknown>;
87
+ }
88
+ /** Where consents and requests live. Every adapter runs `privacyStoreContract` (`@krizaka/privacy/testkit`). */
89
+ interface PrivacyStore {
90
+ insertConsent(consent: ConsentRecord): Promise<void>;
91
+ /** The consent with the last word for this purpose, or null when the person never said anything. */
92
+ latestConsent(subject: Subject, purpose: string): Promise<ConsentRecord | null>;
93
+ /** Every consent of the subject, oldest first. */
94
+ consentHistory(subject: Subject): Promise<ConsentRecord[]>;
95
+ insertRequest(request: PrivacyRequest): Promise<void>;
96
+ getRequest(id: string): Promise<PrivacyRequest | null>;
97
+ finishRequest(id: string, outcome: {
98
+ status: "completed" | "failed";
99
+ at: Date;
100
+ failure?: string;
101
+ }): Promise<void>;
102
+ requestsOf(subject: Subject): Promise<PrivacyRequest[]>;
103
+ }
104
+ /** The structural slice of `@krizaka/audit` this package writes through, so it adds no dependency. */
105
+ interface AuditPort {
106
+ record(query: Query, entry: {
107
+ actorId: string | null;
108
+ actorLabel: string;
109
+ action: string;
110
+ target?: {
111
+ type: string;
112
+ id: string;
113
+ } | null;
114
+ detail?: Record<string, unknown>;
115
+ }): Promise<unknown>;
116
+ }
117
+ /** The structural slice of `@krizaka/outbox` used for a large export. */
118
+ interface OutboxPort {
119
+ append(tx: Query, message: {
120
+ topic: string;
121
+ type: string;
122
+ payload: unknown;
123
+ id?: string;
124
+ }): Promise<unknown>;
125
+ }
126
+ declare const PRIVACY_CODE: {
127
+ readonly badSubject: "PRIVACY_BAD_SUBJECT";
128
+ readonly badPurpose: "PRIVACY_BAD_PURPOSE";
129
+ readonly badConsent: "PRIVACY_BAD_CONSENT";
130
+ readonly unknownRequest: "PRIVACY_UNKNOWN_REQUEST";
131
+ readonly notAnExport: "PRIVACY_NOT_AN_EXPORT";
132
+ readonly alreadyDone: "PRIVACY_ALREADY_DONE";
133
+ readonly contributorFailed: "PRIVACY_CONTRIBUTOR_FAILED";
134
+ readonly noOutbox: "PRIVACY_NO_OUTBOX";
135
+ };
136
+ type PrivacyCode = (typeof PRIVACY_CODE)[keyof typeof PRIVACY_CODE];
137
+ declare class PrivacyError extends Error {
138
+ readonly code: PrivacyCode;
139
+ constructor(code: PrivacyCode, message: string, options?: {
140
+ cause?: unknown;
141
+ });
142
+ }
143
+
144
+ export { type AuditPort as A, type ConsentInput as C, type ExportDocument as E, type OutboxPort as O, type PrivacyContributor as P, REQUEST_KIND as R, type Subject as S, type PrivacyStore as a, type ConsentRecord as b, type PrivacyRequest as c, PRIVACY_CODE as d, type PrivacyCode as e, PrivacyError as f, REQUEST_STATUS as g, type RequestKind as h, type RequestStatus as i };
@@ -0,0 +1,17 @@
1
+ import { Registry } from '@krizaka/settings';
2
+
3
+ /** The settings key of a purpose's retention: `payment-history` → `privacy.retention.paymentHistoryDays` (a key holds letters and digits only). */
4
+ declare const retentionKey: (purpose: string) => string;
5
+ /**
6
+ * The registry fragment of the retention: `privacy.retention.<purpose>Days` for each purpose the product declares, an integer with the
7
+ * product's default. Global scope. The admin sets how long what a purpose collected is kept; the product's job calls `purge`.
8
+ * @param purposes the product's purposes (`screening`, `payment-history`), with their default retention in days
9
+ * @throws PrivacyError for a purpose id that is not well formed, or two that give the same key
10
+ */
11
+ declare function privacySettings(purposes: Readonly<Record<string, {
12
+ retentionDays: number;
13
+ }>>): Registry;
14
+ /** The retention of a purpose as `createPrivacy` takes it, from the product's accessor (`(key) => service.get(key, ctx)`). */
15
+ declare function retentionFromSettings(read: (key: string) => number | undefined | Promise<number | undefined>): (purpose: string) => Promise<number | undefined>;
16
+
17
+ export { privacySettings, retentionFromSettings, retentionKey };
@@ -0,0 +1,26 @@
1
+ import {
2
+ checkPurpose
3
+ } from "./chunk-PMXEX2LW.js";
4
+
5
+ // src/settings.ts
6
+ import { integer } from "@krizaka/settings";
7
+ var retentionKey = (purpose) => `privacy.retention.${purpose.replace(/[-_]([a-z0-9])/g, (_, c) => c.toUpperCase())}Days`;
8
+ function privacySettings(purposes) {
9
+ const fragment = {};
10
+ for (const [purpose, { retentionDays }] of Object.entries(purposes)) {
11
+ checkPurpose(purpose);
12
+ const key = retentionKey(purpose);
13
+ if (key in fragment) throw new RangeError(`privacy purposes give the same settings key: ${key}`);
14
+ fragment[key] = integer("privacy", retentionDays, { min: 1, max: 3650, unit: "days" });
15
+ }
16
+ return fragment;
17
+ }
18
+ function retentionFromSettings(read) {
19
+ return async (purpose) => read(retentionKey(purpose));
20
+ }
21
+ export {
22
+ privacySettings,
23
+ retentionFromSettings,
24
+ retentionKey
25
+ };
26
+ //# sourceMappingURL=settings.js.map
@@ -0,0 +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":[]}
@@ -0,0 +1,7 @@
1
+ import { a as PrivacyStore } from './port-Ds9VVyC2.js';
2
+ import '@krizaka/db';
3
+
4
+ /** What every `PrivacyStore` adapter must do: the same behaviour behind the same port. `make` gives an empty store. */
5
+ declare function privacyStoreContract(name: string, make: () => PrivacyStore | Promise<PrivacyStore>): void;
6
+
7
+ export { privacyStoreContract };
@@ -0,0 +1,63 @@
1
+ // src/testkit.ts
2
+ import { randomUUID } from "crypto";
3
+ import { expect, it } from "vitest";
4
+ var T0 = /* @__PURE__ */ new Date("2026-10-26T12:00:00.000Z");
5
+ var at = (seconds) => new Date(T0.valueOf() + seconds * 1e3);
6
+ var ERIC = { kind: "account", id: "11111111-1111-4111-8111-111111111111" };
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 });
10
+ function privacyStoreContract(name, make) {
11
+ it(`${name}: knows nothing about a person who never said anything`, async () => {
12
+ const store = await make();
13
+ expect(await store.latestConsent(ERIC, "marketing")).toBeNull();
14
+ expect(await store.consentHistory(ERIC)).toEqual([]);
15
+ });
16
+ it(`${name}: the consent with the last word wins, and the history keeps every one in order`, async () => {
17
+ const store = await make();
18
+ const first = consent(ERIC, "marketing", true, 0);
19
+ const second = consent(ERIC, "marketing", false, 10);
20
+ const third = consent(ERIC, "marketing", true, 20);
21
+ for (const c of [first, second, third]) await store.insertConsent(c);
22
+ expect(await store.latestConsent(ERIC, "marketing")).toEqual(third);
23
+ expect((await store.consentHistory(ERIC)).map((c) => c.id)).toEqual([first.id, second.id, third.id]);
24
+ });
25
+ it(`${name}: keeps purposes and subjects apart, whatever the kind of subject`, async () => {
26
+ const store = await make();
27
+ await store.insertConsent(consent(ERIC, "marketing", true, 0));
28
+ await store.insertConsent(consent(ERIC, "screening", false, 1));
29
+ await store.insertConsent(consent(CLIENT, "marketing", false, 2));
30
+ expect((await store.latestConsent(ERIC, "marketing"))?.granted).toBe(true);
31
+ expect((await store.latestConsent(ERIC, "screening"))?.granted).toBe(false);
32
+ expect((await store.latestConsent(CLIENT, "marketing"))?.granted).toBe(false);
33
+ expect(await store.consentHistory(CLIENT)).toHaveLength(1);
34
+ expect(await store.latestConsent({ kind: "client", id: ERIC.id }, "marketing")).toBeNull();
35
+ });
36
+ it(`${name}: records the proof: the notice version, the means and the instant`, async () => {
37
+ const store = await make();
38
+ const c = { ...consent(ERIC, "marketing", true, 5), version: "v7", means: "link" };
39
+ await store.insertConsent(c);
40
+ const found = await store.latestConsent(ERIC, "marketing");
41
+ expect(found).toMatchObject({ version: "v7", means: "link", granted: true });
42
+ expect(found.at.toISOString()).toBe(at(5).toISOString());
43
+ });
44
+ it(`${name}: follows a request from asked to completed, or failed with a code`, async () => {
45
+ const store = await make();
46
+ const done = request(ERIC, "export", 0);
47
+ const broke = request(ERIC, "erasure", 10);
48
+ await store.insertRequest(done);
49
+ await store.insertRequest(broke);
50
+ await store.finishRequest(done.id, { status: "completed", at: at(3) });
51
+ await store.finishRequest(broke.id, { status: "failed", at: at(11), failure: "CONTRIBUTOR_FAILED" });
52
+ expect(await store.getRequest(done.id)).toMatchObject({ kind: "export", status: "completed", failure: null });
53
+ 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" });
55
+ expect(await store.getRequest(randomUUID())).toBeNull();
56
+ expect((await store.requestsOf(ERIC)).map((r) => r.id)).toEqual([broke.id, done.id]);
57
+ expect(await store.requestsOf(CLIENT)).toEqual([]);
58
+ });
59
+ }
60
+ export {
61
+ privacyStoreContract
62
+ };
63
+ //# sourceMappingURL=testkit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testkit.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nimport { expect, it } from \"vitest\";\n\nimport type { ConsentRecord, PrivacyRequest, PrivacyStore, Subject } from \"./port\";\n\nconst T0 = new Date(\"2026-10-26T12:00:00.000Z\");\nconst at = (seconds: number) => new Date(T0.valueOf() + seconds * 1000);\nconst ERIC: Subject = { kind: \"account\", id: \"11111111-1111-4111-8111-111111111111\" };\nconst CLIENT: Subject = { kind: \"client\", id: \"c-42\" };\n\nconst consent = (subject: Subject, purpose: string, granted: boolean, seconds: number): ConsentRecord => ({ id: randomUUID(), subject, purpose, version: \"2026-10-01\", granted, means: \"checkbox\", at: at(seconds) });\nconst request = (subject: Subject, kind: PrivacyRequest[\"kind\"], seconds: number): PrivacyRequest => ({ id: randomUUID(), subject, kind, status: \"requested\", requestedAt: at(seconds), completedAt: null, failure: null });\n\n/** What every `PrivacyStore` adapter must do: the same behaviour behind the same port. `make` gives an empty store. */\nexport function privacyStoreContract(name: string, make: () => PrivacyStore | Promise<PrivacyStore>) {\n it(`${name}: knows nothing about a person who never said anything`, async () => {\n const store = await make();\n expect(await store.latestConsent(ERIC, \"marketing\")).toBeNull();\n expect(await store.consentHistory(ERIC)).toEqual([]);\n });\n\n it(`${name}: the consent with the last word wins, and the history keeps every one in order`, async () => {\n const store = await make();\n const first = consent(ERIC, \"marketing\", true, 0);\n const second = consent(ERIC, \"marketing\", false, 10);\n const third = consent(ERIC, \"marketing\", true, 20);\n for (const c of [first, second, third]) await store.insertConsent(c);\n expect(await store.latestConsent(ERIC, \"marketing\")).toEqual(third);\n expect((await store.consentHistory(ERIC)).map((c) => c.id)).toEqual([first.id, second.id, third.id]);\n });\n\n it(`${name}: keeps purposes and subjects apart, whatever the kind of subject`, async () => {\n const store = await make();\n await store.insertConsent(consent(ERIC, \"marketing\", true, 0));\n await store.insertConsent(consent(ERIC, \"screening\", false, 1));\n await store.insertConsent(consent(CLIENT, \"marketing\", false, 2));\n expect((await store.latestConsent(ERIC, \"marketing\"))?.granted).toBe(true);\n expect((await store.latestConsent(ERIC, \"screening\"))?.granted).toBe(false);\n expect((await store.latestConsent(CLIENT, \"marketing\"))?.granted).toBe(false);\n expect(await store.consentHistory(CLIENT)).toHaveLength(1);\n expect(await store.latestConsent({ kind: \"client\", id: ERIC.id }, \"marketing\")).toBeNull(); // same id, another kind\n });\n\n it(`${name}: records the proof: the notice version, the means and the instant`, async () => {\n const store = await make();\n const c = { ...consent(ERIC, \"marketing\", true, 5), version: \"v7\", means: \"link\" };\n await store.insertConsent(c);\n const found = await store.latestConsent(ERIC, \"marketing\");\n expect(found).toMatchObject({ version: \"v7\", means: \"link\", granted: true });\n expect(found!.at.toISOString()).toBe(at(5).toISOString());\n });\n\n it(`${name}: follows a request from asked to completed, or failed with a code`, async () => {\n const store = await make();\n const done = request(ERIC, \"export\", 0);\n const broke = request(ERIC, \"erasure\", 10);\n await store.insertRequest(done);\n await store.insertRequest(broke);\n await store.finishRequest(done.id, { status: \"completed\", at: at(3) });\n await store.finishRequest(broke.id, { status: \"failed\", at: at(11), failure: \"CONTRIBUTOR_FAILED\" });\n expect(await store.getRequest(done.id)).toMatchObject({ kind: \"export\", status: \"completed\", failure: null });\n expect((await store.getRequest(done.id))!.completedAt!.toISOString()).toBe(at(3).toISOString());\n expect(await store.getRequest(broke.id)).toMatchObject({ kind: \"erasure\", status: \"failed\", failure: \"CONTRIBUTOR_FAILED\" });\n expect(await store.getRequest(randomUUID())).toBeNull();\n expect((await store.requestsOf(ERIC)).map((r) => r.id)).toEqual([broke.id, done.id]); // newest first\n expect(await store.requestsOf(CLIENT)).toEqual([]);\n });\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,QAAQ,UAAU;AAI3B,IAAM,KAAK,oBAAI,KAAK,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,C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AQ,UAAU,IAAI,GAAG,EAAE,GAAG,SAAS,qBAAqB,CAAC;AACnG,WAAO,MAAM,MAAM,WAAW,KAAK,EAAE,CAAC,EAAE,cAAc,EAAE,MAAM,UAAU,QAAQ,aAAa,SAAS,KAAK,CAAC;AAC5G,YAAQ,MAAM,MAAM,WAAW,KAAK,EAAE,GAAI,YAAa,YAAY,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,YAAY,CAAC;AAC9F,WAAO,MAAM,MAAM,WAAW,MAAM,EAAE,CAAC,EAAE,cAAc,EAAE,MAAM,WAAW,QAAQ,UAAU,SAAS,qBAAqB,CAAC;AAC3H,WAAO,MAAM,MAAM,WAAW,WAAW,CAAC,CAAC,EAAE,SAAS;AACtD,YAAQ,MAAM,MAAM,WAAW,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,QAAQ,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;AACnF,WAAO,MAAM,MAAM,WAAW,MAAM,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACnD,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,87 @@
1
1
  {
2
2
  "name": "@krizaka/privacy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
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
+ "keywords": [
6
+ "krizaka",
7
+ "privacy",
8
+ "consent",
9
+ "loi-25",
10
+ "gdpr",
11
+ "export",
12
+ "erasure",
13
+ "postgresql"
14
+ ],
15
+ "homepage": "https://github.com/krizaka/krizaka-ts/tree/main/packages/privacy",
16
+ "bugs": "https://github.com/krizaka/krizaka-ts/issues",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/krizaka/krizaka-ts.git",
20
+ "directory": "packages/privacy"
21
+ },
22
+ "license": "Apache-2.0",
23
+ "author": "Krizaka (https://www.krizaka.com)",
24
+ "type": "module",
25
+ "main": "./dist/index.js",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ },
33
+ "./settings": {
34
+ "types": "./dist/settings.d.ts",
35
+ "import": "./dist/settings.js"
36
+ },
37
+ "./testkit": {
38
+ "types": "./dist/testkit.d.ts",
39
+ "import": "./dist/testkit.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "files": [
44
+ "dist",
45
+ "README.md",
46
+ "LICENSE"
47
+ ],
48
+ "sideEffects": false,
49
+ "engines": {
50
+ "node": ">=22"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^22.10.0",
54
+ "@types/pg": "^8.23.1",
55
+ "eslint": "^9.39.0",
56
+ "pg": "^8.23.1",
57
+ "tsup": "^8.5.0",
58
+ "typescript": "^5.9.3",
59
+ "vitest": "^4.1.11",
60
+ "zod": "^4.6.7",
61
+ "@krizaka/config": "^0.8.1"
62
+ },
63
+ "dependencies": {
64
+ "@krizaka/db": "^0.2.0",
65
+ "@krizaka/settings": "^0.4.0",
66
+ "@krizaka/time": "^0.1.0"
67
+ },
68
+ "peerDependencies": {
69
+ "vitest": ">=4",
70
+ "zod": ">=3.23"
71
+ },
72
+ "peerDependenciesMeta": {
73
+ "vitest": {
74
+ "optional": true
75
+ },
76
+ "zod": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "scripts": {
81
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
82
+ "lint": "eslint . --max-warnings 0 && tsc --noEmit",
83
+ "typecheck": "tsc --noEmit",
84
+ "test": "vitest run",
85
+ "check": "pnpm run lint && pnpm run test && pnpm run build"
86
+ }
6
87
  }