dpdp-kit 0.4.1 → 0.5.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 (47) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +12 -9
  3. package/dist/access.d.ts +3 -2
  4. package/dist/audit.d.ts +7 -2
  5. package/dist/{chunk-5TVA2TKG.js → chunk-3DOVLBUB.js} +12 -2
  6. package/dist/chunk-EMNABUCL.js +34 -0
  7. package/dist/{chunk-HXVP446N.js → chunk-FEGA6SOM.js} +817 -149
  8. package/dist/chunk-HGN6TO6R.js +294 -0
  9. package/dist/{chunk-KLMR7S7I.js → chunk-LVT4OKBC.js} +65 -0
  10. package/dist/chunk-M2PDT6DD.js +88 -0
  11. package/dist/chunk-NBVJQDDP.js +16 -0
  12. package/dist/{chunk-2ELTZSW3.js → chunk-VWGKAQCM.js} +18 -3
  13. package/dist/cli.js +48 -5
  14. package/dist/config.d.ts +67 -0
  15. package/dist/data-access.d.ts +8 -0
  16. package/dist/ddl.d.ts +13 -2
  17. package/dist/dpdp.d.ts +155 -9
  18. package/dist/drizzle.d.ts +108 -6
  19. package/dist/drizzle.js +85 -4
  20. package/dist/erasure.d.ts +1 -1
  21. package/dist/errors.d.ts +1 -1
  22. package/dist/evidence.d.ts +91 -0
  23. package/dist/express.d.ts +30 -0
  24. package/dist/express.js +70 -3
  25. package/dist/fastify.js +3 -3
  26. package/dist/guard.d.ts +23 -2
  27. package/dist/hono.d.ts +21 -0
  28. package/dist/hono.js +11 -3
  29. package/dist/http.d.ts +78 -0
  30. package/dist/index.d.ts +7 -3
  31. package/dist/index.js +375 -125
  32. package/dist/mongodb.d.ts +3 -1
  33. package/dist/mongodb.js +99 -1
  34. package/dist/nestjs.js +1 -1
  35. package/dist/next.d.ts +25 -0
  36. package/dist/next.js +14 -0
  37. package/dist/notice.d.ts +139 -0
  38. package/dist/postgres.d.ts +5 -3
  39. package/dist/postgres.js +8 -2
  40. package/dist/prisma.d.ts +4 -2
  41. package/dist/prisma.js +16 -2
  42. package/dist/records.d.ts +24 -1
  43. package/dist/rights.d.ts +35 -2
  44. package/dist/run-audit.d.ts +8 -0
  45. package/dist/stats.d.ts +41 -0
  46. package/dist/store.d.ts +15 -2
  47. package/package.json +5 -1
