dpdp-kit 0.3.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/dist/prisma.js ADDED
@@ -0,0 +1,281 @@
1
+ import {
2
+ castType,
3
+ isUniqueViolation,
4
+ postgresData,
5
+ postgresStore
6
+ } from "./chunk-KLMR7S7I.js";
7
+ import {
8
+ DPDP_DDL
9
+ } from "./chunk-2ELTZSW3.js";
10
+ import "./chunk-67Q5GFD6.js";
11
+
12
+ // src/prisma.ts
13
+ var prismaQuery = (prisma) => async (text, params) => await prisma.$queryRawUnsafe(text, ...params);
14
+ function prismaStore(prisma) {
15
+ return postgresStore(prismaQuery(prisma));
16
+ }
17
+ function prismaData(prisma, options = {}) {
18
+ return postgresData(prismaQuery(prisma), options);
19
+ }
20
+ var SCALAR = {
21
+ String: { type: "string", sqlType: "text" },
22
+ Boolean: { type: "boolean", sqlType: "boolean" },
23
+ Int: { type: "number", sqlType: "integer" },
24
+ BigInt: { type: "number", sqlType: "bigint" },
25
+ Float: { type: "number", sqlType: "double precision" },
26
+ Decimal: { type: "number", sqlType: "numeric" },
27
+ DateTime: { type: "other", sqlType: "timestamp(3)" },
28
+ Json: { type: "other", sqlType: "jsonb" },
29
+ Bytes: { type: "other", sqlType: "bytea" }
30
+ };
31
+ var NATIVE = {
32
+ Text: "text",
33
+ VarChar: "varchar",
34
+ Char: "char",
35
+ Uuid: "uuid",
36
+ Citext: "citext",
37
+ Inet: "inet",
38
+ Xml: "xml",
39
+ Bit: "bit",
40
+ VarBit: "varbit",
41
+ SmallInt: "smallint",
42
+ Integer: "integer",
43
+ Oid: "oid",
44
+ BigInt: "bigint",
45
+ Real: "real",
46
+ DoublePrecision: "double precision",
47
+ Decimal: "numeric",
48
+ Money: "money",
49
+ Timestamp: "timestamp",
50
+ Timestamptz: "timestamptz",
51
+ Date: "date",
52
+ Time: "time",
53
+ Timetz: "timetz",
54
+ Boolean: "boolean",
55
+ Json: "json",
56
+ JsonB: "jsonb",
57
+ ByteA: "bytea"
58
+ };
59
+ var quote = (name) => `"${name.replace(/"/g, '""')}"`;
60
+ function stripComment(line) {
61
+ let inString = false;
62
+ for (let i = 0; i < line.length; i++) {
63
+ const ch = line[i];
64
+ if (ch === "\\" && inString) i++;
65
+ else if (ch === '"') inString = !inString;
66
+ else if (!inString && ch === "/" && line[i + 1] === "/") return line.slice(0, i);
67
+ }
68
+ return line;
69
+ }
70
+ var mapName = (attrs, prefix) => {
71
+ const m = new RegExp(`(?:^|\\s)${prefix === "@" ? "@" : "@@"}map\\(\\s*(?:name\\s*:\\s*)?"((?:[^"\\\\]|\\\\.)*)"`).exec(attrs);
72
+ return m ? m[1].replace(/\\(.)/g, "$1") : void 0;
73
+ };
74
+ function blocks(text) {
75
+ const out = [];
76
+ let current;
77
+ for (const raw of text.split(/\r?\n/)) {
78
+ const line = stripComment(raw).trim();
79
+ if (!line) continue;
80
+ if (!current) {
81
+ const m = /^(model|view|enum|type)\s+(\w+)\s*\{\s*$/.exec(line);
82
+ if (m) current = { kind: m[1], name: m[2], lines: [] };
83
+ continue;
84
+ }
85
+ if (line === "}") {
86
+ out.push(current);
87
+ current = void 0;
88
+ } else current.lines.push(line);
89
+ }
90
+ return out;
91
+ }
92
+ function prismaSchema(text) {
93
+ const all = blocks(text);
94
+ const enums = new Map(all.filter((b) => b.kind === "enum").map((b) => [b.name, mapName(b.lines.join(" "), "@@") ?? b.name]));
95
+ const composites = new Set(all.filter((b) => b.kind === "type").map((b) => b.name));
96
+ const models = new Set(all.filter((b) => b.kind === "model" || b.kind === "view").map((b) => b.name));
97
+ const tables = [];
98
+ const tableOf = /* @__PURE__ */ new Map();
99
+ const relations = [];
100
+ for (const block of all) {
101
+ if (block.kind !== "model" && block.kind !== "view") continue;
102
+ const columns = [];
103
+ let tableName = block.name;
104
+ for (const line of block.lines) {
105
+ if (line.startsWith("@@")) {
106
+ tableName = mapName(line, "@@") ?? tableName;
107
+ continue;
108
+ }
109
+ const m = /^(\w+)\s+(Unsupported\(\s*"(?:[^"\\]|\\.)*"\s*\)|[\w.]+)(\[\])?(\?)?(.*)$/.exec(line);
110
+ if (!m) continue;
111
+ const [, field, typeName, list, optional, attrs = ""] = m;
112
+ if (models.has(typeName) || composites.has(typeName)) {
113
+ const relation = /@relation\(([^)]*(?:\[[^\]]*\][^)]*)*)\)/.exec(attrs)?.[1] ?? "";
114
+ const fields = /fields\s*:\s*\[([^\]]*)\]/.exec(relation)?.[1];
115
+ if (fields && models.has(typeName)) {
116
+ const action = /onDelete\s*:\s*(\w+)/.exec(relation)?.[1];
117
+ relations.push({
118
+ model: block.name,
119
+ fields: fields.split(",").map((f) => f.trim()).filter(Boolean),
120
+ target: typeName,
121
+ // Prisma's defaults: SetNull for an optional relation, Restrict for a required one.
122
+ onDelete: PRISMA_ACTIONS[action ?? (optional ? "SetNull" : "Restrict")] ?? "no action"
123
+ });
124
+ }
125
+ continue;
126
+ }
127
+ const name = mapName(attrs, "@") ?? field;
128
+ const native = /@db\.(\w+)(\(([^)]*)\))?/.exec(attrs);
129
+ let sqlType;
130
+ let type = "other";
131
+ const unsupported = /^Unsupported\(\s*"((?:[^"\\]|\\.)*)"/.exec(typeName);
132
+ if (unsupported) sqlType = unsupported[1];
133
+ else if (enums.has(typeName)) sqlType = quote(enums.get(typeName));
134
+ else if (SCALAR[typeName]) {
135
+ type = SCALAR[typeName].type;
136
+ sqlType = SCALAR[typeName].sqlType;
137
+ }
138
+ if (native && NATIVE[native[1]]) sqlType = `${NATIVE[native[1]]}${native[2] ?? ""}`;
139
+ if (sqlType && list) sqlType += "[]";
140
+ columns.push({
141
+ name,
142
+ ...name === field ? {} : { key: field },
143
+ notNull: !optional && !list,
144
+ type: list ? "other" : type,
145
+ ...sqlType ? { sqlType } : {}
146
+ });
147
+ }
148
+ tableOf.set(block.name, tableName);
149
+ tables.push({ name: tableName, ...tableName === block.name ? {} : { key: block.name }, columns });
150
+ }
151
+ for (const r of relations) {
152
+ const table = tables.find((t) => (t.key ?? t.name) === r.model);
153
+ if (!table) continue;
154
+ const columnName = (field) => table.columns.find((c) => (c.key ?? c.name) === field)?.name ?? field;
155
+ const reference = { columns: r.fields.map(columnName), table: tableOf.get(r.target) ?? r.target, ...r.onDelete ? { onDelete: r.onDelete } : {} };
156
+ Object.assign(table, { references: [...table.references ?? [], reference] });
157
+ }
158
+ return { tables };
159
+ }
160
+ var PRISMA_ACTIONS = {
161
+ Cascade: "cascade",
162
+ SetNull: "set null",
163
+ SetDefault: "set default",
164
+ Restrict: "restrict",
165
+ NoAction: "no action"
166
+ };
167
+ var PRISMA_MODELS = `/// dpdp-kit: consent events, a hash chain per person (Section 6).
168
+ model DpdpConsentEvent {
169
+ subjectId String @map("subject_id")
170
+ seq Int
171
+ action String
172
+ purposes Json
173
+ noticeVersion String? @map("notice_version")
174
+ language String?
175
+ channel String?
176
+ evidence Json?
177
+ at DateTime @db.Timestamptz(6)
178
+ prevHash String? @map("prev_hash")
179
+ hash String
180
+
181
+ @@id([subjectId, seq])
182
+ @@map("dpdp_consent_events")
183
+ }
184
+
185
+ /// dpdp-kit: rights requests and grievances (Sections 11 to 14).
186
+ model DpdpRequest {
187
+ id String @id
188
+ subjectId String @map("subject_id")
189
+ type String
190
+ status String
191
+ openedAt DateTime @map("opened_at") @db.Timestamptz(6)
192
+ dueAt DateTime @map("due_at") @db.Timestamptz(6)
193
+ closedAt DateTime? @map("closed_at") @db.Timestamptz(6)
194
+ details Json?
195
+ history Json
196
+
197
+ @@index([subjectId], map: "dpdp_requests_subject_idx")
198
+ @@index([status, dueAt], map: "dpdp_requests_status_due_idx")
199
+ @@map("dpdp_requests")
200
+ }
201
+
202
+ /// dpdp-kit: erasure and processor tasks (Section 8(7), Rule 8).
203
+ model DpdpErasureTask {
204
+ id String @id
205
+ subjectId String @map("subject_id")
206
+ reason String
207
+ kind String
208
+ tableKey String? @map("table_key")
209
+ fields Json?
210
+ processor String?
211
+ purposes Json?
212
+ createdAt DateTime @map("created_at") @db.Timestamptz(6)
213
+ dueAt DateTime @map("due_at") @db.Timestamptz(6)
214
+ status String
215
+ attempts Int
216
+ claimedAt DateTime? @map("claimed_at") @db.Timestamptz(6)
217
+ doneAt DateTime? @map("done_at") @db.Timestamptz(6)
218
+ affected Int?
219
+ lastError String? @map("last_error")
220
+ note String?
221
+
222
+ @@index([subjectId], map: "dpdp_erasure_tasks_subject_idx")
223
+ @@index([status, dueAt], map: "dpdp_erasure_tasks_status_due_idx")
224
+ @@map("dpdp_erasure_tasks")
225
+ }
226
+
227
+ /// dpdp-kit: who accessed whose data, and why (Rule 6(1)(c), (e)).
228
+ model DpdpAccessLog {
229
+ id String @id
230
+ at DateTime @db.Timestamptz(6)
231
+ actor String
232
+ subjectId String @map("subject_id")
233
+ action String
234
+ purpose String
235
+ fields Json?
236
+ outOfPurpose Json? @map("out_of_purpose")
237
+ reason String?
238
+ evidence Json?
239
+
240
+ @@index([at], map: "dpdp_access_log_at_idx")
241
+ @@index([subjectId, at], map: "dpdp_access_log_subject_idx")
242
+ @@index([actor, at], map: "dpdp_access_log_actor_idx")
243
+ @@map("dpdp_access_log")
244
+ }
245
+
246
+ /// dpdp-kit: personal data breaches (Section 8(6), Rule 7).
247
+ model DpdpBreach {
248
+ id String @id
249
+ status String
250
+ awareAt DateTime @map("aware_at") @db.Timestamptz(6)
251
+ reportDueAt DateTime @map("report_due_at") @db.Timestamptz(6)
252
+ data Json
253
+
254
+ @@index([status, awareAt], map: "dpdp_breaches_status_idx")
255
+ @@map("dpdp_breaches")
256
+ }
257
+
258
+ /// dpdp-kit: each person affected by a breach, and whether they've been told (Rule 7(1)).
259
+ model DpdpBreachNotice {
260
+ breachId String @map("breach_id")
261
+ subjectId String @map("subject_id")
262
+ status String
263
+ addedAt DateTime @map("added_at") @db.Timestamptz(6)
264
+ sentAt DateTime? @map("sent_at") @db.Timestamptz(6)
265
+ channel String?
266
+
267
+ @@id([breachId, subjectId])
268
+ @@index([breachId, status, addedAt], map: "dpdp_breach_notices_status_idx")
269
+ @@map("dpdp_breach_notices")
270
+ }
271
+ `;
272
+ export {
273
+ DPDP_DDL,
274
+ PRISMA_MODELS,
275
+ castType,
276
+ isUniqueViolation,
277
+ prismaData,
278
+ prismaQuery,
279
+ prismaSchema,
280
+ prismaStore
281
+ };
@@ -15,8 +15,15 @@ export declare function formatGithubAnnotations(issues: readonly Issue[], files:
15
15
  config: string;
16
16
  schema?: string | undefined;
17
17
  }, root: string): string;
