dpdp-kit 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +240 -17
  3. package/dist/access.d.ts +111 -0
  4. package/dist/audit.d.ts +3 -1
  5. package/dist/breach.d.ts +170 -0
  6. package/dist/chunk-2ELTZSW3.js +94 -0
  7. package/dist/chunk-5TVA2TKG.js +37 -0
  8. package/dist/chunk-HXVP446N.js +1051 -0
  9. package/dist/chunk-KLMR7S7I.js +438 -0
  10. package/dist/cli.js +53 -17
  11. package/dist/config.d.ts +69 -0
  12. package/dist/data-access.d.ts +6 -2
  13. package/dist/ddl.d.ts +10 -0
  14. package/dist/dpdp.d.ts +210 -0
  15. package/dist/drizzle.d.ts +403 -11
  16. package/dist/drizzle.js +209 -56
  17. package/dist/errors.d.ts +1 -1
  18. package/dist/express.d.ts +17 -1
  19. package/dist/express.js +10 -2
  20. package/dist/fastify.d.ts +41 -0
  21. package/dist/fastify.js +25 -0
  22. package/dist/guard.d.ts +19 -0
  23. package/dist/hono.d.ts +16 -1
  24. package/dist/hono.js +11 -2
  25. package/dist/index.d.ts +7 -4
  26. package/dist/index.js +420 -100
  27. package/dist/mongodb.d.ts +87 -0
  28. package/dist/mongodb.js +344 -0
  29. package/dist/nestjs.d.ts +65 -0
  30. package/dist/nestjs.js +41 -0
  31. package/dist/postgres.d.ts +45 -0
  32. package/dist/postgres.js +27 -0
  33. package/dist/prisma.d.ts +43 -0
  34. package/dist/prisma.js +281 -0
  35. package/dist/protect.d.ts +74 -0
  36. package/dist/protect.js +114 -0
  37. package/dist/retention.d.ts +1 -1
  38. package/dist/run-audit.d.ts +13 -1
  39. package/dist/safeguards.d.ts +23 -0
  40. package/dist/schedule.d.ts +37 -0
  41. package/dist/schedule.js +66 -0
  42. package/dist/schema-check.d.ts +25 -8
  43. package/dist/store.d.ts +11 -1
  44. package/package.json +58 -5
  45. package/dist/chunk-FGZAH2NF.js +0 -16
  46. package/dist/chunk-KVTUMHXO.js +0 -491