package/dist/index.js CHANGED
@@ -1,15 +1,27 @@
1
1
  import {
2
2
  DEFAULT_ACCESS_LOG_RETENTION,
3
+ DEFAULT_RESPONSE_WITHIN,
4
+ ENGLISH_WORDING,
5
+ LEGITIMATE_USES,
6
+ NOTICE_KINDS,
7
+ NOTICE_LANGUAGES,
3
8
  REDACTED,
4
- REQUEST_TYPES,
5
9
  accessId,
10
+ acknowledgement,
6
11
  audit,
12
+ buildAccessSummary,
13
+ buildNotice,
14
+ canonicalJson,
7
15
  checkSchema,
8
16
  defineConfig,
17
+ describeRetention,
18
+ dueAt,
9
19
  durationMs,
10
20
  erasedValue,
11
21
  fieldsOutsidePurpose,
22
+ formatEvidence,
12
23
  formatSafeguards,
24
+ gapsOf,
13
25
  grantedPurposes,
14
26
  guessPersonal,
15
27
  hasErrors,
@@ -17,17 +29,41 @@ import {
17
29
  isDpdpStore,
18
30
  isDuration,
19
31
  isHighRisk,
32
+ isNoticeLanguage,
33
+ isNoticeStore,
34
+ isUnavailable,
20
35
  maxDuration,
21
36
  memoryStore,
37
+ noticeLanguages,
38
+ objectedPurposes,
22
39
  purposeNames,
40
+ requestStats,
23
41
  resolveFields,
24
42
  reviewAccess,
43
+ rightsInfo,
25
44
  safeguardsReport,
45
+ sameNotice,
46
+ sha256,
47
+ staticEvidence,
26
48
  tokenize
27
- } from "./chunk-HXVP446N.js";
49
+ } from "./chunk-FEGA6SOM.js";
50
+ import {
51
+ memoryData
52
+ } from "./chunk-EMNABUCL.js";
53
+ import {
54
+ isStatsStore
55
+ } from "./chunk-M2PDT6DD.js";
56
+ import {
57
+ handle,
58
+ isApiRoute
59
+ } from "./chunk-HGN6TO6R.js";
60
+ import {
61
+ REQUEST_TYPES,
62
+ isVerified
63
+ } from "./chunk-NBVJQDDP.js";
28
64
  import {
29
65
  CONSENT_REQUIRED_BODY
30
- } from "./chunk-5TVA2TKG.js";
66
+ } from "./chunk-3DOVLBUB.js";
31
67
  import {
32
68
  DpdpError,
33
69
  SeqConflictError
@@ -133,7 +169,7 @@ function planErasure(config, input) {
133
169
  const allFieldsGo = fields.length === Object.keys(table.fields).length && fields.every((f) => f.action !== "keep");
134
170
  let action;
135
171
  if (fields.some((f) => f.action === "hold")) action = "hold";
136
- else if (input.reason !== "withdrawal" && allFieldsGo) action = "delete-rows";
172
+ else if (input.reason !== "withdrawal" && input.reason !== "objection" && allFieldsGo) action = "delete-rows";
137
173
  else if (fields.some((f) => f.action === "erase")) action = "erase-fields";
138
174
  else action = "keep";
139
175
  tables.push({
@@ -163,48 +199,6 @@ function planErasure(config, input) {
163
199
  };
164
200
  }
165
201
 
166
- // src/hash.ts
167
- import { createHash } from "crypto";
168
- function canonicalJson(value) {
169
- if (value === null || typeof value !== "object") return JSON.stringify(value);
170
- if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
171
- const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
172
- return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
173
- }
174
- function sha256(text) {
175
- return createHash("sha256").update(text).digest("hex");
176
- }
177
-
178
- // src/languages.ts
179
- var NOTICE_LANGUAGES = {
180
- en: "English",
181
- as: "Assamese",
182
- bn: "Bengali",
183
- brx: "Bodo",
184
- doi: "Dogri",
185
- gu: "Gujarati",
186
- hi: "Hindi",
187
- kn: "Kannada",
188
- ks: "Kashmiri",
189
- kok: "Konkani",
190
- mai: "Maithili",
191
- ml: "Malayalam",
192
- mni: "Manipuri",
193
- mr: "Marathi",
194
- ne: "Nepali",
195
- or: "Odia",
196
- pa: "Punjabi",
197
- sa: "Sanskrit",
198
- sat: "Santali",
199
- sd: "Sindhi",
200
- ta: "Tamil",
201
- te: "Telugu",
202
- ur: "Urdu"
203
- };
204
- function isNoticeLanguage(value) {
205
- return typeof value === "string" && Object.hasOwn(NOTICE_LANGUAGES, value);
206
- }
207
-
208
202
  // src/retention.ts
209
203
  import { randomUUID } from "crypto";
210
204
  var MAX_ATTEMPTS = 5;
@@ -237,6 +231,8 @@ function tasksFromPlan(config, plan, now) {
237
231
  kind: table.action === "delete-rows" ? "delete-rows" : "erase-fields",
238
232
  table: table.key,
239
233
  ...table.action === "delete-rows" ? {} : { fields: erasable.map((f) => f.field) },
234
+ // Objection tasks record the purposes they serve, so lifting the objection can cancel them.
235
+ ...plan.reason === "objection" ? { purposes: [...plan.ended] } : {},
240
236
  dueAt: due(wait)
241
237
  });
242
238
  }
@@ -303,44 +299,6 @@ async function runDueTasks(input) {
303
299
  return report;
304
300
  }
305
301
 
306
- // src/rights.ts
307
- var DEFAULT_RESPONSE_WITHIN = "90d";
308
- function responseWithin(config, type) {
309
- const setting = config.rights?.responseWithin;
310
- if (setting === void 0) return DEFAULT_RESPONSE_WITHIN;
311
- if (typeof setting === "string") return setting;
312
- return setting[type] ?? DEFAULT_RESPONSE_WITHIN;
313
- }
314
- function dueAt(config, type, openedAt) {
315
- return new Date(Date.parse(openedAt) + durationMs(responseWithin(config, type))).toISOString();
316
- }
317
- async function buildAccessSummary(input) {
318
- const { config, data, subjectId, consents, now } = input;
319
- const legitimateUses = Object.entries(config.purposes).filter(([, def]) => def.basis === "legitimate-use").map(([name]) => name);
320
- const applies = /* @__PURE__ */ new Set([...consents, ...legitimateUses]);
321
- const tables = [];
322
- for (const [key, def] of Object.entries(config.data)) {
323
- const fields = Object.entries(def.fields).map(([field, f]) => ({
324
- field,
325
- category: f.category,
326
- purposes: [...f.purposes]
327
- }));
328
- const rows = await data.read(
329
- def.table,
330
- def.subject,
331
- subjectId,
332
- fields.map((f) => f.field)
333
- );
334
- if (rows.length > 0) tables.push({ key, table: def.table, fields, rows });
335
- }
336
- const sharedWith = Object.entries(config.processors ?? {}).map(([name, p]) => ({
337
- name,
338
- ...p.description !== void 0 ? { description: p.description } : {},
339
- purposes: p.purposes.filter((purpose) => applies.has(purpose))
340
- })).filter((p) => p.purposes.length > 0);
341
- return { subjectId, generatedAt: now, data: tables, consents, legitimateUses, sharedWith };
342
- }
343
-
344
302
  // src/dpdp.ts
345
303
  function hashEvent(event) {
346
304
  return sha256(
@@ -375,11 +333,21 @@ ${lines.join("\n")}`, issues);
375
333
  throw new DpdpError("invalid-subject", "subjectId must be a non-empty string");
376
334
  }
377
335
  }
378
- function checkConsentPurposes(list) {
336
+ const objectable = (p) => purposes[p]?.basis === "legitimate-use" && purposes[p]?.legitimateUse === "7(a)";
337
+ function checkConsentPurposes(list, action) {
379
338
  if (list.length === 0) throw new DpdpError("no-purposes", "Pass at least one purpose");
380
339
  for (const p of list) {
381
340
  const def = purposes[p];
382
341
  if (!def) throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(p)}`);
342
+ if (action === "object" || action === "lift-objection") {
343
+ if (!objectable(p)) {
344
+ throw new DpdpError(
345
+ "not-objectable",
346
+ def.basis === "consent" ? `${JSON.stringify(p)} is a consent purpose: withdraw consent instead of objecting` : `${JSON.stringify(p)} isn't a Section 7(a) use: set legitimateUse: "7(a)" on it if the person gave this data voluntarily`
347
+ );
348
+ }
349
+ continue;
350
+ }
383
351
  if (def.basis !== "consent") {
384
352
  throw new DpdpError(
385
353
  "not-a-consent-purpose",
@@ -390,7 +358,7 @@ ${lines.join("\n")}`, issues);
390
358
  }
391
359
  async function append(subjectId, action, list, meta = {}) {
392
360
  checkSubject(subjectId);
393
- checkConsentPurposes(list);
361
+ checkConsentPurposes(list, action);
394
362
  if (meta.language !== void 0 && !isNoticeLanguage(meta.language)) {
395
363
  throw new DpdpError("invalid-language", `Unknown notice language ${JSON.stringify(meta.language)}`);
396
364
  }
@@ -429,6 +397,10 @@ ${lines.join("\n")}`, issues);
429
397
  checkSubject(subjectId);
430
398
  return [...grantedPurposes(await store.events(subjectId))];
431
399
  }
400
+ function remainingFrom(events) {
401
+ const objected = objectedPurposes(events);
402
+ return [...legitimate.filter((p) => !objected.has(p)), ...grantedPurposes(events)];
403
+ }
432
404
  const nowIso = () => now().toISOString();
433
405
  const processorHooks = options.processors ?? {};
434
406
  function fullStore(feature) {
@@ -467,6 +439,47 @@ ${lines.join("\n")}`, issues);
467
439
  });
468
440
  }
469
441
  }
442
+ function noticeStore() {
443
+ if (!isNoticeStore(store)) {
444
+ throw new DpdpError(
445
+ "store-unsupported",
446
+ "Saved notices need a store that keeps them: any built-in store, or your own NoticeStore"
447
+ );
448
+ }
449
+ return store;
450
+ }
451
+ const builtNotices = /* @__PURE__ */ new Map();
452
+ const savedNotices = /* @__PURE__ */ new Map();
453
+ function noticeFor(language = "en", kind = "consent") {
454
+ const key = `${language}\0${kind}`;
455
+ let notice = builtNotices.get(key);
456
+ if (!notice) {
457
+ notice = buildNotice(config, { language, kind });
458
+ builtNotices.set(key, notice);
459
+ }
460
+ return structuredClone(notice);
461
+ }
462
+ async function recordNotice(notice) {
463
+ if (!isNoticeStore(store)) return;
464
+ const s = store;
465
+ const key = `${notice.version}\0${notice.language}\0${notice.kind}`;
466
+ let saving = savedNotices.get(key);
467
+ if (!saving) {
468
+ saving = (async () => {
469
+ if (await s.savePrivacyNotice(notice, nowIso())) return;
470
+ const existing = await s.getPrivacyNotice(notice.version, notice.language, notice.kind);
471
+ if (existing && !sameNotice(existing.notice, notice)) {
472
+ throw new DpdpError(
473
+ "notice-version-conflict",
474
+ `A different ${notice.language} notice was already saved as version ${JSON.stringify(notice.version)}. Change notice.version when you change the notice, or leave it out to version by content.`
475
+ );
476
+ }
477
+ })();
478
+ savedNotices.set(key, saving);
479
+ saving.catch(() => savedNotices.delete(key));
480
+ }
481
+ await saving;
482
+ }
470
483
  function breachStore() {
471
484
  if (!isBreachStore(store)) {
472
485
  throw new DpdpError(
@@ -518,7 +531,22 @@ ${lines.join("\n")}`, issues);
518
531
  if (!request) throw new DpdpError("request-not-found", `No rights request with id ${JSON.stringify(id)}`);
519
532
  return request;
520
533
  }
521
- async function close(id, status, note) {
534
+ async function usableRequest(id, expect = {}) {
535
+ const request = await requireRequest(id);
536
+ if (expect.subjectId !== void 0 && request.subjectId !== expect.subjectId) {
537
+ throw new DpdpError("request-not-found", `Request ${id} belongs to a different person`);
538
+ }
539
+ if (expect.type !== void 0 && request.type !== expect.type) {
540
+ throw new DpdpError("wrong-request-type", `Request ${id} is a ${request.type} request, not ${expect.type}`);
541
+ }
542
+ if (request.status !== "open") throw new DpdpError("request-closed", `Request ${id} is already ${request.status}`);
543
+ if (config.rights?.verify === "required" && !isVerified(request)) {
544
+ throw new DpdpError("request-not-verified", `Check the identity of the person behind request ${id} first, and record it with rights.verifyIdentity()`);
545
+ }
546
+ return request;
547
+ }
548
+ const byEntry = (by) => by !== void 0 ? { by } : {};
549
+ async function close(id, status, note, by, extra = []) {
522
550
  const request = await requireRequest(id);
523
551
  if (request.status !== "open") {
524
552
  throw new DpdpError("request-closed", `Request ${id} is already ${request.status}`);
@@ -528,7 +556,7 @@ ${lines.join("\n")}`, issues);
528
556
  ...request,
529
557
  status,
530
558
  closedAt: at,
531
- history: [...request.history, { at, status, ...note !== void 0 ? { note } : {} }]
559
+ history: [...request.history, ...extra, { at, status, ...note !== void 0 ? { note } : {}, ...byEntry(by) }]
532
560
  };
533
561
  await fullStore("Rights requests").updateRequest(closed);
534
562
  emit("rights.closed", { request: closed });
@@ -598,31 +626,85 @@ ${lines.join("\n")}`, issues);
598
626
  },
599
627
  consent: {
600
628
  async grant(subjectId, list, meta) {
601
- const event = await append(subjectId, "grant", list, meta);
629
+ let withNotice = meta;
630
+ if (config.notice && meta?.noticeVersion === void 0) {
631
+ checkSubject(subjectId);
632
+ checkConsentPurposes(list, "grant");
633
+ const notice = noticeFor(meta?.language ?? "en", "consent");
634
+ await recordNotice(notice);
635
+ withNotice = { ...meta, noticeVersion: notice.version, language: notice.language };
636
+ }
637
+ const event = await append(subjectId, "grant", list, withNotice);
602
638
  emit("consent.granted", { event });
603
639
  return event;
604
640
  },
605
641
  async withdraw(subjectId, list, meta) {
606
642
  const event = await append(subjectId, "withdraw", list, meta);
607
- const stillGranted = await activeFor(subjectId);
608
643
  const erasure = planErasure(config, {
609
644
  subjectId,
610
645
  reason: "withdrawal",
611
646
  ended: event.purposes,
612
- remaining: [...legitimate, ...stillGranted]
647
+ remaining: remainingFrom(await store.events(subjectId))
613
648
  });
614
649
  const tasks = isDpdpStore(store) ? await schedule(erasure) : [];
615
650
  emit("consent.withdrawn", { event, erasure, tasks });
616
651
  return { event, erasure, tasks };
617
652
  },
653
+ async object(subjectId, list, meta) {
654
+ checkSubject(subjectId);
655
+ const before = objectedPurposes(await store.events(subjectId));
656
+ const event = await append(subjectId, "object", list, meta);
657
+ const ended = event.purposes.filter((p) => !before.has(p));
658
+ const erasure = planErasure(config, {
659
+ subjectId,
660
+ reason: "objection",
661
+ ended,
662
+ remaining: remainingFrom(await store.events(subjectId))
663
+ });
664
+ const tasks = isDpdpStore(store) && ended.length > 0 ? await schedule(erasure) : [];
665
+ emit("consent.objected", { event, erasure, tasks });
666
+ return { event, erasure, tasks };
667
+ },
668
+ async liftObjection(subjectId, list, meta) {
669
+ const event = await append(subjectId, "lift-objection", list, meta);
670
+ const lifted = new Set(event.purposes);
671
+ const cancelled = [];
672
+ let tasks = [];
673
+ if (isDpdpStore(store)) {
674
+ const stillObjected = objectedPurposes(await store.events(subjectId));
675
+ const replan = /* @__PURE__ */ new Set();
676
+ for (const status of ["pending", "failed"]) {
677
+ for (const task of await store.listTasks({ subjectId, status })) {
678
+ if (task.reason !== "objection" || !task.purposes?.some((p) => lifted.has(p))) continue;
679
+ const done = { ...task, status: "cancelled", note: "Objection lifted" };
680
+ await store.updateTask(done);
681
+ cancelled.push(done);
682
+ for (const p of task.purposes) if (stillObjected.has(p)) replan.add(p);
683
+ }
684
+ }
685
+ if (replan.size > 0) {
686
+ tasks = await schedule(
687
+ planErasure(config, { subjectId, reason: "objection", ended: [...replan], remaining: remainingFrom(await store.events(subjectId)) })
688
+ );
689
+ }
690
+ }
691
+ emit("consent.objection-lifted", { event, cancelled, tasks });
692
+ return { event, cancelled, tasks };
693
+ },
618
694
  async has(subjectId, purpose) {
619
695
  checkSubject(subjectId);
620
696
  const def = purposes[purpose];
621
697
  if (!def) throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(purpose)}`);
622
- if (def.basis === "legitimate-use") return true;
698
+ if (def.basis === "legitimate-use") {
699
+ return objectable(purpose) ? !objectedPurposes(await store.events(subjectId)).has(purpose) : true;
700
+ }
623
701
  return grantedPurposes(await store.events(subjectId)).has(purpose);
624
702
  },
625
703
  active: activeFor,
704
+ async objections(subjectId) {
705
+ checkSubject(subjectId);
706
+ return [...objectedPurposes(await store.events(subjectId))];
707
+ },
626
708
  async history(subjectId) {
627
709
  checkSubject(subjectId);
628
710
  return store.events(subjectId);
@@ -753,6 +835,70 @@ ${lines.join("\n")}`, issues);
753
835
  return { deleted: await accessStore().pruneAccess(before), before };
754
836
  }
755
837
  },