18
- /** Load a Drizzle schema file and read its tables. */
18
+ /** Load a schema module and read its tables: Mongoose models it exports, or else Drizzle tables. */
19
19
  export declare function loadDrizzleSchema(file: string): Promise<Schema>;
20
+ /**
21
+ * Read a Prisma schema: a schema.prisma file, or a folder of .prisma files (a multi-file schema,
22
+ * e.g. prisma/schema).
23
+ */
24
+ export declare function loadPrismaSchema(path: string): Promise<Schema>;
25
+ /** A Prisma schema (.prisma file or a folder of them), or else a Drizzle schema module. */
26
+ export declare function loadSchema(path: string): Promise<Schema>;
20
27
  /** Run `dpdp-kit audit`. Returns the exit code: 1 when there are errors (or `--strict` and warnings). */
21
28
  export declare function runAudit(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
22
29
  /**
@@ -8,12 +8,31 @@ export interface SchemaColumn {
8
8
  notNull?: boolean;
9
9
  /** Kind of value the column holds, when known. Used to check each field's `erase` setting. */
10
10
  type?: "string" | "number" | "boolean" | "other";
11
+ /**
12
+ * The column's SQL type (`integer`, `uuid`, `varchar(255)`…), when known. SQL data access casts
13
+ * parameters to it. From `mongooseSchema()`, `array` marks an array, so erasure reaches every element.
14
+ */
15
+ sqlType?: string;
16
+ }
17
+ /** A foreign key: these columns point at rows of another table. */
18
+ export interface SchemaReference {
19
+ /** The referencing columns, as named in the database. */
20
+ columns: readonly string[];
21
+ /** The referenced table's database name. */
22
+ table: string;
23
+ /** What the database does to these rows when the referenced row is deleted. Default "no action". */
24
+ onDelete?: "cascade" | "set null" | "set default" | "restrict" | "no action";
11
25
  }
