dpdp-kit 0.1.1 → 0.1.2

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/README.md CHANGED
@@ -8,6 +8,7 @@
8
8
  - **Keep consent records that show tampering.** Each person's grants and withdrawals form a hash chain, with the notice version and language they saw.
9
9
  - **Know what to erase.** When consent is withdrawn or an account is deleted, get a plan: which fields go, which stay (and why), which tables are under a legal hold, which third parties to tell.
10
10
  - **Check it in CI.** `dpdp-kit audit` fails the build when the data map is inconsistent.
11
+ - **Catch drift.** `dpdp-kit audit --schema` reads your Drizzle schema and fails the build when someone adds a `phone`, `email` or `aadhaar_number` column without saying what it's for, or when the data map points at columns that no longer exist. Compliance that can't quietly fall out of date.
11
12
 
12
13
  ## Node-native
13
14
 
@@ -92,6 +93,37 @@ npx dpdp-kit audit --strict # also fail on warnings
92
93
 
93
94
  The same checks run when the app starts: `createDpdp` throws if the config has errors.
94
95
 
96
+ ### Catch schema drift
97
+
98
+ A data map is only useful while it matches the database. Point the audit at your Drizzle schema (Postgres, MySQL or SQLite):
99
+
100
+ ```bash
101
+ npx dpdp-kit audit --schema src/db/schema.ts
102
+ ```
103
+
104
+ ```
105
+ ✖ error schema.users.aadhaar_number
106
+ Looks like personal data (identity, matched "aadhaar") but isn't in the data map. Add it under `data`
107
+ with the purposes it's held for, or add "users.aadhaar_number" to `notPersonal`.
108
+ ✖ error data.users.fields.interests
109
+ Column "interests" isn't in table "users". Fix the name, or remove it if the column was dropped.
110
+ ⚠ warning schema.users.gender
111
+ Looks like personal data (identity, matched "gender") but isn't in the data map. ...
112
+ ```
113
+
114
+ It checks both directions:
115
+
116
+ - **New personal columns nobody mapped.** Columns are recognised by name: phone and email, Aadhaar, PAN, passport and voter ID, date of birth, names, addresses and PIN codes, UPI, IFSC and bank details, IP addresses and device IDs, health, biometric and location data. Clear cases are errors. Columns that are personal only sometimes, like `name`, `gender` or `city`, or anything named for a company or branch, are warnings.
117
+ - **A data map that points at nothing.** Tables or columns that were renamed or dropped.
118
+
119
+ Columns that describe data rather than hold it, such as `email_verified_at`, `phone_confirmed` and `address_type`, are not flagged. For anything that only looks personal, list it in the config:
120
+
121
+ ```ts
122
+ notPersonal: ["products.name", "branches.*"], // database table and column names
123
+ ```
124
+
125
+ From code, `checkSchema(config, drizzleSchema(schema))` returns the same issues. `drizzleSchema` comes from `dpdp-kit/drizzle`. Matching is by column name, so it can't see personal data hidden inside a JSON column or a vaguely named field. Review those by hand.
126
+
95
127
  ## 3. Record consent
96
128
 
