dpdp-kit 0.2.0 → 0.4.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +240 -17
  3. package/dist/access.d.ts +111 -0
  4. package/dist/audit.d.ts +3 -1
  5. package/dist/breach.d.ts +170 -0
  6. package/dist/chunk-2ELTZSW3.js +94 -0
  7. package/dist/chunk-5TVA2TKG.js +37 -0
  8. package/dist/chunk-HXVP446N.js +1051 -0
  9. package/dist/chunk-KLMR7S7I.js +438 -0
  10. package/dist/cli.js +53 -17
  11. package/dist/config.d.ts +69 -0
  12. package/dist/data-access.d.ts +6 -2
  13. package/dist/ddl.d.ts +10 -0
  14. package/dist/dpdp.d.ts +210 -0
  15. package/dist/drizzle.d.ts +403 -11
  16. package/dist/drizzle.js +209 -56
  17. package/dist/errors.d.ts +1 -1
  18. package/dist/express.d.ts +17 -1
  19. package/dist/express.js +10 -2
  20. package/dist/fastify.d.ts +41 -0
  21. package/dist/fastify.js +25 -0
  22. package/dist/guard.d.ts +19 -0
  23. package/dist/hono.d.ts +16 -1
  24. package/dist/hono.js +11 -2
  25. package/dist/index.d.ts +7 -4
  26. package/dist/index.js +420 -100
  27. package/dist/mongodb.d.ts +87 -0
  28. package/dist/mongodb.js +344 -0
  29. package/dist/nestjs.d.ts +65 -0
  30. package/dist/nestjs.js +41 -0
  31. package/dist/postgres.d.ts +45 -0
  32. package/dist/postgres.js +27 -0
  33. package/dist/prisma.d.ts +43 -0
  34. package/dist/prisma.js +281 -0
  35. package/dist/protect.d.ts +74 -0
  36. package/dist/protect.js +114 -0
  37. package/dist/retention.d.ts +1 -1
  38. package/dist/run-audit.d.ts +13 -1
  39. package/dist/safeguards.d.ts +23 -0
  40. package/dist/schedule.d.ts +37 -0
  41. package/dist/schedule.js +66 -0
  42. package/dist/schema-check.d.ts +25 -8
  43. package/dist/store.d.ts +11 -1
  44. package/package.json +58 -5
  45. package/dist/chunk-FGZAH2NF.js +0 -16
  46. package/dist/chunk-KVTUMHXO.js +0 -491
package/dist/index.js CHANGED
@@ -1,29 +1,102 @@
1
1
  import {
2
- DpdpError,
3
- SeqConflictError
4
- } from "./chunk-67Q5GFD6.js";
5
- import {
6
- CONSENT_REQUIRED_BODY
7
- } from "./chunk-FGZAH2NF.js";
8
- import {
2
+ DEFAULT_ACCESS_LOG_RETENTION,
3
+ REDACTED,
9
4
  REQUEST_TYPES,
5
+ accessId,
10
6
  audit,
11
7
  checkSchema,
8
+ defineConfig,
12
9
  durationMs,
10
+ erasedValue,
11
+ fieldsOutsidePurpose,
12
+ formatSafeguards,
13
+ grantedPurposes,
13
14
  guessPersonal,
14
15
  hasErrors,
16
+ isAccessLogStore,
17
+ isDpdpStore,
15
18
  isDuration,
16
- isRunnable,
19
+ isHighRisk,
17
20
  maxDuration,
21
+ memoryStore,
22
+ purposeNames,
23
+ resolveFields,
24
+ reviewAccess,
25
+ safeguardsReport,
18
26
  tokenize
19
- } from "./chunk-KVTUMHXO.js";
27
+ } from "./chunk-HXVP446N.js";
28
+ import {
29
+ CONSENT_REQUIRED_BODY
30
+ } from "./chunk-5TVA2TKG.js";
31
+ import {
32
+ DpdpError,
33
+ SeqConflictError
34
+ } from "./chunk-67Q5GFD6.js";
20
35
 