12
26
  export interface SchemaTable {
27
+ /** The table's name in the database. */
13
28
  name: string;
29
+ /** The name in code, if different: a Prisma model name (`User` for `@@map("users")`). The data map may use either. */
30
+ key?: string;
14
31
  columns: readonly SchemaColumn[];
32
+ /** Foreign keys from this table. Used to check that legal holds survive account deletion. */
33
+ references?: readonly SchemaReference[];
15
34
  }
16
- /** Your database schema in a neutral shape. `drizzleSchema()` builds one from a Drizzle schema. */
35
+ /** Your database schema in a neutral shape. `drizzleSchema()`, `prismaSchema()` and `mongooseSchema()` build one. */
17
36
  export interface Schema {
18
37
  tables: readonly SchemaTable[];
19
38
  }
package/dist/store.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { AccessEntry, AccessLogStore } from "./access.js";
2
+ import type { Breach, BreachNotice, BreachStore } from "./breach.js";
2
3
  import type { NoticeLanguage } from "./languages.js";
3
4
  import { type ErasureTask, type RequestStore, type RightsRequest, type TaskStore } from "./records.js";
4
5
  export type ConsentAction = "grant" | "withdraw";
@@ -39,11 +40,13 @@ export type DpdpStore = ConsentStore & RequestStore & TaskStore;
39
40
  /** Whether a store can keep rights requests and erasure tasks too (custom stores may not). */
