dpdp-kit 0.1.2 → 0.3.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/CHANGELOG.md +37 -0
- package/README.md +229 -13
- package/dist/access.d.ts +106 -0
- package/dist/audit.d.ts +3 -1
- package/dist/chunk-5TVA2TKG.js +37 -0
- package/dist/chunk-YOEAZX65.js +937 -0
- package/dist/cli.js +48 -10
- package/dist/config.d.ts +79 -0
- package/dist/data-access.d.ts +23 -0
- package/dist/dpdp.d.ts +206 -3
- package/dist/drizzle.d.ts +684 -4
- package/dist/drizzle.js +349 -6
- package/dist/erasure.d.ts +2 -1
- package/dist/errors.d.ts +1 -1
- package/dist/express.d.ts +17 -1
- package/dist/express.js +10 -2
- package/dist/fastify.d.ts +41 -0
- package/dist/fastify.js +25 -0
- package/dist/guard.d.ts +19 -0
- package/dist/hono.d.ts +16 -1
- package/dist/hono.js +11 -2
- package/dist/index.d.ts +11 -5
- package/dist/index.js +482 -51
- package/dist/nestjs.d.ts +65 -0
- package/dist/nestjs.js +41 -0
- package/dist/protect.d.ts +74 -0
- package/dist/protect.js +114 -0
- package/dist/records.d.ts +124 -0
- package/dist/retention.d.ts +47 -0
- package/dist/rights.d.ts +49 -0
- package/dist/run-audit.d.ts +14 -0
- package/dist/safeguards.d.ts +23 -0
- package/dist/schedule.d.ts +37 -0
- package/dist/schedule.js +66 -0
- package/dist/schema-check.d.ts +5 -7
- package/dist/store.d.ts +16 -2
- package/package.json +35 -4
- package/dist/chunk-FGZAH2NF.js +0 -16
- package/dist/chunk-MX5FRZQT.js +0 -455
package/dist/index.js
CHANGED
|
@@ -1,28 +1,40 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
CONSENT_REQUIRED_BODY
|
|
7
|
-
} from "./chunk-FGZAH2NF.js";
|
|
8
|
-
import {
|
|
2
|
+
DEFAULT_ACCESS_LOG_RETENTION,
|
|
3
|
+
REDACTED,
|
|
4
|
+
REQUEST_TYPES,
|
|
5
|
+
accessId,
|
|
9
6
|
audit,
|
|
10
7
|
checkSchema,
|
|
8
|
+
defineConfig,
|
|
11
9
|
durationMs,
|
|
10
|
+
erasedValue,
|
|
11
|
+
fieldsOutsidePurpose,
|
|
12
|
+
formatSafeguards,
|
|
13
|
+
grantedPurposes,
|
|
12
14
|
guessPersonal,
|
|
13
15
|
hasErrors,
|
|
16
|
+
isAccessLogStore,
|
|
17
|
+
isDpdpStore,
|
|
14
18
|
isDuration,
|
|
19
|
+
isHighRisk,
|
|
15
20
|
maxDuration,
|
|
21
|
+
memoryStore,
|
|
22
|
+
purposeNames,
|
|
23
|
+
resolveFields,
|
|
24
|
+
reviewAccess,
|
|
25
|
+
safeguardsReport,
|
|
16
26
|
tokenize
|
|
17
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-YOEAZX65.js";
|
|
28
|
+
import {
|
|
29
|
+
CONSENT_REQUIRED_BODY
|
|
30
|
+
} from "./chunk-5TVA2TKG.js";
|
|
31
|
+
import {
|
|
32
|
+
DpdpError,
|
|
33
|
+
SeqConflictError
|
|
34
|
+
} from "./chunk-67Q5GFD6.js";
|
|
18
35
|
|
|
19
|
-
// src/
|
|
20
|
-
|
|
21
|
-
return config;
|
|
22
|
-
}
|
|
23
|
-
function purposeNames(config) {
|
|
24
|
-
return Object.keys(config.purposes);
|
|
25
|
-
}
|
|
36
|
+
// src/dpdp.ts
|
|
37
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
26
38
|
|
|
27
39
|
// src/erasure.ts
|
|
28
40
|
function erasureDelay(config, ended) {
|
|
@@ -55,7 +67,7 @@ function planErasure(config, input) {
|
|
|
55
67
|
const allFieldsGo = fields.length === Object.keys(table.fields).length && fields.every((f) => f.action !== "keep");
|
|
56
68
|
let action;
|
|
57
69
|
if (fields.some((f) => f.action === "hold")) action = "hold";
|
|
58
|
-
else if (input.reason
|
|
70
|
+
else if (input.reason !== "withdrawal" && allFieldsGo) action = "delete-rows";
|
|
59
71
|
else if (fields.some((f) => f.action === "erase")) action = "erase-fields";
|
|
60
72
|
else action = "keep";
|
|
61
73
|
tables.push({
|
|
@@ -127,6 +139,142 @@ function isNoticeLanguage(value) {
|
|
|
127
139
|
return typeof value === "string" && Object.hasOwn(NOTICE_LANGUAGES, value);
|
|
128
140
|
}
|
|
129
141
|
|
|
142
|
+
// src/retention.ts
|
|
143
|
+
import { randomUUID } from "crypto";
|
|
144
|
+
var MAX_ATTEMPTS = 5;
|
|
145
|
+
var STALE_AFTER_MS = 15 * 60 * 1e3;
|
|
146
|
+
var addMs = (iso, ms) => new Date(Date.parse(iso) + ms).toISOString();
|
|
147
|
+
function tasksFromPlan(config, plan, now) {
|
|
148
|
+
const minimum = config.minimumRetention ?? "0d";
|
|
149
|
+
const base = { subjectId: plan.subjectId, reason: plan.reason, createdAt: now, status: "pending", attempts: 0 };
|
|
150
|
+
const due = (wait) => addMs(now, durationMs(maxDuration(wait, minimum)));
|
|
151
|
+
const tasks = [];
|
|
152
|
+
for (const table of plan.tables) {
|
|
153
|
+
if (table.action === "keep") continue;
|
|
154
|
+
if (table.action === "hold" && table.hold) {
|
|
155
|
+
const fields = table.fields.filter((f) => f.action === "hold").map((f) => f.field);
|
|
156
|
+
tasks.push({
|
|
157
|
+
...base,
|
|
158
|
+
id: randomUUID(),
|
|
159
|
+
kind: table.hold.then === "delete" ? "delete-rows" : "erase-fields",
|
|
160
|
+
table: table.key,
|
|
161
|
+
...table.hold.then === "delete" ? {} : { fields },
|
|
162
|
+
dueAt: due(table.hold.keep)
|
|
163
|
+
});
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const erasable = table.fields.filter((f) => f.action === "erase");
|
|
167
|
+
const wait = erasable.reduce((d, f) => f.after ? maxDuration(d, f.after) : d, "0d");
|
|
168
|
+
tasks.push({
|
|
169
|
+
...base,
|
|
170
|
+
id: randomUUID(),
|
|
171
|
+
kind: table.action === "delete-rows" ? "delete-rows" : "erase-fields",
|
|
172
|
+
table: table.key,
|
|
173
|
+
...table.action === "delete-rows" ? {} : { fields: erasable.map((f) => f.field) },
|
|
174
|
+
dueAt: due(wait)
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
for (const processor of plan.processors) {
|
|
178
|
+
tasks.push({ ...base, id: randomUUID(), kind: "processor-stop", processor: processor.name, purposes: processor.ended, dueAt: now });
|
|
179
|
+
if (processor.action === "erase") {
|
|
180
|
+
tasks.push({
|
|
181
|
+
...base,
|
|
182
|
+
id: randomUUID(),
|
|
183
|
+
kind: "processor-erase",
|
|
184
|
+
processor: processor.name,
|
|
185
|
+
purposes: processor.ended,
|
|
186
|
+
dueAt: due("0d")
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return tasks;
|
|
191
|
+
}
|
|
192
|
+
var errorText = (err) => err instanceof Error ? err.message : String(err);
|
|
193
|
+
async function carryOut(task, input) {
|
|
194
|
+
if (task.kind === "processor-stop" || task.kind === "processor-erase") {
|
|
195
|
+
const hook = input.processors[task.processor ?? ""]?.[task.kind === "processor-stop" ? "stop" : "erase"];
|
|
196
|
+
if (!hook) return { manual: true };
|
|
197
|
+
await hook({ subjectId: task.subjectId, purposes: task.purposes ?? [], reason: task.reason });
|
|
198
|
+
return {};
|
|
199
|
+
}
|
|
200
|
+
const def = input.config.data[task.table ?? ""];
|
|
201
|
+
if (!def) throw new Error(`Table "${task.table}" is no longer in the data map`);
|
|
202
|
+
if (!input.data) throw new Error("No data access configured: pass `data` to createDpdp to erase from your tables");
|
|
203
|
+
if (task.kind === "delete-rows") {
|
|
204
|
+
return { affected: await input.data.deleteRows(def.table, def.subject, task.subjectId) };
|
|
205
|
+
}
|
|
206
|
+
const fields = task.fields ?? [];
|
|
207
|
+
const values = Object.fromEntries(
|
|
208
|
+
fields.map((field) => [field, erasedValue(def.fields[field]?.erase, { subjectId: task.subjectId, table: task.table ?? "", field })])
|
|
209
|
+
);
|
|
210
|
+
return { affected: await input.data.eraseFields(def.table, def.subject, task.subjectId, fields, values) };
|
|
211
|
+
}
|
|
212
|
+
async function runDueTasks(input) {
|
|
213
|
+
const when = { now: input.now, staleBefore: addMs(input.now, -STALE_AFTER_MS), maxAttempts: MAX_ATTEMPTS };
|
|
214
|
+
const report = { done: [], failed: [], manual: [] };
|
|
215
|
+
for (const task of await input.store.dueTasks({ ...when, limit: input.limit })) {
|
|
216
|
+
if (!await input.store.claimTask({ id: task.id, ...when })) continue;
|
|
217
|
+
const attempts = task.attempts + 1;
|
|
218
|
+
try {
|
|
219
|
+
const result = await carryOut(task, input);
|
|
220
|
+
const { lastError: _, claimedAt: __, ...rest } = task;
|
|
221
|
+
const finished = result.manual ? { ...rest, status: "manual", attempts } : {
|
|
222
|
+
...rest,
|
|
223
|
+
status: "done",
|
|
224
|
+
attempts,
|
|
225
|
+
doneAt: input.now,
|
|
226
|
+
...result.affected !== void 0 ? { affected: result.affected } : {}
|
|
227
|
+
};
|
|
228
|
+
await input.store.updateTask(finished);
|
|
229
|
+
(result.manual ? report.manual : report.done).push(finished);
|
|
230
|
+
} catch (err) {
|
|
231
|
+
const { claimedAt: _, ...rest } = task;
|
|
232
|
+
const failed = { ...rest, status: "failed", attempts, lastError: errorText(err) };
|
|
233
|
+
await input.store.updateTask(failed);
|
|
234
|
+
report.failed.push(failed);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return report;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// src/rights.ts
|
|
241
|
+
var DEFAULT_RESPONSE_WITHIN = "90d";
|
|
242
|
+
function responseWithin(config, type) {
|
|
243
|
+
const setting = config.rights?.responseWithin;
|
|
244
|
+
if (setting === void 0) return DEFAULT_RESPONSE_WITHIN;
|
|
245
|
+
if (typeof setting === "string") return setting;
|
|
246
|
+
return setting[type] ?? DEFAULT_RESPONSE_WITHIN;
|
|
247
|
+
}
|
|
248
|
+
function dueAt(config, type, openedAt) {
|
|
249
|
+
return new Date(Date.parse(openedAt) + durationMs(responseWithin(config, type))).toISOString();
|
|
250
|
+
}
|
|
251
|
+
async function buildAccessSummary(input) {
|
|
252
|
+
const { config, data, subjectId, consents, now } = input;
|
|
253
|
+
const legitimateUses = Object.entries(config.purposes).filter(([, def]) => def.basis === "legitimate-use").map(([name]) => name);
|
|
254
|
+
const applies = /* @__PURE__ */ new Set([...consents, ...legitimateUses]);
|
|
255
|
+
const tables = [];
|
|
256
|
+
for (const [key, def] of Object.entries(config.data)) {
|
|
257
|
+
const fields = Object.entries(def.fields).map(([field, f]) => ({
|
|
258
|
+
field,
|
|
259
|
+
category: f.category,
|
|
260
|
+
purposes: [...f.purposes]
|
|
261
|
+
}));
|
|
262
|
+
const rows = await data.read(
|
|
263
|
+
def.table,
|
|
264
|
+
def.subject,
|
|
265
|
+
subjectId,
|
|
266
|
+
fields.map((f) => f.field)
|
|
267
|
+
);
|
|
268
|
+
if (rows.length > 0) tables.push({ key, table: def.table, fields, rows });
|
|
269
|
+
}
|
|
270
|
+
const sharedWith = Object.entries(config.processors ?? {}).map(([name, p]) => ({
|
|
271
|
+
name,
|
|
272
|
+
...p.description !== void 0 ? { description: p.description } : {},
|
|
273
|
+
purposes: p.purposes.filter((purpose) => applies.has(purpose))
|
|
274
|
+
})).filter((p) => p.purposes.length > 0);
|
|
275
|
+
return { subjectId, generatedAt: now, data: tables, consents, legitimateUses, sharedWith };
|
|
276
|
+
}
|
|
277
|
+
|
|
130
278
|
// src/dpdp.ts
|
|
131
279
|
function hashEvent(event) {
|
|
132
280
|
return sha256(
|
|
@@ -144,16 +292,6 @@ function hashEvent(event) {
|
|
|
144
292
|
})
|
|
145
293
|
);
|
|
146
294
|
}
|
|
147
|
-
function grantedFrom(events) {
|
|
148
|
-
const granted = /* @__PURE__ */ new Set();
|
|
149
|
-
for (const e of events) {
|
|
150
|
-
for (const p of e.purposes) {
|
|
151
|
-
if (e.action === "grant") granted.add(p);
|
|
152
|
-
else granted.delete(p);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return granted;
|
|
156
|
-
}
|
|
157
295
|
function createDpdp(options) {
|
|
158
296
|
const { config, store } = options;
|
|
159
297
|
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
@@ -210,7 +348,10 @@ ${lines.join("\n")}`, issues);
|
|
|
210
348
|
await store.insert(event);
|
|
211
349
|
return event;
|
|
212
350
|
} catch (err) {
|
|
213
|
-
if (err instanceof SeqConflictError && attempt < maxRetries)
|
|
351
|
+
if (err instanceof SeqConflictError && attempt < maxRetries) {
|
|
352
|
+
await new Promise((r) => setTimeout(r, Math.random() * 5 * attempt));
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
214
355
|
if (err instanceof SeqConflictError) {
|
|
215
356
|
throw new DpdpError("write-conflict", `Gave up after ${maxRetries} conflicting writes for one subject`);
|
|
216
357
|
}
|
|
@@ -220,12 +361,135 @@ ${lines.join("\n")}`, issues);
|
|
|
220
361
|
}
|
|
221
362
|
async function activeFor(subjectId) {
|
|
222
363
|
checkSubject(subjectId);
|
|
223
|
-
return [...
|
|
364
|
+
return [...grantedPurposes(await store.events(subjectId))];
|
|
224
365
|
}
|
|
225
|
-
|
|
366
|
+
const nowIso = () => now().toISOString();
|
|
367
|
+
const processorHooks = options.processors ?? {};
|
|
368
|
+
function fullStore(feature) {
|
|
369
|
+
if (!isDpdpStore(store)) {
|
|
370
|
+
throw new DpdpError(
|
|
371
|
+
"store-unsupported",
|
|
372
|
+
`${feature} needs a store that keeps requests and tasks: memoryStore(), drizzleStore(db), or a full DpdpStore`
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
return store;
|
|
376
|
+
}
|
|
377
|
+
function dataAccess() {
|
|
378
|
+
if (!options.data) {
|
|
379
|
+
throw new DpdpError("no-data-access", "Pass `data` to createDpdp (e.g. drizzleData(db)) to read or erase personal data");
|
|
380
|
+
}
|
|
381
|
+
return options.data;
|
|
382
|
+
}
|
|
383
|
+
async function schedule(plan) {
|
|
384
|
+
const tasks = tasksFromPlan(config, plan, nowIso());
|
|
385
|
+
if (tasks.length > 0) {
|
|
386
|
+
await fullStore("Scheduling erasure").insertTasks(tasks);
|
|
387
|
+
emit("erasure.scheduled", { plan, tasks });
|
|
388
|
+
}
|
|
389
|
+
return tasks;
|
|
390
|
+
}
|
|
391
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
392
|
+
const onListenerError = options.onListenerError ?? ((err, event) => console.error(`dpdp-kit: a "${event}" listener failed`, err));
|
|
393
|
+
function emit(event, payload) {
|
|
394
|
+
for (const listener of listeners.get(event) ?? []) {
|
|
395
|
+
setImmediate(() => {
|
|
396
|
+
try {
|
|
397
|
+
Promise.resolve(listener(structuredClone(payload))).catch((err) => onListenerError(err, event));
|
|
398
|
+
} catch (err) {
|
|
399
|
+
onListenerError(err, event);
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
function accessStore() {
|
|
405
|
+
if (!isAccessLogStore(store)) {
|
|
406
|
+
throw new DpdpError(
|
|
407
|
+
"store-unsupported",
|
|
408
|
+
"The access log needs a store that keeps it: memoryStore(), drizzleStore(db), or your own AccessLogStore"
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
return store;
|
|
412
|
+
}
|
|
413
|
+
async function requireRequest(id) {
|
|
414
|
+
const request = await fullStore("Rights requests").getRequest(id);
|
|
415
|
+
if (!request) throw new DpdpError("request-not-found", `No rights request with id ${JSON.stringify(id)}`);
|
|
416
|
+
return request;
|
|
417
|
+
}
|
|
418
|
+
async function close(id, status, note) {
|
|
419
|
+
const request = await requireRequest(id);
|
|
420
|
+
if (request.status !== "open") {
|
|
421
|
+
throw new DpdpError("request-closed", `Request ${id} is already ${request.status}`);
|
|
422
|
+
}
|
|
423
|
+
const at = nowIso();
|
|
424
|
+
const closed = {
|
|
425
|
+
...request,
|
|
426
|
+
status,
|
|
427
|
+
closedAt: at,
|
|
428
|
+
history: [...request.history, { at, status, ...note !== void 0 ? { note } : {} }]
|
|
429
|
+
};
|
|
430
|
+
await fullStore("Rights requests").updateRequest(closed);
|
|
431
|
+
emit("rights.closed", { request: closed });
|
|
432
|
+
return closed;
|
|
433
|
+
}
|
|
434
|
+
function accountPlan(subjectId, reason, keepFor) {
|
|
435
|
+
for (const p of keepFor) {
|
|
436
|
+
if (!purposes[p]) throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(p)}`);
|
|
437
|
+
}
|
|
438
|
+
return planErasure(config, {
|
|
439
|
+
subjectId,
|
|
440
|
+
reason,
|
|
441
|
+
ended: Object.keys(purposes).filter((p) => !keepFor.includes(p)),
|
|
442
|
+
remaining: [...keepFor]
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
const api = {
|
|
226
446
|
config,
|
|
447
|
+
async daily(input = {}) {
|
|
448
|
+
const report = { at: nowIso(), skipped: [], errors: [] };
|
|
449
|
+
const step = async (name, run) => {
|
|
450
|
+
try {
|
|
451
|
+
await run();
|
|
452
|
+
} catch (error) {
|
|
453
|
+
report.errors.push({ step: name, message: error instanceof Error ? error.message : String(error), error });
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
if (isDpdpStore(store)) {
|
|
457
|
+
await step("retention", async () => {
|
|
458
|
+
report.retention = await api.retention.run();
|
|
459
|
+
});
|
|
460
|
+
await step("rights", async () => {
|
|
461
|
+
report.overdueRequests = await api.rights.list({ overdue: true });
|
|
462
|
+
});
|
|
463
|
+
} else {
|
|
464
|
+
report.skipped.push("retention", "rights");
|
|
465
|
+
}
|
|
466
|
+
if (isAccessLogStore(store)) {
|
|
467
|
+
await step("access-prune", async () => {
|
|
468
|
+
report.accessPruned = (await api.access.prune()).deleted;
|
|
469
|
+
});
|
|
470
|
+
await step("access-review", async () => {
|
|
471
|
+
report.review = await api.access.review({ ...input.review });
|
|
472
|
+
});
|
|
473
|
+
} else {
|
|
474
|
+
report.skipped.push("access");
|
|
475
|
+
}
|
|
476
|
+
emit("daily.ran", { report });
|
|
477
|
+
return report;
|
|
478
|
+
},
|
|
479
|
+
on(event, listener) {
|
|
480
|
+
let set = listeners.get(event);
|
|
481
|
+
if (!set) listeners.set(event, set = /* @__PURE__ */ new Set());
|
|
482
|
+
set.add(listener);
|
|
483
|
+
return () => {
|
|
484
|
+
set.delete(listener);
|
|
485
|
+
};
|
|
486
|
+
},
|
|
227
487
|
consent: {
|
|
228
|
-
grant
|
|
488
|
+
async grant(subjectId, list, meta) {
|
|
489
|
+
const event = await append(subjectId, "grant", list, meta);
|
|
490
|
+
emit("consent.granted", { event });
|
|
491
|
+
return event;
|
|
492
|
+
},
|
|
229
493
|
async withdraw(subjectId, list, meta) {
|
|
230
494
|
const event = await append(subjectId, "withdraw", list, meta);
|
|
231
495
|
const stillGranted = await activeFor(subjectId);
|
|
@@ -235,14 +499,16 @@ ${lines.join("\n")}`, issues);
|
|
|
235
499
|
ended: event.purposes,
|
|
236
500
|
remaining: [...legitimate, ...stillGranted]
|
|
237
501
|
});
|
|
238
|
-
|
|
502
|
+
const tasks = isDpdpStore(store) ? await schedule(erasure) : [];
|
|
503
|
+
emit("consent.withdrawn", { event, erasure, tasks });
|
|
504
|
+
return { event, erasure, tasks };
|
|
239
505
|
},
|
|
240
506
|
async has(subjectId, purpose) {
|
|
241
507
|
checkSubject(subjectId);
|
|
242
508
|
const def = purposes[purpose];
|
|
243
509
|
if (!def) throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(purpose)}`);
|
|
244
510
|
if (def.basis === "legitimate-use") return true;
|
|
245
|
-
return
|
|
511
|
+
return grantedPurposes(await store.events(subjectId)).has(purpose);
|
|
246
512
|
},
|
|
247
513
|
active: activeFor,
|
|
248
514
|
async history(subjectId) {
|
|
@@ -272,55 +538,220 @@ ${lines.join("\n")}`, issues);
|
|
|
272
538
|
erasure: {
|
|
273
539
|
async plan(subjectId, input) {
|
|
274
540
|
checkSubject(subjectId);
|
|
275
|
-
return
|
|
541
|
+
return accountPlan(subjectId, input.reason, []);
|
|
542
|
+
},
|
|
543
|
+
schedule,
|
|
544
|
+
async deleteAccount(subjectId) {
|
|
545
|
+
checkSubject(subjectId);
|
|
546
|
+
const plan = accountPlan(subjectId, "account-deletion", []);
|
|
547
|
+
return { plan, tasks: await schedule(plan) };
|
|
548
|
+
}
|
|
549
|
+
},
|
|
550
|
+
retention: {
|
|
551
|
+
async run(input = {}) {
|
|
552
|
+
const report = await runDueTasks({
|
|
553
|
+
config,
|
|
554
|
+
store: fullStore("The retention runner"),
|
|
555
|
+
data: options.data,
|
|
556
|
+
processors: processorHooks,
|
|
557
|
+
now: nowIso(),
|
|
558
|
+
limit: input.limit ?? 500
|
|
559
|
+
});
|
|
560
|
+
emit("retention.ran", { report });
|
|
561
|
+
return report;
|
|
562
|
+
},
|
|
563
|
+
async tasks(filter = {}) {
|
|
564
|
+
return fullStore("Erasure tasks").listTasks(filter);
|
|
565
|
+
},
|
|
566
|
+
async markDone(taskId, note) {
|
|
567
|
+
const tasks = fullStore("Erasure tasks");
|
|
568
|
+
const task = await tasks.getTask(taskId);
|
|
569
|
+
if (!task) throw new DpdpError("task-not-found", `No erasure task with id ${JSON.stringify(taskId)}`);
|
|
570
|
+
if (task.status !== "manual" && task.status !== "failed") {
|
|
571
|
+
throw new DpdpError("task-not-manual", `Task ${taskId} is ${task.status}; only manual or failed tasks can be marked done`);
|
|
572
|
+
}
|
|
573
|
+
const done = { ...task, status: "done", doneAt: nowIso(), note };
|
|
574
|
+
await tasks.updateTask(done);
|
|
575
|
+
return done;
|
|
576
|
+
}
|
|
577
|
+
},
|
|
578
|
+
access: {
|
|
579
|
+
async log(input) {
|
|
580
|
+
const log = accessStore();
|
|
581
|
+
if (typeof input.actor !== "string" || input.actor.length === 0) {
|
|
582
|
+
throw new DpdpError("invalid-actor", "actor must be a non-empty string: who is accessing the data");
|
|
583
|
+
}
|
|
584
|
+
const subjects = input.subjectIds ?? (input.subjectId !== void 0 ? [input.subjectId] : []);
|
|
585
|
+
if (subjects.length === 0) throw new DpdpError("invalid-subject", "Pass subjectId or subjectIds");
|
|
586
|
+
for (const id of subjects) checkSubject(id);
|
|
587
|
+
if (!purposes[input.purpose]) {
|
|
588
|
+
throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(input.purpose)}`);
|
|
589
|
+
}
|
|
590
|
+
const { fields, unknown } = resolveFields(config, input.fields ?? []);
|
|
591
|
+
if (unknown.length > 0) {
|
|
592
|
+
throw new DpdpError(
|
|
593
|
+
"unknown-field",
|
|
594
|
+
`Not in the data map: ${unknown.map((k) => JSON.stringify(k)).join(", ")}. Use keys like "users.phone" or "users".`
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
const outside = fieldsOutsidePurpose(config, fields, input.purpose);
|
|
598
|
+
const at = nowIso();
|
|
599
|
+
const entries = [...new Set(subjects)].map((subjectId) => ({
|
|
600
|
+
id: accessId(at),
|
|
601
|
+
at,
|
|
602
|
+
actor: input.actor,
|
|
603
|
+
subjectId,
|
|
604
|
+
action: input.action ?? "read",
|
|
605
|
+
purpose: input.purpose,
|
|
606
|
+
...fields.length > 0 ? { fields } : {},
|
|
607
|
+
...outside.length > 0 ? { outOfPurpose: outside } : {},
|
|
608
|
+
...input.reason !== void 0 ? { reason: input.reason } : {},
|
|
609
|
+
...input.evidence !== void 0 ? { evidence: { ...input.evidence } } : {}
|
|
610
|
+
}));
|
|
611
|
+
await log.insertAccess(entries);
|
|
612
|
+
emit("access.logged", { entries });
|
|
613
|
+
if (outside.length > 0 && options.access?.outOfPurpose === "throw") {
|
|
614
|
+
throw new DpdpError(
|
|
615
|
+
"out-of-purpose",
|
|
616
|
+
`${outside.join(", ")} ${outside.length === 1 ? "isn't" : "aren't"} held for "${input.purpose}". The attempt was logged.`
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
return entries;
|
|
620
|
+
},
|
|
621
|
+
list: (filter = {}) => accessStore().listAccess(filter),
|
|
622
|
+
async review(input = {}) {
|
|
623
|
+
const to = input.to ?? nowIso();
|
|
624
|
+
const from = input.from ?? new Date(Date.parse(to) - durationMs("1d")).toISOString();
|
|
625
|
+
const entries = await accessStore().listAccess(input.to ? { from, to } : { from });
|
|
626
|
+
return reviewAccess({
|
|
627
|
+
config,
|
|
628
|
+
entries,
|
|
629
|
+
from,
|
|
630
|
+
to,
|
|
631
|
+
history: (subjectId) => store.events(subjectId),
|
|
632
|
+
window: input.window ?? "1h",
|
|
633
|
+
maxSubjects: input.maxSubjects ?? 100,
|
|
634
|
+
ignoreActors: input.ignoreActors ?? []
|
|
635
|
+
});
|
|
636
|
+
},
|
|
637
|
+
async prune() {
|
|
638
|
+
const keep = config.security?.accessLogRetention ?? DEFAULT_ACCESS_LOG_RETENTION;
|
|
639
|
+
const keepMs = Math.max(durationMs(keep), durationMs(DEFAULT_ACCESS_LOG_RETENTION));
|
|
640
|
+
const before = new Date(now().getTime() - keepMs).toISOString();
|
|
641
|
+
return { deleted: await accessStore().pruneAccess(before), before };
|
|
642
|
+
}
|
|
643
|
+
},
|
|
644
|
+
rights: {
|
|
645
|
+
async open(subjectId, type, details) {
|
|
646
|
+
checkSubject(subjectId);
|
|
647
|
+
if (!REQUEST_TYPES.includes(type)) {
|
|
648
|
+
throw new DpdpError("invalid-request-type", `Unknown request type ${JSON.stringify(type)}`);
|
|
649
|
+
}
|
|
650
|
+
const openedAt = nowIso();
|
|
651
|
+
const request = {
|
|
652
|
+
id: randomUUID2(),
|
|
653
|
+
subjectId,
|
|
654
|
+
type,
|
|
655
|
+
status: "open",
|
|
656
|
+
openedAt,
|
|
657
|
+
dueAt: dueAt(config, type, openedAt),
|
|
658
|
+
...details !== void 0 ? { details: structuredClone(details) } : {},
|
|
659
|
+
history: [{ at: openedAt, status: "open" }]
|
|
660
|
+
};
|
|
661
|
+
await fullStore("Rights requests").insertRequest(request);
|
|
662
|
+
emit("rights.opened", { request });
|
|
663
|
+
return request;
|
|
664
|
+
},
|
|
665
|
+
get: (id) => fullStore("Rights requests").getRequest(id),
|
|
666
|
+
async list(filter = {}) {
|
|
667
|
+
const { overdue, ...rest } = filter;
|
|
668
|
+
const list = await fullStore("Rights requests").listRequests(overdue ? { ...rest, status: "open" } : rest);
|
|
669
|
+
if (!overdue) return list;
|
|
670
|
+
const at = nowIso();
|
|
671
|
+
return list.filter((r) => r.dueAt < at);
|
|
672
|
+
},
|
|
673
|
+
resolve: (id, note) => close(id, "resolved", note),
|
|
674
|
+
reject: (id, reason) => close(id, "rejected", reason),
|
|
675
|
+
async summary(subjectId) {
|
|
676
|
+
checkSubject(subjectId);
|
|
677
|
+
return buildAccessSummary({
|
|
678
|
+
config,
|
|
679
|
+
data: dataAccess(),
|
|
276
680
|
subjectId,
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
remaining: []
|
|
681
|
+
consents: await activeFor(subjectId),
|
|
682
|
+
now: nowIso()
|
|
280
683
|
});
|
|
684
|
+
},
|
|
685
|
+
async erase(subjectId, input = {}) {
|
|
686
|
+
checkSubject(subjectId);
|
|
687
|
+
if (input.requestId) {
|
|
688
|
+
const request = await requireRequest(input.requestId);
|
|
689
|
+
if (request.subjectId !== subjectId) {
|
|
690
|
+
throw new DpdpError("request-not-found", `Request ${input.requestId} belongs to a different person`);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const plan = accountPlan(subjectId, "erasure-request", input.keepFor ?? []);
|
|
694
|
+
const tasks = await schedule(plan);
|
|
695
|
+
if (input.requestId) {
|
|
696
|
+
await close(input.requestId, "resolved", `Erasure scheduled: ${tasks.length} task(s)`);
|
|
697
|
+
}
|
|
698
|
+
return { plan, tasks };
|
|
281
699
|
}
|
|
282
700
|
}
|
|
283
701
|
};
|
|
702
|
+
return api;
|
|
284
703
|
}
|
|
285
704
|
|
|
286
|
-
// src/
|
|
287
|
-
function
|
|
288
|
-
const
|
|
705
|
+
// src/data-access.ts
|
|
706
|
+
function memoryData(tables) {
|
|
707
|
+
const rowsOf = (table) => tables[table] ??= [];
|
|
708
|
+
const mine = (subjectColumn, subjectId) => (row) => String(row[subjectColumn]) === subjectId;
|
|
289
709
|
return {
|
|
290
|
-
|
|
291
|
-
async
|
|
292
|
-
|
|
293
|
-
return list?.[list.length - 1];
|
|
710
|
+
tables,
|
|
711
|
+
async read(table, subjectColumn, subjectId, columns) {
|
|
712
|
+
return rowsOf(table).filter(mine(subjectColumn, subjectId)).map((row) => Object.fromEntries(columns.map((c) => [c, row[c] ?? null])));
|
|
294
713
|
},
|
|
295
|
-
async
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
list.sort((a, b) => a.seq - b.seq);
|
|
300
|
-
all.set(event.subjectId, list);
|
|
714
|
+
async eraseFields(table, subjectColumn, subjectId, columns, values = {}) {
|
|
715
|
+
const rows = rowsOf(table).filter(mine(subjectColumn, subjectId));
|
|
716
|
+
for (const row of rows) for (const c of columns) row[c] = Object.hasOwn(values, c) ? values[c] : null;
|
|
717
|
+
return rows.length;
|
|
301
718
|
},
|
|
302
|
-
async
|
|
303
|
-
|
|
719
|
+
async deleteRows(table, subjectColumn, subjectId) {
|
|
720
|
+
const before = rowsOf(table).length;
|
|
721
|
+
tables[table] = rowsOf(table).filter((row) => !mine(subjectColumn, subjectId)(row));
|
|
722
|
+
return before - tables[table].length;
|
|
304
723
|
}
|
|
305
724
|
};
|
|
306
725
|
}
|
|
307
726
|
export {
|
|
308
727
|
CONSENT_REQUIRED_BODY,
|
|
728
|
+
DEFAULT_ACCESS_LOG_RETENTION,
|
|
729
|
+
DEFAULT_RESPONSE_WITHIN,
|
|
309
730
|
DpdpError,
|
|
310
731
|
NOTICE_LANGUAGES,
|
|
732
|
+
REDACTED,
|
|
733
|
+
REQUEST_TYPES,
|
|
311
734
|
SeqConflictError,
|
|
312
735
|
audit,
|
|
313
736
|
checkSchema,
|
|
314
737
|
createDpdp,
|
|
315
738
|
defineConfig,
|
|
316
739
|
durationMs,
|
|
740
|
+
erasedValue,
|
|
741
|
+
formatSafeguards,
|
|
317
742
|
guessPersonal,
|
|
318
743
|
hasErrors,
|
|
319
744
|
hashEvent,
|
|
745
|
+
isAccessLogStore,
|
|
746
|
+
isDpdpStore,
|
|
320
747
|
isDuration,
|
|
748
|
+
isHighRisk,
|
|
321
749
|
isNoticeLanguage,
|
|
750
|
+
memoryData,
|
|
322
751
|
memoryStore,
|
|
323
752
|
planErasure,
|
|
324
753
|
purposeNames,
|
|
754
|
+
safeguardsReport,
|
|
755
|
+
tasksFromPlan,
|
|
325
756
|
tokenize
|
|
326
757
|
};
|
package/dist/nestjs.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Dpdp } from "./dpdp.js";
|
|
2
|
+
import { type AccessLogOptions, type GuardOptions } from "./guard.js";
|
|
3
|
+
/**
|
|
4
|
+
* The part of NestJS's `ExecutionContext` these guards use, so dpdp-kit doesn't depend on
|
|
5
|
+
* `@nestjs/common`. For HTTP routes, `switchToHttp().getRequest()` is the Express or Fastify request.
|
|
6
|
+
*/
|
|
7
|
+
export interface ExecutionContextLike {
|
|
8
|
+
switchToHttp(): {
|
|
9
|
+
getRequest<T = any>(): T;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** What NestJS calls on a guard. `@UseGuards()` accepts any object with this method. */
|
|
13
|
+
export interface CanActivateLike {
|
|
14
|
+
canActivate(context: ExecutionContextLike): Promise<boolean>;
|
|
15
|
+
}
|
|
16
|
+
interface RequestOption<Req> {
|
|
17
|
+
/**
|
|
18
|
+
* Where to find the request. Default: `context.switchToHttp().getRequest()`, for HTTP routes. For
|
|
19
|
+
* GraphQL, pass e.g. `(ctx) => GqlExecutionContext.create(ctx).getContext().req`.
|
|
20
|
+
*/
|
|
21
|
+
request?: (context: ExecutionContextLike) => Req | undefined;
|
|
22
|
+
}
|
|
23
|
+
export interface NestGuardOptions<Req> extends GuardOptions<Req>, RequestOption<Req> {
|
|
24
|
+
/**
|
|
25
|
+
* Throw your own exception when consent is missing, for example
|
|
26
|
+
* `(purpose) => new ForbiddenException(CONSENT_REQUIRED_BODY(purpose))`. Default: the guard
|
|
27
|
+
* returns `false`, and NestJS answers 403 Forbidden.
|
|
28
|
+
*/
|
|
29
|
+
onDenied?: (purpose: string, request: Req) => Error;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A NestJS guard that lets the request through only if the person may be processed for `purpose`.
|
|
33
|
+
*
|
|
34
|
+
* ```ts
|
|
35
|
+
* import { ForbiddenException, UseGuards } from "@nestjs/common";
|
|
36
|
+
* import { CONSENT_REQUIRED_BODY } from "dpdp-kit";
|
|
37
|
+
*
|
|
38
|
+
* @UseGuards(consentGuard(dpdp, "marketing_sms", {
|
|
39
|
+
* subject: (req) => req.user?.id,
|
|
40
|
+
* onDenied: (purpose) => new ForbiddenException(CONSENT_REQUIRED_BODY(purpose)),
|
|
41
|
+
* }))
|
|
42
|
+
* @Post("promo")
|
|
43
|
+
* sendPromo() { … }
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export declare function consentGuard<P extends string, Req = any>(dpdp: Dpdp<P>, purpose: P, options: NestGuardOptions<Req>): CanActivateLike;
|
|
47
|
+
/**
|
|
48
|
+
* A NestJS guard that records each request in the access log (Rule 6(1)(c)) and lets it through.
|
|
49
|
+
* If logging fails, or the fields aren't held for the purpose and the instance was created with
|
|
50
|
+
* `access: { outOfPurpose: "throw" }`, the error reaches NestJS's exception filters and the
|
|
51
|
+
* handler doesn't run.
|
|
52
|
+
*
|
|
53
|
+
* ```ts
|
|
54
|
+
* @UseGuards(accessLogGuard(dpdp, {
|
|
55
|
+
* purpose: "account",
|
|
56
|
+
* fields: ["users"],
|
|
57
|
+
* actor: (req) => req.user?.staffId,
|
|
58
|
+
* subject: (req) => req.params.id,
|
|
59
|
+
* }))
|
|
60
|
+
* @Get("admin/users/:id")
|
|
61
|
+
* getUser() { … }
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export declare function accessLogGuard<P extends string, Req = any>(dpdp: Dpdp<P>, options: AccessLogOptions<Req, P> & RequestOption<Req>): CanActivateLike;
|
|
65
|
+
export {};
|