21
- // src/config.ts
22
- function defineConfig(config) {
23
- return config;
36
+ // src/breach.ts
37
+ var BOARD_REPORT_WITHIN_HOURS = 72;
38
+ function isBreachStore(store) {
39
+ const s = store;
40
+ return typeof s.insertBreach === "function" && typeof s.addNotices === "function" && typeof s.countNotices === "function";
41
+ }
42
+ var REPORT_PARTS = [
43
+ ["details", "(i) updated and detailed information"],
44
+ ["facts", "(ii) the facts, circumstances and reasons"],
45
+ ["mitigation", "(iii) measures to mitigate the risk"],
46
+ ["findings", "(iv) findings about who caused it"],
47
+ ["remedial", "(v) measures to prevent recurrence"]
48
+ ];
49
+ function breachStatus(breach, counts, now) {
50
+ const missing = REPORT_PARTS.filter(([k]) => !breach.report[k]).map(([k]) => k);
51
+ const sent = breach.reportSentAt !== void 0;
52
+ const hoursLeft = Math.round((Date.parse(breach.reportDueAt) - Date.parse(now)) / 36e5 * 10) / 10;
53
+ const pending = counts.total - counts.sent;
54
+ const todo = [];
55
+ if (breach.status === "open") {
56
+ if (!breach.boardNotifiedAt) todo.push("Tell the Board without delay: nature, extent, timing, location and likely impact (Rule 7(2)(a)).");
57
+ if (pending > 0) todo.push(`Tell ${pending} affected ${pending === 1 ? "person" : "people"} without delay (Rule 7(1)).`);
58
+ if (counts.total === 0) todo.push("Record who is affected, so each person can be told (Rule 7(1)).");
59
+ if (!sent) {
60
+ todo.push(
61
+ hoursLeft >= 0 ? `Send the Board the detailed report within ${hoursLeft} hours (Rule 7(2)(b)).${missing.length ? ` Still missing: ${REPORT_PARTS.filter(([k]) => missing.includes(k)).map(([, label]) => label).join("; ")}.` : ""}` : `The detailed report to the Board was due ${-hoursLeft} hours ago (Rule 7(2)(b)). Send it now, or record the Board's written extension.`
62
+ );
63
+ }
64
+ }
65
+ return {
66
+ id: breach.id,
67
+ status: breach.status,
68
+ awareAt: breach.awareAt,
69
+ boardNotified: breach.boardNotifiedAt !== void 0,
70
+ report: { dueAt: breach.reportDueAt, sent, overdue: !sent && hoursLeft < 0, hoursLeft, missing },
71
+ people: { total: counts.total, sent: counts.sent, pending },
72
+ todo
73
+ };
24
74
  }
25
- function purposeNames(config) {
26
- return Object.keys(config.purposes);
75
+ function personNotice(config, breach) {
76
+ const when = breach.occurredAt ? ` It happened on ${breach.occurredAt.slice(0, 10)}` : "";
77
+ const description = `${breach.description.trim()}${breach.extent ? ` ${breach.extent.trim()}` : ""}${when ? `${when}.` : ""}`;
78
+ const contact = config.fiduciary.dpo ? `If you have questions, contact ${config.fiduciary.dpo}, on behalf of ${config.fiduciary.name}.` : "";
79
+ const missing = [];
80
+ if (!breach.consequences) missing.push("consequences");
81
+ if (!breach.measures) missing.push("measures");
82
+ if (!breach.safetySteps) missing.push("safetySteps");
83
+ if (!contact) missing.push("contact");
84
+ const parts = {
85
+ description,
86
+ consequences: breach.consequences?.trim() ?? "",
87
+ measures: breach.measures?.trim() ?? "",
88
+ safetySteps: breach.safetySteps?.trim() ?? "",
89
+ contact
90
+ };
91
+ const text = [
92
+ `We're writing to tell you about a personal data breach at ${config.fiduciary.name}.`,
93
+ `What happened: ${parts.description}`,
94
+ parts.consequences && `What this may mean for you: ${parts.consequences}`,
95
+ parts.measures && `What we're doing: ${parts.measures}`,
96
+ parts.safetySteps && `What you can do: ${parts.safetySteps}`,
97
+ parts.contact
98
+ ].filter(Boolean).join("\n\n");
99
+ return { ...parts, text, missing };
27
100
  }
28
101
 
29
102
  // src/dpdp.ts
@@ -196,7 +269,11 @@ async function carryOut(task, input) {
196
269
  if (task.kind === "delete-rows") {
197
270
  return { affected: await input.data.deleteRows(def.table, def.subject, task.subjectId) };
198
271
  }
199
- return { affected: await input.data.eraseFields(def.table, def.subject, task.subjectId, task.fields ?? []) };
272
+ const fields = task.fields ?? [];
273
+ const values = Object.fromEntries(
274
+ fields.map((field) => [field, erasedValue(def.fields[field]?.erase, { subjectId: task.subjectId, table: task.table ?? "", field })])
275
+ );
276
+ return { affected: await input.data.eraseFields(def.table, def.subject, task.subjectId, fields, values) };
200
277
  }
201
278
  async function runDueTasks(input) {
202
279
  const when = { now: input.now, staleBefore: addMs(input.now, -STALE_AFTER_MS), maxAttempts: MAX_ATTEMPTS };
@@ -264,72 +341,6 @@ async function buildAccessSummary(input) {
264
341
  return { subjectId, generatedAt: now, data: tables, consents, legitimateUses, sharedWith };
265
342
  }
266
343
 
267
- // src/store.ts
268
- function isDpdpStore(store) {
269
- const s = store;
270
- return typeof s.insertRequest === "function" && typeof s.insertTasks === "function";
271
- }
272
- function memoryStore() {
273
- const all = /* @__PURE__ */ new Map();
274
- const requests = /* @__PURE__ */ new Map();
275
- const tasks = /* @__PURE__ */ new Map();
276
- const byDue = (a, b) => a.dueAt < b.dueAt ? -1 : a.dueAt > b.dueAt ? 1 : 0;
277
- return {
278
- all,
279
- requests,
280
- tasks,
281
- async insertRequest(request) {
282
- requests.set(request.id, structuredClone(request));
283
- },
284
- async getRequest(id) {
285
- const r = requests.get(id);
286
- return r && structuredClone(r);
287
- },
288
- async updateRequest(request) {
289
- requests.set(request.id, structuredClone(request));
290
- },
291
- async listRequests(filter) {
292
- return [...requests.values()].filter((r) => (!filter.subjectId || r.subjectId === filter.subjectId) && (!filter.status || r.status === filter.status)).sort((a, b) => a.openedAt < b.openedAt ? -1 : 1).map((r) => structuredClone(r));
293
- },
294
- async insertTasks(list) {
295
- for (const t of list) tasks.set(t.id, structuredClone(t));
296
- },
297
- async dueTasks({ limit, ...when }) {
298
- return [...tasks.values()].filter((t) => isRunnable(t, when)).sort(byDue).slice(0, limit).map((t) => structuredClone(t));
299
- },
300
- async claimTask({ id, ...when }) {
301
- const t = tasks.get(id);
302
- if (!t || !isRunnable(t, when)) return false;
303
- tasks.set(id, { ...t, status: "running", claimedAt: when.now });
304
- return true;
305
- },
306
- async updateTask(task) {
307
- tasks.set(task.id, structuredClone(task));
308
- },
309
- async getTask(id) {
310
- const t = tasks.get(id);
311
- return t && structuredClone(t);
312
- },
313
- async listTasks(filter) {
314
- return [...tasks.values()].filter((t) => (!filter.subjectId || t.subjectId === filter.subjectId) && (!filter.status || t.status === filter.status)).sort(byDue).map((t) => structuredClone(t));
315
- },
316
- async lastEvent(subjectId) {
317
- const list = all.get(subjectId);
318
- return list?.[list.length - 1];
319
- },
320
- async insert(event) {
321
- const list = all.get(event.subjectId) ?? [];
322
- if (list.some((e) => e.seq === event.seq)) throw new SeqConflictError(event.subjectId, event.seq);
323
- list.push(structuredClone(event));
324
- list.sort((a, b) => a.seq - b.seq);
325
- all.set(event.subjectId, list);
326
- },
327
- async events(subjectId) {
328
- return structuredClone(all.get(subjectId) ?? []);
329
- }
330
- };
331
- }
332
-
333
344
  // src/dpdp.ts
334
345
  function hashEvent(event) {
335
346
  return sha256(
@@ -347,16 +358,6 @@ function hashEvent(event) {
347
358
  })
348
359
  );
349
360
  }
350
- function grantedFrom(events) {
351
- const granted = /* @__PURE__ */ new Set();
352
- for (const e of events) {
353
- for (const p of e.purposes) {
354
- if (e.action === "grant") granted.add(p);
355
- else granted.delete(p);
356
- }
357
- }
358
- return granted;
359
- }
360
361
  function createDpdp(options) {
361
362
  const { config, store } = options;
362
363
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
@@ -413,7 +414,10 @@ ${lines.join("\n")}`, issues);
413
414
  await store.insert(event);
414
415
  return event;
415
416
  } catch (err) {
416
- if (err instanceof SeqConflictError && attempt < maxRetries) continue;
417
+ if (err instanceof SeqConflictError && attempt < maxRetries) {
418
+ await new Promise((r) => setTimeout(r, Math.random() * 5 * attempt));
419
+ continue;
420
+ }
417
421
  if (err instanceof SeqConflictError) {
418
422
  throw new DpdpError("write-conflict", `Gave up after ${maxRetries} conflicting writes for one subject`);
419
423
  }
@@ -423,7 +427,7 @@ ${lines.join("\n")}`, issues);
423
427
  }
424
428
  async function activeFor(subjectId) {
425
429
  checkSubject(subjectId);
426
- return [...grantedFrom(await store.events(subjectId))];
430
+ return [...grantedPurposes(await store.events(subjectId))];
427
431
  }
428
432
  const nowIso = () => now().toISOString();
429
433
  const processorHooks = options.processors ?? {};
@@ -444,9 +448,71 @@ ${lines.join("\n")}`, issues);
444
448
  }
445
449
  async function schedule(plan) {
446
450
  const tasks = tasksFromPlan(config, plan, nowIso());
447
- if (tasks.length > 0) await fullStore("Scheduling erasure").insertTasks(tasks);
451
+ if (tasks.length > 0) {
452
+ await fullStore("Scheduling erasure").insertTasks(tasks);
453
+ emit("erasure.scheduled", { plan, tasks });
454
+ }
448
455
  return tasks;
449
456
  }
457
+ const listeners = /* @__PURE__ */ new Map();
458
+ const onListenerError = options.onListenerError ?? ((err, event) => console.error(`dpdp-kit: a "${event}" listener failed`, err));
459
+ function emit(event, payload) {
460
+ for (const listener of listeners.get(event) ?? []) {
461
+ setImmediate(() => {
462
+ try {
463
+ Promise.resolve(listener(structuredClone(payload))).catch((err) => onListenerError(err, event));
464
+ } catch (err) {
465
+ onListenerError(err, event);
466
+ }
467
+ });
468
+ }
469
+ }
470
+ function breachStore() {
471
+ if (!isBreachStore(store)) {
472
+ throw new DpdpError(
473
+ "store-unsupported",
474
+ "Breach records need a store that keeps them: memoryStore(), drizzleStore(db), or your own BreachStore"
475
+ );
476
+ }
477
+ return store;
478
+ }
479
+ function checkIso(value, name) {
480
+ if (value !== void 0 && (typeof value !== "string" || Number.isNaN(Date.parse(value)))) {
481
+ throw new DpdpError("invalid-input", `${name} must be an ISO 8601 date and time, e.g. "2027-06-01T10:00:00Z"`);
482
+ }
483
+ }
484
+ async function requireBreach(id, open = false) {
485
+ const breach = await breachStore().getBreach(id);
486
+ if (!breach) throw new DpdpError("breach-not-found", `No breach with id ${JSON.stringify(id)}`);
487
+ if (open && breach.status !== "open") throw new DpdpError("breach-closed", `Breach ${id} is closed`);
488
+ return breach;
489
+ }
490
+ async function changeBreach(id, change, event, note) {
491
+ for (let attempt = 1; ; attempt++) {
492
+ const breach = await requireBreach(id, true);
493
+ const next = { ...change(breach), history: [...breach.history, { at: nowIso(), event, ...note !== void 0 ? { note } : {} }] };
494
+ if (await breachStore().updateBreach(next) !== false) return next;
495
+ if (attempt >= maxRetries) throw new DpdpError("write-conflict", `Gave up after ${maxRetries} conflicting updates to breach ${id}`);
496
+ await new Promise((r) => setTimeout(r, Math.random() * 5 * attempt));
497
+ }
498
+ }
499
+ function breachFields(keys) {
500
+ const { fields, unknown } = resolveFields(config, keys ?? []);
501
+ if (unknown.length > 0) {
502
+ throw new DpdpError("unknown-field", `Not in the data map: ${unknown.map((k) => JSON.stringify(k)).join(", ")}`);
503
+ }
504
+ return fields;
505
+ }
506
+ const BREACH_TEXT = ["occurredAt", "description", "extent", "location", "likelyImpact", "consequences", "measures", "safetySteps"];
507
+ function accessStore() {
508
+ if (!isAccessLogStore(store)) {
509
+ throw new DpdpError(
510
+ "store-unsupported",
511
+ "The access log needs a store that keeps it: memoryStore(), drizzleStore(db), or your own AccessLogStore"
512
+ );
513
+ }
514
+ return store;
515
+ }
450
516
  async function requireRequest(id) {
451
517
  const request = await fullStore("Rights requests").getRequest(id);
452
518
  if (!request) throw new DpdpError("request-not-found", `No rights request with id ${JSON.stringify(id)}`);
@@ -465,6 +531,7 @@ ${lines.join("\n")}`, issues);
465
531
  history: [...request.history, { at, status, ...note !== void 0 ? { note } : {} }]