40
41
  export declare function isDpdpStore(store: ConsentStore): store is DpdpStore;
41
42
  /** Keeps everything in memory. For tests and trying the library out; everything is lost on restart. */
42
- export declare function memoryStore(): DpdpStore & AccessLogStore & {
43
+ export declare function memoryStore(): DpdpStore & AccessLogStore & BreachStore & {
43
44
  readonly all: Map<string, ConsentEvent[]>;
44
45
  readonly requests: Map<string, RightsRequest>;
45
46
  readonly tasks: Map<string, ErasureTask>;
46
47
  readonly accessLog: AccessEntry[];
48
+ readonly breaches: Map<string, Breach>;
49
+ readonly notices: Map<string, BreachNotice>;
47
50
  };
48
51
  /**
49
52
  * Purposes whose latest event is a grant: the person's consent state. Pass `until` (ISO 8601) for
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dpdp-kit",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
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",
@@ -12,14 +12,18 @@
12
12
  "data-protection",
13
13
  "erasure",
14
14
  "compliance",
15
- "drizzle"
15
+ "drizzle",
16
+ "prisma",
17
+ "mongodb",
18
+ "mongoose",
19
+ "postgres"
16
20
  ],
17
21
  "license": "MIT",
18
22
  "repository": {
19
23
  "type": "git",
20
24
  "url": "git+https://github.com/yogesh2902/dpdp-kit.git"
21
25
  },
22
- "homepage": "https://yogesh2902.github.io/dpdp-kit/",
26
+ "homepage": "https://dpdp-kit.js.org/",
23
27
  "bugs": {
24
28
  "url": "https://github.com/yogesh2902/dpdp-kit/issues"
25
29
  },
@@ -69,6 +73,18 @@
69
73
  "types": "./dist/protect.d.ts",
70
74
  "default": "./dist/protect.js"
71
75
  },
76
+ "./postgres": {
77
+ "types": "./dist/postgres.d.ts",
78
+ "default": "./dist/postgres.js"
79
+ },
80
+ "./prisma": {
81
+ "types": "./dist/prisma.d.ts",
82
+ "default": "./dist/prisma.js"
83
+ },
84
+ "./mongodb": {
85
+ "types": "./dist/mongodb.d.ts",
86
+ "default": "./dist/mongodb.js"
87
+ },
72
88
  "./package.json": "./package.json"
73
89
  },
74
90
  "scripts": {
@@ -94,6 +110,8 @@
94
110
  "@nestjs/common": "^12.5.1",
95
111
  "@nestjs/core": "^12.5.1",
96
112
  "@nestjs/platform-express": "^12.5.1",
113
+ "@prisma/adapter-pg": "7.10.1",
114
+ "@prisma/client": "7.10.1",
97
115
  "@types/express": "^5.0.6",
98
116
  "@types/node": "^26.6.6",
99
117
  "@types/pg": "^8.23.1",
@@ -102,7 +120,11 @@
102
120
  "fastify": "^5.12.8",
103
121
  "hono": "^4.13.19",
104
122
  "marked": "^18.2.1",
123
+ "mongodb": "~7.8.0",
124
+ "mongodb-memory-server": "11.3.0",
125
+ "mongoose": "9.12.2",
105
126
  "pg": "^8.23.1",
127
+ "prisma": "7.10.1",
106
128
  "reflect-metadata": "^0.2.2",
107
129
  "rxjs": "^7.8.2",
108
130
  "shiki": "^4.6.0",