package/CHANGELOG.md ADDED
@@ -0,0 +1,90 @@
1
+ # Changelog
2
+
3
+ ## 0.4.0
4
+
5
+ **Prisma, MongoDB and Mongoose, and breach records (Section 8(6), Rule 7).** dpdp-kit now runs on the database you already have, and it records a personal data breach against the Board's 72-hour deadline.
6
+
7
+ ### Added
8
+
9
+ - **Breach records** (Section 8(6), Rule 7): `dpdp.breach.open()` starts the 72-hour clock from when you became aware.
10
+ - Record who is affected (`addAffected`), or everyone a compromised account read (`addAffectedFromAccessLog`).
11
+ - `notice()` drafts the message to each person, Rule 7(1)(a)–(e), with your DPO as the contact.
12
+ - `markNotified()`, `boardNotified()`, `updateReport()` and `boardReport()` cover the detailed report to the Board, Rule 7(2)(b)(i)–(vi). `reportSent()` records sending it, and `extend()` records the Board's written extension.
13
+ - `status()` says what's left to do. `daily()` includes every open breach.
14
+ - New events: `breach.opened`, `breach.reported` and `breach.closed`.
15
+ - Changes made at the same time are all kept, and a closed breach can't change.
16
+ - **`dpdp-kit/prisma`**:
17
+ - `prismaStore(prisma)` keeps consent, requests, tasks, the access log and breaches. `prismaData(prisma, { schema })` reaches your own tables.
18
+ - `prismaSchema(text)` reads `schema.prisma`: models, `@map` and `@@map`, native types, enums and lists.
19
+ - `PRISMA_MODELS` holds dpdp-kit's tables as Prisma models. `prisma migrate diff` finds no difference from `DPDP_DDL`.
20
+ - Works inside `prisma.$transaction` with `prismaStore(tx)`. Tested on Prisma 7 with `@prisma/adapter-pg`.
21
+ - **`dpdp-kit/postgres`**: the same store and data access for any client that runs a `$1`-parameterised query: node-postgres, postgres.js, Kysely, Knex. Also exports `DPDP_DDL` without needing `drizzle-orm`.
22
+ - **`dpdp-kit/mongodb`**:
23
+ - `mongoStore(db)` keeps dpdp-kit's records in `dpdp_*` collections and creates its indexes itself.
24
+ - `mongoData(db, { schema, ObjectId })` reaches your own collections, including nested fields and fields inside arrays of subdocuments.
25
+ - `mongooseSchema(models)` feeds the drift check.
26
+ - Accepts the driver's `Db`, or `() => mongoose.connection.db` so dpdp can be created before Mongoose connects.
27
+ - **`audit --schema` reads Prisma and Mongoose:**
28
+ - `--schema prisma/schema.prisma`, or a folder of `.prisma` files.
29
+ - `--schema src/models.ts` for a file that exports Mongoose models.
30
+ - The data map and `notPersonal` can use model and field names (`User`, `phoneNumber`) as well as the database's names.
31
+ - **Foreign keys that break a legal hold** (`audit --schema`, Drizzle and Prisma). A link from a held table, like invoices kept for GST, to the users table:
32
+ - `ON DELETE CASCADE` would delete the invoices with the account: error `held-rows-cascade`.
33
+ - `SET NULL` on the subject column would lose whose they are: error `held-link-lost`.
34
+ - `RESTRICT`, Prisma's default for a required relation, makes the deletion fail: warning `held-rows-block-delete`.
35
+ - **A `contact-missing` audit warning** when `fiduciary.dpo` isn't set. Section 8(9) requires publishing it, and every breach notice needs it (Rule 7(1)(e)).
36
+ - **Example apps** in `examples/`: the same shop on Express + Prisma + Postgres and on Express + Mongoose + MongoDB. `examples/journey.mjs` takes them through a year: consent, a blocked promo, access logs, a data request, withdrawal, a grievance, deletion, a breach and erasure. CI runs the journey on every change.
37
+
38
+ ### Fixed
39
+
40
+ - **Timestamps on a server in IST.** Prisma's pg adapter shifts `timestamptz` values by the server's time zone. The SQL store reads timestamps back as UTC text, so consent records, deadlines and summaries are exact on a server set to `Asia/Kolkata`. CI now runs its Postgres in IST.
41
+
42
+ ### Upgrading from 0.3.x
43
+
44
+ 1. **New tables.**
45
+ - Drizzle: add `breaches` and `breachNotices` to your schema and generate a migration, or run `BREACH_DDL`.
46
+ - Prisma: add `PRISMA_MODELS`.
47
+ - MongoDB: nothing to do; the collections are created on first use.
48
+ 2. **New audit checks.**
49
+ - If you run `dpdp-kit audit --strict`, set `fiduciary.dpo` (your Data Protection Officer, or a contact person, with their business contact) first.
50
+ - With `--schema`, a foreign key from a table with a `legalHold` to a table whose rows account deletion removes is now reported. Keep that link as a plain, indexed column (see the messages).
51
+ 3. **Custom stores.**
52
+ - Breach records need `BreachStore`. Without it, `dpdp.breach` throws `store-unsupported` and `daily()` skips breaches.
53
+ - `updateBreach` must save only over the version it read, and return `false` otherwise (see `BreachStore`).
54
+ - `AccessLogStore.accessSubjects` is optional and new.
55
+
56
+ ## 0.3.0
57
+
58
+ **Security safeguards and access logs (Rule 6 of the DPDP Rules)**, plus Fastify and NestJS guards, events, `NOT NULL` erasure and daily upkeep.
59
+
60
+ ### Added
61
+
62
+ - **Access log** (Rule 6(1)(c), (e)): `dpdp.access.log()`, `list()`, `review()` and `prune()`. Records who accessed whose personal data, for which purpose and which fields; flags fields read for a purpose they aren't held for (or refuses them with `access: { outOfPurpose: "throw" }`). `review()` reports out-of-purpose reads, consent purposes used without consent at the time, and bulk access (`ignoreActors` exempts batch jobs). `prune()` keeps at least a year.
63
+ - **`dpdp-kit/protect`** (Rule 6(1)(a)): `createEncryptor` (AES-256-GCM, tamper detection, row-binding context, key rotation), `createTokenizer` (keyed HMAC tokens for lookups), `mask`, `maskPhone`, `maskEmail`, `maskAadhaar`, `maskPan`, `generateKey`.
64
+ - **Rule 6 in the config and audit**: `protect` on fields, `contract` on processors, a `security` block (`accessControl`, `backups`, `measures`, `accessLogRetention`). New audit warnings: `unprotected-high-risk-field`, `processor-contract-missing`, `security-measure-missing`; new errors: `access-log-retention-too-short`, `invalid-erase`.
65
+ - **`npx dpdp-kit safeguards`**: Rule 6(1)(a)–(g), what's recorded and what's missing; `--strict` fails on gaps.
66
+ - **Guards**: `dpdp-kit/fastify` (`requireConsent`, `logAccess` as `preHandler` hooks) and `dpdp-kit/nestjs` (`consentGuard`, `accessLogGuard`), plus `logAccess` for Express and Hono.
67
+ - **Events**: `dpdp.on()` for `consent.granted`, `consent.withdrawn`, `erasure.scheduled`, `retention.ran`, `rights.opened`, `rights.closed`, `access.logged`, `daily.ran`.
68
+ - **`erase` on fields**: `"null"` (default), `"redact"` or `{ value }` (fixed or a function), so `NOT NULL` and `UNIQUE` columns can be erased.
69
+ - **Daily upkeep**: `dpdp.daily()` (erasure, access-log pruning and review, overdue requests) and `startDaily()` in `dpdp-kit/schedule`. Each step runs even if another fails (failures are in `report.errors`), and `startDaily` starts each review where the last successful one ended, so a failed night isn't skipped.
70
+ - **`audit --schema` checks erase settings against the columns**: `erase-not-null` when a `NOT NULL` column would be erased to `NULL`, `erase-type-mismatch` when the replacement doesn't fit the column. Without it, such a mistake shows up only when the task runs, often a year later.
71
+ - NestJS guards take a `request` option for GraphQL and other non-HTTP contexts; the Fastify guard falls back to 403 if `onDenied` sends nothing; event listeners each get their own copy of the payload; concurrent consent writes for one person back off with jitter.
72
+
73
+ ### Upgrading from 0.2.x
74
+
75
+ 1. **New table.** Add `accessLog` to your Drizzle schema (`export { accessLog } from "dpdp-kit/drizzle"`) and generate a migration, or run `ACCESS_LOG_DDL`.
76
+ 2. **New audit warnings.** If you run `dpdp-kit audit --strict`, add a `security` block and a `contract` for each processor first, and mark high-risk fields with `protect` (or the build will fail on the new warnings).
77
+ 3. **Custom `DataAccess`.** `eraseFields` now gets an optional fifth argument with each column's replacement value. Implementations that ignore it keep writing `NULL`, as before.
78
+ 4. **Custom stores.** The access log needs `AccessLogStore` (`insertAccess`, `listAccess`, `pruneAccess`). Without it, `dpdp.access` throws `store-unsupported` and `daily()` skips it.
79
+
80
+ ## 0.2.0
81
+
82
+ Rights requests (Sections 11–14, Rule 14), the retention runner (Section 8(7), Rule 8(3), legal holds), processor hooks, `drizzleData`, and the GitHub Action with pull request annotations.
83
+
84
+ ## 0.1.2
85
+
86
+ Schema drift check: `audit --schema`, `checkSchema`, `drizzleSchema`, `notPersonal`.
87
+
88
+ ## 0.1.0
89
+
90
+ Typed config, `audit` and the CLI, hash-chained consent records, erasure plans, the Drizzle store, Express and Hono guards.
package/README.md CHANGED
@@ -4,11 +4,17 @@
4
4
 