466
532
  };
467
533
  await fullStore("Rights requests").updateRequest(closed);
534
+ emit("rights.closed", { request: closed });
468
535
  return closed;
469
536
  }
470
537
  function accountPlan(subjectId, reason, keepFor) {
@@ -478,10 +545,63 @@ ${lines.join("\n")}`, issues);
478
545
  remaining: [...keepFor]
479
546
  });
480
547
  }
481
- return {
548
+ const api = {
482
549
  config,
550
+ async daily(input = {}) {
551
+ const report = { at: nowIso(), skipped: [], errors: [] };
552
+ const step = async (name, run) => {
553
+ try {
554
+ await run();
555
+ } catch (error) {
556
+ report.errors.push({ step: name, message: error instanceof Error ? error.message : String(error), error });
557
+ }
558
+ };
559
+ if (isDpdpStore(store)) {
560
+ await step("retention", async () => {
561
+ report.retention = await api.retention.run();
562
+ });
563
+ await step("rights", async () => {
564
+ report.overdueRequests = await api.rights.list({ overdue: true });
565
+ });
566
+ } else {
567
+ report.skipped.push("retention", "rights");
568
+ }
569
+ if (isBreachStore(store)) {
570
+ await step("breaches", async () => {
571
+ const open = await breachStore().listBreaches({ status: "open" });
572
+ const now2 = nowIso();
573
+ report.breaches = await Promise.all(open.map(async (b) => breachStatus(b, await breachStore().countNotices(b.id), now2)));
574
+ });
575
+ } else {
576
+ report.skipped.push("breaches");
577
+ }
578
+ if (isAccessLogStore(store)) {
579
+ await step("access-prune", async () => {
580
+ report.accessPruned = (await api.access.prune()).deleted;
581
+ });
582
+ await step("access-review", async () => {
583
+ report.review = await api.access.review({ ...input.review });
584
+ });
585
+ } else {
586
+ report.skipped.push("access");
587
+ }
588
+ emit("daily.ran", { report });
589
+ return report;
590
+ },
591
+ on(event, listener) {
592
+ let set = listeners.get(event);
593
+ if (!set) listeners.set(event, set = /* @__PURE__ */ new Set());
594
+ set.add(listener);
595
+ return () => {
596
+ set.delete(listener);
597
+ };
598
+ },
483
599
  consent: {
484
- grant: (subjectId, list, meta) => append(subjectId, "grant", list, meta),
600
+ async grant(subjectId, list, meta) {
601
+ const event = await append(subjectId, "grant", list, meta);
602
+ emit("consent.granted", { event });
603
+ return event;
604
+ },
485
605
  async withdraw(subjectId, list, meta) {
486
606
  const event = await append(subjectId, "withdraw", list, meta);
487
607
  const stillGranted = await activeFor(subjectId);
@@ -492,6 +612,7 @@ ${lines.join("\n")}`, issues);
492
612
  remaining: [...legitimate, ...stillGranted]