97
129
  ```ts
@@ -187,7 +219,8 @@ Section 6(10) puts the burden on you: if consent is questioned in a proceeding,
187
219
 
188
220
  | Version | Adds |
189
221
  |---|---|
190
- | **v0.1** (this) | Config and types, `audit` + CLI, consent records, erasure plans, Drizzle store, Express/Hono guards |
222
+ | **v0.1** | Config and types, `audit` + CLI, consent records, erasure plans, Drizzle store, Express/Hono guards |
223
+ | **v0.1.2** | Schema drift check: `audit --schema`, `checkSchema`, `drizzleSchema`, `notPersonal` |
191
224
  | v0.2 | User rights requests (Sections 11–14, Rule 14; grievances answered within 90 days, Rule 14(3)), recording objections to a Section 7(a) use, applying erasure plans, processor hooks, React notice that meets Rule 3 + privacy centre |
192
225
  | v0.3 | Breach records with deadlines (Section 8(6), Rule 7: people and the Board without delay, detailed report to the Board within 72 hours), children and guardian consent (Section 9, Rule 10), inactivity erasure with 48 hours' warning for large e-commerce, gaming and social media platforms (Rule 8(1)–(2), Third Schedule), Consent Manager interop (Sections 6(7)–6(9), Rule 4), Prisma store |
193
226
 
package/dist/audit.d.ts CHANGED
@@ -2,8 +2,8 @@ import type { DpdpConfig } from "./config.js";
2
2
  export type IssueLevel = "error" | "warning";
3
3
  export interface Issue {
4
4
  level: IssueLevel;
5
- code: "no-purposes" | "invalid-basis" | "invalid-retention" | "invalid-duration" | "unknown-purpose" | "field-without-purpose" | "table-without-fields" | "missing-subject-column" | "unused-purpose" | "minimum-retention-missing" | "minimum-retention-too-short" | "grievance-missing" | "fiduciary-missing";
6
- /** Where in the config, e.g. `data.users.fields.phone`. */
5
+ code: "no-purposes" | "invalid-basis" | "invalid-retention" | "invalid-duration" | "unknown-purpose" | "field-without-purpose" | "table-without-fields" | "missing-subject-column" | "unused-purpose" | "minimum-retention-missing" | "minimum-retention-too-short" | "grievance-missing" | "fiduciary-missing" | "invalid-not-personal" | "unknown-table" | "unknown-column" | "unmapped-personal-column" | "stale-not-personal";
6
+ /** Where in the config (`data.users.fields.phone`), or in the schema (`schema.users.phone`). */
7
7
  path: string;
8
8
  message: string;
9
9
  }
@@ -0,0 +1,455 @@
1
+ // src/duration.ts
2
+ var PATTERN = /^(\d+)(h|d|y)$/;
3
+ var HOUR_MS = 60 * 60 * 1e3;
4
+ var UNIT_MS = { h: HOUR_MS, d: 24 * HOUR_MS, y: 365 * 24 * HOUR_MS };
5
+ function isDuration(value) {
6
+ return typeof value === "string" && PATTERN.test(value);
7
+ }
8
+ function durationMs(value) {
9
+ const match = PATTERN.exec(value);
10
+ if (!match) throw new TypeError(`Not a duration: ${JSON.stringify(value)} (use e.g. "48h", "30d", "1y")`);
11
+ const [, amount, unit] = match;
12
+ return Number(amount) * UNIT_MS[unit];
13
+ }
14
+ function maxDuration(a, b) {
15
+ return durationMs(b) > durationMs(a) ? b : a;
16
+ }
17
+
18
+ // src/audit.ts
19
+ var ONE_YEAR_MS = durationMs("1y");
20
+ function checkRetention(retain, path, issues) {
21
+ if (retain === "while-active" || isDuration(retain)) return;
22
+ if (retain && typeof retain === "object" && "afterWithdrawal" in retain) {
23
+ if (!isDuration(retain.afterWithdrawal)) {
24
+ issues.push({
25
+ level: "error",
26
+ code: "invalid-duration",
27
+ path: `${path}.afterWithdrawal`,
28
+ message: `${JSON.stringify(retain.afterWithdrawal)} is not a duration. Use e.g. "0d", "30d", "1y".`
29
+ });
30
+ }
31
+ return;
32
+ }
33
+ issues.push({
34
+ level: "error",
35
+ code: "invalid-retention",
36
+ path,
37
+ message: `Retention must be "while-active", a duration like "1y", or { afterWithdrawal: "30d" }.`
38
+ });
39
+ }
40
+ function checkPurposeList(purposes, known, used, path, issues) {
41
+ if (!purposes || purposes.length === 0) {
42
+ issues.push({
43
+ level: "error",
44
+ code: "field-without-purpose",
45
+ path: `${path}.purposes`,
46
+ message: "List at least one purpose. Personal data with no purpose must not be collected."
47
+ });
48
+ return;
49
+ }
50
+ for (const p of purposes) {
51
+ used.add(p);
52
+ if (!known.has(p)) {
53
+ issues.push({
54
+ level: "error",
55
+ code: "unknown-purpose",
56
+ path: `${path}.purposes`,
57
+ message: `Unknown purpose ${JSON.stringify(p)}. Declare it under \`purposes\` or fix the spelling.`
58
+ });
59
+ }
60
+ }
61
+ }
62
+ function audit(config) {
63
+ const issues = [];
64
+ const purposes = config.purposes ?? {};
65
+ const known = new Set(Object.keys(purposes));
66
+ const used = /* @__PURE__ */ new Set();
67
+ if (!config.fiduciary?.name) {
68
+ issues.push({
69
+ level: "error",
70
+ code: "fiduciary-missing",
71
+ path: "fiduciary.name",
72
+ message: "Name the Data Fiduciary (your organisation). It appears on every notice."
73
+ });
74
+ }
75
+ if (!config.fiduciary?.grievanceUrl) {
76
+ issues.push({
77
+ level: "warning",
78
+ code: "grievance-missing",
79
+ path: "fiduciary.grievanceUrl",
80
+ 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."
81
+ });
82
+ }
83
+ if (known.size === 0) {
84
+ issues.push({ level: "error", code: "no-purposes", path: "purposes", message: "Declare at least one purpose." });
85
+ }
86
+ for (const [name, def] of Object.entries(purposes)) {
87
+ const path = `purposes.${name}`;
88
+ if (def.basis !== "consent" && def.basis !== "legitimate-use") {
89
+ issues.push({
90
+ level: "error",
91
+ code: "invalid-basis",
92
+ path: `${path}.basis`,
93
+ message: `Basis must be "consent" or "legitimate-use".`
94
+ });
95
+ }
96
+ checkRetention(def.retain, `${path}.retain`, issues);
97
+ if (def.basis === "legitimate-use" && typeof def.retain === "object") {
98
+ issues.push({
99
+ level: "error",
100
+ code: "invalid-retention",
101
+ path: `${path}.retain`,
102
+ message: 'afterWithdrawal only applies to consent purposes (Section 6(4)). Use "while-active" or a duration for a legitimate use.'
103
+ });
104
+ }
105
+ }
106
+ for (const [key, table] of Object.entries(config.data ?? {})) {
107
+ const path = `data.${key}`;
108
+ if (!table.subject) {
109
+ issues.push({
110
+ level: "error",
111
+ code: "missing-subject-column",
112
+ path: `${path}.subject`,
113
+ message: "Name the column that holds the person's id, so their rows can be found."
114
+ });
115
+ }
116
+ const fields = Object.entries(table.fields ?? {});
117
+ if (fields.length === 0) {
118
+ issues.push({
119
+ level: "warning",
120
+ code: "table-without-fields",
121
+ path: `${path}.fields`,
122
+ message: "No personal fields listed. Remove the table from the map, or list its fields."
123
+ });
124
+ }
125
+ for (const [field, def] of fields) {
126
+ checkPurposeList(def.purposes, known, used, `${path}.fields.${field}`, issues);
127
+ }
128
+ if (table.legalHold && !isDuration(table.legalHold.keep)) {
129
+ issues.push({
130
+ level: "error",
131
+ code: "invalid-duration",
132
+ path: `${path}.legalHold.keep`,
133
+ message: `${JSON.stringify(table.legalHold.keep)} is not a duration. Use e.g. "8y".`
134
+ });
135
+ }
136
+ }
137
+ for (const [name, processor] of Object.entries(config.processors ?? {})) {
138
+ checkPurposeList(processor.purposes, known, used, `processors.${name}`, issues);
139
+ }
140
+ for (const name of known) {
141
+ if (!used.has(name)) {
142
+ issues.push({
143
+ level: "warning",
144
+ code: "unused-purpose",
145
+ path: `purposes.${name}`,
146
+ message: "No field or processor uses this purpose. Remove it, or map the data it covers."
147
+ });
148
+ }
149
+ }
150
+ for (const entry of config.notPersonal ?? []) {
151
+ if (!/^[^.\s]+(\.[^.\s]+)*\.([^.\s]+|\*)$/.test(entry)) {
152
+ issues.push({
153
+ level: "error",
154
+ code: "invalid-not-personal",
155
+ path: "notPersonal",
156
+ message: `${JSON.stringify(entry)} should be "table.column" or "table.*".`
157
+ });
158
+ }
159
+ }
160
+ const minimum = config.minimumRetention;
161
+ if (minimum === void 0) {
162
+ issues.push({
163
+ level: "warning",
164
+ code: "minimum-retention-missing",
165
+ path: "minimumRetention",
166
+ 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").'
167
+ });
168
+ } else if (!isDuration(minimum)) {
169
+ issues.push({
170
+ level: "error",
171
+ code: "invalid-duration",
172
+ path: "minimumRetention",
173
+ message: `${JSON.stringify(minimum)} is not a duration. Use e.g. "1y".`
174
+ });
175
+ } else if (durationMs(minimum) < ONE_YEAR_MS) {
176
+ issues.push({
177
+ level: "error",
178
+ code: "minimum-retention-too-short",
179
+ path: "minimumRetention",
180
+ 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".'
181
+ });
182
+ }
183
+ return issues;
184
+ }
185
+ function hasErrors(issues) {
186
+ return issues.some((i) => i.level === "error");
187
+ }
188
+
189
+ // src/personal.ts
190
+ var rule = (spec, category, confidence = "strong") => ({
191
+ tokens: spec.split(" "),
192
+ category,
193
+ confidence
194
+ });
195
+ var RULES = [
196
+ // device and online identifiers
197
+ rule("ip address", "device"),
198
+ rule("ip", "device"),
199
+ rule("imei", "device"),
200
+ rule("device id", "device"),
201
+ rule("user agent", "device"),
202
+ rule("fcm token", "device"),
203
+ rule("push token", "device"),
204
+ rule("advertising id", "device"),
205
+ rule("gaid", "device"),
206
+ rule("idfa", "device"),
207
+ // Indian and other government identifiers
208
+ rule("aadhaar", "identity"),
209
+ rule("aadhar", "identity"),
210
+ rule("uidai", "identity"),
211
+ rule("pan", "identity"),
212
+ rule("passport", "identity"),
213
+ rule("voter id", "identity"),
214
+ rule("epic", "identity"),
215
+ rule("driving licence", "identity"),
216
+ rule("driving license", "identity"),
217
+ rule("abha", "health"),
218
+ // dates of birth and names
219
+ rule("date of birth", "identity"),
220
+ rule("birth date", "identity"),
221
+ rule("birthdate", "identity"),
222
+ rule("birthday", "identity"),
223
+ rule("dob", "identity"),
224
+ rule("first name", "identity"),
225
+ rule("last name", "identity"),
226
+ rule("middle name", "identity"),
227
+ rule("full name", "identity"),
228
+ rule("surname", "identity"),
229
+ rule("father name", "identity"),
230
+ rule("mother name", "identity"),
231
+ rule("guardian name", "identity"),
232
+ rule("parent name", "identity"),
233
+ // contact
234
+ rule("phone", "contact"),
235
+ rule("mobile", "contact"),
236
+ rule("msisdn", "contact"),
237
+ rule("whatsapp", "contact"),
238
+ rule("email", "contact"),
239
+ rule("address", "contact"),
240
+ rule("pincode", "contact"),
241
+ rule("pin code", "contact"),
242
+ rule("postcode", "contact"),
243
+ rule("postal code", "contact"),
244
+ rule("zipcode", "contact"),
245
+ rule("zip code", "contact"),
246
+ // financial
247
+ rule("account number", "financial"),
248
+ rule("bank account", "financial"),
249
+ rule("ifsc", "financial"),
250
+ rule("upi", "financial"),
251
+ rule("vpa", "financial"),
252
+ rule("card number", "financial"),
253
+ rule("iban", "financial"),
254
+ rule("salary", "financial"),
255
+ rule("income", "financial"),
256
+ // health and biometric
257
+ rule("blood group", "health"),
258
+ rule("diagnosis", "health"),
259
+ rule("medical", "health"),
260
+ rule("allergy", "health"),
261
+ rule("allergies", "health"),
262
+ rule("prescription", "health"),
263
+ rule("fingerprint", "biometric"),
264
+ rule("biometric", "biometric"),
265
+ rule("face embedding", "biometric"),
266
+ // location
267
+ rule("latitude", "location"),
268
+ rule("longitude", "location"),
269
+ rule("lat", "location"),
270
+ rule("lng", "location"),
271
+ rule("gps", "location"),
272
+ // weak: personal in a people table, not in a products table
273
+ rule("name", "identity", "weak"),
274
+ rule("gender", "identity", "weak"),
275
+ rule("age", "identity", "weak"),
276
+ rule("photo", "identity", "weak"),
277
+ rule("avatar", "identity", "weak"),
278
+ rule("selfie", "biometric", "weak"),
279
+ rule("signature", "identity", "weak"),
280
+ rule("city", "location", "weak"),
281
+ rule("street", "contact", "weak"),
282
+ rule("location", "location", "weak")
283
+ ];
284
+ var DESCRIPTIVE_ENDINGS = /* @__PURE__ */ new Set([
285
+ "verified",
286
+ "verification",
287
+ "confirmed",
288
+ "enabled",
289
+ "disabled",
290
+ "count",
291
+ "type",
292
+ "status",
293
+ "kind",
294
+ "flag",
295
+ "visible",
296
+ "public",
297
+ "at",
298
+ "sent",
299
+ "in",
300
+ "out",
301
+ "allowed",
302
+ "required"
303
+ ]);
304
+ var ORGANISATION_WORDS = /* @__PURE__ */ new Set([
305
+ "company",
306
+ "business",
307
+ "org",
308
+ "organisation",
309
+ "organization",
310
+ "merchant",
311
+ "vendor",
312
+ "supplier",
313
+ "firm",
314
+ "branch",
315
+ "office",
316
+ "school",
317
+ "institute",
318
+ "college"
319
+ ]);
320
+ function tokenize(name) {
321
+ 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);
322
+ }
323
+ function containsRun(tokens, run) {
324
+ outer: for (let i = 0; i + run.length <= tokens.length; i++) {
325
+ for (let j = 0; j < run.length; j++) if (tokens[i + j] !== run[j]) continue outer;
326
+ return true;
327
+ }
328
+ return false;
329
+ }
330
+ function guessPersonal(columnName) {
331
+ const tokens = tokenize(columnName);
332
+ if (tokens.length === 0) return void 0;
333
+ const last = tokens[tokens.length - 1];
334
+ if (tokens.length > 1 && DESCRIPTIVE_ENDINGS.has(last)) return void 0;
335
+ const organisational = tokens.some((t) => ORGANISATION_WORDS.has(t));
336
+ for (const r of RULES) {
337
+ if (containsRun(tokens, r.tokens)) {
338
+ return {
339
+ category: r.category,
340
+ confidence: organisational ? "weak" : r.confidence,
341
+ matched: r.tokens.join(" ")
342
+ };
343
+ }
344
+ }
345
+ return void 0;
346
+ }
347
+
348
+ // src/schema-check.ts
349
+ var OWN_TABLE_PREFIX = "dpdp_";
350
+ var matches = (column, name) => column.name === name || column.key === name;
351
+ function parseNotPersonal(entries) {
352
+ const columns = /* @__PURE__ */ new Set();
353
+ const tables = /* @__PURE__ */ new Set();
354
+ for (const entry of entries ?? []) {
355
+ const dot = entry.lastIndexOf(".");
356
+ if (dot <= 0) continue;
357
+ const table = entry.slice(0, dot);
358
+ const column = entry.slice(dot + 1);
359
+ if (column === "*") tables.add(table);
360
+ else columns.add(`${table}.${column}`);
361
+ }
362
+ return { columns, tables };
363
+ }
364
+ function strongest(a, b) {
365
+ if (!a) return b;
366
+ if (!b) return a;
367
+ return b.confidence === "strong" && a.confidence === "weak" ? b : a;
368
+ }
369
+ function checkSchema(config, schema) {
370
+ const issues = [];
371
+ const byName = /* @__PURE__ */ new Map();
372
+ for (const table of schema.tables) if (!byName.has(table.name)) byName.set(table.name, table);
373
+ const mapped = /* @__PURE__ */ new Map();
374
+ for (const [key, def] of Object.entries(config.data ?? {})) {
375
+ const table = byName.get(def.table);
376
+ if (!table) {
377
+ issues.push({
378
+ level: "error",
379
+ code: "unknown-table",
380
+ path: `data.${key}.table`,
381
+ message: `Table "${def.table}" isn't in the schema. Fix the name, or remove it from the data map if the table is gone.`
382
+ });
383
+ continue;
384
+ }
385
+ const list = mapped.get(table.name) ?? [];
386
+ const subject = table.columns.find((c) => matches(c, def.subject));
387
+ if (subject) list.push(subject);
388
+ else {
389
+ issues.push({
390
+ level: "error",
391
+ code: "unknown-column",
392
+ path: `data.${key}.subject`,
393
+ message: `Column "${def.subject}" isn't in table "${table.name}". The subject column must exist to find a person's rows.`
394
+ });
395
+ }
396
+ for (const field of Object.keys(def.fields ?? {})) {
397
+ const column = table.columns.find((c) => matches(c, field));
398
+ if (column) list.push(column);
399
+ else {
400
+ issues.push({
401
+ level: "error",
402
+ code: "unknown-column",
403
+ path: `data.${key}.fields.${field}`,
404
+ message: `Column "${field}" isn't in table "${table.name}". Fix the name, or remove it if the column was dropped.`
405
+ });
406
+ }
407
+ }
408
+ mapped.set(table.name, list);
409
+ }
410
+ const ignore = parseNotPersonal(config.notPersonal);
411
+ for (const entry of config.notPersonal ?? []) {
412
+ const dot = entry.lastIndexOf(".");
413
+ const tableName = entry.slice(0, Math.max(dot, 0));
414
+ const columnName = entry.slice(dot + 1);
415
+ const table = byName.get(tableName);
416
+ const exists = table && (columnName === "*" || table.columns.some((c) => matches(c, columnName)));
417
+ if (!exists) {
418
+ issues.push({
419
+ level: "warning",
420
+ code: "stale-not-personal",
421
+ path: "notPersonal",
422
+ message: `"${entry}" doesn't match any table or column. Use "table.column" or "table.*", or remove it.`
423
+ });
424
+ }
425
+ }
426
+ for (const table of byName.values()) {
427
+ if (table.name.startsWith(OWN_TABLE_PREFIX) || ignore.tables.has(table.name)) continue;
428
+ const known = mapped.get(table.name) ?? [];
429
+ for (const column of table.columns) {
430
+ if (known.includes(column)) continue;
431
+ if (ignore.columns.has(`${table.name}.${column.name}`)) continue;
432
+ if (column.key && ignore.columns.has(`${table.name}.${column.key}`)) continue;
433
+ const guess = strongest(guessPersonal(column.name), column.key ? guessPersonal(column.key) : void 0);
434
+ if (!guess) continue;
435
+ issues.push({
436
+ level: guess.confidence === "strong" ? "error" : "warning",
437
+ code: "unmapped-personal-column",
438
+ path: `schema.${table.name}.${column.name}`,
439
+ 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\`.`
440
+ });
441
+ }
442
+ }
443
+ return issues;
444
+ }
445
+
446
+ export {
447
+ isDuration,
448
+ durationMs,
449
+ maxDuration,
450
+ audit,
451
+ hasErrors,
452
+ tokenize,
453
+ guessPersonal,
454
+ checkSchema
455
+ };
package/dist/cli.js CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- audit
4
- } from "./chunk-HRKHRKV4.js";
3
+ audit,
4
+ checkSchema
5
+ } from "./chunk-MX5FRZQT.js";
5
6
 
