dpdp-kit 0.4.0 → 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 +45 -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
@@ -1,3 +1,10 @@
1
+ import {
2
+ statsFromEvents
3
+ } from "./chunk-M2PDT6DD.js";
4
+ import {
5
+ REQUEST_TYPES,
6
+ isRunnable
7
+ } from "./chunk-NBVJQDDP.js";
1
8
  import {
2
9
  DpdpError,
3
10
  SeqConflictError
@@ -20,22 +27,14 @@ function maxDuration(a, b) {
20
27
  return durationMs(b) > durationMs(a) ? b : a;
21
28
  }
22
29
 
23
- // src/records.ts
24
- var REQUEST_TYPES = ["access", "correction", "erasure", "grievance", "nomination"];
25
- function isRunnable(task, { now, staleBefore, maxAttempts }) {
26
- if (task.dueAt > now) return false;
27
- if (task.status === "pending") return true;
28
- if (task.status === "failed") return task.attempts < maxAttempts;
29
- if (task.status === "running") return (task.claimedAt ?? "") < staleBefore;
30
- return false;
31
- }
32
-
33
30
  // src/store.ts
34
31
  function isDpdpStore(store) {
35
32
  const s = store;
36
33
  return typeof s.insertRequest === "function" && typeof s.insertTasks === "function";
37
34
  }
38
35
  function memoryStore() {
36
+ const privacyNotices = /* @__PURE__ */ new Map();
37
+ const privacyKey = (version, language, kind) => `${version}\0${language}\0${kind}`;
39
38
  const all = /* @__PURE__ */ new Map();
40
39
  const requests = /* @__PURE__ */ new Map();
41
40
  const tasks = /* @__PURE__ */ new Map();
@@ -52,6 +51,31 @@ function memoryStore() {
52
51
  accessLog,
53
52
  breaches,
54
53
  notices,
54
+ privacyNotices,
55
+ async consentStats(from, to) {
56
+ return statsFromEvents(all.values(), from, to);
57
+ },
58
+ async taskCounts(now) {
59
+ const counts2 = { byStatus: {}, late: 0 };
60
+ for (const t of tasks.values()) {
61
+ counts2.byStatus[t.status] = (counts2.byStatus[t.status] ?? 0) + 1;
62
+ if ((t.status === "pending" || t.status === "failed") && t.dueAt < now) counts2.late++;
63
+ }
64
+ return counts2;
65
+ },
66
+ async savePrivacyNotice(notice, at) {
67
+ const key = privacyKey(notice.version, notice.language, notice.kind);
68
+ if (privacyNotices.has(key)) return false;
69
+ privacyNotices.set(key, { notice: structuredClone(notice), firstShownAt: at });
70
+ return true;
71
+ },
72
+ async getPrivacyNotice(version, language, kind) {
73
+ const n = privacyNotices.get(privacyKey(version, language, kind));
74
+ return n && structuredClone(n);
75
+ },
76
+ async listPrivacyNotices() {
77
+ return [...privacyNotices.values()].sort((a, b) => a.firstShownAt < b.firstShownAt ? -1 : a.firstShownAt > b.firstShownAt ? 1 : 0).map((n) => structuredClone(n));
78
+ },
55
79
  async insertBreach(breach) {
56
80
  breaches.set(breach.id, structuredClone(breach));
57
81
  },
@@ -176,11 +200,22 @@ function grantedPurposes(events, until) {
176
200
  if (until !== void 0 && e.at > until) break;
177
201
  for (const p of e.purposes) {
178
202
  if (e.action === "grant") granted.add(p);
179
- else granted.delete(p);
203
+ else if (e.action === "withdraw") granted.delete(p);
180
204
  }
181
205
  }
182
206
  return granted;
183
207
  }
208
+ function objectedPurposes(events, until) {
209
+ const objected = /* @__PURE__ */ new Set();
210
+ for (const e of events) {
211
+ if (until !== void 0 && e.at > until) break;
212
+ for (const p of e.purposes) {
213
+ if (e.action === "object") objected.add(p);
214
+ else if (e.action === "lift-objection") objected.delete(p);
215
+ }
216
+ }
217
+ return objected;
218
+ }
184
219
 
185
220
  // src/access.ts
186
221
  import { randomBytes } from "crypto";
@@ -198,12 +233,12 @@ function resolveFields(config, keys) {
198
233
  const fields = /* @__PURE__ */ new Set();
199
234
  const unknown = [];
200
235
  for (const key of keys) {
201
- const [table, field, ...extra] = key.split(".");
202
- const def = table ? config.data[table] : void 0;
236
+ const [table2, field, ...extra] = key.split(".");
237
+ const def = table2 ? config.data[table2] : void 0;
203
238
  if (!def || extra.length > 0) {
204
239
  unknown.push(key);
205
240
  } else if (field === void 0 || field === "*") {
206
- for (const f of Object.keys(def.fields)) fields.add(`${table}.${f}`);
241
+ for (const f of Object.keys(def.fields)) fields.add(`${table2}.${f}`);
207
242
  } else if (def.fields[field]) {
208
243
  fields.add(key);
209
244
  } else {
@@ -214,8 +249,8 @@ function resolveFields(config, keys) {
214
249
  }
215
250
  function fieldsOutsidePurpose(config, fields, purpose) {
216
251
  return fields.filter((key) => {
217
- const [table, field] = key.split(".");
218
- const def = config.data[table]?.fields[field];
252
+ const [table2, field] = key.split(".");
253
+ const def = config.data[table2]?.fields[field];
219
254
  return !def || !def.purposes.includes(purpose);
220
255
  });
221
256
  }
@@ -242,11 +277,27 @@ async function reviewAccess(input) {
242
277
  }
243
278
  }
244
279
  const consentPurposes = new Set(Object.keys(config.purposes).filter((p) => config.purposes[p]?.basis === "consent"));
280
+ const objectable = new Set(
281
+ Object.keys(config.purposes).filter((p) => config.purposes[p]?.basis === "legitimate-use" && config.purposes[p]?.legitimateUse === "7(a)")
282
+ );
245
283
  const needConsent = entries.filter((e) => consentPurposes.has(e.purpose));
284
+ const needNoObjection = entries.filter((e) => objectable.has(e.purpose));
246
285
  const histories = /* @__PURE__ */ new Map();
247
- await eachLimited([...new Set(needConsent.map((e) => e.subjectId))], 16, async (subjectId) => {
286
+ await eachLimited([...new Set([...needConsent, ...needNoObjection].map((e) => e.subjectId))], 16, async (subjectId) => {
248
287
  histories.set(subjectId, await input.history(subjectId));
249
288
  });
289
+ for (const e of needNoObjection) {
290
+ if (objectedPurposes(histories.get(e.subjectId) ?? [], e.at).has(e.purpose)) {
291
+ findings.push({
292
+ kind: "objected",
293
+ actor: e.actor,
294
+ subjectId: e.subjectId,
295
+ purpose: e.purpose,
296
+ entries: [e.id],
297
+ message: `${e.actor} accessed data for "${e.purpose}" after the person objected to that use (Section 7(a)).`
298
+ });
299
+ }
300
+ }
250
301
  for (const e of needConsent) {
251
302
  if (!grantedPurposes(histories.get(e.subjectId) ?? [], e.at).has(e.purpose)) {
252
303
  findings.push({
@@ -270,20 +321,20 @@ async function reviewAccess(input) {
270
321
  }
271
322
  for (const [actor, list] of byActor) {
272
323
  list.sort((a, b) => a.at < b.at ? -1 : a.at > b.at ? 1 : 0);
273
- const counts = /* @__PURE__ */ new Map();
324
+ const counts2 = /* @__PURE__ */ new Map();
274
325
  let start = 0;
275
326
  let peak = { subjects: 0, from: 0, to: 0 };
276
327
  for (let end = 0; end < list.length; end++) {
277
328
  const e = list[end];
278
- counts.set(e.subjectId, (counts.get(e.subjectId) ?? 0) + 1);
329
+ counts2.set(e.subjectId, (counts2.get(e.subjectId) ?? 0) + 1);
279
330
  while (Date.parse(e.at) - Date.parse(list[start].at) > windowMs) {
280
331
  const s = list[start].subjectId;
281
- const n = counts.get(s) - 1;
282
- if (n === 0) counts.delete(s);
283
- else counts.set(s, n);
332
+ const n = counts2.get(s) - 1;
333
+ if (n === 0) counts2.delete(s);
334
+ else counts2.set(s, n);
284
335
  start++;
285
336
  }
286
- if (counts.size > peak.subjects) peak = { subjects: counts.size, from: start, to: end };
337
+ if (counts2.size > peak.subjects) peak = { subjects: counts2.size, from: start, to: end };
287
338
  }
288
339
  if (peak.subjects > input.maxSubjects) {
289
340
  findings.push({
@@ -298,6 +349,165 @@ async function reviewAccess(input) {
298
349
  return { from: input.from, to: input.to, scanned: entries.length, findings };
299
350
  }
300
351
 
352
+ // src/config.ts
353
+ var LEGITIMATE_USES = ["7(a)", "7(b)", "7(c)", "7(d)", "7(e)", "7(f)", "7(g)", "7(h)", "7(i)"];
354
+ var REDACTED = "[erased]";
355
+ function defineConfig(config) {
356
+ return config;
357
+ }
358
+ function purposeNames(config) {
359
+ return Object.keys(config.purposes);
360
+ }
361
+ function erasedValue(erase, field) {
362
+ if (erase === void 0 || erase === "null") return null;
363
+ if (erase === "redact") return REDACTED;
364
+ const value = typeof erase.value === "function" ? erase.value(field) : erase.value;
365
+ if (value !== null && !["string", "number", "boolean"].includes(typeof value)) {
366
+ throw new DpdpError(
367
+ "invalid-erase",
368
+ `The erase value for ${field.table}.${field.field} must be a string, number, boolean or null; got ${value === void 0 ? "undefined (does the function return?)" : typeof value}`
369
+ );
370
+ }
371
+ return value;
372
+ }
373
+
374
+ // src/languages.ts
375
+ var NOTICE_LANGUAGES = {
376
+ en: "English",
377
+ as: "Assamese",
378
+ bn: "Bengali",
379
+ brx: "Bodo",
380
+ doi: "Dogri",
381
+ gu: "Gujarati",
382
+ hi: "Hindi",
383
+ kn: "Kannada",
384
+ ks: "Kashmiri",
385
+ kok: "Konkani",
386
+ mai: "Maithili",
387
+ ml: "Malayalam",
388
+ mni: "Manipuri",
389
+ mr: "Marathi",
390
+ ne: "Nepali",
391
+ or: "Odia",
392
+ pa: "Punjabi",
393
+ sa: "Sanskrit",
394
+ sat: "Santali",
395
+ sd: "Sindhi",
396
+ ta: "Tamil",
397
+ te: "Telugu",
398
+ ur: "Urdu"
399
+ };
400
+ function isNoticeLanguage(value) {
401
+ return typeof value === "string" && Object.hasOwn(NOTICE_LANGUAGES, value);
402
+ }
403
+
404
+ // src/hash.ts
405
+ import { createHash } from "crypto";
406
+ function canonicalJson(value) {
407
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
408
+ if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
409
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
410
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
411
+ }
412
+ function sha256(text) {
413
+ return createHash("sha256").update(text).digest("hex");
414
+ }
415
+
416
+ // src/notice.ts
417
+ var NOTICE_KINDS = ["consent", "existing-users"];
418
+ var ENGLISH_WORDING = {
419
+ title: "Privacy notice: {fiduciary}",
420
+ introConsent: "{fiduciary} asks for your consent to use the personal data below, for the purposes described.",
421
+ introExisting: "You gave {fiduciary} consent to use your personal data before the Digital Personal Data Protection Act, 2023 came into force. This is the personal data we have processed, and why.",
422
+ data: "Data used:",
423
+ withdraw: "You can withdraw your consent at any time, as easily as you gave it: {withdraw}",
424
+ rights: "To access, correct or erase your data, nominate someone to act for you, or raise a grievance: {rights}",
425
+ contact: "Questions about your data: {contact}",
426
+ complaint: "If you're not satisfied with how we handle your grievance, you can complain to the Data Protection Board of India.",
427
+ complaintWithLink: "If you're not satisfied with how we handle your grievance, you can complain to the Data Protection Board of India: {complaint}",
428
+ website: "More about how we use your data: {website}"
429
+ };
430
+ var REQUIRED_PLACEHOLDERS = {
431
+ withdraw: "{withdraw}",
432
+ rights: "{rights}",
433
+ contact: "{contact}",
434
+ complaintWithLink: "{complaint}",
435
+ website: "{website}"
436
+ };
437
+ function isNoticeStore(store) {
438
+ const s = store;
439
+ return typeof s.savePrivacyNotice === "function" && typeof s.getPrivacyNotice === "function";
440
+ }
441
+ function noticeLanguages(config) {
442
+ return ["en", ...Object.keys(config.notice?.translations ?? {}).filter((l) => l !== "en")];
443
+ }
444
+ function humanise(name) {
445
+ const words = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_\-.]+/g, " ").trim().toLowerCase();
446
+ return words.charAt(0).toUpperCase() + words.slice(1);
447
+ }
448
+ var fill = (template, values) => template.replace(/\{(\w+)\}/g, (m, k) => values[k] ?? m);
449
+ function buildNotice(config, options = {}) {
450
+ const notice = config.notice;
451
+ if (!notice) throw new DpdpError("notice-not-configured", "Add notice: { links: { website, withdraw, rights } } to the config to build notices");
452
+ const language = options.language ?? "en";
453
+ const kind = options.kind ?? "consent";
454
+ if (!isNoticeLanguage(language)) throw new DpdpError("invalid-language", `Unknown notice language ${JSON.stringify(language)}`);
455
+ if (!NOTICE_KINDS.includes(kind)) throw new DpdpError("invalid-input", `Unknown notice kind ${JSON.stringify(kind)}`);
456
+ const translation = language === "en" ? void 0 : notice.translations?.[language];
457
+ if (language !== "en" && !translation) {
458
+ throw new DpdpError("notice-language-unavailable", `There's no ${language} notice: add notice.translations.${language} to the config`);
459
+ }
460
+ const missing = (what) => {
461
+ throw new DpdpError("notice-translation-incomplete", `The ${language} notice has no ${what}. Run the audit to see everything missing.`);
462
+ };
463
+ const wording = translation ? translation.wording : ENGLISH_WORDING;
464
+ const fiduciary = translation?.fiduciary ?? config.fiduciary.name;
465
+ const links = { ...notice.links, ...translation?.links };
466
+ const items = [];
467
+ for (const [purpose, def] of Object.entries(config.purposes)) {
468
+ if (def.basis !== "consent") continue;
469
+ const description = translation ? translation.purposes[purpose] : def.description;
470
+ if (!description) {
471
+ if (translation) missing(`description for purpose ${purpose}`);
472
+ throw new DpdpError("notice-description-missing", `Purpose ${purpose} needs a description for the notice (Rule 3(b)(ii))`);
473
+ }
474
+ const data = [];
475
+ for (const [key, table2] of Object.entries(config.data)) {
476
+ for (const [field, f] of Object.entries(table2.fields)) {
477
+ if (!f.purposes.includes(purpose)) continue;
478
+ const label = translation ? translation.fields[`${key}.${field}`] ?? missing(`label for ${key}.${field}`) : f.label ?? humanise(field);
479
+ const same = data.find((d) => d.label === label);
480
+ if (same) same.fields.push(`${key}.${field}`);
481
+ else data.push({ label, category: f.category, fields: [`${key}.${field}`] });
482
+ }
483
+ }
484
+ items.push({ purpose, description, data });
485
+ }
486
+ const contact = config.fiduciary.dpo;
487
+ const values = { fiduciary, contact: contact ?? "", ...links, complaint: links.complaint ?? "" };
488
+ const lines = [fill(wording.title, values), "", fill(kind === "consent" ? wording.introConsent : wording.introExisting, values), ""];
489
+ for (const item of items) {
490
+ lines.push(`\u2022 ${item.description}`, ` ${wording.data} ${item.data.map((d) => d.label).join(", ")}`);
491
+ }
492
+ lines.push("", fill(wording.withdraw, values), fill(wording.rights, values));
493
+ if (contact) lines.push(fill(wording.contact, values));
494
+ lines.push(fill(links.complaint ? wording.complaintWithLink : wording.complaint, values), fill(wording.website, values));
495
+ const content = {
496
+ language,
497
+ kind,
498
+ fiduciary,
499
+ items,
500
+ links,
501
+ ...contact ? { contact } : {},
502
+ text: lines.join("\n")
503
+ };
504
+ return { version: notice.version ?? noticeHash(content), ...content };
505
+ }
506
+ function noticeHash(content) {
507
+ return sha256(canonicalJson(content)).slice(0, 12);
508
+ }
509
+ var sameNotice = (a, b) => canonicalJson(a) === canonicalJson(b);
510
+
301
511
  // src/personal.ts
302
512
  var rule = (spec, category, confidence = "strong") => ({
303
513
  tokens: spec.split(" "),
@@ -552,10 +762,35 @@ function audit(config) {
552
762
  message: 'afterWithdrawal only applies to consent purposes (Section 6(4)). Use "while-active" or a duration for a legitimate use.'
553
763
  });
554
764
  }
765
+ if (def.legitimateUse !== void 0) {
766
+ if (def.basis !== "legitimate-use") {
767
+ issues.push({
768
+ level: "error",
769
+ code: "invalid-legitimate-use",
770
+ path: `${path}.legitimateUse`,
771
+ message: 'legitimateUse only applies to legitimate-use purposes. Remove it, or set basis: "legitimate-use".'
772
+ });
773
+ } else if (!LEGITIMATE_USES.includes(def.legitimateUse)) {
774
+ issues.push({
775
+ level: "error",
776
+ code: "invalid-legitimate-use",
777
+ path: `${path}.legitimateUse`,
778
+ message: `legitimateUse must be one of ${LEGITIMATE_USES.join(", ")}: the clause of Section 7 this use relies on.`
779
+ });
780
+ }
781
+ } else if (def.basis === "legitimate-use") {
782
+ issues.push({
783
+ level: "warning",
784
+ code: "legitimate-use-clause-missing",
785
+ path: `${path}.legitimateUse`,
786
+ message: 'Say which clause of Section 7 this use relies on, e.g. legitimateUse: "7(a)" for data the person gave voluntarily for this purpose (they can then object), or "7(i)" for employment. Processing without consent needs one of them.',
787
+ since: "0.5"
788
+ });
789
+ }
555
790
  }
556
- for (const [key, table] of Object.entries(config.data ?? {})) {
791
+ for (const [key, table2] of Object.entries(config.data ?? {})) {
557
792
  const path = `data.${key}`;
558
- if (!table.subject) {
793
+ if (!table2.subject) {
559
794
  issues.push({
560
795
  level: "error",
561
796
  code: "missing-subject-column",
@@ -563,7 +798,7 @@ function audit(config) {
563
798
  message: "Name the column that holds the person's id, so their rows can be found."
564
799
  });
565
800
  }
566
- const fields = Object.entries(table.fields ?? {});
801
+ const fields = Object.entries(table2.fields ?? {});
567
802
  if (fields.length === 0) {
568
803
  issues.push({
569
804
  level: "warning",
@@ -575,12 +810,12 @@ function audit(config) {
575
810
  for (const [field, def] of fields) {
576
811
  checkPurposeList(def.purposes, known, used, `${path}.fields.${field}`, issues);
577
812
  }
578
- if (table.legalHold && !isDuration(table.legalHold.keep)) {
813
+ if (table2.legalHold && !isDuration(table2.legalHold.keep)) {
579
814
  issues.push({
580
815
  level: "error",
581
816
  code: "invalid-duration",
582
817
  path: `${path}.legalHold.keep`,
583
- message: `${JSON.stringify(table.legalHold.keep)} is not a duration. Use e.g. "8y".`
818
+ message: `${JSON.stringify(table2.legalHold.keep)} is not a duration. Use e.g. "8y".`
584
819
  });
585
820
  }
586
821
  }
@@ -631,6 +866,19 @@ function audit(config) {
631
866
  }
632
867
  }
633
868
  }
869
+ const verify = config.rights?.verify;
870
+ if (verify !== void 0 && verify !== "required" && verify !== "optional") {
871
+ issues.push({ level: "error", code: "invalid-rights-verify", path: "rights.verify", message: 'Use "required" or "optional".' });
872
+ }
873
+ if (!config.rights?.how?.trim()) {
874
+ issues.push({
875
+ level: "warning",
876
+ code: "rights-how-missing",
877
+ path: "rights.how",
878
+ message: 'Rule 14(1)(a) requires publishing how people make a request. Say it in a sentence, e.g. how: "In the app: Settings \u2192 Privacy, or email privacy@example.in".',
879
+ since: "0.5"
880
+ });
881
+ }
634
882
  const minimum = config.minimumRetention;
635
883
  if (minimum === void 0) {
636
884
  issues.push({
@@ -656,11 +904,13 @@ function audit(config) {
656
904
  }
657
905
  checkSecurity(config, issues);
658
906
  checkErase(config, issues);
907
+ checkTransfers(config, issues);
908
+ checkNotice(config, issues);
659
909
  return issues;
660
910
  }
661
911
  function checkErase(config, issues) {
662
- for (const [key, table] of Object.entries(config.data ?? {})) {
663
- for (const [field, def] of Object.entries(table.fields ?? {})) {
912
+ for (const [key, table2] of Object.entries(config.data ?? {})) {
913
+ for (const [field, def] of Object.entries(table2.fields ?? {})) {
664
914
  const erase = def.erase;
665
915
  if (erase === void 0 || erase === "null" || erase === "redact") continue;
666
916
  if (erase && typeof erase === "object" && "value" in erase) {
@@ -704,8 +954,8 @@ var SECURITY_MEASURES = [
704
954
  ["measures", "(g)", "the technical and organisational measures that make the safeguards work (for example training and access reviews)"]
705
955
  ];
706
956
  function checkSecurity(config, issues) {
707
- for (const [key, table] of Object.entries(config.data ?? {})) {
708
- for (const [field, def] of Object.entries(table.fields ?? {})) {
957
+ for (const [key, table2] of Object.entries(config.data ?? {})) {
958
+ for (const [field, def] of Object.entries(table2.fields ?? {})) {
709
959
  if (!def.protect && isHighRisk(field, def.category)) {
710
960
  issues.push({
711
961
  level: "warning",
@@ -756,26 +1006,494 @@ function checkSecurity(config, issues) {
756
1006
  function hasErrors(issues) {
757
1007
  return issues.some((i) => i.level === "error");
758
1008
  }
1009
+ var COUNTRY = /^[A-Z]{2}$/;
1010
+ function checkTransfers(config, issues) {
1011
+ const badCountry = (value, path) => {
1012
+ if (typeof value === "string" && COUNTRY.test(value)) return false;
1013
+ issues.push({
1014
+ level: "error",
1015
+ code: "invalid-country",
1016
+ path,
1017
+ message: `${JSON.stringify(value)} is not a country code. Use ISO 3166-1 alpha-2 in capitals, e.g. "IN", "US", "SG".`
1018
+ });
1019
+ return true;
1020
+ };
1021
+ const restricted = /* @__PURE__ */ new Set();
1022
+ (config.transfers?.restricted ?? []).forEach((c, i) => {
1023
+ if (!badCountry(c, `transfers.restricted.${i}`)) restricted.add(c);
1024
+ });
1025
+ const keepInIndia = new Set(config.transfers?.keepInIndia ?? []);
1026
+ for (const p of keepInIndia) {
1027
+ if (!config.purposes[p]) {
1028
+ issues.push({ level: "error", code: "unknown-purpose", path: "transfers.keepInIndia", message: `Unknown purpose ${JSON.stringify(p)}.` });
1029
+ }
1030
+ }
1031
+ for (const [name, def] of Object.entries(config.processors ?? {})) {
1032
+ const path = `processors.${name}.countries`;
1033
+ if (def.foreignState) {
1034
+ issues.push({
1035
+ level: "warning",
1036
+ code: "foreign-state-transfer",
1037
+ path: `processors.${name}.foreignState`,
1038
+ message: `Rule 15 lets the Central Government set requirements, by general or special order, for making personal data available to a foreign State or an entity it controls. Check for any order that applies before sharing data with ${name}.`,
1039
+ since: "0.5"
1040
+ });
1041
+ }
1042
+ if (def.countries === void 0 || def.countries.length === 0) {
1043
+ issues.push({
1044
+ level: "warning",
1045
+ code: "processor-countries-missing",
1046
+ path,
1047
+ message: `Say where ${name} handles the data, e.g. countries: ["IN"] or ["IN", "US"]. Section 16 lets the Central Government restrict transfers to countries it notifies, so you need to know.`,
1048
+ since: "0.5"
1049
+ });
1050
+ continue;
1051
+ }
1052
+ const countries = def.countries.filter((c, i) => !badCountry(c, `${path}.${i}`));
1053
+ for (const c of countries.filter((c2) => restricted.has(c2))) {
1054
+ issues.push({
1055
+ level: "error",
1056
+ code: "transfer-restricted",
1057
+ path,
1058
+ message: `${name} handles data in ${c}, which transfers.restricted lists as a country transfers are restricted to under Section 16(1). Stop the transfer or move the processing.`
1059
+ });
1060
+ }
1061
+ const local = def.purposes.filter((p) => keepInIndia.has(p));
1062
+ const abroad = countries.filter((c) => c !== "IN");
1063
+ if (local.length > 0 && abroad.length > 0) {
1064
+ issues.push({
1065
+ level: "error",
1066
+ code: "transfer-outside-india",
1067
+ path,
1068
+ message: `${name} handles data for ${local.join(", ")}, which transfers.keepInIndia says must stay in India, in ${abroad.join(", ")}.`
1069
+ });
1070
+ }
1071
+ }
1072
+ }
1073
+ function checkNotice(config, issues) {
1074
+ const notice = config.notice;
1075
+ if (!notice) return;
1076
+ const links = notice.links ?? {};
1077
+ for (const [key, what] of [
1078
+ ["website", "the link to your website or app (Rule 3(c))"],
1079
+ ["withdraw", "where to withdraw consent, as easily as it was given (Rule 3(c)(i))"],
1080
+ ["rights", "where to exercise rights under the Act (Rule 3(c)(ii))"]
1081
+ ]) {
1082
+ if (typeof links[key] !== "string" || links[key].trim() === "") {
1083
+ issues.push({ level: "error", code: "notice-link-missing", path: `notice.links.${key}`, message: `The notice must give ${what}: a URL, or a short description such as "Settings \u2192 Privacy in the app".` });
1084
+ }
1085
+ }
1086
+ const consentPurposes = Object.entries(config.purposes).filter(([, d]) => d.basis === "consent").map(([p]) => p);
1087
+ const noticeFields = Object.entries(config.data).flatMap(
1088
+ ([key, table2]) => Object.entries(table2.fields ?? {}).filter(([, f]) => f.purposes?.some((p) => consentPurposes.includes(p))).map(([field, f]) => ({ key: `${key}.${field}`, label: f.label }))
1089
+ );
1090
+ for (const p of consentPurposes) {
1091
+ if (!config.purposes[p]?.description?.trim()) {
1092
+ issues.push({
1093
+ level: "error",
1094
+ code: "notice-description-missing",
1095
+ path: `purposes.${p}.description`,
1096
+ message: `The notice must state each purpose and what it provides (Rule 3(b)(ii)), e.g. "Offers and order updates by SMS".`
1097
+ });
1098
+ }
1099
+ }
1100
+ for (const f of noticeFields.filter((f2) => !f2.label)) {
1101
+ issues.push({
1102
+ level: "warning",
1103
+ code: "notice-label-missing",
1104
+ path: `data.${f.key.replace(".", ".fields.")}.label`,
1105
+ message: `The notice lists each item of data (Rule 3(b)(i)). Without a label it shows the field name made readable; set label to what people would call it, e.g. "Mobile number".`
1106
+ });
1107
+ }
1108
+ for (const [language, t] of Object.entries(notice.translations ?? {})) {
1109
+ const path = `notice.translations.${language}`;
1110
+ if (!isNoticeLanguage(language) || language === "en") {
1111
+ issues.push({
1112
+ level: "error",
1113
+ code: "invalid-notice-language",
1114
+ path,
1115
+ message: language === "en" ? "English is built in: remove this translation." : `${JSON.stringify(language)} is not English or a language of the Eighth Schedule. Use codes such as "hi", "ta", "bn".`
1116
+ });
1117
+ continue;
1118
+ }
1119
+ const incomplete = (where, message) => issues.push({ level: "error", code: "notice-translation-incomplete", path: `${path}.${where}`, message });
1120
+ if (!t) continue;
1121
+ for (const p of consentPurposes) {
1122
+ if (!t.purposes?.[p]?.trim()) incomplete(`purposes.${p}`, `Describe purpose ${p} in this language.`);
1123
+ }
1124
+ for (const f of noticeFields) {
1125
+ if (!t.fields?.[f.key]?.trim()) incomplete(`fields.${f.key}`, `Give the label for ${f.key} in this language.`);
1126
+ }
1127
+ for (const key of Object.keys(ENGLISH_WORDING)) {
1128
+ const text = t.wording?.[key];
1129
+ const needs = REQUIRED_PLACEHOLDERS[key];
1130
+ if (typeof text !== "string" || text.trim() === "") incomplete(`wording.${key}`, `Translate this sentence: ${JSON.stringify(ENGLISH_WORDING[key])}.`);
1131
+ else if (needs && !text.includes(needs)) incomplete(`wording.${key}`, `Keep ${needs} in this sentence, so the notice still shows it.`);
1132
+ }
1133
+ }
1134
+ }
759
1135
 
760
- // src/config.ts
761
- var REDACTED = "[erased]";
762
- function defineConfig(config) {
763
- return config;
1136
+ // src/rights.ts
1137
+ var DEFAULT_RESPONSE_WITHIN = "90d";
1138
+ function responseWithin(config, type) {
1139
+ const setting = config.rights?.responseWithin;
1140
+ if (setting === void 0) return DEFAULT_RESPONSE_WITHIN;
1141
+ if (typeof setting === "string") return setting;
1142
+ return setting[type] ?? DEFAULT_RESPONSE_WITHIN;
764
1143
  }
765
- function purposeNames(config) {
766
- return Object.keys(config.purposes);
1144
+ function dueAt(config, type, openedAt) {
1145
+ return new Date(Date.parse(openedAt) + durationMs(responseWithin(config, type))).toISOString();
767
1146
  }
768
- function erasedValue(erase, field) {
769
- if (erase === void 0 || erase === "null") return null;
770
- if (erase === "redact") return REDACTED;
771
- const value = typeof erase.value === "function" ? erase.value(field) : erase.value;
772
- if (value !== null && !["string", "number", "boolean"].includes(typeof value)) {
773
- throw new DpdpError(
774
- "invalid-erase",
775
- `The erase value for ${field.table}.${field.field} must be a string, number, boolean or null; got ${value === void 0 ? "undefined (does the function return?)" : typeof value}`
1147
+ async function buildAccessSummary(input) {
1148
+ const { config, data, subjectId, consents, now } = input;
1149
+ const objections = input.objections ?? [];
1150
+ const legitimateUses = Object.entries(config.purposes).filter(([name, def]) => def.basis === "legitimate-use" && !objections.includes(name)).map(([name]) => name);
1151
+ const applies = /* @__PURE__ */ new Set([...consents, ...legitimateUses]);
1152
+ const tables = [];
1153
+ for (const [key, def] of Object.entries(config.data)) {
1154
+ const fields = Object.entries(def.fields).map(([field, f]) => ({
1155
+ field,
1156
+ category: f.category,
1157
+ purposes: [...f.purposes]
1158
+ }));
1159
+ const rows = await data.read(
1160
+ def.table,
1161
+ def.subject,
1162
+ subjectId,
1163
+ fields.map((f) => f.field)
776
1164
  );
1165
+ if (rows.length > 0) tables.push({ key, table: def.table, fields, rows });
777
1166
  }
778
- return value;
1167
+ const sharedWith = Object.entries(config.processors ?? {}).map(([name, p]) => ({
1168
+ name,
1169
+ ...p.description !== void 0 ? { description: p.description } : {},
1170
+ purposes: p.purposes.filter((purpose) => applies.has(purpose)),
1171
+ ...p.countries?.length ? { countries: [...p.countries] } : {}
1172
+ })).filter((p) => p.purposes.length > 0);
1173
+ return {
1174
+ subjectId,
1175
+ generatedAt: now,
1176
+ data: tables,
1177
+ consents,
1178
+ legitimateUses,
1179
+ ...objections.length > 0 ? { objections: [...objections] } : {},
1180
+ sharedWith
1181
+ };
1182
+ }
1183
+ var REQUEST_LABELS = {
1184
+ access: "request to see your personal data",
1185
+ correction: "request to correct your personal data",
1186
+ erasure: "request to erase your personal data",
1187
+ grievance: "grievance",
1188
+ nomination: "nomination"
1189
+ };
1190
+ var indianDate = (iso) => new Date(iso).toLocaleDateString("en-IN", { day: "numeric", month: "long", year: "numeric", timeZone: "Asia/Kolkata" });
1191
+ function acknowledgement(config, request) {
1192
+ const contact = config.fiduciary.dpo;
1193
+ const text = [
1194
+ `We received your ${REQUEST_LABELS[request.type]} on ${indianDate(request.openedAt)}. Your reference is ${request.id}.`,
1195
+ `We'll respond by ${indianDate(request.dueAt)}.`,
1196
+ ...contact ? [`Questions in the meantime: ${contact}.`] : []
1197
+ ].join(" ");
1198
+ return { reference: request.id, type: request.type, receivedAt: request.openedAt, dueAt: request.dueAt, ...contact ? { contact } : {}, text };
1199
+ }
1200
+ function rightsInfo(config) {
1201
+ const r = config.rights ?? {};
1202
+ return {
1203
+ ...r.how !== void 0 ? { how: r.how } : {},
1204
+ identifiers: [...r.identifiers ?? []],
1205
+ responseWithin: Object.fromEntries(REQUEST_TYPES.map((t) => [t, responseWithin(config, t)])),
1206
+ ...config.fiduciary.dpo ? { contact: config.fiduciary.dpo } : {},
1207
+ ...config.fiduciary.grievanceUrl ? { grievanceUrl: config.fiduciary.grievanceUrl } : {},
1208
+ verify: r.verify ?? "optional"
1209
+ };
1210
+ }
1211
+
1212
+ // src/safeguards.ts
1213
+ function safeguardsReport(config) {
1214
+ const security = config.security ?? {};
1215
+ const report = [];
1216
+ const protectedFields = [];
1217
+ const unprotected = [];
1218
+ for (const [key, table2] of Object.entries(config.data ?? {})) {
1219
+ for (const [field, def] of Object.entries(table2.fields ?? {})) {
1220
+ if (def.protect) protectedFields.push(`${key}.${field}: ${def.protect}`);
1221
+ else if (isHighRisk(field, def.category)) unprotected.push(`${key}.${field}`);
1222
+ }
1223
+ }
1224
+ report.push({
1225
+ clause: "(a)",
1226
+ title: "Encryption, obfuscation, masking or virtual tokens",
1227
+ status: unprotected.length === 0 ? protectedFields.length > 0 ? "declared" : "missing" : protectedFields.length > 0 ? "partly" : "missing",
1228
+ details: [
1229
+ ...protectedFields,
1230
+ ...unprotected.map((f) => `${f}: high-risk and unprotected; encrypt it (dpdp-kit/protect) and set protect`),
1231
+ ...protectedFields.length === 0 && unprotected.length === 0 ? ["No field declares protect. Mark how sensitive fields are stored."] : []
1232
+ ]
1233
+ });
1234
+ const described = (clause, title, value, key, hint) => ({
1235
+ clause,
1236
+ title,
1237
+ status: value ? "declared" : "missing",
1238
+ details: [value ?? `Add security.${key}: ${hint}`]
1239
+ });
1240
+ report.push(described("(b)", "Access control to computer resources", security.accessControl, "accessControl", "how access is controlled, e.g. SSO and least-privilege roles"));
1241
+ report.push({
1242
+ clause: "(c)",
1243
+ title: "Logs, monitoring and review of access",
1244
+ status: "in-code",
1245
+ details: ["Record access with dpdp.access.log() and run dpdp.access.review() daily to find unauthorised access."]
1246
+ });
1247
+ report.push(described("(d)", "Continued processing after a compromise (e.g. backups)", security.backups, "backups", "your backups and how often restores are tested"));
1248
+ const logKeep = security.accessLogRetention ?? DEFAULT_ACCESS_LOG_RETENTION;
1249
+ const logsOk = isDuration(logKeep) && durationMs(logKeep) >= durationMs("1y");
1250
+ const dataOk = config.minimumRetention !== void 0 && isDuration(config.minimumRetention) && durationMs(config.minimumRetention) >= durationMs("1y");
1251
+ report.push({
1252
+ clause: "(e)",
1253
+ title: "Keep logs and personal data for one year",
1254
+ status: logsOk && dataOk ? "declared" : logsOk || dataOk ? "partly" : "missing",
1255
+ details: [
1256
+ logsOk ? `Access log kept ${logKeep}; prune with dpdp.access.prune()` : `security.accessLogRetention must be at least "1y"`,
1257
+ dataOk ? `Personal data kept at least ${config.minimumRetention} (minimumRetention)` : `Set minimumRetention: "1y"`
1258
+ ]
1259
+ });
1260
+ const processors = Object.entries(config.processors ?? {});
1261
+ const withContract = processors.filter(([, p]) => p.contract);
1262
+ report.push({
1263
+ clause: "(f)",
1264
+ title: "Security safeguards in contracts with Data Processors",
1265
+ status: processors.length === 0 || withContract.length === processors.length ? "declared" : withContract.length > 0 ? "partly" : "missing",
1266
+ details: processors.length === 0 ? ["No processors declared."] : processors.map(([name, p]) => p.contract ? `${name}: ${p.contract}` : `${name}: add contract, where the security provision is`)
1267
+ });
1268
+ report.push(described("(g)", "Technical and organisational measures", security.measures, "measures", "e.g. security training and periodic access reviews"));
1269
+ return report;
1270
+ }
1271
+ var MARK = { declared: "\u2714", "in-code": "\u25C6", partly: "\u25D0", missing: "\u2716" };
1272
+ function formatSafeguards(report) {
1273
+ const lines = ["Rule 6(1) of the DPDP Rules: reasonable security safeguards", ""];
1274
+ for (const s of report) {
1275
+ lines.push(`${MARK[s.status]} ${s.clause} ${s.title} [${s.status}]`);
1276
+ for (const d of s.details) lines.push(` ${d}`);
1277
+ }
1278
+ const missing = report.filter((s) => s.status === "missing" || s.status === "partly").length;
1279
+ lines.push("", missing === 0 ? "Every safeguard is recorded or provided." : `${missing} safeguard(s) missing or partly recorded.`);
1280
+ lines.push("This reads your config, not your infrastructure: keep the descriptions true.");
1281
+ return lines.join("\n");
1282
+ }
1283
+
1284
+ // src/evidence.ts
1285
+ var isUnavailable = (v) => typeof v === "object" && v !== null && "unavailable" in v;
1286
+ function describeRetention(retain) {
1287
+ if (typeof retain === "string") return retain === "while-active" ? "while the purpose is active" : `${retain} after collection`;
1288
+ return retain.afterWithdrawal === "0d" ? "until consent is withdrawn" : `${retain.afterWithdrawal} after consent is withdrawn`;
1289
+ }
1290
+ function staticEvidence(config, generatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
1291
+ const report = {
1292
+ generatedAt,
1293
+ fiduciary: { ...config.fiduciary },
1294
+ purposes: Object.entries(config.purposes).map(([purpose, d]) => ({
1295
+ purpose,
1296
+ basis: d.basis,
1297
+ ...d.legitimateUse ? { legitimateUse: d.legitimateUse } : {},
1298
+ ...d.description ? { description: d.description } : {},
1299
+ retain: describeRetention(d.retain)
1300
+ })),
1301
+ data: Object.entries(config.data).map(([key, t]) => ({
1302
+ key,
1303
+ table: t.table,
1304
+ fields: Object.entries(t.fields).map(([field, f]) => ({ field, category: f.category, purposes: [...f.purposes], ...f.protect ? { protect: f.protect } : {} })),
1305
+ ...t.legalHold ? { legalHold: { ...t.legalHold } } : {}
1306
+ })),
1307
+ processors: Object.entries(config.processors ?? {}).map(([name, p]) => ({
1308
+ name,
1309
+ purposes: [...p.purposes],
1310
+ ...p.contract ? { contract: p.contract } : {},
1311
+ ...p.countries ? { countries: [...p.countries] } : {},
1312
+ ...p.foreignState ? { foreignState: true } : {}
1313
+ })),
1314
+ ...config.minimumRetention ? { minimumRetention: config.minimumRetention } : {},
1315
+ audit: audit(config),
1316
+ safeguards: safeguardsReport(config),
1317
+ rights: rightsInfo(config),
1318
+ gaps: []
1319
+ };
1320
+ report.gaps = gapsOf(report);
1321
+ return report;
1322
+ }
1323
+ function requestStats(requests, from, to, now) {
1324
+ const stats = { opened: {}, closed: 0, closedLate: 0, byStatus: {}, overdue: 0 };
1325
+ for (const r of requests) {
1326
+ if (r.openedAt >= from && r.openedAt < to) stats.opened[r.type] = (stats.opened[r.type] ?? 0) + 1;
1327
+ if (r.closedAt && r.closedAt >= from && r.closedAt < to) {
1328
+ stats.closed++;
1329
+ if (r.closedAt > r.dueAt) stats.closedLate++;
1330
+ }
1331
+ stats.byStatus[r.status] = (stats.byStatus[r.status] ?? 0) + 1;
1332
+ if (r.status === "open" && r.dueAt < now) stats.overdue++;
1333
+ }
1334
+ return stats;
1335
+ }
1336
+ function gapsOf(r) {
1337
+ const gaps = [];
1338
+ for (const i of r.audit.filter((i2) => i2.level === "error")) gaps.push(`Audit error at ${i.path}: ${i.message}`);
1339
+ const warnings = r.audit.filter((i) => i.level === "warning");
1340
+ if (warnings.length > 0) gaps.push(`${warnings.length} audit warning(s): ${warnings.map((i) => i.path).join(", ")}`);
1341
+ for (const s of r.safeguards.filter((s2) => s2.status === "missing" || s2.status === "partly")) {
1342
+ gaps.push(`Rule 6(1)${s.clause} ${s.title}: ${s.status === "missing" ? "not recorded" : "partly recorded"}`);
1343
+ }
1344
+ if (r.requests && !isUnavailable(r.requests)) {
1345
+ if (r.requests.overdue > 0) gaps.push(`${r.requests.overdue} rights request(s) open past their due date`);
1346
+ if (r.requests.closedLate > 0) gaps.push(`${r.requests.closedLate} rights request(s) answered late in the period`);
1347
+ }
1348
+ if (r.erasure && !isUnavailable(r.erasure)) {
1349
+ if (r.erasure.late > 0) gaps.push(`${r.erasure.late} erasure task(s) past their due date: is the retention runner running?`);
1350
+ const manual = r.erasure.byStatus.manual ?? 0;
1351
+ if (manual > 0) gaps.push(`${manual} erasure task(s) waiting for a person (manual)`);
1352
+ }
1353
+ if (r.access && !isUnavailable(r.access)) {
1354
+ const n = Object.values(r.access.findings).reduce((a, b) => a + (b ?? 0), 0);
1355
+ if (n > 0) gaps.push(`${n} access review finding(s) in the period`);
1356
+ }
1357
+ if (r.breaches && !isUnavailable(r.breaches)) {
1358
+ for (const b of r.breaches) for (const t of b.todo) gaps.push(`Breach ${b.id}: ${t}`);
1359
+ }
1360
+ return gaps;
1361
+ }
1362
+ var table = (head, rows) => rows.length === 0 ? "_None._" : [`| ${head.join(" | ")} |`, `|${head.map(() => "---").join("|")}|`, ...rows.map((r) => `| ${r.map(cell).join(" | ")} |`)].join("\n");
1363
+ var cell = (v) => v.replace(/\|/g, "\\|").replace(/\n/g, " ");
1364
+ var counts = (o) => Object.entries(o).filter(([, n]) => (n ?? 0) > 0).map(([k, n]) => `${k}: ${n}`).join(", ") || "none";
1365
+ var day = (iso) => iso.slice(0, 10);
1366
+ function formatEvidence(r) {
1367
+ const out = [];
1368
+ const section = (title, body) => out.push(`## ${title}`, "", body, "");
1369
+ const unavailable = (v) => `_Not available: ${v.unavailable}._`;
1370
+ out.push(`# DPDP Act evidence: ${r.fiduciary.name}`, "");
1371
+ out.push(`Generated ${r.generatedAt}${r.period ? `, for ${day(r.period.from)} to ${day(r.period.to)}` : ", from the configuration only"}.`, "");
1372
+ out.push(
1373
+ "> This report shows what the organisation has declared in its dpdp-kit configuration and what dpdp-kit has recorded. It is evidence of practice, not a certificate of compliance, and it can't see systems dpdp-kit isn't connected to.",
1374
+ ""
1375
+ );
1376
+ section("What needs attention", r.gaps.length === 0 ? "Nothing outstanding." : r.gaps.map((g) => `- ${g}`).join("\n"));
1377
+ section(
1378
+ "Data Fiduciary",
1379
+ [`- Name: ${r.fiduciary.name}`, `- Contact (Section 8(9), Rule 9): ${r.fiduciary.dpo ?? "not set"}`, `- Grievances (Section 8(10)): ${r.fiduciary.grievanceUrl ?? "not set"}`].join("\n")
1380
+ );
1381
+ section(
1382
+ "Purposes (Sections 4 to 7)",
1383
+ table(
1384
+ ["Purpose", "Basis", "Description", "Kept"],
1385
+ r.purposes.map((p) => [p.purpose, p.basis === "consent" ? "Consent" : `Legitimate use${p.legitimateUse ? `, Section ${p.legitimateUse}` : ""}`, p.description ?? "", p.retain])
1386
+ )
1387
+ );
1388
+ section(
1389
+ "Personal data held",
1390
+ r.data.map(
1391
+ (t) => `**${t.key}** (\`${t.table}\`)${t.legalHold ? `: kept ${t.legalHold.keep} for ${t.legalHold.reason}, then ${t.legalHold.then === "delete" ? "deleted" : "anonymised"}` : ""}
1392
+
1393
+ ` + table(["Field", "Category", "Purposes", "Protection"], t.fields.map((f) => [f.field, f.category, f.purposes.join(", "), f.protect ?? ""]))
1394
+ ).join("\n\n") + (r.minimumRetention ? `
1395
+
1396
+ Minimum retention (Rule 8(3)): ${r.minimumRetention}.` : "")
1397
+ );
1398
+ section(
1399
+ "Data Processors (Section 8(2), Rule 6(1)(f), Section 16)",
1400
+ table(
1401
+ ["Processor", "Purposes", "Contract", "Countries"],
1402
+ r.processors.map((p) => [p.name, p.purposes.join(", "), p.contract ?? "not recorded", `${p.countries?.join(", ") ?? "not recorded"}${p.foreignState ? " (foreign State)" : ""}`])
1403
+ )
1404
+ );
1405
+ section(
1406
+ "Security safeguards (Rule 6(1))",
1407
+ table(
1408
+ ["Clause", "Safeguard", "Status", "Details"],
1409
+ r.safeguards.map((s) => [s.clause, s.title, s.status, s.details.join("; ")])
1410
+ )
1411
+ );
1412
+ section(
1413
+ "How people exercise their rights (Rule 14)",
1414
+ [
1415
+ `- How to make a request: ${r.rights.how ?? "not published"}`,
1416
+ `- Identifiers asked for: ${r.rights.identifiers.join(", ") || "none listed"}`,
1417
+ `- Answer within: ${Object.entries(r.rights.responseWithin).map(([t, d]) => `${t} ${d}`).join(", ")}`,
1418
+ `- Identity check before acting on a request: ${r.rights.verify}`
1419
+ ].join("\n")
1420
+ );
1421
+ if (r.notices) {
1422
+ section(
1423
+ "Notices shown (Section 5, Rule 3)",
1424
+ isUnavailable(r.notices) ? unavailable(r.notices) : table(["Version", "Language", "Kind", "Purposes", "First shown"], r.notices.map((n) => [n.version, n.language, n.kind, String(n.purposes), n.firstShownAt]))
1425
+ );
1426
+ }
1427
+ if (r.consent) {
1428
+ const c = r.consent;
1429
+ section(
1430
+ "Consent (Section 6)",
1431
+ isUnavailable(c) ? unavailable(c) : [
1432
+ `${c.events} consent event(s) from ${c.people} person(s) in the period: ${counts(c.byAction)}.`,
1433
+ "",
1434
+ table(
1435
+ ["Purpose", "In the period", "Granted now", "Objecting now"],
1436
+ [.../* @__PURE__ */ new Set([...Object.keys(c.byPurpose), ...Object.keys(c.grantedNow), ...Object.keys(c.objectedNow)])].map((p) => [
1437
+ p,
1438
+ counts(c.byPurpose[p] ?? {}),
1439
+ String(c.grantedNow[p] ?? 0),
1440
+ String(c.objectedNow[p] ?? 0)
1441
+ ])
1442
+ )
1443
+ ].join("\n")
1444
+ );
1445
+ }
1446
+ if (r.requests) {
1447
+ const q = r.requests;
1448
+ section(
1449
+ "Rights requests (Sections 11 to 14)",
1450
+ isUnavailable(q) ? unavailable(q) : [
1451
+ `- Opened in the period: ${counts(q.opened)}`,
1452
+ `- Answered in the period: ${q.closed}, of which late: ${q.closedLate}`,
1453
+ `- All requests now: ${counts(q.byStatus)}`,
1454
+ `- Open past their due date now: ${q.overdue}`
1455
+ ].join("\n")
1456
+ );
1457
+ }
1458
+ if (r.erasure) {
1459
+ const e = r.erasure;
1460
+ section("Erasure (Section 8(7), Rule 8)", isUnavailable(e) ? unavailable(e) : `Tasks by status: ${counts(e.byStatus)}. Past their due date: ${e.late}.`);
1461
+ }
1462
+ if (r.access) {
1463
+ const a = r.access;
1464
+ section(
1465
+ "Access review (Rule 6(1)(c))",
1466
+ isUnavailable(a) ? unavailable(a) : [
1467
+ `${a.scanned} access(es) reviewed. Findings: ${counts(a.findings)}.`,
1468
+ ...a.examples.length ? ["", table(["Kind", "Who", "Whose data", "Finding"], a.examples.map((f) => [f.kind, f.actor, f.subjectId ?? "", f.message]))] : []
1469
+ ].join("\n")
1470
+ );
1471
+ }
1472
+ if (r.breaches) {
1473
+ const b = r.breaches;
1474
+ section(
1475
+ "Breaches (Section 8(6), Rule 7)",
1476
+ isUnavailable(b) ? unavailable(b) : table(
1477
+ ["Breach", "Aware", "Status", "Board told", "Detailed report", "People told"],
1478
+ b.map((x) => [
1479
+ x.id,
1480
+ x.awareAt,
1481
+ x.status,
1482
+ x.boardNotified ? "yes" : "no",
1483
+ x.report.sent ? "sent" : `${x.report.overdue ? "overdue" : "due"} ${x.report.dueAt}`,
1484
+ `${x.people.sent} of ${x.people.total}`
1485
+ ])
1486
+ )
1487
+ );
1488
+ }
1489
+ const errors = r.audit.filter((i) => i.level === "error");
1490
+ const warnings = r.audit.filter((i) => i.level === "warning");
1491
+ section(
1492
+ "Configuration audit",
1493
+ errors.length + warnings.length === 0 ? "No problems found." : table(["Level", "Where", "Problem"], [...errors, ...warnings].map((i) => [i.level, i.path, i.message]))
1494
+ );
1495
+ return `${out.join("\n").trimEnd()}
1496
+ `;
779
1497
  }
780
1498
 
781
1499
  // src/schema-check.ts
@@ -787,10 +1505,10 @@ function parseNotPersonal(entries) {
787
1505
  for (const entry of entries ?? []) {
788
1506
  const dot = entry.lastIndexOf(".");
789
1507
  if (dot <= 0) continue;
790
- const table = entry.slice(0, dot);
1508
+ const table2 = entry.slice(0, dot);
791
1509
  const column = entry.slice(dot + 1);
792
- if (column === "*") tables.add(table);
793
- else columns.add(`${table}.${column}`);
1510
+ if (column === "*") tables.add(table2);
1511
+ else columns.add(`${table2}.${column}`);
794
1512
  }
795
1513
  return { columns, tables };
796
1514
  }
@@ -826,12 +1544,12 @@ function checkEraseAgainstColumn(erase, column, path, where, issues) {
826
1544
  function checkSchema(config, schema) {
827
1545
  const issues = [];
828
1546
  const byName = /* @__PURE__ */ new Map();
829
- for (const table of schema.tables) if (!byName.has(table.name)) byName.set(table.name, table);
830
- for (const table of schema.tables) if (table.key && !byName.has(table.key)) byName.set(table.key, table);
1547
+ for (const table2 of schema.tables) if (!byName.has(table2.name)) byName.set(table2.name, table2);
1548
+ for (const table2 of schema.tables) if (table2.key && !byName.has(table2.key)) byName.set(table2.key, table2);
831
1549
  const mapped = /* @__PURE__ */ new Map();
832
1550
  for (const [key, def] of Object.entries(config.data ?? {})) {
833
- const table = byName.get(def.table);
834
- if (!table) {
1551
+ const table2 = byName.get(def.table);
1552
+ if (!table2) {
835
1553
  issues.push({
836
1554
  level: "error",
837
1555
  code: "unknown-table",
@@ -840,40 +1558,40 @@ function checkSchema(config, schema) {
840
1558
  });
841
1559
  continue;
842
1560
  }
843
- const list = mapped.get(table.name) ?? [];
844
- const subject = table.columns.find((c) => matches(c, def.subject));
1561
+ const list = mapped.get(table2.name) ?? [];
1562
+ const subject = table2.columns.find((c) => matches(c, def.subject));
845
1563
  if (subject) list.push(subject);
846
1564
  else {
847
1565
  issues.push({
848
1566
  level: "error",
849
1567
  code: "unknown-column",
850
1568
  path: `data.${key}.subject`,
851
- message: `Column "${def.subject}" isn't in table "${table.name}". The subject column must exist to find a person's rows.`
1569
+ message: `Column "${def.subject}" isn't in table "${table2.name}". The subject column must exist to find a person's rows.`
852
1570
  });
853
1571
  }
854
1572
  for (const [field, fieldDef] of Object.entries(def.fields ?? {})) {
855
- const column = table.columns.find((c) => matches(c, field));
1573
+ const column = table2.columns.find((c) => matches(c, field));
856
1574
  if (column) {
857
1575
  list.push(column);
858
- checkEraseAgainstColumn(fieldDef.erase, column, `data.${key}.fields.${field}.erase`, `${table.name}.${column.name}`, issues);
1576
+ checkEraseAgainstColumn(fieldDef.erase, column, `data.${key}.fields.${field}.erase`, `${table2.name}.${column.name}`, issues);
859
1577
  } else {
860
1578
  issues.push({
861
1579
  level: "error",
862
1580
  code: "unknown-column",
863
1581
  path: `data.${key}.fields.${field}`,
864
- message: `Column "${field}" isn't in table "${table.name}". Fix the name, or remove it if the column was dropped.`
1582
+ message: `Column "${field}" isn't in table "${table2.name}". Fix the name, or remove it if the column was dropped.`
865
1583
  });
866
1584
  }
867
1585
  }
868
- mapped.set(table.name, list);
1586
+ mapped.set(table2.name, list);
869
1587
  }
870
1588
  const ignore = parseNotPersonal(config.notPersonal);
871
1589
  for (const entry of config.notPersonal ?? []) {
872
1590
  const dot = entry.lastIndexOf(".");
873
1591
  const tableName = entry.slice(0, Math.max(dot, 0));
874
1592
  const columnName = entry.slice(dot + 1);
875
- const table = byName.get(tableName);
876
- const exists = table && (columnName === "*" || table.columns.some((c) => matches(c, columnName)));
1593
+ const table2 = byName.get(tableName);
1594
+ const exists = table2 && (columnName === "*" || table2.columns.some((c) => matches(c, columnName)));
877
1595
  if (!exists) {
878
1596
  issues.push({
879
1597
  level: "warning",
@@ -883,11 +1601,11 @@ function checkSchema(config, schema) {
883
1601
  });
884
1602
  }
885
1603
  }
886
- for (const table of new Set(byName.values())) {
887
- const tableNames = table.key ? [table.name, table.key] : [table.name];
888
- if (table.name.startsWith(OWN_TABLE_PREFIX) || tableNames.some((t) => ignore.tables.has(t))) continue;
889
- const known = mapped.get(table.name) ?? [];
890
- for (const column of table.columns) {
1604
+ for (const table2 of new Set(byName.values())) {
1605
+ const tableNames = table2.key ? [table2.name, table2.key] : [table2.name];
1606
+ if (table2.name.startsWith(OWN_TABLE_PREFIX) || tableNames.some((t) => ignore.tables.has(t))) continue;
1607
+ const known = mapped.get(table2.name) ?? [];
1608
+ for (const column of table2.columns) {
891
1609
  if (known.includes(column)) continue;
892
1610
  const columnNames = column.key ? [column.name, column.key] : [column.name];
893
1611
  if (tableNames.some((t) => columnNames.some((c) => ignore.columns.has(`${t}.${c}`)))) continue;
@@ -896,8 +1614,8 @@ function checkSchema(config, schema) {
896
1614
  issues.push({
897
1615
  level: guess.confidence === "strong" ? "error" : "warning",
898
1616
  code: "unmapped-personal-column",
899
- path: `schema.${table.name}.${column.name}`,
900
- message: `Looks like personal data (${guess.category}, matched "${guess.matched}") but isn't in the data map. Add it under \`data\` with the purposes it's held for, or add "${table.name}.${column.name}" to \`notPersonal\`.`
1617
+ path: `schema.${table2.name}.${column.name}`,
1618
+ message: `Looks like personal data (${guess.category}, matched "${guess.matched}") but isn't in the data map. Add it under \`data\` with the purposes it's held for, or add "${table2.name}.${column.name}" to \`notPersonal\`.`
901
1619
  });
902
1620
  }
903
1621
  }
@@ -950,102 +1668,52 @@ function checkHeldReferences(config, byName) {
950
1668
  return issues;
951
1669
  }
952
1670
 
953
- // src/safeguards.ts
954
- function safeguardsReport(config) {
955
- const security = config.security ?? {};
956
- const report = [];
957
- const protectedFields = [];
958
- const unprotected = [];
959
- for (const [key, table] of Object.entries(config.data ?? {})) {
960
- for (const [field, def] of Object.entries(table.fields ?? {})) {
961
- if (def.protect) protectedFields.push(`${key}.${field}: ${def.protect}`);
962
- else if (isHighRisk(field, def.category)) unprotected.push(`${key}.${field}`);
963
- }
964
- }
965
- report.push({
966
- clause: "(a)",
967
- title: "Encryption, obfuscation, masking or virtual tokens",
968
- status: unprotected.length === 0 ? protectedFields.length > 0 ? "declared" : "missing" : protectedFields.length > 0 ? "partly" : "missing",
969
- details: [
970
- ...protectedFields,
971
- ...unprotected.map((f) => `${f}: high-risk and unprotected; encrypt it (dpdp-kit/protect) and set protect`),
972
- ...protectedFields.length === 0 && unprotected.length === 0 ? ["No field declares protect. Mark how sensitive fields are stored."] : []
973
- ]
974
- });
975
- const described = (clause, title, value, key, hint) => ({
976
- clause,
977
- title,
978
- status: value ? "declared" : "missing",
979
- details: [value ?? `Add security.${key}: ${hint}`]
980
- });
981
- report.push(described("(b)", "Access control to computer resources", security.accessControl, "accessControl", "how access is controlled, e.g. SSO and least-privilege roles"));
982
- report.push({
983
- clause: "(c)",
984
- title: "Logs, monitoring and review of access",
985
- status: "in-code",
986
- details: ["Record access with dpdp.access.log() and run dpdp.access.review() daily to find unauthorised access."]
987
- });
988
- report.push(described("(d)", "Continued processing after a compromise (e.g. backups)", security.backups, "backups", "your backups and how often restores are tested"));
989
- const logKeep = security.accessLogRetention ?? DEFAULT_ACCESS_LOG_RETENTION;
990
- const logsOk = isDuration(logKeep) && durationMs(logKeep) >= durationMs("1y");
991
- const dataOk = config.minimumRetention !== void 0 && isDuration(config.minimumRetention) && durationMs(config.minimumRetention) >= durationMs("1y");
992
- report.push({
993
- clause: "(e)",
994
- title: "Keep logs and personal data for one year",
995
- status: logsOk && dataOk ? "declared" : logsOk || dataOk ? "partly" : "missing",
996
- details: [
997
- logsOk ? `Access log kept ${logKeep}; prune with dpdp.access.prune()` : `security.accessLogRetention must be at least "1y"`,
998
- dataOk ? `Personal data kept at least ${config.minimumRetention} (minimumRetention)` : `Set minimumRetention: "1y"`
999
- ]
1000
- });
1001
- const processors = Object.entries(config.processors ?? {});
1002
- const withContract = processors.filter(([, p]) => p.contract);
1003
- report.push({
1004
- clause: "(f)",
1005
- title: "Security safeguards in contracts with Data Processors",
1006
- status: processors.length === 0 || withContract.length === processors.length ? "declared" : withContract.length > 0 ? "partly" : "missing",
1007
- details: processors.length === 0 ? ["No processors declared."] : processors.map(([name, p]) => p.contract ? `${name}: ${p.contract}` : `${name}: add contract, where the security provision is`)
1008
- });
1009
- report.push(described("(g)", "Technical and organisational measures", security.measures, "measures", "e.g. security training and periodic access reviews"));
1010
- return report;
1011
- }
1012
- var MARK = { declared: "\u2714", "in-code": "\u25C6", partly: "\u25D0", missing: "\u2716" };
1013
- function formatSafeguards(report) {
1014
- const lines = ["Rule 6(1) of the DPDP Rules: reasonable security safeguards", ""];
1015
- for (const s of report) {
1016
- lines.push(`${MARK[s.status]} ${s.clause} ${s.title} [${s.status}]`);
1017
- for (const d of s.details) lines.push(` ${d}`);
1018
- }
1019
- const missing = report.filter((s) => s.status === "missing" || s.status === "partly").length;
1020
- lines.push("", missing === 0 ? "Every safeguard is recorded or provided." : `${missing} safeguard(s) missing or partly recorded.`);
1021
- lines.push("This reads your config, not your infrastructure: keep the descriptions true.");
1022
- return lines.join("\n");
1023
- }
1024
-
1025
1671
  export {
1026
1672
  isDuration,
1027
1673
  durationMs,
1028
1674
  maxDuration,
1029
- REQUEST_TYPES,
1030
1675
  isDpdpStore,
1031
1676
  memoryStore,
1032
1677
  grantedPurposes,
1678
+ objectedPurposes,
1033
1679
  isAccessLogStore,
1034
1680
  accessId,
1035
1681
  DEFAULT_ACCESS_LOG_RETENTION,
1036
1682
  resolveFields,
1037
1683
  fieldsOutsidePurpose,
1038
1684
  reviewAccess,
1685
+ LEGITIMATE_USES,
1686
+ REDACTED,
1687
+ defineConfig,
1688
+ purposeNames,
1689
+ erasedValue,
1690
+ NOTICE_LANGUAGES,
1691
+ isNoticeLanguage,
1692
+ canonicalJson,
1693
+ sha256,
1694
+ NOTICE_KINDS,
1695
+ ENGLISH_WORDING,
1696
+ isNoticeStore,
1697
+ noticeLanguages,
1698
+ buildNotice,
1699
+ sameNotice,
1039
1700
  tokenize,
1040
1701
  guessPersonal,
1041
1702
  audit,
1042
1703
  isHighRisk,
1043
1704
  hasErrors,
1044
- REDACTED,
1045
- defineConfig,
1046
- purposeNames,
1047
- erasedValue,
1048
- checkSchema,
1705
+ DEFAULT_RESPONSE_WITHIN,
1706
+ dueAt,
1707
+ buildAccessSummary,
1708
+ acknowledgement,
1709
+ rightsInfo,
1049
1710
  safeguardsReport,
1050
- formatSafeguards
1711
+ formatSafeguards,
1712
+ isUnavailable,
1713
+ describeRetention,
1714
+ staticEvidence,
1715
+ requestStats,
1716
+ gapsOf,
1717
+ formatEvidence,
1718
+ checkSchema
1051
1719
  };