dpdp-kit 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/README.md +240 -17
- package/dist/access.d.ts +111 -0
- package/dist/audit.d.ts +3 -1
- package/dist/breach.d.ts +170 -0
- package/dist/chunk-2ELTZSW3.js +94 -0
- package/dist/chunk-5TVA2TKG.js +37 -0
- package/dist/chunk-HXVP446N.js +1051 -0
- package/dist/chunk-KLMR7S7I.js +438 -0
- package/dist/cli.js +53 -17
- package/dist/config.d.ts +69 -0
- package/dist/data-access.d.ts +6 -2
- package/dist/ddl.d.ts +10 -0
- package/dist/dpdp.d.ts +210 -0
- package/dist/drizzle.d.ts +403 -11
- package/dist/drizzle.js +209 -56
- package/dist/errors.d.ts +1 -1
- package/dist/express.d.ts +17 -1
- package/dist/express.js +10 -2
- package/dist/fastify.d.ts +41 -0
- package/dist/fastify.js +25 -0
- package/dist/guard.d.ts +19 -0
- package/dist/hono.d.ts +16 -1
- package/dist/hono.js +11 -2
- package/dist/index.d.ts +7 -4
- package/dist/index.js +420 -100
- package/dist/mongodb.d.ts +87 -0
- package/dist/mongodb.js +344 -0
- package/dist/nestjs.d.ts +65 -0
- package/dist/nestjs.js +41 -0
- package/dist/postgres.d.ts +45 -0
- package/dist/postgres.js +27 -0
- package/dist/prisma.d.ts +43 -0
- package/dist/prisma.js +281 -0
- package/dist/protect.d.ts +74 -0
- package/dist/protect.js +114 -0
- package/dist/retention.d.ts +1 -1
- package/dist/run-audit.d.ts +13 -1
- package/dist/safeguards.d.ts +23 -0
- package/dist/schedule.d.ts +37 -0
- package/dist/schedule.js +66 -0
- package/dist/schema-check.d.ts +25 -8
- package/dist/store.d.ts +11 -1
- package/package.json +58 -5
- package/dist/chunk-FGZAH2NF.js +0 -16
- package/dist/chunk-KVTUMHXO.js +0 -491
|
@@ -0,0 +1,1051 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DpdpError,
|
|
3
|
+
SeqConflictError
|
|
4
|
+
} from "./chunk-67Q5GFD6.js";
|
|
5
|
+
|
|
6
|
+
// src/duration.ts
|
|
7
|
+
var PATTERN = /^(\d+)(h|d|y)$/;
|
|
8
|
+
var HOUR_MS = 60 * 60 * 1e3;
|
|
9
|
+
var UNIT_MS = { h: HOUR_MS, d: 24 * HOUR_MS, y: 365 * 24 * HOUR_MS };
|
|
10
|
+
function isDuration(value) {
|
|
11
|
+
return typeof value === "string" && PATTERN.test(value);
|
|
12
|
+
}
|
|
13
|
+
function durationMs(value) {
|
|
14
|
+
const match = PATTERN.exec(value);
|
|
15
|
+
if (!match) throw new TypeError(`Not a duration: ${JSON.stringify(value)} (use e.g. "48h", "30d", "1y")`);
|
|
16
|
+
const [, amount, unit] = match;
|
|
17
|
+
return Number(amount) * UNIT_MS[unit];
|
|
18
|
+
}
|
|
19
|
+
function maxDuration(a, b) {
|
|
20
|
+
return durationMs(b) > durationMs(a) ? b : a;
|
|
21
|
+
}
|
|
22
|
+
|
|
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
|
+
// src/store.ts
|
|
34
|
+
function isDpdpStore(store) {
|
|
35
|
+
const s = store;
|
|
36
|
+
return typeof s.insertRequest === "function" && typeof s.insertTasks === "function";
|
|
37
|
+
}
|
|
38
|
+
function memoryStore() {
|
|
39
|
+
const all = /* @__PURE__ */ new Map();
|
|
40
|
+
const requests = /* @__PURE__ */ new Map();
|
|
41
|
+
const tasks = /* @__PURE__ */ new Map();
|
|
42
|
+
const accessLog = [];
|
|
43
|
+
const breaches = /* @__PURE__ */ new Map();
|
|
44
|
+
const notices = /* @__PURE__ */ new Map();
|
|
45
|
+
const noticeKey = (breachId, subjectId) => `${breachId}\0${subjectId}`;
|
|
46
|
+
const noticesOf = (breachId) => [...notices.values()].filter((n) => n.breachId === breachId);
|
|
47
|
+
const byDue = (a, b) => a.dueAt < b.dueAt ? -1 : a.dueAt > b.dueAt ? 1 : 0;
|
|
48
|
+
return {
|
|
49
|
+
all,
|
|
50
|
+
requests,
|
|
51
|
+
tasks,
|
|
52
|
+
accessLog,
|
|
53
|
+
breaches,
|
|
54
|
+
notices,
|
|
55
|
+
async insertBreach(breach) {
|
|
56
|
+
breaches.set(breach.id, structuredClone(breach));
|
|
57
|
+
},
|
|
58
|
+
async getBreach(id) {
|
|
59
|
+
const b = breaches.get(id);
|
|
60
|
+
return b && structuredClone(b);
|
|
61
|
+
},
|
|
62
|
+
async updateBreach(breach) {
|
|
63
|
+
const stored = breaches.get(breach.id);
|
|
64
|
+
if (!stored || stored.history.length !== breach.history.length - 1) return false;
|
|
65
|
+
breaches.set(breach.id, structuredClone(breach));
|
|
66
|
+
return true;
|
|
67
|
+
},
|
|
68
|
+
async listBreaches(filter) {
|
|
69
|
+
return [...breaches.values()].filter((b) => !filter.status || b.status === filter.status).sort((a, b) => a.awareAt < b.awareAt ? 1 : a.awareAt > b.awareAt ? -1 : 0).map((b) => structuredClone(b));
|
|
70
|
+
},
|
|
71
|
+
async addNotices(list) {
|
|
72
|
+
let added = 0;
|
|
73
|
+
for (const n of list) {
|
|
74
|
+
const key = noticeKey(n.breachId, n.subjectId);
|
|
75
|
+
if (notices.has(key)) continue;
|
|
76
|
+
notices.set(key, structuredClone(n));
|
|
77
|
+
added++;
|
|
78
|
+
}
|
|
79
|
+
return added;
|
|
80
|
+
},
|
|
81
|
+
async markNotices(breachId, subjectIds, sentAt, channel) {
|
|
82
|
+
let changed = 0;
|
|
83
|
+
for (const subjectId of subjectIds) {
|
|
84
|
+
const n = notices.get(noticeKey(breachId, subjectId));
|
|
85
|
+
if (!n || n.status === "sent") continue;
|
|
86
|
+
notices.set(noticeKey(breachId, subjectId), { ...n, status: "sent", sentAt, ...channel !== void 0 ? { channel } : {} });
|
|
87
|
+
changed++;
|
|
88
|
+
}
|
|
89
|
+
return changed;
|
|
90
|
+
},
|
|
91
|
+
async listNotices(breachId, filter) {
|
|
92
|
+
const list = noticesOf(breachId).filter((n) => !filter.status || n.status === filter.status).sort((a, b) => a.addedAt < b.addedAt ? -1 : a.addedAt > b.addedAt ? 1 : 0).map((n) => structuredClone(n));
|
|
93
|
+
return filter.limit === void 0 ? list : list.slice(0, filter.limit);
|
|
94
|
+
},
|
|
95
|
+
async countNotices(breachId) {
|
|
96
|
+
const list = noticesOf(breachId);
|
|
97
|
+
const sentTimes = list.flatMap((n) => n.sentAt ? [n.sentAt] : []).sort();
|
|
98
|
+
return {
|
|
99
|
+
total: list.length,
|
|
100
|
+
sent: sentTimes.length,
|
|
101
|
+
...sentTimes.length ? { firstSentAt: sentTimes[0], lastSentAt: sentTimes[sentTimes.length - 1] } : {}
|
|
102
|
+
};
|
|
103
|
+
},
|
|
104
|
+
async insertAccess(entries) {
|
|
105
|
+
for (const e of entries) accessLog.push(structuredClone(e));
|
|
106
|
+
},
|
|
107
|
+
async accessSubjects(filter) {
|
|
108
|
+
return [...new Set((await this.listAccess(filter)).map((e) => e.subjectId))];
|
|
109
|
+
},
|
|
110
|
+
async listAccess(filter) {
|
|
111
|
+
const list = accessLog.filter(
|
|
112
|
+
(e) => (!filter.subjectId || e.subjectId === filter.subjectId) && (!filter.actor || e.actor === filter.actor) && (!filter.purpose || e.purpose === filter.purpose) && (!filter.from || e.at >= filter.from) && (!filter.to || e.at < filter.to)
|
|
113
|
+
).sort((a, b) => a.at < b.at ? -1 : a.at > b.at ? 1 : 0).map((e) => structuredClone(e));
|
|
114
|
+
return filter.limit === void 0 ? list : list.slice(0, filter.limit);
|
|
115
|
+
},
|
|
116
|
+
async pruneAccess(before) {
|
|
117
|
+
const keep = accessLog.filter((e) => e.at >= before);
|
|
118
|
+
const deleted = accessLog.length - keep.length;
|
|
119
|
+
accessLog.splice(0, accessLog.length, ...keep);
|
|
120
|
+
return deleted;
|
|
121
|
+
},
|
|
122
|
+
async insertRequest(request) {
|
|
123
|
+
requests.set(request.id, structuredClone(request));
|
|
124
|
+
},
|
|
125
|
+
async getRequest(id) {
|
|
126
|
+
const r = requests.get(id);
|
|
127
|
+
return r && structuredClone(r);
|
|
128
|
+
},
|
|
129
|
+
async updateRequest(request) {
|
|
130
|
+
requests.set(request.id, structuredClone(request));
|
|
131
|
+
},
|
|
132
|
+
async listRequests(filter) {
|
|
133
|
+
return [...requests.values()].filter((r) => (!filter.subjectId || r.subjectId === filter.subjectId) && (!filter.status || r.status === filter.status)).sort((a, b) => a.openedAt < b.openedAt ? -1 : 1).map((r) => structuredClone(r));
|
|
134
|
+
},
|
|
135
|
+
async insertTasks(list) {
|
|
136
|
+
for (const t of list) tasks.set(t.id, structuredClone(t));
|
|
137
|
+
},
|
|
138
|
+
async dueTasks({ limit, ...when }) {
|
|
139
|
+
return [...tasks.values()].filter((t) => isRunnable(t, when)).sort(byDue).slice(0, limit).map((t) => structuredClone(t));
|
|
140
|
+
},
|
|
141
|
+
async claimTask({ id, ...when }) {
|
|
142
|
+
const t = tasks.get(id);
|
|
143
|
+
if (!t || !isRunnable(t, when)) return false;
|
|
144
|
+
tasks.set(id, { ...t, status: "running", claimedAt: when.now });
|
|
145
|
+
return true;
|
|
146
|
+
},
|
|
147
|
+
async updateTask(task) {
|
|
148
|
+
tasks.set(task.id, structuredClone(task));
|
|
149
|
+
},
|
|
150
|
+
async getTask(id) {
|
|
151
|
+
const t = tasks.get(id);
|
|
152
|
+
return t && structuredClone(t);
|
|
153
|
+
},
|
|
154
|
+
async listTasks(filter) {
|
|
155
|
+
return [...tasks.values()].filter((t) => (!filter.subjectId || t.subjectId === filter.subjectId) && (!filter.status || t.status === filter.status)).sort(byDue).map((t) => structuredClone(t));
|
|
156
|
+
},
|
|
157
|
+
async lastEvent(subjectId) {
|
|
158
|
+
const list = all.get(subjectId);
|
|
159
|
+
return list?.[list.length - 1];
|
|
160
|
+
},
|
|
161
|
+
async insert(event) {
|
|
162
|
+
const list = all.get(event.subjectId) ?? [];
|
|
163
|
+
if (list.some((e) => e.seq === event.seq)) throw new SeqConflictError(event.subjectId, event.seq);
|
|
164
|
+
list.push(structuredClone(event));
|
|
165
|
+
list.sort((a, b) => a.seq - b.seq);
|
|
166
|
+
all.set(event.subjectId, list);
|
|
167
|
+
},
|
|
168
|
+
async events(subjectId) {
|
|
169
|
+
return structuredClone(all.get(subjectId) ?? []);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
function grantedPurposes(events, until) {
|
|
174
|
+
const granted = /* @__PURE__ */ new Set();
|
|
175
|
+
for (const e of events) {
|
|
176
|
+
if (until !== void 0 && e.at > until) break;
|
|
177
|
+
for (const p of e.purposes) {
|
|
178
|
+
if (e.action === "grant") granted.add(p);
|
|
179
|
+
else granted.delete(p);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return granted;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// src/access.ts
|
|
186
|
+
import { randomBytes } from "crypto";
|
|
187
|
+
function isAccessLogStore(store) {
|
|
188
|
+
const s = store;
|
|
189
|
+
return typeof s.insertAccess === "function" && typeof s.listAccess === "function" && typeof s.pruneAccess === "function";
|
|
190
|
+
}
|
|
191
|
+
var sequence = 0;
|
|
192
|
+
function accessId(at) {
|
|
193
|
+
sequence = (sequence + 1) % 36 ** 4;
|
|
194
|
+
return `${Date.parse(at).toString(36).padStart(9, "0")}-${sequence.toString(36).padStart(4, "0")}-${randomBytes(6).toString("hex")}`;
|
|
195
|
+
}
|
|
196
|
+
var DEFAULT_ACCESS_LOG_RETENTION = "1y";
|
|
197
|
+
function resolveFields(config, keys) {
|
|
198
|
+
const fields = /* @__PURE__ */ new Set();
|
|
199
|
+
const unknown = [];
|
|
200
|
+
for (const key of keys) {
|
|
201
|
+
const [table, field, ...extra] = key.split(".");
|
|
202
|
+
const def = table ? config.data[table] : void 0;
|
|
203
|
+
if (!def || extra.length > 0) {
|
|
204
|
+
unknown.push(key);
|
|
205
|
+
} else if (field === void 0 || field === "*") {
|
|
206
|
+
for (const f of Object.keys(def.fields)) fields.add(`${table}.${f}`);
|
|
207
|
+
} else if (def.fields[field]) {
|
|
208
|
+
fields.add(key);
|
|
209
|
+
} else {
|
|
210
|
+
unknown.push(key);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return { fields: [...fields], unknown };
|
|
214
|
+
}
|
|
215
|
+
function fieldsOutsidePurpose(config, fields, purpose) {
|
|
216
|
+
return fields.filter((key) => {
|
|
217
|
+
const [table, field] = key.split(".");
|
|
218
|
+
const def = config.data[table]?.fields[field];
|
|
219
|
+
return !def || !def.purposes.includes(purpose);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
async function eachLimited(items, limit, fn) {
|
|
223
|
+
let next = 0;
|
|
224
|
+
const worker = async () => {
|
|
225
|
+
while (next < items.length) await fn(items[next++]);
|
|
226
|
+
};
|
|
227
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
228
|
+
}
|
|
229
|
+
async function reviewAccess(input) {
|
|
230
|
+
const { config, entries } = input;
|
|
231
|
+
const findings = [];
|
|
232
|
+
for (const e of entries) {
|
|
233
|
+
if (e.outOfPurpose && e.outOfPurpose.length > 0) {
|
|
234
|
+
findings.push({
|
|
235
|
+
kind: "out-of-purpose",
|
|
236
|
+
actor: e.actor,
|
|
237
|
+
subjectId: e.subjectId,
|
|
238
|
+
purpose: e.purpose,
|
|
239
|
+
entries: [e.id],
|
|
240
|
+
message: `${e.actor} accessed ${e.outOfPurpose.join(", ")} for "${e.purpose}", which those fields aren't held for.`
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const consentPurposes = new Set(Object.keys(config.purposes).filter((p) => config.purposes[p]?.basis === "consent"));
|
|
245
|
+
const needConsent = entries.filter((e) => consentPurposes.has(e.purpose));
|
|
246
|
+
const histories = /* @__PURE__ */ new Map();
|
|
247
|
+
await eachLimited([...new Set(needConsent.map((e) => e.subjectId))], 16, async (subjectId) => {
|
|
248
|
+
histories.set(subjectId, await input.history(subjectId));
|
|
249
|
+
});
|
|
250
|
+
for (const e of needConsent) {
|
|
251
|
+
if (!grantedPurposes(histories.get(e.subjectId) ?? [], e.at).has(e.purpose)) {
|
|
252
|
+
findings.push({
|
|
253
|
+
kind: "no-consent",
|
|
254
|
+
actor: e.actor,
|
|
255
|
+
subjectId: e.subjectId,
|
|
256
|
+
purpose: e.purpose,
|
|
257
|
+
entries: [e.id],
|
|
258
|
+
message: `${e.actor} accessed data for "${e.purpose}" when the person hadn't consented to it.`
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const windowMs = durationMs(input.window);
|
|
263
|
+
const ignored = new Set(input.ignoreActors ?? []);
|
|
264
|
+
const byActor = /* @__PURE__ */ new Map();
|
|
265
|
+
for (const e of entries) {
|
|
266
|
+
if (ignored.has(e.actor)) continue;
|
|
267
|
+
const list = byActor.get(e.actor);
|
|
268
|
+
if (list) list.push(e);
|
|
269
|
+
else byActor.set(e.actor, [e]);
|
|
270
|
+
}
|
|
271
|
+
for (const [actor, list] of byActor) {
|
|
272
|
+
list.sort((a, b) => a.at < b.at ? -1 : a.at > b.at ? 1 : 0);
|
|
273
|
+
const counts = /* @__PURE__ */ new Map();
|
|
274
|
+
let start = 0;
|
|
275
|
+
let peak = { subjects: 0, from: 0, to: 0 };
|
|
276
|
+
for (let end = 0; end < list.length; end++) {
|
|
277
|
+
const e = list[end];
|
|
278
|
+
counts.set(e.subjectId, (counts.get(e.subjectId) ?? 0) + 1);
|
|
279
|
+
while (Date.parse(e.at) - Date.parse(list[start].at) > windowMs) {
|
|
280
|
+
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);
|
|
284
|
+
start++;
|
|
285
|
+
}
|
|
286
|
+
if (counts.size > peak.subjects) peak = { subjects: counts.size, from: start, to: end };
|
|
287
|
+
}
|
|
288
|
+
if (peak.subjects > input.maxSubjects) {
|
|
289
|
+
findings.push({
|
|
290
|
+
kind: "bulk-access",
|
|
291
|
+
actor,
|
|
292
|
+
subjects: peak.subjects,
|
|
293
|
+
entries: list.slice(peak.from, peak.to + 1).map((e) => e.id),
|
|
294
|
+
message: `${actor} accessed the data of ${peak.subjects} people within ${input.window} (more than ${input.maxSubjects}).`
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return { from: input.from, to: input.to, scanned: entries.length, findings };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// src/personal.ts
|
|
302
|
+
var rule = (spec, category, confidence = "strong") => ({
|
|
303
|
+
tokens: spec.split(" "),
|
|
304
|
+
category,
|
|
305
|
+
confidence
|
|
306
|
+
});
|
|
307
|
+
var RULES = [
|
|
308
|
+
// device and online identifiers
|
|
309
|
+
rule("ip address", "device"),
|
|
310
|
+
rule("ip", "device"),
|
|
311
|
+
rule("imei", "device"),
|
|
312
|
+
rule("device id", "device"),
|
|
313
|
+
rule("user agent", "device"),
|
|
314
|
+
rule("fcm token", "device"),
|
|
315
|
+
rule("push token", "device"),
|
|
316
|
+
rule("advertising id", "device"),
|
|
317
|
+
rule("gaid", "device"),
|
|
318
|
+
rule("idfa", "device"),
|
|
319
|
+
// Indian and other government identifiers
|
|
320
|
+
rule("aadhaar", "identity"),
|
|
321
|
+
rule("aadhar", "identity"),
|
|
322
|
+
rule("uidai", "identity"),
|
|
323
|
+
rule("pan", "identity"),
|
|
324
|
+
rule("passport", "identity"),
|
|
325
|
+
rule("voter id", "identity"),
|
|
326
|
+
rule("epic", "identity"),
|
|
327
|
+
rule("driving licence", "identity"),
|
|
328
|
+
rule("driving license", "identity"),
|
|
329
|
+
rule("abha", "health"),
|
|
330
|
+
// dates of birth and names
|
|
331
|
+
rule("date of birth", "identity"),
|
|
332
|
+
rule("birth date", "identity"),
|
|
333
|
+
rule("birthdate", "identity"),
|
|
334
|
+
rule("birthday", "identity"),
|
|
335
|
+
rule("dob", "identity"),
|
|
336
|
+
rule("first name", "identity"),
|
|
337
|
+
rule("last name", "identity"),
|
|
338
|
+
rule("middle name", "identity"),
|
|
339
|
+
rule("full name", "identity"),
|
|
340
|
+
rule("surname", "identity"),
|
|
341
|
+
rule("father name", "identity"),
|
|
342
|
+
rule("mother name", "identity"),
|
|
343
|
+
rule("guardian name", "identity"),
|
|
344
|
+
rule("parent name", "identity"),
|
|
345
|
+
// contact
|
|
346
|
+
rule("phone", "contact"),
|
|
347
|
+
rule("mobile", "contact"),
|
|
348
|
+
rule("msisdn", "contact"),
|
|
349
|
+
rule("whatsapp", "contact"),
|
|
350
|
+
rule("email", "contact"),
|
|
351
|
+
rule("address", "contact"),
|
|
352
|
+
rule("pincode", "contact"),
|
|
353
|
+
rule("pin code", "contact"),
|
|
354
|
+
rule("postcode", "contact"),
|
|
355
|
+
rule("postal code", "contact"),
|
|
356
|
+
rule("zipcode", "contact"),
|
|
357
|
+
rule("zip code", "contact"),
|
|
358
|
+
// financial
|
|
359
|
+
rule("account number", "financial"),
|
|
360
|
+
rule("bank account", "financial"),
|
|
361
|
+
rule("ifsc", "financial"),
|
|
362
|
+
rule("upi", "financial"),
|
|
363
|
+
rule("vpa", "financial"),
|
|
364
|
+
rule("card number", "financial"),
|
|
365
|
+
rule("iban", "financial"),
|
|
366
|
+
rule("salary", "financial"),
|
|
367
|
+
rule("income", "financial"),
|
|
368
|
+
// health and biometric
|
|
369
|
+
rule("blood group", "health"),
|
|
370
|
+
rule("diagnosis", "health"),
|
|
371
|
+
rule("medical", "health"),
|
|
372
|
+
rule("allergy", "health"),
|
|
373
|
+
rule("allergies", "health"),
|
|
374
|
+
rule("prescription", "health"),
|
|
375
|
+
rule("fingerprint", "biometric"),
|
|
376
|
+
rule("biometric", "biometric"),
|
|
377
|
+
rule("face embedding", "biometric"),
|
|
378
|
+
// location
|
|
379
|
+
rule("latitude", "location"),
|
|
380
|
+
rule("longitude", "location"),
|
|
381
|
+
rule("lat", "location"),
|
|
382
|
+
rule("lng", "location"),
|
|
383
|
+
rule("gps", "location"),
|
|
384
|
+
// weak: personal in a people table, not in a products table
|
|
385
|
+
rule("name", "identity", "weak"),
|
|
386
|
+
rule("gender", "identity", "weak"),
|
|
387
|
+
rule("age", "identity", "weak"),
|
|
388
|
+
rule("photo", "identity", "weak"),
|
|
389
|
+
rule("avatar", "identity", "weak"),
|
|
390
|
+
rule("selfie", "biometric", "weak"),
|
|
391
|
+
rule("signature", "identity", "weak"),
|
|
392
|
+
rule("city", "location", "weak"),
|
|
393
|
+
rule("street", "contact", "weak"),
|
|
394
|
+
rule("location", "location", "weak")
|
|
395
|
+
];
|
|
396
|
+
var DESCRIPTIVE_ENDINGS = /* @__PURE__ */ new Set([
|
|
397
|
+
"verified",
|
|
398
|
+
"verification",
|
|
399
|
+
"confirmed",
|
|
400
|
+
"enabled",
|
|
401
|
+
"disabled",
|
|
402
|
+
"count",
|
|
403
|
+
"type",
|
|
404
|
+
"status",
|
|
405
|
+
"kind",
|
|
406
|
+
"flag",
|
|
407
|
+
"visible",
|
|
408
|
+
"public",
|
|
409
|
+
"at",
|
|
410
|
+
"sent",
|
|
411
|
+
"in",
|
|
412
|
+
"out",
|
|
413
|
+
"allowed",
|
|
414
|
+
"required"
|
|
415
|
+
]);
|
|
416
|
+
var ORGANISATION_WORDS = /* @__PURE__ */ new Set([
|
|
417
|
+
"company",
|
|
418
|
+
"business",
|
|
419
|
+
"org",
|
|
420
|
+
"organisation",
|
|
421
|
+
"organization",
|
|
422
|
+
"merchant",
|
|
423
|
+
"vendor",
|
|
424
|
+
"supplier",
|
|
425
|
+
"firm",
|
|
426
|
+
"branch",
|
|
427
|
+
"office",
|
|
428
|
+
"school",
|
|
429
|
+
"institute",
|
|
430
|
+
"college"
|
|
431
|
+
]);
|
|
432
|
+
function tokenize(name) {
|
|
433
|
+
return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
434
|
+
}
|
|
435
|
+
function containsRun(tokens, run) {
|
|
436
|
+
outer: for (let i = 0; i + run.length <= tokens.length; i++) {
|
|
437
|
+
for (let j = 0; j < run.length; j++) if (tokens[i + j] !== run[j]) continue outer;
|
|
438
|
+
return true;
|
|
439
|
+
}
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
function guessPersonal(columnName) {
|
|
443
|
+
const tokens = tokenize(columnName);
|
|
444
|
+
if (tokens.length === 0) return void 0;
|
|
445
|
+
const last = tokens[tokens.length - 1];
|
|
446
|
+
if (tokens.length > 1 && DESCRIPTIVE_ENDINGS.has(last)) return void 0;
|
|
447
|
+
const organisational = tokens.some((t) => ORGANISATION_WORDS.has(t));
|
|
448
|
+
for (const r of RULES) {
|
|
449
|
+
if (containsRun(tokens, r.tokens)) {
|
|
450
|
+
return {
|
|
451
|
+
category: r.category,
|
|
452
|
+
confidence: organisational ? "weak" : r.confidence,
|
|
453
|
+
matched: r.tokens.join(" ")
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return void 0;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// src/audit.ts
|
|
461
|
+
var ONE_YEAR_MS = durationMs("1y");
|
|
462
|
+
function checkRetention(retain, path, issues) {
|
|
463
|
+
if (retain === "while-active" || isDuration(retain)) return;
|
|
464
|
+
if (retain && typeof retain === "object" && "afterWithdrawal" in retain) {
|
|
465
|
+
if (!isDuration(retain.afterWithdrawal)) {
|
|
466
|
+
issues.push({
|
|
467
|
+
level: "error",
|
|
468
|
+
code: "invalid-duration",
|
|
469
|
+
path: `${path}.afterWithdrawal`,
|
|
470
|
+
message: `${JSON.stringify(retain.afterWithdrawal)} is not a duration. Use e.g. "0d", "30d", "1y".`
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
issues.push({
|
|
476
|
+
level: "error",
|
|
477
|
+
code: "invalid-retention",
|
|
478
|
+
path,
|
|
479
|
+
message: `Retention must be "while-active", a duration like "1y", or { afterWithdrawal: "30d" }.`
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
function checkPurposeList(purposes, known, used, path, issues) {
|
|
483
|
+
if (!purposes || purposes.length === 0) {
|
|
484
|
+
issues.push({
|
|
485
|
+
level: "error",
|
|
486
|
+
code: "field-without-purpose",
|
|
487
|
+
path: `${path}.purposes`,
|
|
488
|
+
message: "List at least one purpose. Personal data with no purpose must not be collected."
|
|
489
|
+
});
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
for (const p of purposes) {
|
|
493
|
+
used.add(p);
|
|
494
|
+
if (!known.has(p)) {
|
|
495
|
+
issues.push({
|
|
496
|
+
level: "error",
|
|
497
|
+
code: "unknown-purpose",
|
|
498
|
+
path: `${path}.purposes`,
|
|
499
|
+
message: `Unknown purpose ${JSON.stringify(p)}. Declare it under \`purposes\` or fix the spelling.`
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function audit(config) {
|
|
505
|
+
const issues = [];
|
|
506
|
+
const purposes = config.purposes ?? {};
|
|
507
|
+
const known = new Set(Object.keys(purposes));
|
|
508
|
+
const used = /* @__PURE__ */ new Set();
|
|
509
|
+
if (!config.fiduciary?.name) {
|
|
510
|
+
issues.push({
|
|
511
|
+
level: "error",
|
|
512
|
+
code: "fiduciary-missing",
|
|
513
|
+
path: "fiduciary.name",
|
|
514
|
+
message: "Name the Data Fiduciary (your organisation). It appears on every notice."
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
if (!config.fiduciary?.grievanceUrl) {
|
|
518
|
+
issues.push({
|
|
519
|
+
level: "warning",
|
|
520
|
+
code: "grievance-missing",
|
|
521
|
+
path: "fiduciary.grievanceUrl",
|
|
522
|
+
message: "Add where people can raise a grievance. Section 8(10) requires a grievance mechanism, and Section 5(1)(ii) requires the notice to say how to use it."
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
if (!config.fiduciary?.dpo) {
|
|
526
|
+
issues.push({
|
|
527
|
+
level: "warning",
|
|
528
|
+
code: "contact-missing",
|
|
529
|
+
path: "fiduciary.dpo",
|
|
530
|
+
message: "Add your Data Protection Officer, or a person who can answer questions about personal data, with their business contact. Section 8(9) requires publishing it, and Rule 7(1)(e) requires it in every breach notice."
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
if (known.size === 0) {
|
|
534
|
+
issues.push({ level: "error", code: "no-purposes", path: "purposes", message: "Declare at least one purpose." });
|
|
535
|
+
}
|
|
536
|
+
for (const [name, def] of Object.entries(purposes)) {
|
|
537
|
+
const path = `purposes.${name}`;
|
|
538
|
+
if (def.basis !== "consent" && def.basis !== "legitimate-use") {
|
|
539
|
+
issues.push({
|
|
540
|
+
level: "error",
|
|
541
|
+
code: "invalid-basis",
|
|
542
|
+
path: `${path}.basis`,
|
|
543
|
+
message: `Basis must be "consent" or "legitimate-use".`
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
checkRetention(def.retain, `${path}.retain`, issues);
|
|
547
|
+
if (def.basis === "legitimate-use" && typeof def.retain === "object") {
|
|
548
|
+
issues.push({
|
|
549
|
+
level: "error",
|
|
550
|
+
code: "invalid-retention",
|
|
551
|
+
path: `${path}.retain`,
|
|
552
|
+
message: 'afterWithdrawal only applies to consent purposes (Section 6(4)). Use "while-active" or a duration for a legitimate use.'
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
for (const [key, table] of Object.entries(config.data ?? {})) {
|
|
557
|
+
const path = `data.${key}`;
|
|
558
|
+
if (!table.subject) {
|
|
559
|
+
issues.push({
|
|
560
|
+
level: "error",
|
|
561
|
+
code: "missing-subject-column",
|
|
562
|
+
path: `${path}.subject`,
|
|
563
|
+
message: "Name the column that holds the person's id, so their rows can be found."
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
const fields = Object.entries(table.fields ?? {});
|
|
567
|
+
if (fields.length === 0) {
|
|
568
|
+
issues.push({
|
|
569
|
+
level: "warning",
|
|
570
|
+
code: "table-without-fields",
|
|
571
|
+
path: `${path}.fields`,
|
|
572
|
+
message: "No personal fields listed. Remove the table from the map, or list its fields."
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
for (const [field, def] of fields) {
|
|
576
|
+
checkPurposeList(def.purposes, known, used, `${path}.fields.${field}`, issues);
|
|
577
|
+
}
|
|
578
|
+
if (table.legalHold && !isDuration(table.legalHold.keep)) {
|
|
579
|
+
issues.push({
|
|
580
|
+
level: "error",
|
|
581
|
+
code: "invalid-duration",
|
|
582
|
+
path: `${path}.legalHold.keep`,
|
|
583
|
+
message: `${JSON.stringify(table.legalHold.keep)} is not a duration. Use e.g. "8y".`
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
for (const [name, processor] of Object.entries(config.processors ?? {})) {
|
|
588
|
+
checkPurposeList(processor.purposes, known, used, `processors.${name}`, issues);
|
|
589
|
+
}
|
|
590
|
+
for (const name of known) {
|
|
591
|
+
if (!used.has(name)) {
|
|
592
|
+
issues.push({
|
|
593
|
+
level: "warning",
|
|
594
|
+
code: "unused-purpose",
|
|
595
|
+
path: `purposes.${name}`,
|
|
596
|
+
message: "No field or processor uses this purpose. Remove it, or map the data it covers."
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
for (const entry of config.notPersonal ?? []) {
|
|
601
|
+
if (!/^[^.\s]+(\.[^.\s]+)*\.([^.\s]+|\*)$/.test(entry)) {
|
|
602
|
+
issues.push({
|
|
603
|
+
level: "error",
|
|
604
|
+
code: "invalid-not-personal",
|
|
605
|
+
path: "notPersonal",
|
|
606
|
+
message: `${JSON.stringify(entry)} should be "table.column" or "table.*".`
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
const within = config.rights?.responseWithin;
|
|
611
|
+
if (within !== void 0) {
|
|
612
|
+
const entries = typeof within === "string" ? [["", within]] : Object.entries(within);
|
|
613
|
+
for (const [type, value] of entries) {
|
|
614
|
+
const path = type ? `rights.responseWithin.${type}` : "rights.responseWithin";
|
|
615
|
+
if (type && !REQUEST_TYPES.includes(type)) {
|
|
616
|
+
issues.push({
|
|
617
|
+
level: "error",
|
|
618
|
+
code: "invalid-request-type",
|
|
619
|
+
path,
|
|
620
|
+
message: `Unknown request type. Use one of: ${REQUEST_TYPES.join(", ")}.`
|
|
621
|
+
});
|
|
622
|
+
} else if (!isDuration(value)) {
|
|
623
|
+
issues.push({ level: "error", code: "invalid-duration", path, message: `${JSON.stringify(value)} is not a duration. Use e.g. "30d".` });
|
|
624
|
+
} else if ((type === "" || type === "grievance") && durationMs(value) > durationMs("90d")) {
|
|
625
|
+
issues.push({
|
|
626
|
+
level: "error",
|
|
627
|
+
code: "grievance-response-too-long",
|
|
628
|
+
path,
|
|
629
|
+
message: 'Rule 14(3) of the DPDP Rules requires answering grievances within ninety days. Use at most "90d".'
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
const minimum = config.minimumRetention;
|
|
635
|
+
if (minimum === void 0) {
|
|
636
|
+
issues.push({
|
|
637
|
+
level: "warning",
|
|
638
|
+
code: "minimum-retention-missing",
|
|
639
|
+
path: "minimumRetention",
|
|
640
|
+
message: 'Set minimumRetention. Rule 8(3) of the DPDP Rules requires keeping personal data, traffic data and logs of each processing for at least one year from the processing ("1y").'
|
|
641
|
+
});
|
|
642
|
+
} else if (!isDuration(minimum)) {
|
|
643
|
+
issues.push({
|
|
644
|
+
level: "error",
|
|
645
|
+
code: "invalid-duration",
|
|
646
|
+
path: "minimumRetention",
|
|
647
|
+
message: `${JSON.stringify(minimum)} is not a duration. Use e.g. "1y".`
|
|
648
|
+
});
|
|
649
|
+
} else if (durationMs(minimum) < ONE_YEAR_MS) {
|
|
650
|
+
issues.push({
|
|
651
|
+
level: "error",
|
|
652
|
+
code: "minimum-retention-too-short",
|
|
653
|
+
path: "minimumRetention",
|
|
654
|
+
message: 'Rule 8(3) of the DPDP Rules requires keeping personal data, traffic data and logs of each processing for at least one year. Use at least "1y".'
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
checkSecurity(config, issues);
|
|
658
|
+
checkErase(config, issues);
|
|
659
|
+
return issues;
|
|
660
|
+
}
|
|
661
|
+
function checkErase(config, issues) {
|
|
662
|
+
for (const [key, table] of Object.entries(config.data ?? {})) {
|
|
663
|
+
for (const [field, def] of Object.entries(table.fields ?? {})) {
|
|
664
|
+
const erase = def.erase;
|
|
665
|
+
if (erase === void 0 || erase === "null" || erase === "redact") continue;
|
|
666
|
+
if (erase && typeof erase === "object" && "value" in erase) {
|
|
667
|
+
const value = erase.value;
|
|
668
|
+
if (value === null || ["string", "number", "boolean", "function"].includes(typeof value)) continue;
|
|
669
|
+
}
|
|
670
|
+
issues.push({
|
|
671
|
+
level: "error",
|
|
672
|
+
code: "invalid-erase",
|
|
673
|
+
path: `data.${key}.fields.${field}.erase`,
|
|
674
|
+
message: 'erase must be "null", "redact", or { value } with a string, number, boolean, null, or a function returning one.'
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
var HIGH_RISK_MATCHES = /* @__PURE__ */ new Set([
|
|
680
|
+
"aadhaar",
|
|
681
|
+
"aadhar",
|
|
682
|
+
"uidai",
|
|
683
|
+
"pan",
|
|
684
|
+
"passport",
|
|
685
|
+
"voter id",
|
|
686
|
+
"epic",
|
|
687
|
+
"driving licence",
|
|
688
|
+
"driving license",
|
|
689
|
+
"abha",
|
|
690
|
+
"account number",
|
|
691
|
+
"bank account",
|
|
692
|
+
"card number",
|
|
693
|
+
"iban"
|
|
694
|
+
]);
|
|
695
|
+
var HIGH_RISK_CATEGORIES = /* @__PURE__ */ new Set(["health", "biometric"]);
|
|
696
|
+
function isHighRisk(field, category) {
|
|
697
|
+
if (HIGH_RISK_CATEGORIES.has(category)) return true;
|
|
698
|
+
const guess = guessPersonal(field);
|
|
699
|
+
return guess !== void 0 && guess.confidence === "strong" && (HIGH_RISK_MATCHES.has(guess.matched) || HIGH_RISK_CATEGORIES.has(guess.category));
|
|
700
|
+
}
|
|
701
|
+
var SECURITY_MEASURES = [
|
|
702
|
+
["accessControl", "(b)", "how access to your computer resources is controlled (for example SSO and least-privilege roles)"],
|
|
703
|
+
["backups", "(d)", "how processing continues after a compromise or loss of data (for example tested backups)"],
|
|
704
|
+
["measures", "(g)", "the technical and organisational measures that make the safeguards work (for example training and access reviews)"]
|
|
705
|
+
];
|
|
706
|
+
function checkSecurity(config, issues) {
|
|
707
|
+
for (const [key, table] of Object.entries(config.data ?? {})) {
|
|
708
|
+
for (const [field, def] of Object.entries(table.fields ?? {})) {
|
|
709
|
+
if (!def.protect && isHighRisk(field, def.category)) {
|
|
710
|
+
issues.push({
|
|
711
|
+
level: "warning",
|
|
712
|
+
code: "unprotected-high-risk-field",
|
|
713
|
+
path: `data.${key}.fields.${field}.protect`,
|
|
714
|
+
message: `${field} looks like high-risk personal data. Rule 6(1)(a) lists encryption, obfuscation, masking and virtual tokens as safeguards: store it protected (see dpdp-kit/protect) and say how with protect: "encrypted" | "tokenised" | "masked" | "hashed".`
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
for (const [name, def] of Object.entries(config.processors ?? {})) {
|
|
720
|
+
if (!def.contract) {
|
|
721
|
+
issues.push({
|
|
722
|
+
level: "warning",
|
|
723
|
+
code: "processor-contract-missing",
|
|
724
|
+
path: `processors.${name}.contract`,
|
|
725
|
+
message: `Rule 6(1)(f) requires a provision for reasonable security safeguards in your contract with each Data Processor. Record where it is, e.g. contract: "DPA signed 2026-03-01, clause 7".`
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
for (const [key, clause, what] of SECURITY_MEASURES) {
|
|
730
|
+
if (!config.security?.[key]) {
|
|
731
|
+
issues.push({
|
|
732
|
+
level: "warning",
|
|
733
|
+
code: "security-measure-missing",
|
|
734
|
+
path: `security.${key}`,
|
|
735
|
+
message: `Rule 6(1)${clause} requires ${what}. Describe what you do in a sentence, as evidence.`
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
const keep = config.security?.accessLogRetention;
|
|
740
|
+
if (keep !== void 0 && !isDuration(keep)) {
|
|
741
|
+
issues.push({
|
|
742
|
+
level: "error",
|
|
743
|
+
code: "invalid-duration",
|
|
744
|
+
path: "security.accessLogRetention",
|
|
745
|
+
message: `${JSON.stringify(keep)} is not a duration. Use e.g. "1y".`
|
|
746
|
+
});
|
|
747
|
+
} else if (keep !== void 0 && durationMs(keep) < ONE_YEAR_MS) {
|
|
748
|
+
issues.push({
|
|
749
|
+
level: "error",
|
|
750
|
+
code: "access-log-retention-too-short",
|
|
751
|
+
path: "security.accessLogRetention",
|
|
752
|
+
message: 'Rule 6(1)(e) of the DPDP Rules requires keeping access logs for one year to detect and investigate unauthorised access. Use at least "1y".'
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
function hasErrors(issues) {
|
|
757
|
+
return issues.some((i) => i.level === "error");
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// src/config.ts
|
|
761
|
+
var REDACTED = "[erased]";
|
|
762
|
+
function defineConfig(config) {
|
|
763
|
+
return config;
|
|
764
|
+
}
|
|
765
|
+
function purposeNames(config) {
|
|
766
|
+
return Object.keys(config.purposes);
|
|
767
|
+
}
|
|
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}`
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
return value;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// src/schema-check.ts
|
|
782
|
+
var OWN_TABLE_PREFIX = "dpdp_";
|
|
783
|
+
var matches = (column, name) => column.name === name || column.key === name;
|
|
784
|
+
function parseNotPersonal(entries) {
|
|
785
|
+
const columns = /* @__PURE__ */ new Set();
|
|
786
|
+
const tables = /* @__PURE__ */ new Set();
|
|
787
|
+
for (const entry of entries ?? []) {
|
|
788
|
+
const dot = entry.lastIndexOf(".");
|
|
789
|
+
if (dot <= 0) continue;
|
|
790
|
+
const table = entry.slice(0, dot);
|
|
791
|
+
const column = entry.slice(dot + 1);
|
|
792
|
+
if (column === "*") tables.add(table);
|
|
793
|
+
else columns.add(`${table}.${column}`);
|
|
794
|
+
}
|
|
795
|
+
return { columns, tables };
|
|
796
|
+
}
|
|
797
|
+
function strongest(a, b) {
|
|
798
|
+
if (!a) return b;
|
|
799
|
+
if (!b) return a;
|
|
800
|
+
return b.confidence === "strong" && a.confidence === "weak" ? b : a;
|
|
801
|
+
}
|
|
802
|
+
function checkEraseAgainstColumn(erase, column, path, where, issues) {
|
|
803
|
+
const fixed = erase === void 0 || erase === "null" ? null : erase === "redact" ? REDACTED : typeof erase.value === "function" ? void 0 : erase.value;
|
|
804
|
+
if (fixed === void 0) return;
|
|
805
|
+
if (fixed === null) {
|
|
806
|
+
if (column.notNull) {
|
|
807
|
+
issues.push({
|
|
808
|
+
level: "error",
|
|
809
|
+
code: "erase-not-null",
|
|
810
|
+
path,
|
|
811
|
+
message: `${where} is NOT NULL, so erasing it to NULL will fail. Set erase: "redact" for text, or erase: { value: \u2026 } with something the column accepts.`
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const kind = typeof fixed;
|
|
817
|
+
if (column.type && column.type !== "other" && column.type !== kind) {
|
|
818
|
+
issues.push({
|
|
819
|
+
level: "error",
|
|
820
|
+
code: "erase-type-mismatch",
|
|
821
|
+
path,
|
|
822
|
+
message: `${where} holds ${column.type} values, but erase writes a ${kind} (${JSON.stringify(fixed)}). Use erase: { value: \u2026 } with a ${column.type}.`
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
function checkSchema(config, schema) {
|
|
827
|
+
const issues = [];
|
|
828
|
+
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);
|
|
831
|
+
const mapped = /* @__PURE__ */ new Map();
|
|
832
|
+
for (const [key, def] of Object.entries(config.data ?? {})) {
|
|
833
|
+
const table = byName.get(def.table);
|
|
834
|
+
if (!table) {
|
|
835
|
+
issues.push({
|
|
836
|
+
level: "error",
|
|
837
|
+
code: "unknown-table",
|
|
838
|
+
path: `data.${key}.table`,
|
|
839
|
+
message: `Table "${def.table}" isn't in the schema. Fix the name, or remove it from the data map if the table is gone.`
|
|
840
|
+
});
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
const list = mapped.get(table.name) ?? [];
|
|
844
|
+
const subject = table.columns.find((c) => matches(c, def.subject));
|
|
845
|
+
if (subject) list.push(subject);
|
|
846
|
+
else {
|
|
847
|
+
issues.push({
|
|
848
|
+
level: "error",
|
|
849
|
+
code: "unknown-column",
|
|
850
|
+
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.`
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
for (const [field, fieldDef] of Object.entries(def.fields ?? {})) {
|
|
855
|
+
const column = table.columns.find((c) => matches(c, field));
|
|
856
|
+
if (column) {
|
|
857
|
+
list.push(column);
|
|
858
|
+
checkEraseAgainstColumn(fieldDef.erase, column, `data.${key}.fields.${field}.erase`, `${table.name}.${column.name}`, issues);
|
|
859
|
+
} else {
|
|
860
|
+
issues.push({
|
|
861
|
+
level: "error",
|
|
862
|
+
code: "unknown-column",
|
|
863
|
+
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.`
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
mapped.set(table.name, list);
|
|
869
|
+
}
|
|
870
|
+
const ignore = parseNotPersonal(config.notPersonal);
|
|
871
|
+
for (const entry of config.notPersonal ?? []) {
|
|
872
|
+
const dot = entry.lastIndexOf(".");
|
|
873
|
+
const tableName = entry.slice(0, Math.max(dot, 0));
|
|
874
|
+
const columnName = entry.slice(dot + 1);
|
|
875
|
+
const table = byName.get(tableName);
|
|
876
|
+
const exists = table && (columnName === "*" || table.columns.some((c) => matches(c, columnName)));
|
|
877
|
+
if (!exists) {
|
|
878
|
+
issues.push({
|
|
879
|
+
level: "warning",
|
|
880
|
+
code: "stale-not-personal",
|
|
881
|
+
path: "notPersonal",
|
|
882
|
+
message: `"${entry}" doesn't match any table or column. Use "table.column" or "table.*", or remove it.`
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
}
|
|
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) {
|
|
891
|
+
if (known.includes(column)) continue;
|
|
892
|
+
const columnNames = column.key ? [column.name, column.key] : [column.name];
|
|
893
|
+
if (tableNames.some((t) => columnNames.some((c) => ignore.columns.has(`${t}.${c}`)))) continue;
|
|
894
|
+
const guess = strongest(guessPersonal(column.name), column.key ? guessPersonal(column.key) : void 0);
|
|
895
|
+
if (!guess) continue;
|
|
896
|
+
issues.push({
|
|
897
|
+
level: guess.confidence === "strong" ? "error" : "warning",
|
|
898
|
+
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\`.`
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
issues.push(...checkHeldReferences(config, byName));
|
|
905
|
+
return issues;
|
|
906
|
+
}
|
|
907
|
+
function checkHeldReferences(config, byName) {
|
|
908
|
+
const issues = [];
|
|
909
|
+
const entries = Object.entries(config.data ?? {});
|
|
910
|
+
const deleted = new Set(entries.filter(([, def]) => !def.legalHold).flatMap(([, def]) => byName.get(def.table) ? [byName.get(def.table).name] : []));
|
|
911
|
+
for (const [key, def] of entries) {
|
|
912
|
+
const hold = def.legalHold;
|
|
913
|
+
const held = byName.get(def.table);
|
|
914
|
+
if (!hold || !held) continue;
|
|
915
|
+
const subject = held.columns.find((c) => matches(c, def.subject))?.name;
|
|
916
|
+
for (const ref of held.references ?? []) {
|
|
917
|
+
const target = byName.get(ref.table)?.name ?? ref.table;
|
|
918
|
+
if (!deleted.has(target) || target === held.name) continue;
|
|
919
|
+
const where = `${held.name}.${ref.columns.join(", ")}`;
|
|
920
|
+
const path = `schema.${held.name}.${ref.columns.join(",")}`;
|
|
921
|
+
const keep = `the legal hold (${hold.reason}, ${hold.keep})`;
|
|
922
|
+
const plain = `Drop the foreign key and keep ${ref.columns.join(", ")} as a plain, indexed column, so the ${held.name} rows outlive the account.`;
|
|
923
|
+
const onDelete = ref.onDelete ?? "no action";
|
|
924
|
+
if (onDelete === "cascade") {
|
|
925
|
+
issues.push({
|
|
926
|
+
level: "error",
|
|
927
|
+
code: "held-rows-cascade",
|
|
928
|
+
path,
|
|
929
|
+
message: `${where} references ${target} with ON DELETE CASCADE, so deleting an account also deletes the ${held.name} rows that ${keep} says to keep. ${plain}`
|
|
930
|
+
});
|
|
931
|
+
} else if (onDelete === "set null" || onDelete === "set default") {
|
|
932
|
+
if (subject && ref.columns.includes(subject)) {
|
|
933
|
+
issues.push({
|
|
934
|
+
level: "error",
|
|
935
|
+
code: "held-link-lost",
|
|
936
|
+
path,
|
|
937
|
+
message: `${where} references ${target} with ON DELETE ${onDelete.toUpperCase()}, so deleting an account clears whose ${held.name} rows they are, and they can't be found to ${hold.then} when ${keep} ends. ${plain}`
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
} else {
|
|
941
|
+
issues.push({
|
|
942
|
+
level: "warning",
|
|
943
|
+
code: "held-rows-block-delete",
|
|
944
|
+
path,
|
|
945
|
+
message: `${where} references ${target} (ON DELETE ${onDelete.toUpperCase()}), so deleting an account fails while ${keep} keeps the ${held.name} rows. The erasure task will fail and retry. ${plain}`
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
return issues;
|
|
951
|
+
}
|
|
952
|
+
|
|
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
|
+
export {
|
|
1026
|
+
isDuration,
|
|
1027
|
+
durationMs,
|
|
1028
|
+
maxDuration,
|
|
1029
|
+
REQUEST_TYPES,
|
|
1030
|
+
isDpdpStore,
|
|
1031
|
+
memoryStore,
|
|
1032
|
+
grantedPurposes,
|
|
1033
|
+
isAccessLogStore,
|
|
1034
|
+
accessId,
|
|
1035
|
+
DEFAULT_ACCESS_LOG_RETENTION,
|
|
1036
|
+
resolveFields,
|
|
1037
|
+
fieldsOutsidePurpose,
|
|
1038
|
+
reviewAccess,
|
|
1039
|
+
tokenize,
|
|
1040
|
+
guessPersonal,
|
|
1041
|
+
audit,
|
|
1042
|
+
isHighRisk,
|
|
1043
|
+
hasErrors,
|
|
1044
|
+
REDACTED,
|
|
1045
|
+
defineConfig,
|
|
1046
|
+
purposeNames,
|
|
1047
|
+
erasedValue,
|
|
1048
|
+
checkSchema,
|
|
1049
|
+
safeguardsReport,
|
|
1050
|
+
formatSafeguards
|
|
1051
|
+
};
|