6
7
  // src/run-audit.ts
7
8
  import { existsSync } from "fs";
@@ -12,10 +13,13 @@ function findConfig(cwd, explicit) {
12
13
  if (explicit) return resolve(cwd, explicit);
13
14
  return CONFIG_FILES.map((f) => resolve(cwd, f)).find((f) => existsSync(f));
14
15
  }
15
- async function loadConfig(file) {
16
+ async function loadModule(file) {
16
17
  const { createJiti } = await import("jiti");
17
18
  const jiti = createJiti(pathToFileURL(file).href);
18
- const mod = await jiti.import(file);
19
+ return await jiti.import(file);
20
+ }
21
+ async function loadConfig(file) {
22
+ const mod = await loadModule(file);
19
23
  const config = [mod.default, mod.config, mod.default?.config].find(
20
24
  (c) => typeof c === "object" && c !== null && "purposes" in c
21
25
  );
@@ -35,16 +39,41 @@ function formatIssues(issues) {
35
39
  lines.push("", `${errors.length} error(s), ${warnings.length} warning(s)`);
36
40
  return lines.join("\n");
37
41
  }
42
+ async function loadDrizzleSchema(file) {
43
+ const mod = await loadModule(file);
44
+ let drizzleSchema;
45
+ try {
46
+ ({ drizzleSchema } = await import("./drizzle.js"));
47
+ } catch {
48
+ throw new Error("--schema reads a Drizzle schema, so drizzle-orm must be installed in this project.");
49
+ }
50
+ const schema = drizzleSchema(mod);
51
+ if (schema.tables.length === 0) {
52
+ throw new Error(`${file} exports no Drizzle tables. Point --schema at the file that defines them.`);
53
+ }
54
+ return schema;
55
+ }
56
+ var flagValue = (argv, flag) => {
57
+ const i = argv.indexOf(flag);
58
+ return i >= 0 ? argv[i + 1] : void 0;
59
+ };
38
60
  async function runAudit(argv, cwd, log) {
39
- const configFlag = argv.indexOf("--config");
40
- const explicit = configFlag >= 0 ? argv[configFlag + 1] : void 0;
61
+ const explicit = flagValue(argv, "--config");
62
+ const schemaFlag = flagValue(argv, "--schema");
41
63
  const strict = argv.includes("--strict");
42
64
  const file = findConfig(cwd, explicit);
43
65
  if (!file || !existsSync(file)) {
44
66
  log(explicit ? `Config file not found: ${explicit}` : `No config found. Create one of: ${CONFIG_FILES.join(", ")}`);
45
67
  return 1;
46
68
  }
47
- const issues = audit(await loadConfig(file));
69
+ const schemaFile = schemaFlag ? resolve(cwd, schemaFlag) : void 0;
70
+ if (schemaFile && !existsSync(schemaFile)) {
71
+ log(`Schema file not found: ${schemaFlag}`);
72
+ return 1;
73
+ }
74
+ const config = await loadConfig(file);
75
+ const issues = audit(config);
76
+ if (schemaFile) issues.push(...checkSchema(config, await loadDrizzleSchema(schemaFile)));
48
77
  log(formatIssues(issues));
49
78
  const failing = issues.filter((i) => i.level === "error" || strict && i.level === "warning");
50
79
  return failing.length > 0 ? 1 : 0;
@@ -54,10 +83,15 @@ async function runAudit(argv, cwd, log) {
54
83
  var HELP = `dpdp-kit \u2014 DPDP Act tooling for Node.js
55
84
 
56
85
  Usage:
57
- dpdp-kit audit [--config <file>] [--strict] Check your data map and purposes
86
+ dpdp-kit audit [--config <file>] [--schema <file>] [--strict]
87
+
88
+ Checks your data map and purposes. With --schema, also compares the data map with your
89
+ Drizzle schema: personal-looking columns missing from the map, and map entries that no
90
+ longer exist.
58
91
 
59
92
  Options:
60
93
  --config <file> Config file (default: dpdp.config.ts / .mts / .js / .mjs)
94
+ --schema <file> Drizzle schema file (Postgres, MySQL or SQLite), e.g. src/db/schema.ts
61
95
  --strict Fail on warnings too
62
96
  `;
63
97
  var [command, ...rest] = process.argv.slice(2);
package/dist/config.d.ts CHANGED
@@ -92,6 +92,11 @@ export interface DpdpConfig<P extends string = string> {
92
92
  * security investigations.
93
93
  */
94
94
  minimumRetention?: Duration;
95
+ /**
96
+ * Columns whose names look personal but aren't, for the schema drift check: `"products.name"`,
97
+ * or `"products.*"` for a whole table. Use database table and column names.
98
+ */
99
+ notPersonal?: readonly string[];
95
100
  }
96
101
  /** Purpose names of a config, e.g. `"account" | "marketing_sms"`. */
97
102
  export type PurposeOf<C> = C extends DpdpConfig<infer P> ? P : never;
package/dist/drizzle.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type PgDatabase } from "drizzle-orm/pg-core";
2
+ import type { Schema } from "./schema-check.js";
2
3
  import type { ConsentStore } from "./store.js";
3
4
  /**
4
5
  * The consent events table. Export it from your Drizzle schema so drizzle-kit creates it:
@@ -213,4 +214,14 @@ type AnyPgDatabase = PgDatabase<any, any, any>;
213
214
  * PGlite and other Drizzle Postgres drivers.
214
215
  */
215
216
  export declare function drizzleStore(db: AnyPgDatabase): ConsentStore;
217
+ /**
218
+ * Read a Drizzle schema module (Postgres, MySQL or SQLite) for `checkSchema()`. Pass the module
219
+ * itself, so every exported table is found:
220
+ *
221
+ * ```ts
222
+ * import * as schema from "./db/schema";
223
+ * checkSchema(config, drizzleSchema(schema));
224
+ * ```
225
+ */
226
+ export declare function drizzleSchema(module: Record<string, unknown>): Schema;
216
227
  export {};
package/dist/drizzle.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-67Q5GFD6.js";
4
4
 
5
5
  // src/drizzle.ts
6
- import { asc, desc, eq } from "drizzle-orm";
6
+ import { asc, desc, eq, getTableColumns, getTableName, is, Table } from "drizzle-orm";
7
7
  import { integer, jsonb, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
8
8
  var consentEvents = pgTable(
9
9
  "dpdp_consent_events",
@@ -90,8 +90,22 @@ function drizzleStore(db) {
90
90
  }
91
91
  };
92
92
  }
93
+ function drizzleSchema(module) {
94
+ const tables = /* @__PURE__ */ new Map();
95
+ for (const value of Object.values(module)) {
96
+ if (!is(value, Table)) continue;
97
+ const name = getTableName(value);
98
+ if (tables.has(name)) continue;
99
+ const columns = Object.entries(getTableColumns(value)).map(
100
+ ([key, column]) => key === column.name ? { name: column.name } : { name: column.name, key }
101
+ );
102
+ tables.set(name, { name, columns });
103
+ }
104
+ return { tables: [...tables.values()] };
105
+ }
93
106
  export {
94
107
  CONSENT_EVENTS_DDL,
95
108
  consentEvents,
109
+ drizzleSchema,
96
110
  drizzleStore
97
111
  };
package/dist/index.d.ts CHANGED
@@ -6,4 +6,6 @@ export { type ErasurePlan, type ErasureReason, type FieldPlan, type PlanInput, t
6
6
  export { DpdpError, type DpdpErrorCode, SeqConflictError } from "./errors.js";
7
7
  export { CONSENT_REQUIRED_BODY, type GuardOptions } from "./guard.js";
8
8
  export { isNoticeLanguage, NOTICE_LANGUAGES, type NoticeLanguage } from "./languages.js";
9
+ export { type Confidence, guessPersonal, type PersonalGuess, tokenize } from "./personal.js";
10
+ export { checkSchema, type Schema, type SchemaColumn, type SchemaTable } from "./schema-check.js";
9
11
  export { type ConsentAction, type ConsentEvent, type ConsentStore, memoryStore } from "./store.js";
package/dist/index.js CHANGED
@@ -7,11 +7,14 @@ import {
7
7
  } from "./chunk-FGZAH2NF.js";
8
8
  import {
9
9
  audit,
10
+ checkSchema,
10
11
  durationMs,
12
+ guessPersonal,
11
13
  hasErrors,
12
14
  isDuration,
13
- maxDuration
14
- } from "./chunk-HRKHRKV4.js";
15
+ maxDuration,
16
+ tokenize
17
+ } from "./chunk-MX5FRZQT.js";
15
18
 
16
19
  // src/config.ts
17
20
  function defineConfig(config) {
@@ -307,14 +310,17 @@ export {
307
310
  NOTICE_LANGUAGES,
308
311
  SeqConflictError,
309
312
  audit,
313
+ checkSchema,
310
314
  createDpdp,
311
315
  defineConfig,
312
316
  durationMs,
317
+ guessPersonal,
313
318
  hasErrors,
314
319
  hashEvent,
315
320
  isDuration,
316
321
  isNoticeLanguage,
317
322
  memoryStore,
318
323
  planErasure,
319
- purposeNames
324
+ purposeNames,
325
+ tokenize
320
326
  };
@@ -0,0 +1,17 @@
1
+ import type { Category } from "./config.js";
2
+ /**
3
+ * How sure we are that a column holds personal data, judging only by its name.
4
+ * - `strong`: almost always personal (phone, email, aadhaar, date_of_birth, ip_address…).
5
+ * - `weak`: often personal, often not (`name` is a person in `users` but a product in `products`).
6
+ */
7
+ export type Confidence = "strong" | "weak";
8
+ export interface PersonalGuess {
9
+ category: Category;
10
+ confidence: Confidence;
11
+ /** What matched, for the audit message, e.g. `"phone"`. */
12
+ matched: string;
13
+ }
14
+ /** `phoneNumber`, `phone_number`, `PhoneNumber`, `phone-number` → `["phone", "number"]`. */
15
+ export declare function tokenize(name: string): string[];
16
+ /** Guess, from its name alone, whether a column holds personal data. */
17
+ export declare function guessPersonal(columnName: string): PersonalGuess | undefined;
@@ -1,9 +1,12 @@
1
1
  import { type Issue } from "./audit.js";
2
2
  import type { DpdpConfig } from "./config.js";
3
+ import { type Schema } from "./schema-check.js";
3
4
  export declare const CONFIG_FILES: string[];
4
5
  export declare function findConfig(cwd: string, explicit?: string): string | undefined;
5
6
  /** Load a config file (TypeScript or JavaScript). Accepts a default export or `export const config`. */
6
7
  export declare function loadConfig(file: string): Promise<DpdpConfig<string>>;
7
8
  export declare function formatIssues(issues: readonly Issue[]): string;
9
+ /** Load a Drizzle schema file and read its tables. */
10
+ export declare function loadDrizzleSchema(file: string): Promise<Schema>;
8
11
  /** Run `dpdp-kit audit`. Returns the exit code: 1 when there are errors (or `--strict` and warnings). */
9
12
  export declare function runAudit(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
@@ -0,0 +1,22 @@
1
+ import type { Issue } from "./audit.js";
2
+ import type { DpdpConfig } from "./config.js";
3
+ /** A column as your ORM sees it: its database name, and the property name in code if different. */
4
+ export interface SchemaColumn {
5
+ name: string;
6
+ key?: string;
7
+ }
8
+ export interface SchemaTable {
9
+ name: string;
10
+ columns: readonly SchemaColumn[];
11
+ }
12
+ /** Your database schema in a neutral shape. `drizzleSchema()` builds one from a Drizzle schema. */
13
+ export interface Schema {
14
+ tables: readonly SchemaTable[];
15
+ }
16
+ /**
17
+ * Compare the data map with the real schema, both ways:
18
+ * - columns that look personal but aren't in the data map (strong guesses are errors, weak ones
19
+ * warnings), so a new `phone` column can't ship without a purpose;
20
+ * - data map entries whose table or column no longer exists, so the map can't go stale.
21
+ */
22
+ export declare function checkSchema(config: DpdpConfig<string>, schema: Schema): Issue[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dpdp-kit",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Build India's DPDP Act 2023 into your Node.js backend: declared purposes, tamper-evident consent records, erasure plans and an audit you can run in CI.",
5
5
  "keywords": [
6
6
  "dpdp",
@@ -1,185 +0,0 @@
1
- // src/duration.ts
2
- var PATTERN = /^(\d+)(h|d|y)$/;
3
- var HOUR_MS = 60 * 60 * 1e3;
4
- var UNIT_MS = { h: HOUR_MS, d: 24 * HOUR_MS, y: 365 * 24 * HOUR_MS };
5
- function isDuration(value) {
6
- return typeof value === "string" && PATTERN.test(value);
7
- }
8
- function durationMs(value) {
9
- const match = PATTERN.exec(value);
10
- if (!match) throw new TypeError(`Not a duration: ${JSON.stringify(value)} (use e.g. "48h", "30d", "1y")`);
11
- const [, amount, unit] = match;
12
- return Number(amount) * UNIT_MS[unit];
13
- }
14
- function maxDuration(a, b) {
15
- return durationMs(b) > durationMs(a) ? b : a;
16
- }
17
-
18
- // src/audit.ts
19
- var ONE_YEAR_MS = durationMs("1y");
20
- function checkRetention(retain, path, issues) {
21
- if (retain === "while-active" || isDuration(retain)) return;
22
- if (retain && typeof retain === "object" && "afterWithdrawal" in retain) {
23
- if (!isDuration(retain.afterWithdrawal)) {
24
- issues.push({
25
- level: "error",
26
- code: "invalid-duration",
27
- path: `${path}.afterWithdrawal`,
28
- message: `${JSON.stringify(retain.afterWithdrawal)} is not a duration. Use e.g. "0d", "30d", "1y".`
29
- });
30
- }
31
- return;
32
- }
33
- issues.push({
34
- level: "error",
35
- code: "invalid-retention",
36
- path,
37
- message: `Retention must be "while-active", a duration like "1y", or { afterWithdrawal: "30d" }.`
38
- });
39
- }
40
- function checkPurposeList(purposes, known, used, path, issues) {
41
- if (!purposes || purposes.length === 0) {
42
- issues.push({
43
- level: "error",
44
- code: "field-without-purpose",
45
- path: `${path}.purposes`,
46
- message: "List at least one purpose. Personal data with no purpose must not be collected."
47
- });
48
- return;
49
- }
50
- for (const p of purposes) {
51
- used.add(p);
52
- if (!known.has(p)) {
53
- issues.push({
54
- level: "error",
55
- code: "unknown-purpose",
56
- path: `${path}.purposes`,
57
- message: `Unknown purpose ${JSON.stringify(p)}. Declare it under \`purposes\` or fix the spelling.`
58
- });
59
- }
60
- }
61
- }
62
- function audit(config) {
63
- const issues = [];
64
- const purposes = config.purposes ?? {};
65
- const known = new Set(Object.keys(purposes));
66
- const used = /* @__PURE__ */ new Set();
67
- if (!config.fiduciary?.name) {
68
- issues.push({
69
- level: "error",
70
- code: "fiduciary-missing",
71
- path: "fiduciary.name",
72
- message: "Name the Data Fiduciary (your organisation). It appears on every notice."
73
- });
74
- }
75
- if (!config.fiduciary?.grievanceUrl) {
76
- issues.push({
77
- level: "warning",
78
- code: "grievance-missing",
79
- path: "fiduciary.grievanceUrl",
80
- 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."
81
- });
82
- }
83
- if (known.size === 0) {
84
- issues.push({ level: "error", code: "no-purposes", path: "purposes", message: "Declare at least one purpose." });
85
- }
86
- for (const [name, def] of Object.entries(purposes)) {
87
- const path = `purposes.${name}`;
88
- if (def.basis !== "consent" && def.basis !== "legitimate-use") {
89
- issues.push({
90
- level: "error",
91
- code: "invalid-basis",
92
- path: `${path}.basis`,
93
- message: `Basis must be "consent" or "legitimate-use".`
94
- });
95
- }
96
- checkRetention(def.retain, `${path}.retain`, issues);
97
- if (def.basis === "legitimate-use" && typeof def.retain === "object") {
98
- issues.push({
99
- level: "error",
100
- code: "invalid-retention",
101
- path: `${path}.retain`,
102
- message: 'afterWithdrawal only applies to consent purposes (Section 6(4)). Use "while-active" or a duration for a legitimate use.'
103
- });
104
- }
105
- }
106
- for (const [key, table] of Object.entries(config.data ?? {})) {
107
- const path = `data.${key}`;
108
- if (!table.subject) {
109
- issues.push({
110
- level: "error",
111
- code: "missing-subject-column",
112
- path: `${path}.subject`,
113
- message: "Name the column that holds the person's id, so their rows can be found."
114
- });
115
- }
116
- const fields = Object.entries(table.fields ?? {});
117
- if (fields.length === 0) {
118
- issues.push({
119
- level: "warning",
120
- code: "table-without-fields",
121
- path: `${path}.fields`,
122
- message: "No personal fields listed. Remove the table from the map, or list its fields."
123
- });
124
- }
125
- for (const [field, def] of fields) {
126
- checkPurposeList(def.purposes, known, used, `${path}.fields.${field}`, issues);
127
- }
128
- if (table.legalHold && !isDuration(table.legalHold.keep)) {
129
- issues.push({
130
- level: "error",
131
- code: "invalid-duration",
132
- path: `${path}.legalHold.keep`,
133
- message: `${JSON.stringify(table.legalHold.keep)} is not a duration. Use e.g. "8y".`
134
- });
135
- }
136
- }
137
- for (const [name, processor] of Object.entries(config.processors ?? {})) {
138
- checkPurposeList(processor.purposes, known, used, `processors.${name}`, issues);
139
- }
140
- for (const name of known) {
141
- if (!used.has(name)) {
142
- issues.push({
143
- level: "warning",
144
- code: "unused-purpose",
145
- path: `purposes.${name}`,
146
- message: "No field or processor uses this purpose. Remove it, or map the data it covers."
147
- });
148
- }
149
- }
150
- const minimum = config.minimumRetention;
151
- if (minimum === void 0) {
152
- issues.push({
153
- level: "warning",
154
- code: "minimum-retention-missing",
155
- path: "minimumRetention",
156
- 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").'
157
- });
158
- } else if (!isDuration(minimum)) {
159
- issues.push({
160
- level: "error",
161
- code: "invalid-duration",
162
- path: "minimumRetention",
163
- message: `${JSON.stringify(minimum)} is not a duration. Use e.g. "1y".`
164
- });
165
- } else if (durationMs(minimum) < ONE_YEAR_MS) {
166
- issues.push({
167
- level: "error",
168
- code: "minimum-retention-too-short",
169
- path: "minimumRetention",
170
- 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".'
171
- });
172
- }
173
- return issues;
174
- }
175
- function hasErrors(issues) {
176
- return issues.some((i) => i.level === "error");
177
- }
178
-
179
- export {
180
- isDuration,
181
- durationMs,
182
- maxDuration,
183
- audit,
184
- hasErrors
185
- };