dpdp-scanner 0.0.0-stage → 1.0.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/dist/index.js ADDED
@@ -0,0 +1,693 @@
1
+ // src/scan.ts
2
+ import { open, readdir, readFile, stat } from "fs/promises";
3
+ import { join, relative, sep } from "path";
4
+ import { DEFAULT_TYPES, detect, maskValue } from "dpdp-india";
5
+
6
+ // src/fields.ts
7
+ var CATEGORIES = {
8
+ "government-id": { label: "Government ID", sensitivity: "high" },
9
+ financial: { label: "Financial", sensitivity: "high" },
10
+ health: { label: "Health", sensitivity: "high" },
11
+ biometric: { label: "Biometric", sensitivity: "high" },
12
+ children: { label: "Children's data", sensitivity: "high" },
13
+ "date-of-birth": { label: "Date of birth / age", sensitivity: "medium" },
14
+ demographic: { label: "Demographic", sensitivity: "medium" },
15
+ contact: { label: "Contact", sensitivity: "medium" },
16
+ address: { label: "Address", sensitivity: "medium" },
17
+ location: { label: "Location", sensitivity: "medium" },
18
+ name: { label: "Name", sensitivity: "medium" },
19
+ "online-identifier": { label: "Online identifier", sensitivity: "low" }
20
+ };
21
+ var CATEGORY_NOTES = {
22
+ "government-id": "Government IDs (Aadhaar, PAN, passport\u2026): keep them only where you need them, and mask, encrypt or tokenise them everywhere else.",
23
+ financial: "Financial data: encrypt at rest, restrict access, and keep it out of logs and analytics.",
24
+ health: "Health data: encrypt at rest and limit access to the people who need it.",
25
+ biometric: "Biometric data: store templates rather than raw images where you can, encrypted, with strict access control.",
26
+ children: "Children's data: the DPDP Act requires verifiable consent from a parent or guardian before processing personal data of anyone under 18.",
27
+ "date-of-birth": "Date of birth and age can tell you a user is under 18, which brings the DPDP Act's parental-consent rules into play."
28
+ };
29
+ var CVV_NOTE = "Card security codes (CVV/CVC) must never be stored after authorisation (PCI DSS).";
30
+ var w = (body) => new RegExp(`(?:^|_)(?:${body})(?:_|$)`);
31
+ var RULES = [
32
+ // Not personal data on their own: stop these before the general rules catch them.
33
+ { pattern: w("(?:file|table|column|product|company|org|organi[sz]ation|business|brand|host|domain|app|project|display|role|class|module|package|bank|branch|city|state|country|category|event|tag|plan|model|device|template|field|key|attr|attribute|type|step|page|route|queue|bucket|channel|group|team|store|shop|vendor|item|service)_name"), category: "name", label: "", confidence: "low" },
34
+ { pattern: w("(?:mac|wallet|contract|server|base|smart_contract|token|router|memory|start|end|return|web|url|redirect|callback|webhook|bind|listen|proxy|gateway|broadcast|multicast|subnet)_addr(?:ess)?"), category: "online-identifier", label: "", confidence: "low" },
35
+ // Account handles, not names. Whole-name match only, so `last_login_ip` still counts as an IP address.
36
+ { pattern: /^(?:user_?name|login|login_id|handle|nickname|nick_name|screen_name|display_name)$/, category: "name", label: "", confidence: "low" },
37
+ // Matched early: both contain "address", which the postal address rule would otherwise take.
38
+ { pattern: w("e_?mail(?:_(?:id|address|addr))?|mail_id"), category: "contact", label: "Email address", confidence: "high" },
39
+ { pattern: w("ip_?(?:address|addr|v4|v6)|client_ip|remote_ip|user_ip|last_ip|signup_ip|login_ip|remote_addr(?:ess)?|ip"), category: "online-identifier", label: "IP address", confidence: "medium" },
40
+ // Government IDs
41
+ { pattern: w("aadh?aa?r|adhaa?r|aadhar|uidai|uid_(?:no|num|number)"), category: "government-id", label: "Aadhaar number", confidence: "high" },
42
+ { pattern: w("aadhaar_vid|virtual_id"), category: "government-id", label: "Aadhaar virtual ID", confidence: "medium" },
43
+ { pattern: w("pan_(?:no|num|number|card|id)|pancard|pan_card_no|pan_card_number"), category: "government-id", label: "PAN", confidence: "high" },
44
+ { pattern: w("pan"), category: "government-id", label: "PAN", confidence: "medium" },
45
+ { pattern: w("gstin|gst_(?:no|num|number|in)"), category: "government-id", label: "GSTIN", confidence: "medium" },
46
+ { pattern: w("passport(?:_(?:no|num|number|id))?"), category: "government-id", label: "Passport number", confidence: "high" },
47
+ { pattern: w("voter_id|voterid|epic(?:_(?:no|num|number))?"), category: "government-id", label: "Voter ID (EPIC)", confidence: "high" },
48
+ { pattern: w("(?:driving_)?licen[cs]e_(?:no|num|number)|dl_(?:no|num|number)|driving_licen[cs]e"), category: "government-id", label: "Driving licence number", confidence: "high" },
49
+ { pattern: w("ration_card(?:_(?:no|num|number))?"), category: "government-id", label: "Ration card number", confidence: "high" },
50
+ { pattern: w("ssn|social_security(?:_number)?|national_id|tax_id|(?:tin|nid)_(?:no|num|number)"), category: "government-id", label: "National or tax ID", confidence: "medium" },
51
+ // Short codes only count as the whole name: `tin`, but not `tin_can`.
52
+ { pattern: /^(?:tin|nid)$/, category: "government-id", label: "National or tax ID", confidence: "low" },
53
+ { pattern: w("abha(?:_(?:no|num|number|id|address))?|health_id"), category: "health", label: "ABHA health ID", confidence: "high" },
54
+ // Financial
55
+ { pattern: w("cvv\\d?|cvc\\d?|card_(?:cvv|cvc|security_code)|security_code"), category: "financial", label: "Card security code (CVV)", confidence: "high", note: CVV_NOTE },
56
+ { pattern: w("(?:credit|debit)?_?card_(?:no|num|number)|card_number|cc_(?:no|num|number)|credit_card|debit_card|pan_card_number"), category: "financial", label: "Card number", confidence: "high" },
57
+ { pattern: w("(?:bank_)?account_(?:no|num|number)|acc(?:t)?_(?:no|num|number)|bank_account|iban"), category: "financial", label: "Bank account number", confidence: "high" },
58
+ { pattern: w("ifsc(?:_code)?"), category: "financial", label: "IFSC code", confidence: "medium" },
59
+ { pattern: w("upi(?:_id|_address|_handle)?|vpa"), category: "financial", label: "UPI ID", confidence: "high" },
60
+ { pattern: w("salary|income|ctc|annual_income|net_worth|credit_score|cibil(?:_score)?"), category: "financial", label: "Income or credit score", confidence: "medium" },
61
+ // Health
62
+ { pattern: w("blood_(?:group|type)"), category: "health", label: "Blood group", confidence: "high" },
63
+ { pattern: w("medical(?:_\\w+)?|diagnos[ie]s|disease|illness|prescription|medication|allerg(?:y|ies)|disabilit(?:y|ies)|treatment|symptoms?|health_(?:record|condition|status|data|info)|mental_health|pregnan(?:t|cy)"), category: "health", label: "Health information", confidence: "high" },
64
+ // Biometric
65
+ { pattern: w("biometric(?:_\\w+)?|fingerprint|finger_print|thumb_?print|iris(?:_scan)?|retina|face_(?:id|data|template|encoding|embedding|vector|scan)|facial_\\w+|voice_?print|palm_?print"), category: "biometric", label: "Biometric data", confidence: "high" },
66
+ { pattern: w("selfie|photo|photograph|profile_(?:photo|pic|picture|image)|avatar|headshot"), category: "biometric", label: "Photo of a person", confidence: "low" },
67
+ // Children
68
+ { pattern: w("guardian(?:_\\w+)?|parent_(?:name|email|phone|mobile|consent)|parental_consent|is_minor|is_child|minor_(?:name|age|dob)|child_(?:name|age|dob)"), category: "children", label: "Child or guardian information", confidence: "high" },
69
+ // Date of birth
70
+ { pattern: w("dob|date_of_birth|birth_?date|birthday|birth_year|year_of_birth"), category: "date-of-birth", label: "Date of birth", confidence: "high" },
71
+ { pattern: w("age"), category: "date-of-birth", label: "Age", confidence: "medium" },
72
+ // Demographic
73
+ { pattern: w("gender|sex"), category: "demographic", label: "Gender", confidence: "high" },
74
+ { pattern: w("religion|caste|sub_caste|tribe"), category: "demographic", label: "Religion or caste", confidence: "high" },
75
+ { pattern: w("marital_status|nationality|mother_tongue|sexual_orientation|political_\\w+"), category: "demographic", label: "Personal characteristics", confidence: "high" },
76
+ // Contact (email is matched near the top)
77
+ { pattern: w("(?:mobile|phone|cell|contact|whatsapp|alternate|alt|emergency|home|work|primary|secondary)_?(?:no|num|number|phone|mobile)|phone(?:_number)?|mobile(?:_number)?|msisdn|telephone|tel|whatsapp|landline"), category: "contact", label: "Phone number", confidence: "high" },
78
+ // Address
79
+ { pattern: w("(?:home|postal|permanent|current|residential|billing|shipping|delivery|mailing|street|correspondence)?_?addr(?:ess)?(?:_line)?_?\\d?|street(?:_\\w+)?|house_(?:no|number|name)|flat_(?:no|number)|landmark|locality"), category: "address", label: "Postal address", confidence: "high" },
80
+ { pattern: w("pin_?code|postal_code|post_code|zip(?:_?code)?"), category: "address", label: "PIN code", confidence: "medium" },
81
+ // Location
82
+ { pattern: w("lat(?:itude)?|lng|lon|longitude|geo_?(?:location|point|lat|lng)?|gps(?:_\\w+)?|coordinates|current_location|last_location|live_location|user_location"), category: "location", label: "Location", confidence: "medium" },
83
+ { pattern: w("location"), category: "location", label: "Location", confidence: "low" },
84
+ // Name
85
+ { pattern: w("(?:first|last|full|middle|given|family|sur|maiden|legal|father|mother|spouse|husband|wife|nominee|customer|patient|employee|student|applicant|account_holder|card_holder|holder|contact|member|beneficiary)_?name|surname|fname|lname"), category: "name", label: "Person's name", confidence: "high" },
86
+ { pattern: w("name"), category: "name", label: "Name", confidence: "low" },
87
+ // Online identifiers (IP address is matched near the top)
88
+ { pattern: w("imei|device_(?:id|uuid|fingerprint)|advertising_id|ad_id|gaid|idfa|idfv|android_id"), category: "online-identifier", label: "Device identifier", confidence: "medium" }
89
+ ];
90
+ var PERSON_TABLE = /(?:^|_)(?:users?|customers?|clients?|members?|employees?|staff|patients?|students?|persons?|people|contacts?|profiles?|accounts?|applicants?|candidates?|guardians?|parents?|beneficiar(?:y|ies)|nominees?|leads?|subscribers?|tenants?|drivers?|riders?|passengers?|guests?|visitors?|kyc|borrowers?|policyholders?|donors?|volunteers?|teachers?|doctors?)(?:_|$)/;
91
+ function words(name) {
92
+ return name.replace(/([a-z\d])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase().split(/[^a-z\d]+/).filter(Boolean);
93
+ }
94
+ function classifyField(field, table) {
95
+ const key = words(field).join("_");
96
+ if (!key) return null;
97
+ for (const rule of RULES) {
98
+ if (!rule.pattern.test(key)) continue;
99
+ if (!rule.label) return null;
100
+ let confidence = rule.confidence;
101
+ if (rule.label === "Name" && table && PERSON_TABLE.test(words(table).join("_"))) confidence = "medium";
102
+ const { sensitivity } = CATEGORIES[rule.category];
103
+ return { category: rule.category, label: rule.label, sensitivity, confidence, ...rule.note ? { note: rule.note } : {} };
104
+ }
105
+ return null;
106
+ }
107
+
108
+ // src/schemas.ts
109
+ var lineAt = (text, index) => text.slice(0, index).split("\n").length;
110
+ var bare = (name) => name.replace(/["`[\]]/g, "").split(".").pop().trim();
111
+ function closing(text, open2) {
112
+ const pairs = { "(": ")", "{": "}", "[": "]" };
113
+ const want = pairs[text[open2]];
114
+ const start = text[open2];
115
+ let depth = 0;
116
+ for (let i = open2; i < text.length; i++) {
117
+ const c = text[i];
118
+ if (c === '"' || c === "'" || c === "`") {
119
+ const end = text.indexOf(c, i + 1);
120
+ if (end === -1) return -1;
121
+ i = end;
122
+ } else if (c === start) depth++;
123
+ else if (c === want && --depth === 0) return i;
124
+ }
125
+ return -1;
126
+ }
127
+ function splitTop(text, offset) {
128
+ const out = [];
129
+ let depth = 0;
130
+ let start = 0;
131
+ for (let i = 0; i < text.length; i++) {
132
+ const c = text[i];
133
+ if (c === "(" || c === "{" || c === "[") depth++;
134
+ else if (c === ")" || c === "}" || c === "]") depth--;
135
+ else if (c === "'" || c === '"' || c === "`") {
136
+ const end = text.indexOf(c, i + 1);
137
+ if (end !== -1) i = end;
138
+ } else if (c === "," && depth === 0) {
139
+ out.push({ part: text.slice(start, i), at: offset + start });
140
+ start = i + 1;
141
+ }
142
+ }
143
+ out.push({ part: text.slice(start), at: offset + start });
144
+ return out;
145
+ }
146
+ function blankComments(text, style) {
147
+ const blank = (m) => m.replace(/[^\n]/g, " ");
148
+ if (style === "sql") return text.replace(/--[^\n]*/g, blank).replace(/\/\*[\s\S]*?\*\//g, blank);
149
+ if (style === "hash") return text.replace(/(^|\s)#[^\n]*/g, blank);
150
+ return text.replace(/\/\*[\s\S]*?\*\//g, blank).replace(/(^|[^:"'])\/\/[^\n]*/g, (m, p) => p + blank(m.slice(p.length)));
151
+ }
152
+ function objectKeys(text, open2, table, source, src) {
153
+ const close = closing(text, open2);
154
+ if (close === -1) return [];
155
+ const out = [];
156
+ for (const { part, at } of splitTop(text.slice(open2 + 1, close), open2 + 1)) {
157
+ const m = /^\s*(?:["'`]?)([A-Za-z_$][\w$]*)(?:["'`]?)\s*:/.exec(part);
158
+ if (m) out.push({ table, field: m[1], line: lineAt(src, at + m[0].indexOf(m[1])), source });
159
+ }
160
+ return out;
161
+ }
162
+ var SQL_NOT_COLUMN = /^(?:primary|foreign|constraint|unique|key|index|check|exclude|fulltext|spatial|like|period)\b/i;
163
+ function sqlFields(src) {
164
+ const text = blankComments(src, "sql");
165
+ const out = [];
166
+ const create = /\bcreate\s+(?:or\s+replace\s+)?(?:(?:global\s+|local\s+)?(?:temporary|temp)\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?([\w."`[\]]+)\s*\(/gi;
167
+ for (let m; m = create.exec(text); ) {
168
+ const table = bare(m[1]);
169
+ const open2 = m.index + m[0].length - 1;
170
+ const close = closing(text, open2);
171
+ if (close === -1) continue;
172
+ for (const { part, at } of splitTop(text.slice(open2 + 1, close), open2 + 1)) {
173
+ const col = /^\s*([\w"`[\]]+)/.exec(part);
174
+ if (!col || SQL_NOT_COLUMN.test(col[1])) continue;
175
+ out.push({ table, field: bare(col[1]), line: lineAt(src, at + col.index + col[0].indexOf(col[1])), source: "sql" });
176
+ }
177
+ }
178
+ const alter = /\balter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?([\w."`[\]]+)\s+add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?([\w"`[\]]+)/gi;
179
+ for (let m; m = alter.exec(text); ) {
180
+ if (SQL_NOT_COLUMN.test(m[2])) continue;
181
+ out.push({ table: bare(m[1]), field: bare(m[2]), line: lineAt(src, m.index + m[0].lastIndexOf(m[2])), source: "sql" });
182
+ }
183
+ return out;
184
+ }
185
+ function prismaFields(src) {
186
+ const text = blankComments(src, "c");
187
+ const out = [];
188
+ for (let m, re = /\b(?:model|type)\s+(\w+)\s*\{/g; m = re.exec(text); ) {
189
+ const open2 = m.index + m[0].length - 1;
190
+ const close = closing(text, open2);
191
+ if (close === -1) continue;
192
+ const body = text.slice(open2 + 1, close);
193
+ for (let f, fre = /^[ \t]*(\w+)[ \t]+[A-Z]\w*/gm; f = fre.exec(body); ) {
194
+ out.push({ table: m[1], field: f[1], line: lineAt(src, open2 + 1 + f.index + f[0].indexOf(f[1])), source: "prisma" });
195
+ }
196
+ }
197
+ return out;
198
+ }
199
+ function graphqlFields(src) {
200
+ const text = blankComments(src, "hash");
201
+ const out = [];
202
+ for (let m, re = /\b(?:type|input|interface)\s+(\w+)[^{]*\{/g; m = re.exec(text); ) {
203
+ const open2 = m.index + m[0].length - 1;
204
+ const close = closing(text, open2);
205
+ if (close === -1) continue;
206
+ const body = text.slice(open2 + 1, close);
207
+ for (let f, fre = /^[ \t]*(\w+)\s*(?:\([^)]*\))?\s*:/gm; f = fre.exec(body); ) {
208
+ out.push({ table: m[1], field: f[1], line: lineAt(src, open2 + 1 + f.index + f[0].indexOf(f[1])), source: "graphql" });
209
+ }
210
+ }
211
+ return out;
212
+ }
213
+ function pythonFields(src) {
214
+ const text = blankComments(src, "hash");
215
+ const out = [];
216
+ const classes = [...text.matchAll(/^class\s+(\w+)\s*\(([^)]*)\)\s*:/gm)];
217
+ classes.forEach((c, i) => {
218
+ const bases = c[2];
219
+ const django = /\bmodels\.Model\b|\bModel\b/.test(bases);
220
+ const start = c.index + c[0].length;
221
+ const end = i + 1 < classes.length ? classes[i + 1].index : text.length;
222
+ const body = text.slice(start, end);
223
+ for (let f, fre = /^[ \t]+(\w+)\s*(?::\s*Mapped\[[^\]]*\]\s*)?=\s*(models\.\w+|(?:sa\.|db\.)?(?:Column|mapped_column))\s*\(/gm; f = fre.exec(body); ) {
224
+ const source = f[2].startsWith("models.") ? "django" : "sqlalchemy";
225
+ if (source === "django" && !django) continue;
226
+ out.push({ table: c[1], field: f[1], line: lineAt(src, start + f.index + f[0].indexOf(f[1])), source });
227
+ }
228
+ for (let f, fre = /^[ \t]+(\w+)\s*:\s*Mapped\[/gm; f = fre.exec(body); ) {
229
+ if (!out.some((o) => o.table === c[1] && o.field === f[1])) {
230
+ out.push({ table: c[1], field: f[1], line: lineAt(src, start + f.index + f[0].indexOf(f[1])), source: "sqlalchemy" });
231
+ }
232
+ }
233
+ });
234
+ return out;
235
+ }
236
+ function jsFields(src) {
237
+ const text = blankComments(src, "c");
238
+ const out = [];
239
+ for (let m, re = /(?:(?:const|let|var)\s+(\w+)\s*=\s*)?(?:new\s+)?(?:mongoose\.)?Schema\s*(?:<[^>]*>)?\s*\(\s*\{/g; m = re.exec(text); ) {
240
+ const table = m[1]?.replace(/Schema$/i, "") || void 0;
241
+ out.push(...objectKeys(text, m.index + m[0].length - 1, table, "mongoose", src));
242
+ }
243
+ for (let m, re = /\.define\s*\(\s*["'`](\w+)["'`]\s*,\s*\{/g; m = re.exec(text); ) {
244
+ out.push(...objectKeys(text, m.index + m[0].length - 1, m[1], "sequelize", src));
245
+ }
246
+ for (let m, re = /\b(\w+)\.init\s*\(\s*\{/g; m = re.exec(text); ) {
247
+ out.push(...objectKeys(text, m.index + m[0].length - 1, m[1], "sequelize", src));
248
+ }
249
+ for (let m, re = /\b(?:pg|mysql|sqlite|singlestore)Table\s*\(\s*["'`](\w+)["'`]\s*,\s*\{/g; m = re.exec(text); ) {
250
+ out.push(...objectKeys(text, m.index + m[0].length - 1, m[1], "drizzle", src));
251
+ }
252
+ if (/@Entity\s*\(/.test(text)) {
253
+ for (let c, cre = /@Entity\s*\([^)]*\)\s*(?:export\s+)?(?:default\s+)?class\s+(\w+)[^{]*\{/g; c = cre.exec(text); ) {
254
+ const open2 = c.index + c[0].length - 1;
255
+ const close = closing(text, open2);
256
+ if (close === -1) continue;
257
+ const body = text.slice(open2 + 1, close);
258
+ for (let f, fre = /@(?:Column|PrimaryColumn|PrimaryGeneratedColumn|CreateDateColumn|UpdateDateColumn)\s*\([^)]*\)\s*(?:@\w+\s*(?:\([^)]*\))?\s*)*(?:public\s+|private\s+|readonly\s+)*(\w+)[?!]?\s*:/g; f = fre.exec(body); ) {
259
+ out.push({ table: c[1], field: f[1], line: lineAt(src, open2 + 1 + f.index + f[0].lastIndexOf(f[1])), source: "typeorm" });
260
+ }
261
+ }
262
+ }
263
+ return out;
264
+ }
265
+ function railsFields(src) {
266
+ const text = blankComments(src, "hash");
267
+ const out = [];
268
+ for (let m, re = /create_table\s+["':](\w+)/g; m = re.exec(text); ) {
269
+ const end = text.indexOf("\n end", m.index);
270
+ const body = text.slice(m.index, end === -1 ? void 0 : end);
271
+ for (let f, fre = /\bt\.(?!index|timestamps|references|belongs_to)\w+\s+["':](\w+)/g; f = fre.exec(body); ) {
272
+ out.push({ table: m[1], field: f[1], line: lineAt(src, m.index + f.index + f[0].lastIndexOf(f[1])), source: "rails" });
273
+ }
274
+ }
275
+ for (let m, re = /add_column\s+["':](\w+)["']?\s*,\s*["':](\w+)/g; m = re.exec(text); ) {
276
+ out.push({ table: m[1], field: m[2], line: lineAt(src, m.index + m[0].lastIndexOf(m[2])), source: "rails" });
277
+ }
278
+ return out;
279
+ }
280
+ function laravelFields(src) {
281
+ const text = blankComments(src, "c");
282
+ const out = [];
283
+ for (let m, re = /Schema::(?:create|table)\s*\(\s*["'](\w+)["']/g; m = re.exec(text); ) {
284
+ const next = text.indexOf("Schema::", m.index + 1);
285
+ const body = text.slice(m.index, next === -1 ? void 0 : next);
286
+ for (let f, fre = /\$table->(?!index|unique|primary|foreign|timestamps|softDeletes|rememberToken|id\b|dropColumn)\w+\(\s*["'](\w+)["']/g; f = fre.exec(body); ) {
287
+ out.push({ table: m[1], field: f[1], line: lineAt(src, m.index + f.index + f[0].lastIndexOf(f[1])), source: "laravel" });
288
+ }
289
+ }
290
+ return out;
291
+ }
292
+ function jsonSchemaFields(src) {
293
+ let doc;
294
+ try {
295
+ doc = JSON.parse(src);
296
+ } catch {
297
+ return [];
298
+ }
299
+ const source = doc && typeof doc === "object" && ("openapi" in doc || "swagger" in doc) ? "openapi" : "json-schema";
300
+ const out = [];
301
+ let from = 0;
302
+ const visit = (node, name) => {
303
+ if (Array.isArray(node)) return node.forEach((n) => visit(n, name));
304
+ if (!node || typeof node !== "object") return;
305
+ const obj = node;
306
+ const title = typeof obj.title === "string" ? obj.title : name;
307
+ for (const [key, value] of Object.entries(obj)) {
308
+ if (key === "properties" && value && typeof value === "object" && !Array.isArray(value)) {
309
+ for (const field of Object.keys(value)) {
310
+ const at = src.indexOf(JSON.stringify(field), from);
311
+ if (at !== -1) from = at;
312
+ out.push({ table: title, field, line: at === -1 ? 1 : lineAt(src, at), source });
313
+ }
314
+ }
315
+ visit(value, key === "schemas" || key === "definitions" || key === "$defs" ? void 0 : typeof value === "object" && key !== "properties" ? key : title);
316
+ }
317
+ };
318
+ visit(doc, void 0);
319
+ return out;
320
+ }
321
+ function yamlSchemaFields(src) {
322
+ if (!/^\s*properties:\s*$/m.test(src)) return [];
323
+ const source = /^(?:openapi|swagger):/m.test(src) ? "openapi" : "json-schema";
324
+ const lines = src.split("\n");
325
+ const out = [];
326
+ const names = [];
327
+ for (let i = 0; i < lines.length; i++) {
328
+ const line = lines[i];
329
+ const m = /^(\s*)([\w$-]+):/.exec(line);
330
+ if (!m) continue;
331
+ const indent = m[1].length;
332
+ while (names.length && names[names.length - 1].indent >= indent) names.pop();
333
+ names.push({ indent, key: m[2] });
334
+ if (m[2] !== "properties" || line.trim() !== "properties:") continue;
335
+ const owner = names.length >= 2 ? names[names.length - 2].key : void 0;
336
+ let child = -1;
337
+ for (let j = i + 1; j < lines.length; j++) {
338
+ const l = lines[j];
339
+ if (!l.trim() || l.trim().startsWith("#")) continue;
340
+ const k = /^(\s*)([\w$-]+):/.exec(l);
341
+ const ind = /^\s*/.exec(l)?.[0].length ?? 0;
342
+ if (ind <= indent) break;
343
+ if (k && (child === -1 || ind === child)) {
344
+ child = ind;
345
+ out.push({ table: owner === "items" ? void 0 : owner, field: k[2], line: j + 1, source });
346
+ }
347
+ }
348
+ }
349
+ return out;
350
+ }
351
+ function extractFields(path, src) {
352
+ const p = path.toLowerCase().replace(/\\/g, "/");
353
+ const ext = p.slice(p.lastIndexOf(".") + 1);
354
+ if (ext === "sql") return sqlFields(src);
355
+ if (ext === "prisma") return prismaFields(src);
356
+ if (ext === "graphql" || ext === "gql") return graphqlFields(src);
357
+ if (ext === "py") return /\bmodels\.|\bColumn\s*\(|\bmapped_column\s*\(|Mapped\[/.test(src) ? pythonFields(src) : [];
358
+ if (ext === "rb") return /create_table|add_column/.test(src) ? railsFields(src) : [];
359
+ if (ext === "php") return /Schema::/.test(src) ? laravelFields(src) : [];
360
+ if (["js", "mjs", "cjs", "ts", "mts", "cts", "jsx", "tsx"].includes(ext)) {
361
+ return /Schema\s*(?:<[^>]*>)?\s*\(|\.define\s*\(|\.init\s*\(|Table\s*\(|@Entity/.test(src) ? jsFields(src) : [];
362
+ }
363
+ if (ext === "json") return /"properties"\s*:/.test(src) && !p.endsWith("package.json") && !p.endsWith("package-lock.json") ? jsonSchemaFields(src) : [];
364
+ if (ext === "yaml" || ext === "yml") return yamlSchemaFields(src);
365
+ return [];
366
+ }
367
+
368
+ // src/scan.ts
369
+ var SKIP_DIRS = [
370
+ "node_modules",
371
+ ".git",
372
+ ".hg",
373
+ ".svn",
374
+ "dist",
375
+ "build",
376
+ "out",
377
+ "coverage",
378
+ ".next",
379
+ ".nuxt",
380
+ ".svelte-kit",
381
+ ".turbo",
382
+ ".cache",
383
+ ".parcel-cache",
384
+ ".vercel",
385
+ ".netlify",
386
+ "vendor",
387
+ "target",
388
+ "__pycache__",
389
+ ".venv",
390
+ "venv",
391
+ ".tox",
392
+ ".mypy_cache",
393
+ ".pytest_cache",
394
+ ".gradle",
395
+ ".terraform",
396
+ "bower_components",
397
+ "jspm_packages",
398
+ ".yarn"
399
+ ];
400
+ var SKIP_FILES = /(?:^|[\\/])(?:package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|composer\.lock|Gemfile\.lock|poetry\.lock|Cargo\.lock|go\.sum)$|\.(?:min\.(?:js|css)|map|svg|lock)$/i;
401
+ var RANK = { low: 0, medium: 1, high: 2 };
402
+ var SENSITIVITY_RANK = { high: 0, medium: 1, low: 2 };
403
+ var VALUE_CATEGORY = {
404
+ aadhaar: { category: "government-id", label: "Aadhaar number" },
405
+ pan: { category: "government-id", label: "PAN" },
406
+ gstin: { category: "government-id", label: "GSTIN" },
407
+ voter_id: { category: "government-id", label: "Voter ID (EPIC)" },
408
+ passport: { category: "government-id", label: "Passport number" },
409
+ phone: { category: "contact", label: "Phone number" },
410
+ email: { category: "contact", label: "Email address" },
411
+ upi: { category: "financial", label: "UPI ID" },
412
+ card: { category: "financial", label: "Card number" },
413
+ bank_account: { category: "financial", label: "Bank account number" },
414
+ ifsc: { category: "financial", label: "IFSC code" }
415
+ };
416
+ async function isBinary(path) {
417
+ const fh = await open(path, "r");
418
+ try {
419
+ const buf = Buffer.alloc(8e3);
420
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
421
+ return buf.subarray(0, bytesRead).includes(0);
422
+ } finally {
423
+ await fh.close();
424
+ }
425
+ }
426
+ async function* walk(path, skip) {
427
+ const info = await stat(path);
428
+ if (info.isFile()) {
429
+ yield path;
430
+ return;
431
+ }
432
+ if (!info.isDirectory()) return;
433
+ const entries = await readdir(path, { withFileTypes: true });
434
+ entries.sort((a, b) => a.name.localeCompare(b.name));
435
+ for (const entry of entries) {
436
+ if (skip.has(entry.name)) continue;
437
+ const full = join(path, entry.name);
438
+ if (entry.isDirectory()) yield* walk(full, skip);
439
+ else if (entry.isFile()) yield full;
440
+ }
441
+ }
442
+ var display = (file) => {
443
+ const rel = relative(process.cwd(), file);
444
+ return (rel && !rel.startsWith("..") ? rel : file).split(sep).join("/");
445
+ };
446
+ function findValues(text, file, minConfidence = "medium") {
447
+ const out = [];
448
+ const types = DEFAULT_TYPES.filter((t) => t !== "email");
449
+ text.split("\n").forEach((line, i) => {
450
+ for (const m of detect(line, { types: [...types], minConfidence })) {
451
+ const { category, label } = VALUE_CATEGORY[m.type];
452
+ out.push({
453
+ file,
454
+ line: i + 1,
455
+ column: m.start + 1,
456
+ type: m.type,
457
+ category,
458
+ label,
459
+ sensitivity: CATEGORIES[category].sensitivity,
460
+ confidence: m.confidence,
461
+ preview: maskValue(m)
462
+ });
463
+ }
464
+ });
465
+ return out;
466
+ }
467
+ function findFields(text, file, minConfidence = "medium") {
468
+ const out = [];
469
+ for (const f of extractFields(file, text)) {
470
+ const match = classifyField(f.field, f.table);
471
+ if (match && RANK[match.confidence] >= RANK[minConfidence]) out.push({ file, ...f, ...match });
472
+ }
473
+ return out;
474
+ }
475
+ function summarize(fields, values) {
476
+ const by = /* @__PURE__ */ new Map();
477
+ const row = (category) => {
478
+ let r = by.get(category);
479
+ if (!r) by.set(category, r = { category, ...CATEGORIES[category], fields: 0, values: 0 });
480
+ return r;
481
+ };
482
+ for (const f of fields) row(f.category).fields++;
483
+ for (const v of values) row(v.category).values++;
484
+ const order = Object.keys(CATEGORIES);
485
+ const summary = [...by.values()].sort(
486
+ (a, b) => SENSITIVITY_RANK[a.sensitivity] - SENSITIVITY_RANK[b.sensitivity] || order.indexOf(a.category) - order.indexOf(b.category)
487
+ );
488
+ const notes = [];
489
+ for (const s of summary) {
490
+ const note = CATEGORY_NOTES[s.category];
491
+ if (note) notes.push(note);
492
+ }
493
+ for (const note of new Set(fields.map((f) => f.note).filter((n) => Boolean(n)))) notes.unshift(note);
494
+ if (values.length) {
495
+ notes.push(
496
+ "Personal data is written into files (code, fixtures, seeds or logs). If it's real, remove it and rotate anything exposed; for test data, use made-up values that fail the checksums."
497
+ );
498
+ }
499
+ return { summary, notes };
500
+ }
501
+ async function scan(paths, options = {}) {
502
+ const minConfidence = options.minConfidence ?? "medium";
503
+ const maxSize = options.maxFileSize ?? 2 * 1024 * 1024;
504
+ const skip = /* @__PURE__ */ new Set([...SKIP_DIRS, ...options.exclude ?? []]);
505
+ const fields = [];
506
+ const values = [];
507
+ let files = 0;
508
+ let schemaFiles = 0;
509
+ for (const root of paths.length ? paths : ["."]) {
510
+ for await (const path of walk(root, skip)) {
511
+ if (SKIP_FILES.test(path)) continue;
512
+ const info = await stat(path);
513
+ if (info.size > maxSize || info.size === 0 || await isBinary(path)) continue;
514
+ const text = (await readFile(path, "utf8")).replace(/\r\n/g, "\n");
515
+ const file = display(path);
516
+ files++;
517
+ if (options.schemas !== false) {
518
+ const found = findFields(text, file, minConfidence);
519
+ if (extractFields(path, text).length) schemaFiles++;
520
+ fields.push(...found);
521
+ }
522
+ if (options.values !== false) values.push(...findValues(text, file, minConfidence));
523
+ }
524
+ }
525
+ fields.sort((a, b) => SENSITIVITY_RANK[a.sensitivity] - SENSITIVITY_RANK[b.sensitivity] || a.file.localeCompare(b.file) || a.line - b.line);
526
+ return { paths: paths.length ? paths : ["."], files, schemaFiles, fields, values, ...summarize(fields, values) };
527
+ }
528
+
529
+ // src/report.ts
530
+ var DISCLAIMER = "dpdp-scanner is an independent open-source tool. It is not affiliated with or endorsed by the Government of India, MeitY or the Data Protection Board of India, and its output is not legal advice.";
531
+ var where = (f) => f.table ? `${f.table}.${f.field}` : f.field;
532
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
533
+ var SENSITIVITY_MARK = { high: "\u25CF", medium: "\u25D0", low: "\u25CB" };
534
+ function pad(s, n) {
535
+ return s.length >= n ? s : s + " ".repeat(n - s.length);
536
+ }
537
+ function toTable(report, opts = {}) {
538
+ const limit = opts.limit ?? 50;
539
+ const out = [];
540
+ const head = `Scanned ${plural(report.files, "file")}, ${report.schemaFiles} with a schema or model.`;
541
+ if (!report.fields.length && !report.values.length) {
542
+ return `${head}
543
+ \u2714 No personal data found.
544
+ `;
545
+ }
546
+ out.push(`Personal data found: ${plural(report.fields.length, "field")} in schemas, ${plural(report.values.length, "value")} in files.`, "");
547
+ const w2 = Math.max(...report.summary.map((s) => s.label.length), 8);
548
+ out.push(` ${pad("Category", w2 + 3)}Sensitivity Fields Values`);
549
+ for (const s of report.summary) {
550
+ out.push(` ${SENSITIVITY_MARK[s.sensitivity]} ${pad(s.label, w2)} ${pad(s.sensitivity, 11)} ${pad(String(s.fields), 6)} ${s.values}`);
551
+ }
552
+ if (report.fields.length) {
553
+ out.push("", "Fields");
554
+ const rows = report.fields.slice(0, limit);
555
+ const cw = Math.max(...rows.map((f) => where(f).length));
556
+ const lw = Math.max(...rows.map((f) => f.label.length));
557
+ for (const f of rows) out.push(` ${SENSITIVITY_MARK[f.sensitivity]} ${pad(where(f), cw)} ${pad(f.label, lw)} ${f.file}:${f.line}`);
558
+ if (report.fields.length > limit) out.push(` \u2026 and ${report.fields.length - limit} more (use --format markdown or json for all)`);
559
+ }
560
+ if (report.values.length) {
561
+ out.push("", "Values written in files (masked)");
562
+ const rows = report.values.slice(0, limit);
563
+ const pw = Math.max(...rows.map((v) => v.preview.length));
564
+ const lw = Math.max(...rows.map((v) => v.label.length));
565
+ for (const v of rows) out.push(` ${SENSITIVITY_MARK[v.sensitivity]} ${pad(v.preview, pw)} ${pad(v.label, lw)} ${v.file}:${v.line}`);
566
+ if (report.values.length > limit) out.push(` \u2026 and ${report.values.length - limit} more`);
567
+ }
568
+ if (report.notes.length) {
569
+ out.push("", "What to do");
570
+ for (const n of report.notes) out.push(` \u2022 ${n}`);
571
+ }
572
+ out.push("", head, "");
573
+ return out.join("\n");
574
+ }
575
+ function toJson(report) {
576
+ return JSON.stringify(report, null, 2) + "\n";
577
+ }
578
+ var md = (s) => s.replace(/\|/g, "\\|");
579
+ function toMarkdown(report, opts = {}) {
580
+ const date = (opts.date ?? /* @__PURE__ */ new Date()).toISOString().slice(0, 10);
581
+ const out = [`# ${opts.title ?? "Personal data inventory"}`, ""];
582
+ out.push(
583
+ `Generated by [dpdp-scanner](https://www.npmjs.com/package/dpdp-scanner) on ${date}. Scanned ${plural(report.files, "file")} in \`${report.paths.join("`, `")}\`.`,
584
+ ""
585
+ );
586
+ if (!report.fields.length && !report.values.length) {
587
+ out.push("No personal data was found in schemas, models or files.", "", `> ${DISCLAIMER}`, "");
588
+ return out.join("\n");
589
+ }
590
+ out.push("## Summary", "", "| Category | Sensitivity | Fields | Values in files |", "|---|---|---|---|");
591
+ for (const s of report.summary) out.push(`| ${s.label} | ${s.sensitivity} | ${s.fields} | ${s.values} |`);
592
+ out.push("");
593
+ if (report.fields.length) {
594
+ out.push("## Where personal data is stored", "", "Tables, models and schemas with fields that hold personal data.", "");
595
+ const byTable = /* @__PURE__ */ new Map();
596
+ for (const f of report.fields) {
597
+ const key = `${f.table ?? "(no table)"}\0${f.file}`;
598
+ byTable.set(key, [...byTable.get(key) ?? [], f]);
599
+ }
600
+ for (const [key, rows] of byTable) {
601
+ const [table, file] = key.split("\0");
602
+ out.push(`### ${md(table)}`, "", `\`${file}\` (${rows[0].source})`, "", "| Field | Personal data | Category | Sensitivity | Line |", "|---|---|---|---|---|");
603
+ for (const f of rows) out.push(`| \`${md(f.field)}\` | ${f.label} | ${CATEGORIES[f.category].label} | ${f.sensitivity} | ${f.line} |`);
604
+ out.push("");
605
+ }
606
+ }
607
+ if (report.values.length) {
608
+ out.push("## Personal data written in files", "", "Shown masked. Check whether each one is real.", "", "| File | Line | Type | Masked value | Confidence |", "|---|---|---|---|---|");
609
+ for (const v of report.values) out.push(`| \`${md(v.file)}\` | ${v.line} | ${v.label} | \`${md(v.preview)}\` | ${v.confidence} |`);
610
+ out.push("");
611
+ }
612
+ if (report.notes.length) {
613
+ out.push("## What to do", "");
614
+ for (const n of report.notes) out.push(`- ${n}`);
615
+ out.push("");
616
+ }
617
+ out.push("---", "", `<sub>${DISCLAIMER}</sub>`, "");
618
+ return out.join("\n");
619
+ }
620
+ var LEVEL = { high: "warning", medium: "note", low: "note" };
621
+ function toSarif(report, version = "0.0.0") {
622
+ const categories = Object.keys(CATEGORIES);
623
+ const rules = [
624
+ ...categories.map((c) => ({
625
+ id: `field/${c}`,
626
+ name: `PersonalDataField${CATEGORIES[c].label.replace(/[^A-Za-z]/g, "")}`,
627
+ shortDescription: { text: `${CATEGORIES[c].label} stored in a schema or model` },
628
+ defaultConfiguration: { level: LEVEL[CATEGORIES[c].sensitivity] },
629
+ properties: { tags: ["privacy", "dpdp", "personal-data"] }
630
+ })),
631
+ ...categories.map((c) => ({
632
+ id: `value/${c}`,
633
+ name: `PersonalDataValue${CATEGORIES[c].label.replace(/[^A-Za-z]/g, "")}`,
634
+ shortDescription: { text: `${CATEGORIES[c].label} written into a file` },
635
+ defaultConfiguration: { level: "warning" },
636
+ properties: { tags: ["privacy", "dpdp", "personal-data"] }
637
+ }))
638
+ ];
639
+ const results = [
640
+ ...report.fields.map((f) => ({
641
+ ruleId: `field/${f.category}`,
642
+ level: LEVEL[f.sensitivity],
643
+ message: { text: `${where(f)} stores ${f.label.toLowerCase()} (${f.sensitivity} sensitivity).${f.note ? ` ${f.note}` : ""}` },
644
+ locations: [{ physicalLocation: { artifactLocation: { uri: f.file }, region: { startLine: f.line } } }]
645
+ })),
646
+ ...report.values.map((v) => ({
647
+ ruleId: `value/${v.category}`,
648
+ level: v.sensitivity === "high" ? "error" : "warning",
649
+ message: { text: `${v.label} written in this file: ${v.preview} (${v.confidence} confidence).` },
650
+ locations: [{ physicalLocation: { artifactLocation: { uri: v.file }, region: { startLine: v.line, startColumn: v.column } } }]
651
+ }))
652
+ ];
653
+ return JSON.stringify(
654
+ {
655
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
656
+ version: "2.1.0",
657
+ runs: [{ tool: { driver: { name: "dpdp-scanner", version, informationUri: "https://github.com/ckgiri/dpdp-scanner", rules } }, results }]
658
+ },
659
+ null,
660
+ 2
661
+ ) + "\n";
662
+ }
663
+ var FAIL_RANK = { high: 3, medium: 2, low: 1 };
664
+ function shouldFail(report, level) {
665
+ const min = level === "any" ? 1 : FAIL_RANK[level];
666
+ return [...report.fields, ...report.values].some((f) => FAIL_RANK[f.sensitivity] >= min);
667
+ }
668
+ export {
669
+ CATEGORIES,
670
+ CATEGORY_NOTES,
671
+ SKIP_DIRS,
672
+ classifyField,
673
+ extractFields,
674
+ findFields,
675
+ findValues,
676
+ graphqlFields,
677
+ jsFields,
678
+ jsonSchemaFields,
679
+ laravelFields,
680
+ prismaFields,
681
+ pythonFields,
682
+ railsFields,
683
+ scan,
684
+ shouldFail,
685
+ sqlFields,
686
+ summarize,
687
+ toJson,
688
+ toMarkdown,
689
+ toSarif,
690
+ toTable,
691
+ words,
692
+ yamlSchemaFields
693
+ };