493
613
  });
494
614
  const tasks = isDpdpStore(store) ? await schedule(erasure) : [];
615
+ emit("consent.withdrawn", { event, erasure, tasks });
495
616
  return { event, erasure, tasks };
496
617
  },
497
618
  async has(subjectId, purpose) {
@@ -499,7 +620,7 @@ ${lines.join("\n")}`, issues);
499
620
  const def = purposes[purpose];
500
621
  if (!def) throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(purpose)}`);
501
622
  if (def.basis === "legitimate-use") return true;
502
- return grantedFrom(await store.events(subjectId)).has(purpose);
623
+ return grantedPurposes(await store.events(subjectId)).has(purpose);
503
624
  },
504
625
  active: activeFor,
505
626
  async history(subjectId) {
@@ -540,7 +661,7 @@ ${lines.join("\n")}`, issues);
540
661
  },
541
662
  retention: {
542
663
  async run(input = {}) {
543
- return runDueTasks({
664
+ const report = await runDueTasks({
544
665
  config,
545
666
  store: fullStore("The retention runner"),
546
667
  data: options.data,
@@ -548,6 +669,8 @@ ${lines.join("\n")}`, issues);
548
669
  now: nowIso(),
549
670
  limit: input.limit ?? 500
550
671
  });
672
+ emit("retention.ran", { report });
673
+ return report;
551
674
  },