5
5
  **The Node.js-native toolkit for India's Digital Personal Data Protection Act, 2023.** Build it into your Node.js backend.
6
6
 
7
+ **Website and docs: [dpdp-kit.js.org](https://dpdp-kit.js.org/)**
8
+
9
+ ![dpdp-kit catching an unmapped aadhaar_number column in CI, then passing once it's mapped](docs/media/demo.gif)
10
+
7
11
  - **Declare why you hold each piece of personal data**, in one typed config file. A misspelt purpose is a type error.
8
12
  - **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
13
  - **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.
14
+ - **Handle a breach on time.** Record it, find and tell the people affected, and track the Board's 72-hour deadline (Section 8(6), Rule 7).
15
+ - **Show who touched what.** An access log records who read whose data and why, flags reads outside a field's purpose, and keeps a year of entries, as Rule 6 requires. Encryption, tokens and masking for Aadhaar, PAN and other identifiers come in `dpdp-kit/protect`.
10
16
  - **Check it in CI.** `dpdp-kit audit` fails the build when the data map is inconsistent, and the GitHub Action puts each problem on the pull request.
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.
17
+ - **Catch drift.** `dpdp-kit audit --schema` reads your Drizzle, Prisma or Mongoose 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.
12
18
 
13
19
  ## Node-native
14
20
 
@@ -16,10 +22,10 @@ dpdp-kit is a TypeScript library that runs **inside your Node.js process**, not
16
22
 
17
23
  - **No separate server.** There's nothing to deploy, no sidecar to keep running, and no REST API between your code and your consent records.
18
24
  - **No hosted service.** No account, no API key, and no network calls. Personal data never leaves your infrastructure.
19
- - **Your own database.** Consent records go into your own Postgres, through the Drizzle setup you already have, in the same database as the rest of your data.
20
- - **Fits your Node stack.** Typed config, middleware for Express and Hono, a CLI for CI, and works with ESM, `require()` and TypeScript.
25
+ - **Your own database.** Consent records go into your own Postgres or MongoDB, through the Drizzle, Prisma or Mongoose setup you already have (or any Postgres client), in the same database as the rest of your data.
26
+ - **Fits your Node stack.** Typed config, guards for Express, Hono, Fastify and NestJS, a CLI for CI, and works with ESM, `require()` and TypeScript.
21
27
 
22
- > **Not legal advice.** dpdp-kit helps you put compliance into practice; it does not make an app compliant on its own. Section and rule references point you to the text so you can check them. Have your own lawyer review your purposes, notices and retention periods.
28
+ > **Not legal advice.** dpdp-kit helps you put compliance into practice; it does not make an app compliant on its own. Section and rule references point you to the text so you can check them. Have your own lawyer review your purposes, notices and retention periods. [Who does what](https://dpdp-kit.js.org/docs/responsibility/) lists every duty in the Act and Rules, what dpdp-kit does and what your company still does.
23
29
 
24
30
  ## Install
25
31
 
@@ -29,6 +35,15 @@ npm install dpdp-kit
29
35
 
30
36
  Node.js 20.19 or later. The package is ESM-only; `require("dpdp-kit")` also works on those Node versions.
31
37
 
38
+ | Your stack | Store and data access | Drift check |
39
+ |---|---|---|
40
+ | Drizzle (Postgres) | `dpdp-kit/drizzle` | `--schema src/db/schema.ts` |
41
+ | Prisma (Postgres) | `dpdp-kit/prisma` | `--schema prisma/schema.prisma` |
42
+ | MongoDB or Mongoose | `dpdp-kit/mongodb` | `--schema src/models.ts` |
43
+ | Any other Postgres client | `dpdp-kit/postgres` | |
44
+
45
+ **Start from a working app:** [`examples/`](examples/) has the same shop on Express + Prisma + Postgres and on Express + Mongoose + MongoDB. A script takes each one through a year of customers, support, a breach and erasure. CI runs it on every change.
46
+
32
47
  ## 1. Declare your data
33
48
 
34
49
  ```ts
@@ -95,10 +110,12 @@ The same checks run when the app starts: `createDpdp` throws if the config has e
95
110
 
96
111
  ### Catch schema drift
97
112
 
98
- A data map is only useful while it matches the database. Point the audit at your Drizzle schema (Postgres, MySQL or SQLite):
113
+ A data map is only useful while it matches the database. Point the audit at your Drizzle schema (Postgres, MySQL or SQLite), your Prisma schema or your Mongoose models:
99
114
 
100
115
  ```bash
101
116
  npx dpdp-kit audit --schema src/db/schema.ts
117
+ npx dpdp-kit audit --schema prisma/schema.prisma # or a folder of .prisma files
118
+ npx dpdp-kit audit --schema src/models.ts # a file that exports Mongoose models
102
119
  ```
103
120
 
104
121
  ```
@@ -115,6 +132,13 @@ It checks both directions:
115
132
 
116
133
  - **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
134
  - **A data map that points at nothing.** Tables or columns that were renamed or dropped.
135
+ - **Erase settings a column can't take.** Erasing a `NOT NULL` column to null, or writing text into a number column.
136
+ - **Foreign keys that break a legal hold.** Account deletion deletes the person's rows but keeps held ones, like invoices kept for GST. A foreign key from the held table to the users table defeats that:
137
+ - `ON DELETE CASCADE` deletes the invoices with the account (an error).
138
+ - `SET NULL` on the subject column loses whose invoices they are (an error).
139
+ - `RESTRICT`, Prisma's default for a required relation, makes the deletion fail (a warning).
140
+
141
+ Keep the link as a plain, indexed column instead.
118
142
 
119
143
  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
144
 
@@ -122,11 +146,11 @@ Columns that describe data rather than hold it, such as `email_verified_at`, `ph
122
146
  notPersonal: ["products.name", "branches.*"], // database table and column names
123
147
  ```
124
148
 
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.
149
+ From code, `checkSchema(config, drizzleSchema(schema))` returns the same issues. `drizzleSchema` comes from `dpdp-kit/drizzle`, `prismaSchema(text)` from `dpdp-kit/prisma`, and `mongooseSchema(models)` from `dpdp-kit/mongodb`. With Prisma, the data map can use model and field names (`User`, `phoneNumber`) or the database's (`users`, `phone_number`). 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
150
 
127
151
  ### In GitHub Actions
128
152
 
129
- Add the audit to any workflow. Problems show up as annotations on the pull request, plus a summary on the run page:
153
+ Add the audit to any workflow (it's on the [GitHub Marketplace](https://github.com/marketplace/actions/dpdp-kit-audit) as DPDP Kit Audit). Problems show up as annotations on the pull request, plus a summary on the run page:
130
154
 
131
155
  ```yaml
132
156
  # .github/workflows/dpdp.yml
@@ -141,15 +165,15 @@ jobs:
141
165
  with:
142
166
  node-version: 22
143
167
  - run: npm ci # so your config can import dpdp-kit
144
- - uses: yogesh2902/dpdp-kit@main
168
+ - uses: yogesh2902/dpdp-kit@v0
145
169
  with:
146
- schema: src/db/schema.ts # optional: also check for drift
170
+ schema: src/db/schema.ts # optional: Drizzle, prisma/schema.prisma or Mongoose models
147
171
  # config: dpdp.config.ts # default: found automatically
148
172
  # strict: true # fail on warnings too
149
173
  # working-directory: apps/api # for monorepos
150
174
  ```
151
175
 
152
- The Action runs the dpdp-kit your project installed, falling back to `npx dpdp-kit@latest`. It sets `errors` and `warnings` outputs. Annotations need dpdp-kit 0.2.0 or later; with 0.1.x the check still runs and fails the build, without annotations. Outside GitHub, `npx dpdp-kit audit --format github` prints the same annotation lines.
176
+ `@v0` follows the latest 0.x release; to pin one, use its tag, e.g. `yogesh2902/dpdp-kit@v0.4.0` (each release is on the [releases page](https://github.com/yogesh2902/dpdp-kit/releases)). The Action runs the dpdp-kit your project installed, falling back to `npx dpdp-kit@latest`. It sets `errors` and `warnings` outputs. Annotations need dpdp-kit 0.2.0 or later; with 0.1.x the check still runs and fails the build, without annotations. Outside GitHub, `npx dpdp-kit audit --format github` prints the same annotation lines.
153
177
 
154
178
  ## 3. Record consent
155
179
 
@@ -228,7 +252,17 @@ const report = await dpdp.retention.run(); // { done, failed, manual }
228
252
  - **Failures are retried**, up to 5 times. `lastError` keeps the database's message for developers, for example when a column is `NOT NULL`.
229
253
  - **A processor with no hook** gives a `manual` task. Handle it yourself (email their support), then `retention.markDone(taskId, "ticket 4411")`.
230
254
  - **Consent records are never erased.** Section 6(10) makes you prove consent, and Rule 8(3) requires keeping records of processing.
231
- - **Erasure sets columns to `NULL`**, so erasable columns must be nullable. Data access currently covers Postgres.
255
+ - **Erasure sets columns to `NULL` by default.** For a `NOT NULL` column, say what to write instead with the field's `erase` setting (below). Data access currently covers Postgres.
256
+
257
+ ```ts
258
+ fields: {
259
+ nickname: { category: "identity", purposes: ["newsletter"], erase: "redact" }, // "[erased]"
260
+ points: { category: "behavioural", purposes: ["newsletter"], erase: { value: 0 } },
261
+ email: { category: "contact", purposes: ["newsletter"], erase: { value: ({ subjectId }) => `erased-${subjectId}@invalid` } }, // NOT NULL UNIQUE
262
+ },
263
+ ```
264
+
265
+ The replacement must not identify the person: use their internal id, never a hash of their data. `dpdp-kit audit --schema` checks each setting against your columns (a `NOT NULL` column erased to `NULL`, or text into a number column), so a mistake fails CI now instead of the erasure a year from now.
232
266
 
233
267
  ## 5. Rights requests
234
268
 
@@ -264,7 +298,70 @@ Corrections and nominations are recorded with the request (`details`); your app
264
298
  rights: { responseWithin: { grievance: "30d", access: "30d" } },
265
299
  ```
266
300
 
267
- ## 6. Guard routes
301
+ ## 6. Security safeguards and access logs
302
+
303
+ Rule 6(1) of the DPDP Rules sets the minimum security safeguards, and a breach of Section 8(5) carries the Act's highest penalty, up to ₹250 crore. The parts that live in code are built in.
304
+
305
+ **Access log (Rule 6(1)(c) and (e)).** Record who accessed whose data, why, and which fields:
306
+
307
+ ```ts
308
+ await dpdp.access.log({
309
+ actor: "support:priya", // who
310
+ subjectId: userId, // whose data
311
+ purpose: "account", // why: one of your purposes
312
+ fields: ["users.phone", "orders"], // what: "table.field", or a whole table
313
+ reason: "ticket 4411",
314
+ });
315
+
316
+ await dpdp.access.list({ subjectId: userId }); // investigate one person, an actor, or a period
317
+ await dpdp.access.review(); // daily: find unauthorised access
318
+ await dpdp.access.prune(); // keeps at least a year, as Rule 6(1)(e) requires
319
+ ```
320
+
321
+ A field read for a purpose it isn't held for is recorded as `outOfPurpose` (or refused, with `createDpdp({ ..., access: { outOfPurpose: "throw" } })`). `review()` reports reads outside their purpose, consent purposes used when the person hadn't consented at that moment, and one actor reaching more than 100 people within an hour (both adjustable). Or log whole routes:
322
+
323
+ ```ts
324
+ import { logAccess } from "dpdp-kit/express"; // or "dpdp-kit/hono"
325
+ app.get("/admin/users/:id", logAccess(dpdp, {
326
+ purpose: "account",
327
+ fields: ["users"],
328
+ actor: (req) => req.staff?.id,
329
+ subject: (req) => req.params.id,
330
+ }), handler);
331
+ ```
332
+
333
+ **Encryption, masking and virtual tokens (Rule 6(1)(a)).** `dpdp-kit/protect` has AES-256-GCM field encryption with key rotation, keyed tokens for lookups, and masking:
334
+
335
+ ```ts
336
+ import { createEncryptor, createTokenizer, maskAadhaar } from "dpdp-kit/protect";
337
+
338
+ const enc = createEncryptor({ keys: { k1: process.env.DPDP_KEY_1! }, current: "k1" });
339
+ const stored = enc.encrypt(aadhaar, `users.aadhaar:${user.id}`); // bound to this row
340
+ enc.decrypt(stored, `users.aadhaar:${user.id}`);
341
+
342
+ const tokens = createTokenizer({ key: process.env.DPDP_TOKEN_KEY! });
343
+ tokens.token(email); // same email → same token, so you can look rows up without storing the email in the clear
344
+
345
+ maskAadhaar("1234 5678 9012"); // "XXXX XXXX 9012"
346
+ ```
347
+
348
+ Generate keys with `generateKey()` and keep them in your secrets manager. To rotate, add a new key, make it `current`, and re-encrypt values where `needsRotation(value)` is true.
349
+
350
+ **The rest, as evidence in the config.** Say how each field is protected, where each processor contract has its security clause (Rule 6(1)(f)), and the safeguards that live outside code:
351
+
352
+ ```ts
353
+ data: { users: { /* … */ fields: { aadhaar: { category: "identity", purposes: ["kyc"], protect: "encrypted" } } } },
354
+ processors: { msg91: { purposes: ["marketing_sms"], contract: "DPA signed 2026-03-01, clause 7" } },
355
+ security: {
356
+ accessControl: "SSO with least-privilege roles", // Rule 6(1)(b)
357
+ backups: "Encrypted daily backups, restore tested monthly", // Rule 6(1)(d)
358
+ measures: "Annual security training, quarterly access reviews", // Rule 6(1)(g)
359
+ },
360
+ ```
361
+
362
+ The audit warns about high-risk identifiers (Aadhaar, PAN, passport, bank account, card numbers, health and biometric data) without `protect`, processors without `contract`, and missing `security` entries. `npx dpdp-kit safeguards` prints the whole of Rule 6(1), (a) to (g), with what's recorded and what's missing (`--strict` fails on gaps).
363
+
364
+ ## 7. Guard routes
268
365
 
269
366
  ```ts
270
367
  // Express
@@ -276,7 +373,67 @@ import { requireConsent } from "dpdp-kit/hono";
276
373
  app.post("/promo", requireConsent(dpdp, "marketing_sms", { subject: (c) => c.get("userId") }), handler);
277
374
  ```
278
375
 
279
- Without consent, the middleware responds `403 { error: "consent_required", purpose, message }`. The message is plain enough to show to people. Pass `onDenied` to send your own response.
376
+ ```ts
377
+ // Fastify
378
+ import { requireConsent } from "dpdp-kit/fastify";
379
+ app.post("/promo", { preHandler: requireConsent(dpdp, "marketing_sms", { subject: (req) => req.user?.id }) }, handler);
380
+
381
+ // NestJS
382
+ import { consentGuard } from "dpdp-kit/nestjs";
383
+ @UseGuards(consentGuard(dpdp, "marketing_sms", { subject: (req) => req.user?.id }))
384
+ @Post("promo")
385
+ sendPromo() {}
386
+ ```
387
+
388
+ Without consent, the middleware responds `403 { error: "consent_required", purpose, message }`. The message is plain enough to show to people. Pass `onDenied` to send your own response; in NestJS, return the exception to throw, e.g. `(purpose) => new ForbiddenException(CONSENT_REQUIRED_BODY(purpose))`. Access logging works the same way in every framework: `logAccess` for Express, Hono and Fastify, `accessLogGuard` for NestJS.
389
+
390
+ ## 8. Events
391
+
392
+ Listen for changes to feed your own audit trail, alerts or analytics:
393
+
394
+ ```ts
395
+ const off = dpdp.on("consent.withdrawn", ({ event }) => analytics.forget(event.subjectId, event.purposes));
396
+ dpdp.on("access.logged", ({ entries }) => {
397
+ if (entries.some((e) => e.outOfPurpose)) slack.alert("Out-of-purpose read", entries);
398
+ });
399
+ ```
400
+
401
+ Events: `consent.granted`, `consent.withdrawn`, `erasure.scheduled`, `retention.ran`, `rights.opened`, `rights.closed`, `access.logged`. Listeners run after the change is saved and after the call returns, and a listener that throws can't break it: errors go to `onListenerError` (default `console.error`). For work that must happen exactly once, like telling a vendor to erase, use processor hooks and the retention runner instead.
402
+
403
+ ## 9. Daily upkeep
404
+
405
+ One call does the jobs that must happen on time: carry out due erasure, prune access logs older than a year, review the last day of access, and list overdue rights requests.
406
+
407
+ ```ts
408
+ const report = await dpdp.daily(); // { retention, accessPruned, review, overdueRequests, skipped }
409
+
410
+ // schedule it in-process, with no dependencies:
411
+ import { startDaily } from "dpdp-kit/schedule";
412
+ startDaily(dpdp, { at: "03:00", onReport: (r) => r.retention?.failed.length && alert(r) });
413
+ ```
414
+
415
+ Or call `dpdp.daily()` from node-cron, a BullMQ repeatable job (to run it once across servers), or your platform's cron. It's safe to run from several servers at once.
416
+
417
+ ## 10. Breach records
418
+
419
+ Section 8(6) and Rule 7: on becoming aware of a personal data breach, tell each affected person and the Board without delay, and send the Board a detailed report within 72 hours. Failing to notify carries up to ₹200 crore.
420
+
421
+ ```ts
422
+ const breach = await dpdp.breach.open({ description: "A storage bucket exposed order exports.", fields: ["users.phone", "orders"] });
423
+ await dpdp.breach.addAffectedFromAccessLog(breach.id, { actor: "support:ravi" }); // or addAffected(id, userIds)
424
+
425
+ const notice = await dpdp.breach.notice(breach.id); // Rule 7(1)(a)–(e), with fiduciary.dpo as the contact
426
+ await dpdp.breach.markNotified(breach.id, sentIds, { channel: "email" });
427
+
428
+ await dpdp.breach.boardNotified(breach.id); // Rule 7(2)(a)
429
+ await dpdp.breach.updateReport(breach.id, { details, facts, mitigation, findings, remedial });
430
+ const report = await dpdp.breach.boardReport(breach.id); // (i)–(vi), (vi) built from the notice records
431
+ await dpdp.breach.reportSent(breach.id);
432
+
433
+ await dpdp.breach.status(breach.id); // { report: { dueAt, hoursLeft, overdue }, people: { total, sent, pending }, todo }
434
+ ```
435
+
436
+ `dpdp.daily()` reports every open breach and its deadline, and a written Board extension can be recorded with `extend()`. dpdp-kit keeps the record and the clocks; you send the messages.
280
437
 
281
438
  ## Storage
282
439
 
@@ -286,18 +443,81 @@ Add the tables to your schema so drizzle-kit creates them:
286
443
 
287
444
  ```ts
288
445
  // schema.ts
289
- export { consentEvents, erasureTasks, rightsRequests } from "dpdp-kit/drizzle";
446
+ export { accessLog, breachNotices, breaches, consentEvents, erasureTasks, rightsRequests } from "dpdp-kit/drizzle";
290
447
  ```
291
448
 
292
449
  If you don't use drizzle-kit, run `DPDP_DDL` (exported from `dpdp-kit/drizzle`). This works with any Drizzle Postgres driver: node-postgres, postgres.js, Neon, PGlite.
293
450
 
294
451
  > **Upgrading from 0.1.x?** Add `rightsRequests` and `erasureTasks` to your schema and generate a migration, or run `RECORDS_DDL`. `withdraw()` now schedules erasure tasks, so it needs the `dpdp_erasure_tasks` table.
452
+ >
453
+ > **Upgrading from 0.3.x?** Add `breaches` and `breachNotices` to your schema and generate a migration, or run `BREACH_DDL`. The audit now also warns when `fiduciary.dpo` is missing (Section 8(9), Rule 7(1)(e)).
454
+ >
455
+ > **Upgrading from 0.2.x?** Add `accessLog` to your schema and generate a migration, or run `ACCESS_LOG_DDL`, before using `dpdp.access`. The audit now warns about the Rule 6 safeguards; if you run it with `--strict`, add a `security` block and processor `contract`s first.
295
456
 
296
457
  `drizzleData(db, { schema })` reaches your own tables. Pass your schema module when the data map uses Drizzle property names (`userId`) rather than column names (`user_id`).
297
458
 
459
+ ### Prisma (Postgres)
460
+
461
+ Add dpdp-kit's models to `schema.prisma` and run `prisma migrate dev`:
462
+
463
+ ```ts
464
+ import { PRISMA_MODELS } from "dpdp-kit/prisma";
465
+ console.log(PRISMA_MODELS); // paste into schema.prisma, or save as prisma/schema/dpdp.prisma
466
+ ```
467
+
468
+ ```ts
469
+ import { readFileSync } from "node:fs";
470
+ import { createDpdp } from "dpdp-kit";
471
+ import { prismaData, prismaSchema, prismaStore } from "dpdp-kit/prisma";
472
+
473
+ const schema = prismaSchema(readFileSync("prisma/schema.prisma", "utf8"));
474
+ const dpdp = createDpdp({ config, store: prismaStore(prisma), data: prismaData(prisma, { schema }) });
475
+ ```
476
+
477
+ It runs parameterised SQL through `prisma.$queryRawUnsafe`, and works inside `prisma.$transaction(async (tx) => …)` with `prismaStore(tx)`. Tested on Prisma 7 with `@prisma/adapter-pg`. Every parameter has an explicit cast, so earlier versions should work too, but they aren't tested. The models match `DPDP_DDL`, so either can create the tables.
478
+
479
+ ### Any other Postgres client
480
+
481
+ `dpdp-kit/postgres` needs only a function that runs a query with `$1` parameters: node-postgres, postgres.js, Kysely, Knex or Slonik.
482
+
483
+ ```ts
484
+ import pg from "pg";
485
+ import { postgresData, postgresStore } from "dpdp-kit/postgres";
486
+
487
+ const pool = new pg.Pool();
488
+ const query = async (text: string, params: readonly unknown[]) => (await pool.query(text, [...params])).rows;
489
+ const dpdp = createDpdp({ config, store: postgresStore(query), data: postgresData(query) });
490
+ ```
491
+
492
+ Create the tables by running `DPDP_DDL`, a plain SQL string exported by `dpdp-kit/postgres`.
493
+
494
+ ### MongoDB and Mongoose
495
+
496
+ ```ts
497
+ import { createDpdp } from "dpdp-kit";
498
+ import { mongoData, mongooseSchema, mongoStore } from "dpdp-kit/mongodb";
499
+
500
+ // the official driver
501
+ const dpdp = createDpdp({ config, store: mongoStore(client.db()), data: mongoData(client.db(), { ObjectId }) });
502
+
503
+ // Mongoose: a function, so dpdp can be created before mongoose.connect()
504
+ const db = () => mongoose.connection.db;
505
+ const dpdp = createDpdp({
506
+ config,
507
+ store: mongoStore(db),
508
+ data: mongoData(db, { schema: mongooseSchema(mongoose), ObjectId: mongoose.Types.ObjectId }),
509
+ });
510
+ ```
511
+
512
+ - Records go into `dpdp_*` collections. The store creates their indexes before its first write, including the unique `(subjectId, seq)` index that keeps each consent chain from forking. Call `createMongoIndexes(db)` from a deploy script if the app's user can't create indexes.
513
+ - In the data map, `table` is a collection, or a Mongoose model name with `schema`. Fields are document paths, so `"address.city"` works. With a Mongoose schema, `id` means `_id`.
514
+ - Pass `ObjectId` to find people by an ObjectId `_id`. Ids that look like numbers also match number fields.
515
+ - Erasure removes a field (`$unset`), or sets the field's `erase` replacement.
516
+ - `dpdp-kit audit --schema src/models.ts` reads the Mongoose models a file exports.
517
+
298
518
  ### Anything else
299
519
 
300
- Implement `DpdpStore`: consent events (`lastEvent`, `insert`, `events`), requests and tasks (see `RequestStore` and `TaskStore`). `insert` must throw `SeqConflictError` on a duplicate `(subjectId, seq)`, and `claimTask` must be atomic. A store with only the three consent methods still works for consent; rights and retention then throw `store-unsupported`. Implement `DataAccess` (`read`, `eraseFields`, `deleteRows`) for another database. `memoryStore()` and `memoryData()` are included for tests.
520
+ Implement `DpdpStore`: consent events (`lastEvent`, `insert`, `events`), requests and tasks (see `RequestStore` and `TaskStore`), and `AccessLogStore` for the access log. `insert` must throw `SeqConflictError` on a duplicate `(subjectId, seq)`, and `claimTask` must be atomic. A store with only the three consent methods still works for consent; rights and retention then throw `store-unsupported`. Implement `DataAccess` (`read`, `eraseFields`, `deleteRows`) for another database. `memoryStore()` and `memoryData()` are included for tests.
301
521
 
302
522
  ## How the consent record works
303
523
 
@@ -315,8 +535,11 @@ Section 6(10) puts the burden on you: if consent is questioned in a proceeding,
315
535
  | **v0.1** | Config and types, `audit` + CLI, consent records, erasure plans, Drizzle store, Express/Hono guards |
316
536
  | **v0.1.2** | Schema drift check: `audit --schema`, `checkSchema`, `drizzleSchema`, `notPersonal` |
317
537
  | **v0.2.0** | Rights requests (Sections 11–14, Rule 14), retention runner that carries out erasure (Section 8(7), Rule 8(3), legal holds), processor hooks, `drizzleData`, GitHub Action with pull request annotations |
318
- | later | Recording objections to a Section 7(a) use, React notice that meets Rule 3 + privacy centre, MySQL and SQLite data access |
319
- | 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 |
538
+ | **v0.3.0** | Security safeguards (Rule 6): access log with review and one-year retention, `dpdp-kit/protect` (encryption, virtual tokens, masking), `protect` / `contract` / `security` in the config, `dpdp-kit safeguards`; Fastify and NestJS guards; `logAccess` for every framework; events (`dpdp.on`); `erase` replacements for `NOT NULL` columns; `dpdp.daily()` and `startDaily` |
539
+ | **v0.4.0** | **Breach records** (Section 8(6), Rule 7) with the 72-hour Board report; **Prisma**, **MongoDB and Mongoose** and plain-SQL Postgres stores and data access; drift checks on Prisma schemas and Mongoose models; example apps run in CI |
540
+ | next (0.5) | Notices that meet Rule 3 from the config, recording objections to a Section 7(a) use, an HTTP API with Express, Hono and Next.js adapters, completing rights requests, cross-border transfer records (Section 16) |
541
+ | after (0.6) | MySQL and SQLite data access, React and React Native consent screens, Next.js and Expo example apps |
542
+ | later | Children and guardian consent (Section 9, Rule 10), inactivity erasure (Rule 8(1)–(2), Third Schedule), erasure beyond SQL (files, caches, search indexes), Consent Manager interop (Sections 6(7)–6(9), Rule 4) |
320
543
 
321
544
  ## When the Rules apply
322
545
 
@@ -0,0 +1,111 @@
1
+ import type { DpdpConfig } from "./config.js";
2
+ import { type Duration } from "./duration.js";
3
+ import { type ConsentEvent } from "./store.js";
4
+ /** What was done with the data. Free text is allowed; these are the common ones. */
5
+ export type AccessAction = "read" | "export" | "update" | "delete" | "search" | (string & {});
6
+ /**
7
+ * One access to one person's personal data. Rule 6(1)(c) of the DPDP Rules requires "visibility on
8
+ * the accessing of such personal data, through appropriate logs, monitoring and review", and Rule
9
+ * 6(1)(e) requires keeping those logs for a year.
10
+ */
11
+ export interface AccessEntry {
12
+ id: string;
13
+ /** ISO 8601 timestamp. */
14
+ at: string;
15
+ /** Who accessed the data: a staff user's id, a service or job name. */
16
+ actor: string;
17
+ /** Whose data it was. */
18
+ subjectId: string;
19
+ action: AccessAction;
20
+ /** Why: one of the config's purposes. */
21
+ purpose: string;
22
+ /** What was accessed, as data map keys: `"users.phone"`. */
23
+ fields?: string[];
24
+ /** The fields from `fields` that aren't held for `purpose`. */
25
+ outOfPurpose?: string[];
26
+ /** Free text, e.g. a support ticket number. */
27
+ reason?: string;
28
+ /** Details of the request, e.g. IP address, user agent, request id. */
29
+ evidence?: Record<string, string>;
30
+ }
31
+ export interface AccessFilter {
32
+ subjectId?: string;
33
+ actor?: string;
34
+ purpose?: string;
35
+ /** ISO 8601, inclusive. */
36
+ from?: string;
37
+ /** ISO 8601, exclusive. */
38
+ to?: string;
39
+ limit?: number;
40
+ }
41
+ /** Storage for the access log. Both built-in stores implement it. */
42
+ export interface AccessLogStore {
43
+ insertAccess(entries: readonly AccessEntry[]): Promise<void>;
44
+ /** Entries matching the filter, oldest first. */
45
+ listAccess(filter: AccessFilter): Promise<AccessEntry[]>;
46
+ /** Delete entries older than `before` (ISO 8601). Returns how many were deleted. */
47
+ pruneAccess(before: string): Promise<number>;
48
+ /**
49
+ * The distinct people in entries matching the filter. Optional: without it, dpdp-kit reads the
50
+ * entries and collects them itself, which loads every entry into memory.
51
+ */
52
+ accessSubjects?(filter: Omit<AccessFilter, "limit">): Promise<string[]>;
53
+ }
54
+ export declare function isAccessLogStore(store: object): store is AccessLogStore;
55
+ /**
56
+ * An id that sorts in the order entries were written: the time, then a per-process counter for
57
+ * entries in the same millisecond, then random bits so ids from different servers never collide.
58
+ */
59
+ export declare function accessId(at: string): string;
60
+ /** Default and minimum time to keep the access log (Rule 6(1)(e)). */
61
+ export declare const DEFAULT_ACCESS_LOG_RETENTION = "1y";
62
+ /**
63
+ * Expand field keys against the data map: `"users.phone"` stays as it is; `"users.*"` and
64
+ * `"users"` become every personal field of that table. Returns the keys it doesn't know too.
65
+ */
66
+ export declare function resolveFields(config: DpdpConfig<string>, keys: readonly string[]): {
67
+ fields: string[];
68
+ unknown: string[];
69
+ };
70
+ /** The fields that aren't held for `purpose` according to the data map. */
71
+ export declare function fieldsOutsidePurpose(config: DpdpConfig<string>, fields: readonly string[], purpose: string): string[];
72
+ export type AccessFindingKind = "out-of-purpose" | "no-consent" | "bulk-access";
73
+ export interface AccessFinding {
74
+ kind: AccessFindingKind;
75
+ actor: string;
76
+ /** Plain-language explanation, for whoever reviews the log. */
77
+ message: string;
78
+ /** Ids of the log entries involved. */
79
+ entries: string[];
80
+ subjectId?: string;
81
+ purpose?: string;
82
+ /** For `bulk-access`: distinct people accessed within one window. */
83
+ subjects?: number;
84
+ }
85
+ export interface AccessReview {
86
+ from: string;
87
+ to: string;
88
+ /** Entries looked at. */
89
+ scanned: number;
90
+ findings: AccessFinding[];
91
+ }
92
+ export interface ReviewInput {
93
+ config: DpdpConfig<string>;
94
+ entries: readonly AccessEntry[];
95
+ from: string;
96
+ to: string;
97
+ /** Consent events for a person, oldest first. */
98
+ history: (subjectId: string) => Promise<readonly ConsentEvent[]>;
99
+ /** Window for bulk-access detection, e.g. `"1h"`. */
100
+ window: Duration;
101
+ /** More distinct people than this within one window is reported as bulk access. */
102
+ maxSubjects: number;
103
+ /** Actors exempt from bulk-access findings (batch jobs). */
104
+ ignoreActors?: readonly string[];
105
+ }
106
+ /**
107
+ * Look through access log entries for signs of unauthorised access (Rule 6(1)(c)): fields read for
108
+ * a purpose they aren't held for, consent purposes used without consent at the time, and one actor
109
+ * reaching an unusual number of people in a short time.
110
+ */
111
+ export declare function reviewAccess(input: ReviewInput): Promise<AccessReview>;
package/dist/audit.d.ts CHANGED
@@ -2,7 +2,7 @@ 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" | "invalid-not-personal" | "unknown-table" | "unknown-column" | "unmapped-personal-column" | "stale-not-personal" | "grievance-response-too-long" | "invalid-request-type";
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" | "contact-missing" | "fiduciary-missing" | "invalid-not-personal" | "unknown-table" | "unknown-column" | "unmapped-personal-column" | "stale-not-personal" | "grievance-response-too-long" | "invalid-request-type" | "unprotected-high-risk-field" | "processor-contract-missing" | "security-measure-missing" | "access-log-retention-too-short" | "invalid-erase" | "erase-not-null" | "erase-type-mismatch" | "held-rows-cascade" | "held-link-lost" | "held-rows-block-delete";
6
6
  /** Where in the config (`data.users.fields.phone`), or in the schema (`schema.users.phone`). */
7
7
  path: string;
8
8
  message: string;
@@ -12,4 +12,6 @@ export interface Issue {
12
12
  * reviewer should look at. This checks the config's own consistency, not legal compliance.
13
13
  */
14
14
  export declare function audit(config: DpdpConfig<string>): Issue[];
15
+ /** Whether a field holds high-risk data, judging by its declared category and its name. */
16
+ export declare function isHighRisk(field: string, category: string): boolean;
15
17
  export declare function hasErrors(issues: readonly Issue[]): boolean;