838
+ async evidence(input = {}) {
839
+ const at = nowIso();
840
+ checkIso(input.from, "from");
841
+ checkIso(input.to, "to");
842
+ const to = new Date(input.to ?? at).toISOString();
843
+ const from = input.from !== void 0 ? new Date(input.from).toISOString() : new Date(Date.parse(to) - durationMs("30d")).toISOString();
844
+ const report = staticEvidence(config, at);
845
+ report.period = { from, to };
846
+ const without = (what) => ({ unavailable: `the store doesn't keep ${what}` });
847
+ report.notices = isNoticeStore(store) ? (await store.listPrivacyNotices()).map((n) => ({
848
+ version: n.notice.version,
849
+ language: n.notice.language,
850
+ kind: n.notice.kind,
851
+ firstShownAt: n.firstShownAt,
852
+ purposes: n.notice.items.length
853
+ })) : without("notices");
854
+ report.consent = isStatsStore(store) ? await store.consentStats(from, to) : { unavailable: "the store can't count consent events (add consentStats)" };
855
+ if (isDpdpStore(store)) {
856
+ report.requests = requestStats(await store.listRequests({}), from, to, at);
857
+ if (isStatsStore(store)) report.erasure = await store.taskCounts(at);
858
+ else {
859
+ const counts = { byStatus: {}, late: 0 };
860
+ for (const t of await store.listTasks({})) {
861
+ counts.byStatus[t.status] = (counts.byStatus[t.status] ?? 0) + 1;
862
+ if ((t.status === "pending" || t.status === "failed") && t.dueAt < at) counts.late++;
863
+ }
864
+ report.erasure = counts;
865
+ }
866
+ } else {
867
+ report.requests = without("rights requests");
868
+ report.erasure = without("erasure tasks");
869
+ }
870
+ if (isAccessLogStore(store)) {
871
+ const review = await api.access.review({ from, to, ...input.review });
872
+ const findings = {};
873
+ for (const f of review.findings) findings[f.kind] = (findings[f.kind] ?? 0) + 1;
874
+ report.access = { scanned: review.scanned, findings, examples: review.findings.slice(0, input.examples ?? 20) };
875
+ } else report.access = without("an access log");
876
+ if (isBreachStore(store)) {
877
+ const relevant = (await store.listBreaches({})).filter((b) => b.status === "open" || b.awareAt >= from && b.awareAt < to);
878
+ report.breaches = await Promise.all(relevant.map((b) => api.breach.status(b.id)));
879
+ } else report.breaches = without("breaches");
880
+ report.gaps = gapsOf(report);
881
+ return report;
882
+ },
883
+ notice: {
884
+ build(options2 = {}) {
885
+ return noticeFor(options2.language, options2.kind);
886
+ },
887
+ async show(options2 = {}) {
888
+ const notice = noticeFor(options2.language, options2.kind);
889
+ await recordNotice(notice);
890
+ return notice;
891
+ },
892
+ async get(version, options2 = {}) {
893
+ return noticeStore().getPrivacyNotice(version, options2.language ?? "en", options2.kind ?? "consent");
894
+ },
895
+ async list() {
896
+ return noticeStore().listPrivacyNotices();
897
+ },
898
+ languages() {
899
+ return noticeLanguages(config);
900
+ }
901
+ },
756
902
  breach: {
757
903
  async open(input) {
758
904
  if (!input || typeof input.description !== "string" || input.description.trim() === "") {
@@ -900,30 +1046,143 @@ ${lines.join("\n")}`, issues);
900
1046
  const at = nowIso();
901
1047
  return list.filter((r) => r.dueAt < at);
902
1048
  },
903
- resolve: (id, note) => close(id, "resolved", note),
904
- reject: (id, reason) => close(id, "rejected", reason),
905
- async summary(subjectId) {
1049
+ resolve: (id, note, opts = {}) => close(id, "resolved", note, opts.by),
1050
+ reject: (id, reason, opts = {}) => close(id, "rejected", reason, opts.by),
1051
+ async acknowledgement(id) {
1052
+ return acknowledgement(config, await requireRequest(id));
1053
+ },
1054
+ async verifyIdentity(id, input) {
1055
+ if (!input || typeof input.method !== "string" || !input.method.trim() || typeof input.by !== "string" || !input.by.trim()) {
1056
+ throw new DpdpError("invalid-input", "Say how the identity was checked and by whom: { method, by }");
1057
+ }
1058
+ const request = await requireRequest(id);
1059
+ if (request.status !== "open") throw new DpdpError("request-closed", `Request ${id} is already ${request.status}`);
1060
+ const verified = {
1061
+ ...request,
1062
+ history: [...request.history, { at: nowIso(), status: "open", event: "verified", method: input.method, by: input.by }]
1063
+ };
1064
+ await fullStore("Rights requests").updateRequest(verified);
1065
+ emit("rights.verified", { request: verified });
1066
+ return verified;
1067
+ },
1068
+ async correct(requestId, changes, opts = {}) {
1069
+ const request = await usableRequest(requestId, { type: "correction" });
1070
+ const data = dataAccess();
1071
+ if (typeof data.updateFields !== "function") {
1072
+ throw new DpdpError("data-access-unsupported", "This data access can't write corrections: give it updateFields (the built-in ones have it)");
1073
+ }
1074
+ const keys = Object.keys(changes ?? {});
1075
+ if (keys.length === 0) throw new DpdpError("invalid-input", `Pass the fields to correct, e.g. { "users.phone": "98\u2026" }`);
1076
+ const byTable = /* @__PURE__ */ new Map();
1077
+ for (const key of keys) {
1078
+ const dot = key.indexOf(".");
1079
+ const tableKey = dot < 0 ? key : key.slice(0, dot);
1080
+ const field = key.slice(dot + 1);
1081
+ const table = config.data[tableKey];
1082
+ if (dot < 0 || !table || !Object.hasOwn(table.fields, field)) {
1083
+ throw new DpdpError("unknown-field", `Not in the data map: ${JSON.stringify(key)}. Use keys like "users.phone".`);
1084
+ }
1085
+ if (table.legalHold) {
1086
+ throw new DpdpError("not-correctable", `${tableKey} is kept under a legal hold (${table.legalHold.reason}): correct it through the process that law sets`);
1087
+ }
1088
+ const value = changes[key];
1089
+ if (value === void 0 || ["function", "symbol", "bigint"].includes(typeof value)) {
1090
+ throw new DpdpError("invalid-input", `${key}: pass a string, number, boolean, null, or a JSON value`);
1091
+ }
1092
+ byTable.set(tableKey, { ...byTable.get(tableKey), [field]: value });
1093
+ }
1094
+ if (opts.where && byTable.size > 1) throw new DpdpError("invalid-input", "where applies to one table: correct one table at a time");
1095
+ for (const [column, value] of Object.entries(opts.where ?? {})) {
1096
+ const t = config.data[[...byTable.keys()][0]];
1097
+ if (column === t.subject) throw new DpdpError("invalid-input", `where can't name the subject column ${JSON.stringify(column)}: the request already decides whose rows these are`);
1098
+ if (!["string", "number", "boolean"].includes(typeof value)) {
1099
+ throw new DpdpError("invalid-input", `where.${column}: pass a string, number or boolean to match`);
1100
+ }
1101
+ }
1102
+ const changed = {};
1103
+ for (const [tableKey, values] of byTable) {
1104
+ const t = config.data[tableKey];
1105
+ changed[tableKey] = await data.updateFields(t.table, t.subject, request.subjectId, values, opts.where);
1106
+ }
1107
+ const rows = Object.values(changed).reduce((a, b) => a + b, 0);
1108
+ if (rows === 0) {
1109
+ throw new DpdpError("no-matching-rows", `No rows of this person matched${opts.where ? " where" : ""}: nothing was corrected and request ${requestId} is still open`);
1110
+ }
1111
+ const entry = { at: nowIso(), status: "open", event: "corrected", fields: keys, ...byEntry(opts.by) };
1112
+ let updated;
1113
+ if (opts.resolve === false) {
1114
+ updated = { ...request, history: [...request.history, entry] };
1115
+ await fullStore("Rights requests").updateRequest(updated);
1116
+ } else {
1117
+ updated = await close(requestId, "resolved", `Corrected ${keys.join(", ")} (${rows} row${rows === 1 ? "" : "s"})`, opts.by, [entry]);
1118
+ }
1119
+ emit("rights.corrected", { request: updated, fields: keys });
1120
+ return { request: updated, changed };
1121
+ },
1122
+ async nominate(subjectId, nominee, opts = {}) {
1123
+ checkSubject(subjectId);
1124
+ for (const k of ["name", "contact"]) {
1125
+ if (typeof nominee?.[k] !== "string" || !nominee[k].trim()) throw new DpdpError("invalid-input", `The nominee needs a ${k}`);
1126
+ }
1127
+ const details = { name: nominee.name, contact: nominee.contact, ...nominee.relation !== void 0 ? { relation: nominee.relation } : {} };
1128
+ let request;
1129
+ if (opts.requestId) {
1130
+ const existing = await usableRequest(opts.requestId, { subjectId, type: "nomination" });
1131
+ request = { ...existing, details: { ...existing.details, ...details } };
1132
+ await fullStore("Rights requests").updateRequest(request);
1133
+ } else {
1134
+ request = await api.rights.open(subjectId, "nomination", details);
1135
+ }
1136
+ const closed = await close(request.id, "resolved", "Nominee recorded", opts.by);
1137
+ const recorded = { id: closed.id, subjectId, ...details, nominatedAt: closed.closedAt };
1138
+ emit("rights.nominated", { nominee: recorded });
1139
+ return recorded;
1140
+ },
1141
+ async nominees(subjectId) {
1142
+ checkSubject(subjectId);
1143
+ const list = await fullStore("Rights requests").listRequests({ subjectId, status: "resolved" });
1144
+ return list.filter((r) => r.type === "nomination" && typeof r.details?.name === "string" && !r.history.some((e) => e.event === "revoked")).map((r) => ({
1145
+ id: r.id,
1146
+ subjectId: r.subjectId,
1147
+ name: String(r.details.name),
1148
+ contact: String(r.details.contact ?? ""),
1149
+ ...typeof r.details.relation === "string" ? { relation: r.details.relation } : {},
1150
+ nominatedAt: r.closedAt ?? r.openedAt
1151
+ }));
1152
+ },
1153
+ async revokeNominee(subjectId, nomineeId, opts = {}) {
1154
+ checkSubject(subjectId);
1155
+ const request = await fullStore("Rights requests").getRequest(nomineeId);
1156
+ if (!request || request.subjectId !== subjectId || request.type !== "nomination" || request.status !== "resolved") {
1157
+ throw new DpdpError("nominee-not-found", `No nominee ${JSON.stringify(nomineeId)} for this person`);
1158
+ }
1159
+ if (request.history.some((e) => e.event === "revoked")) return;
1160
+ await fullStore("Rights requests").updateRequest({
1161
+ ...request,
1162
+ history: [...request.history, { at: nowIso(), status: "resolved", event: "revoked", ...byEntry(opts.by) }]
1163
+ });
1164
+ },
1165
+ how: () => rightsInfo(config),
1166
+ async summary(subjectId, opts = {}) {
906
1167
  checkSubject(subjectId);
1168
+ if (opts.requestId !== void 0) await usableRequest(opts.requestId, { subjectId });
1169
+ const events = await store.events(subjectId);
907
1170
  return buildAccessSummary({
908
1171
  config,
909
1172
  data: dataAccess(),
910
1173
  subjectId,
911
- consents: await activeFor(subjectId),
1174
+ consents: [...grantedPurposes(events)],
1175
+ objections: [...objectedPurposes(events)],
912
1176
  now: nowIso()
913
1177
  });
914
1178
  },
915
1179
  async erase(subjectId, input = {}) {
916
1180
  checkSubject(subjectId);
917
- if (input.requestId) {
918
- const request = await requireRequest(input.requestId);
919
- if (request.subjectId !== subjectId) {
920
- throw new DpdpError("request-not-found", `Request ${input.requestId} belongs to a different person`);
921
- }
922
- }
1181
+ if (input.requestId) await usableRequest(input.requestId, { subjectId, type: "erasure" });
923
1182
  const plan = accountPlan(subjectId, "erasure-request", input.keepFor ?? []);
924
1183
  const tasks = await schedule(plan);
925
1184
  if (input.requestId) {
926
- await close(input.requestId, "resolved", `Erasure scheduled: ${tasks.length} task(s)`);
1185
+ await close(input.requestId, "resolved", `Erasure scheduled: ${tasks.length} task(s)`, input.by);
927
1186
  }
928
1187
  return { plan, tasks };
929
1188
  }
@@ -931,61 +1190,52 @@ ${lines.join("\n")}`, issues);
931
1190
  };
932
1191
  return api;
933
1192
  }
934
-
935
- // src/data-access.ts
936
- function memoryData(tables) {
937
- const rowsOf = (table) => tables[table] ??= [];
938
- const mine = (subjectColumn, subjectId) => (row) => String(row[subjectColumn]) === subjectId;
939
- return {
940
- tables,
941
- async read(table, subjectColumn, subjectId, columns) {
942
- return rowsOf(table).filter(mine(subjectColumn, subjectId)).map((row) => Object.fromEntries(columns.map((c) => [c, row[c] ?? null])));
943
- },
944
- async eraseFields(table, subjectColumn, subjectId, columns, values = {}) {
945
- const rows = rowsOf(table).filter(mine(subjectColumn, subjectId));
946
- for (const row of rows) for (const c of columns) row[c] = Object.hasOwn(values, c) ? values[c] : null;
947
- return rows.length;
948
- },
949
- async deleteRows(table, subjectColumn, subjectId) {
950
- const before = rowsOf(table).length;
951
- tables[table] = rowsOf(table).filter((row) => !mine(subjectColumn, subjectId)(row));
952
- return before - tables[table].length;
953
- }
954
- };
955
- }
956
1193
  export {
957
1194
  BOARD_REPORT_WITHIN_HOURS,
958
1195
  CONSENT_REQUIRED_BODY,
959
1196
  DEFAULT_ACCESS_LOG_RETENTION,
960
1197
  DEFAULT_RESPONSE_WITHIN,
961
1198
  DpdpError,
1199
+ ENGLISH_WORDING,
1200
+ LEGITIMATE_USES,
1201
+ NOTICE_KINDS,
962
1202
  NOTICE_LANGUAGES,
963
1203
  REDACTED,
964
1204
  REQUEST_TYPES,
965
1205
  SeqConflictError,
966
1206
  audit,
967
1207
  breachStatus,
1208
+ buildNotice,
968
1209
  checkSchema,
969
1210
  createDpdp,
970
1211
  defineConfig,
1212
+ describeRetention,
971
1213
  durationMs,
972
1214
  erasedValue,
1215
+ formatEvidence,
973
1216
  formatSafeguards,
974
1217
  guessPersonal,
1218
+ handle,
975
1219
  hasErrors,
976
1220
  hashEvent,
977
1221
  isAccessLogStore,
1222
+ isApiRoute,
978
1223
  isBreachStore,
979
1224
  isDpdpStore,
980
1225
  isDuration,
981
1226
  isHighRisk,
982
1227
  isNoticeLanguage,
1228
+ isNoticeStore,
1229
+ isStatsStore,
1230
+ isUnavailable,
1231
+ isVerified,
983
1232
  memoryData,
984
1233
  memoryStore,
985
1234
  personNotice,
986
1235
  planErasure,
987
1236
  purposeNames,
988
1237
  safeguardsReport,
1238
+ staticEvidence,
989
1239
  tasksFromPlan,
990
1240
  tokenize
991
1241
  };