552
675
  async tasks(filter = {}) {
553
676
  return fullStore("Erasure tasks").listTasks(filter);
@@ -564,6 +687,190 @@ ${lines.join("\n")}`, issues);
564
687
  return done;
565
688
  }
566
689
  },
690
+ access: {
691
+ async log(input) {
692
+ const log = accessStore();
693
+ if (typeof input.actor !== "string" || input.actor.length === 0) {
694
+ throw new DpdpError("invalid-actor", "actor must be a non-empty string: who is accessing the data");
695
+ }
696
+ const subjects = input.subjectIds ?? (input.subjectId !== void 0 ? [input.subjectId] : []);
697
+ if (subjects.length === 0) throw new DpdpError("invalid-subject", "Pass subjectId or subjectIds");
698
+ for (const id of subjects) checkSubject(id);
699
+ if (!purposes[input.purpose]) {
700
+ throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(input.purpose)}`);
701
+ }
702
+ const { fields, unknown } = resolveFields(config, input.fields ?? []);
703
+ if (unknown.length > 0) {
704
+ throw new DpdpError(
705
+ "unknown-field",
706
+ `Not in the data map: ${unknown.map((k) => JSON.stringify(k)).join(", ")}. Use keys like "users.phone" or "users".`
707
+ );
708
+ }
709
+ const outside = fieldsOutsidePurpose(config, fields, input.purpose);
710
+ const at = nowIso();
711
+ const entries = [...new Set(subjects)].map((subjectId) => ({
712
+ id: accessId(at),
713
+ at,
714
+ actor: input.actor,
715
+ subjectId,
716
+ action: input.action ?? "read",
717
+ purpose: input.purpose,
718
+ ...fields.length > 0 ? { fields } : {},
719
+ ...outside.length > 0 ? { outOfPurpose: outside } : {},
720
+ ...input.reason !== void 0 ? { reason: input.reason } : {},
721
+ ...input.evidence !== void 0 ? { evidence: { ...input.evidence } } : {}
722
+ }));
723
+ await log.insertAccess(entries);
724
+ emit("access.logged", { entries });
725
+ if (outside.length > 0 && options.access?.outOfPurpose === "throw") {
726
+ throw new DpdpError(
727
+ "out-of-purpose",
728
+ `${outside.join(", ")} ${outside.length === 1 ? "isn't" : "aren't"} held for "${input.purpose}". The attempt was logged.`
729
+ );
730
+ }
731
+ return entries;
732
+ },
733
+ list: (filter = {}) => accessStore().listAccess(filter),
734
+ async review(input = {}) {
735
+ const to = input.to ?? nowIso();
736
+ const from = input.from ?? new Date(Date.parse(to) - durationMs("1d")).toISOString();
737
+ const entries = await accessStore().listAccess(input.to ? { from, to } : { from });
738
+ return reviewAccess({
739
+ config,
740
+ entries,
741
+ from,
742
+ to,
743
+ history: (subjectId) => store.events(subjectId),
744
+ window: input.window ?? "1h",
745
+ maxSubjects: input.maxSubjects ?? 100,
746
+ ignoreActors: input.ignoreActors ?? []
747
+ });
748
+ },
749
+ async prune() {
750
+ const keep = config.security?.accessLogRetention ?? DEFAULT_ACCESS_LOG_RETENTION;
751
+ const keepMs = Math.max(durationMs(keep), durationMs(DEFAULT_ACCESS_LOG_RETENTION));
752
+ const before = new Date(now().getTime() - keepMs).toISOString();
753
+ return { deleted: await accessStore().pruneAccess(before), before };
754
+ }
755
+ },
756
+ breach: {
757
+ async open(input) {
758
+ if (!input || typeof input.description !== "string" || input.description.trim() === "") {
759
+ throw new DpdpError("invalid-input", "Describe the breach: description is required (Rule 7(1)(a), 7(2)(a))");
760
+ }
761
+ checkIso(input.awareAt, "awareAt");
762
+ checkIso(input.occurredAt, "occurredAt");
763
+ const awareAt = input.awareAt ? new Date(input.awareAt).toISOString() : nowIso();
764
+ const text = Object.fromEntries(BREACH_TEXT.filter((k) => input[k] !== void 0).map((k) => [k, input[k]]));
765
+ const breach = {
766
+ id: randomUUID2(),
767
+ ...text,
768
+ description: input.description,
769
+ awareAt,
770
+ fields: breachFields(input.fields),
771
+ reportDueAt: new Date(Date.parse(awareAt) + BOARD_REPORT_WITHIN_HOURS * 36e5).toISOString(),
772
+ report: {},
773
+ status: "open",
774
+ history: [{ at: nowIso(), event: "opened" }]
775
+ };
776
+ await breachStore().insertBreach(breach);
777
+ emit("breach.opened", { breach });
778
+ return breach;
779
+ },
780
+ async update(id, input) {
781
+ checkIso(input.occurredAt, "occurredAt");
782
+ const text = Object.fromEntries(BREACH_TEXT.filter((k) => input[k] !== void 0).map((k) => [k, input[k]]));
783
+ const fields = input.fields ? { fields: breachFields(input.fields) } : {};
784
+ return changeBreach(id, (breach) => ({ ...breach, ...text, ...fields }), "updated");
785
+ },
786
+ get: (id) => breachStore().getBreach(id),
787
+ list: (filter = {}) => breachStore().listBreaches(filter),
788
+ async status(id) {
789
+ const breach = await requireBreach(id);
790
+ return breachStatus(breach, await breachStore().countNotices(id), nowIso());
791
+ },
792
+ async addAffected(id, subjectIds) {
793
+ await requireBreach(id, true);
794
+ for (const subjectId of subjectIds) checkSubject(subjectId);
795
+ const addedAt = nowIso();
796
+ return breachStore().addNotices([...new Set(subjectIds)].map((subjectId) => ({ breachId: id, subjectId, status: "pending", addedAt })));
797
+ },
798
+ async addAffectedFromAccessLog(id, filter) {
799
+ await requireBreach(id, true);
800
+ const { limit: _, ...where } = filter;
801
+ const access = accessStore();
802
+ const subjects = access.accessSubjects ? await access.accessSubjects(where) : [...new Set((await access.listAccess(where)).map((e) => e.subjectId))];
803
+ let added = 0;
804
+ for (let i = 0; i < subjects.length; i += 5e3) added += await api.breach.addAffected(id, subjects.slice(i, i + 5e3));
805
+ return added;
806
+ },
807
+ async notice(id) {
808
+ return personNotice(config, await requireBreach(id));
809
+ },
810
+ pending: async (id, limit) => {
811
+ await requireBreach(id);
812
+ return breachStore().listNotices(id, { status: "pending", ...limit !== void 0 ? { limit } : {} });
813
+ },
814
+ async markNotified(id, subjectIds, input = {}) {
815
+ await requireBreach(id, true);
816
+ checkIso(input.at, "at");
817
+ const at = input.at ? new Date(input.at).toISOString() : nowIso();
818
+ return breachStore().markNotices(id, [...new Set(subjectIds)], at, input.channel);
819
+ },
820
+ async boardNotified(id, input = {}) {
821
+ checkIso(input.at, "at");
822
+ const at = input.at ? new Date(input.at).toISOString() : nowIso();
823
+ return changeBreach(id, (breach) => ({ ...breach, boardNotifiedAt: at }), "board notified");
824
+ },
825
+ async updateReport(id, parts) {
826
+ const keys = ["details", "facts", "mitigation", "findings", "remedial"];
827
+ const given = Object.fromEntries(keys.filter((k) => parts[k] !== void 0).map((k) => [k, parts[k]]));
828
+ return changeBreach(id, (breach) => ({ ...breach, report: { ...breach.report, ...given } }), "report updated");
829
+ },
830
+ async boardReport(id) {
831
+ const breach = await requireBreach(id);
832
+ const counts = await breachStore().countNotices(id);
833
+ const status = breachStatus(breach, counts, nowIso());
834
+ return {
835
+ breachId: id,
836
+ awareAt: breach.awareAt,
837
+ dueAt: breach.reportDueAt,
838
+ details: breach.report.details ?? "",
839
+ facts: breach.report.facts ?? "",
840
+ mitigation: breach.report.mitigation ?? "",
841
+ findings: breach.report.findings ?? "",
842
+ remedial: breach.report.remedial ?? "",
843
+ intimations: {
844
+ total: counts.total,
845
+ sent: counts.sent,
846
+ pending: counts.total - counts.sent,
847
+ ...counts.firstSentAt ? { firstSentAt: counts.firstSentAt } : {},
848
+ ...counts.lastSentAt ? { lastSentAt: counts.lastSentAt } : {}
849
+ },
850
+ missing: status.report.missing
851
+ };
852
+ },
853
+ async reportSent(id, input = {}) {
854
+ checkIso(input.at, "at");
855
+ const at = input.at ? new Date(input.at).toISOString() : nowIso();
856
+ const saved = await changeBreach(id, (breach) => ({ ...breach, reportSentAt: at }), "report sent");
857
+ emit("breach.reported", { breach: saved });
858
+ return saved;
859
+ },
860
+ async extend(id, input) {
861
+ checkIso(input.until, "until");
862
+ if (!input.reference) throw new DpdpError("invalid-input", "Record the Board's written permission: reference is required");
863
+ const until = new Date(input.until).toISOString();
864
+ const extension = { until, reference: input.reference, recordedAt: nowIso() };
865
+ return changeBreach(id, (breach) => ({ ...breach, reportDueAt: until, extension }), "extended", input.reference);
866
+ },
867
+ async close(id, note) {
868
+ const closedAt = nowIso();
869
+ const saved = await changeBreach(id, (breach) => ({ ...breach, status: "closed", closedAt }), "closed", note);
870
+ emit("breach.closed", { breach: saved });
871
+ return saved;
872
+ }
873
+ },
567
874
  rights: {
568
875
  async open(subjectId, type, details) {
569
876
  checkSubject(subjectId);
@@ -582,6 +889,7 @@ ${lines.join("\n")}`, issues);
582
889
  history: [{ at: openedAt, status: "open" }]
583
890
  };
584
891
  await fullStore("Rights requests").insertRequest(request);
892
+ emit("rights.opened", { request });
585
893
  return request;
586
894
  },
587
895
  get: (id) => fullStore("Rights requests").getRequest(id),
@@ -621,6 +929,7 @@ ${lines.join("\n")}`, issues);
621
929
  }
622
930
  }
623
931
  };
932
+ return api;
624
933
  }
625
934
 
626
935
  // src/data-access.ts
@@ -632,9 +941,9 @@ function memoryData(tables) {
632
941
  async read(table, subjectColumn, subjectId, columns) {
633
942
  return rowsOf(table).filter(mine(subjectColumn, subjectId)).map((row) => Object.fromEntries(columns.map((c) => [c, row[c] ?? null])));
634
943
  },
635
- async eraseFields(table, subjectColumn, subjectId, columns) {
944
+ async eraseFields(table, subjectColumn, subjectId, columns, values = {}) {
636
945
  const rows = rowsOf(table).filter(mine(subjectColumn, subjectId));
637
- for (const row of rows) for (const c of columns) row[c] = null;
946
+ for (const row of rows) for (const c of columns) row[c] = Object.hasOwn(values, c) ? values[c] : null;
638
947
  return rows.length;
639
948
  },
640
949
  async deleteRows(table, subjectColumn, subjectId) {
@@ -645,27 +954,38 @@ function memoryData(tables) {
645
954
  };
646
955
  }
647
956
  export {
957
+ BOARD_REPORT_WITHIN_HOURS,
648
958
  CONSENT_REQUIRED_BODY,
959
+ DEFAULT_ACCESS_LOG_RETENTION,
649
960
  DEFAULT_RESPONSE_WITHIN,
650
961
  DpdpError,
651
962
  NOTICE_LANGUAGES,
963
+ REDACTED,
652
964
  REQUEST_TYPES,
653
965
  SeqConflictError,
654
966
  audit,
967
+ breachStatus,
655
968
  checkSchema,
656
969
  createDpdp,
657
970
  defineConfig,
658
971
  durationMs,
972
+ erasedValue,
973
+ formatSafeguards,
659
974
  guessPersonal,
660
975
  hasErrors,
661
976
  hashEvent,
977
+ isAccessLogStore,
978
+ isBreachStore,
662
979
  isDpdpStore,
663
980
  isDuration,
981
+ isHighRisk,
664
982
  isNoticeLanguage,
665
983
  memoryData,
666
984
  memoryStore,
985
+ personNotice,
667
986
  planErasure,
668
987
  purposeNames,
988
+ safeguardsReport,
669
989
  tasksFromPlan,
670
990
  tokenize
671
991
  };