dpdp-kit 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1
4
+
5
+ The GitHub Action's description is now short enough for the GitHub Marketplace (under 125 characters), so this release can be listed there. No changes to the library.
6
+
7
+ ## 0.4.0
8
+
9
+ **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.
10
+
11
+ ### Added
12
+
13
+ - **Breach records** (Section 8(6), Rule 7): `dpdp.breach.open()` starts the 72-hour clock from when you became aware.
14
+ - Record who is affected (`addAffected`), or everyone a compromised account read (`addAffectedFromAccessLog`).
15
+ - `notice()` drafts the message to each person, Rule 7(1)(a)–(e), with your DPO as the contact.
16
+ - `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.
17
+ - `status()` says what's left to do. `daily()` includes every open breach.
18
+ - New events: `breach.opened`, `breach.reported` and `breach.closed`.
19
+ - Changes made at the same time are all kept, and a closed breach can't change.
20
+ - **`dpdp-kit/prisma`**:
21
+ - `prismaStore(prisma)` keeps consent, requests, tasks, the access log and breaches. `prismaData(prisma, { schema })` reaches your own tables.
22
+ - `prismaSchema(text)` reads `schema.prisma`: models, `@map` and `@@map`, native types, enums and lists.
23
+ - `PRISMA_MODELS` holds dpdp-kit's tables as Prisma models. `prisma migrate diff` finds no difference from `DPDP_DDL`.
24
+ - Works inside `prisma.$transaction` with `prismaStore(tx)`. Tested on Prisma 7 with `@prisma/adapter-pg`.
25
+ - **`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`.
26
+ - **`dpdp-kit/mongodb`**:
27
+ - `mongoStore(db)` keeps dpdp-kit's records in `dpdp_*` collections and creates its indexes itself.
28
+ - `mongoData(db, { schema, ObjectId })` reaches your own collections, including nested fields and fields inside arrays of subdocuments.
29
+ - `mongooseSchema(models)` feeds the drift check.
30
+ - Accepts the driver's `Db`, or `() => mongoose.connection.db` so dpdp can be created before Mongoose connects.
31
+ - **`audit --schema` reads Prisma and Mongoose:**
32
+ - `--schema prisma/schema.prisma`, or a folder of `.prisma` files.
33
+ - `--schema src/models.ts` for a file that exports Mongoose models.
34
+ - The data map and `notPersonal` can use model and field names (`User`, `phoneNumber`) as well as the database's names.
35
+ - **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:
36
+ - `ON DELETE CASCADE` would delete the invoices with the account: error `held-rows-cascade`.
37
+ - `SET NULL` on the subject column would lose whose they are: error `held-link-lost`.
38
+ - `RESTRICT`, Prisma's default for a required relation, makes the deletion fail: warning `held-rows-block-delete`.
39
+ - **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)).
40
+ - **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.
41
+
42
+ ### Fixed
43
+
44
+ - **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.
45
+
46
+ ### Upgrading from 0.3.x
47
+
48
+ 1. **New tables.**
49
+ - Drizzle: add `breaches` and `breachNotices` to your schema and generate a migration, or run `BREACH_DDL`.
50
+ - Prisma: add `PRISMA_MODELS`.
51
+ - MongoDB: nothing to do; the collections are created on first use.
52
+ 2. **New audit checks.**
53
+ - If you run `dpdp-kit audit --strict`, set `fiduciary.dpo` (your Data Protection Officer, or a contact person, with their business contact) first.
54
+ - 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).
55
+ 3. **Custom stores.**
56
+ - Breach records need `BreachStore`. Without it, `dpdp.breach` throws `store-unsupported` and `daily()` skips breaches.
57
+ - `updateBreach` must save only over the version it read, and return `false` otherwise (see `BreachStore`).
58
+ - `AccessLogStore.accessSubjects` is optional and new.
59
+
3
60
  ## 0.3.0
4
61
 
5
62
  **Security safeguards and access logs (Rule 6 of the DPDP Rules)**, plus Fastify and NestJS guards, events, `NOT NULL` erasure and daily upkeep.
package/README.md CHANGED
@@ -4,16 +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: [yogesh2902.github.io/dpdp-kit](https://yogesh2902.github.io/dpdp-kit/)**
7
+ **Website and docs: [dpdp-kit.js.org](https://dpdp-kit.js.org/)**
8
8
 
9
9
  ![dpdp-kit catching an unmapped aadhaar_number column in CI, then passing once it's mapped](docs/media/demo.gif)
10
10
 
11
11
  - **Declare why you hold each piece of personal data**, in one typed config file. A misspelt purpose is a type error.
12
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.
13
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).
14
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`.
15
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.
16
- - **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.
17
18
 
18
19
  ## Node-native
19
20
 
@@ -21,10 +22,10 @@ dpdp-kit is a TypeScript library that runs **inside your Node.js process**, not
21
22
 
22
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.
23
24
  - **No hosted service.** No account, no API key, and no network calls. Personal data never leaves your infrastructure.
24
- - **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.
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.
25
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.
26
27
 
27
- > **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.
28
29
 
29
30
  ## Install
30
31
 
@@ -34,6 +35,15 @@ npm install dpdp-kit
34
35
 
35
36
  Node.js 20.19 or later. The package is ESM-only; `require("dpdp-kit")` also works on those Node versions.
36
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
+
37
47
  ## 1. Declare your data
38
48
 
39
49
  ```ts
@@ -100,10 +110,12 @@ The same checks run when the app starts: `createDpdp` throws if the config has e
100
110
 
101
111
  ### Catch schema drift
102
112
 
103
- 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:
104
114
 
105
115
  ```bash
106
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
107
119
  ```
108
120
 
109
121
  ```
@@ -120,6 +132,13 @@ It checks both directions:
120
132
 
121
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.
122
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.
123
142
 
124
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:
125
144
 
@@ -127,11 +146,11 @@ Columns that describe data rather than hold it, such as `email_verified_at`, `ph
127
146
  notPersonal: ["products.name", "branches.*"], // database table and column names
128
147
  ```
129
148
 
130
- 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.
131
150
 
132
151
  ### In GitHub Actions
133
152
 
134
- 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:
135
154
 
136
155
  ```yaml
137
156
  # .github/workflows/dpdp.yml
@@ -146,15 +165,15 @@ jobs:
146
165
  with:
147
166
  node-version: 22
148
167
  - run: npm ci # so your config can import dpdp-kit
149
- - uses: yogesh2902/dpdp-kit@main
168
+ - uses: yogesh2902/dpdp-kit@v0
150
169
  with:
151
- schema: src/db/schema.ts # optional: also check for drift
170
+ schema: src/db/schema.ts # optional: Drizzle, prisma/schema.prisma or Mongoose models
152
171
  # config: dpdp.config.ts # default: found automatically
153
172
  # strict: true # fail on warnings too
154
173
  # working-directory: apps/api # for monorepos
155
174
  ```
156
175
 
157
- 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.
158
177
 
159
178
  ## 3. Record consent
160
179
 
@@ -395,6 +414,27 @@ startDaily(dpdp, { at: "03:00", onReport: (r) => r.retention?.failed.length && a
395
414
 
396
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.
397
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.
437
+
398
438
  ## Storage
399
439
 
400
440
  ### Drizzle (Postgres)
@@ -403,17 +443,78 @@ Add the tables to your schema so drizzle-kit creates them:
403
443
 
404
444
  ```ts
405
445
  // schema.ts
406
- export { accessLog, consentEvents, erasureTasks, rightsRequests } from "dpdp-kit/drizzle";
446
+ export { accessLog, breachNotices, breaches, consentEvents, erasureTasks, rightsRequests } from "dpdp-kit/drizzle";
407
447
  ```
408
448
 
409
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.
410
450
 
411
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.
412
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
+ >
413
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.
414
456
 
415
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`).
416
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
+
417
518
  ### Anything else
418
519
 
419
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.
@@ -435,9 +536,9 @@ Section 6(10) puts the burden on you: if consent is questioned in a proceeding,
435
536
  | **v0.1.2** | Schema drift check: `audit --schema`, `checkSchema`, `drizzleSchema`, `notPersonal` |
436
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 |
437
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` |
438
- | next (0.4) | **Prisma and MongoDB** stores and data access (with a Prisma schema drift check); **breach records** with the deadlines of Section 8(6) and Rule 7 |
439
- | then (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) |
440
- | after (0.6) | MySQL and SQLite data access, React and React Native consent screens, example apps |
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 |
441
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) |
442
543
 
443
544
  ## When the Rules apply
package/dist/access.d.ts CHANGED
@@ -45,6 +45,11 @@ export interface AccessLogStore {
45
45
  listAccess(filter: AccessFilter): Promise<AccessEntry[]>;
46
46
  /** Delete entries older than `before` (ISO 8601). Returns how many were deleted. */
47
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[]>;
48
53
  }
49
54
  export declare function isAccessLogStore(store: object): store is AccessLogStore;
50
55
  /**
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" | "unprotected-high-risk-field" | "processor-contract-missing" | "security-measure-missing" | "access-log-retention-too-short" | "invalid-erase" | "erase-not-null" | "erase-type-mismatch";
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;
@@ -0,0 +1,170 @@
1
+ import type { DpdpConfig } from "./config.js";
2
+ /** Rule 7(2)(b): the detailed report is due within seventy-two hours of becoming aware. */
3
+ export declare const BOARD_REPORT_WITHIN_HOURS = 72;
4
+ export interface BreachInput {
5
+ /** When you became aware of the breach (ISO 8601). Rule 7's clock starts here. Default: now. */
6
+ awareAt?: string;
7
+ /** When it happened, as far as you know (ISO 8601). */
8
+ occurredAt?: string;
9
+ /** What happened: its nature (Rule 7(1)(a), 7(2)(a)). */
10
+ description: string;
11
+ /** How much data and how many people (Rule 7(1)(a), 7(2)(a)). */
12
+ extent?: string;
13
+ /** Where it happened: system, region or vendor (Rule 7(2)(a)). */
14
+ location?: string;
15
+ /** The likely impact, for the Board (Rule 7(2)(a)). */
16
+ likelyImpact?: string;
17
+ /** The consequences likely for the people affected (Rule 7(1)(b)). */
18
+ consequences?: string;
19
+ /** What you've done and are doing to reduce the risk (Rule 7(1)(c)). */
20
+ measures?: string;
21
+ /** What people can do to protect themselves (Rule 7(1)(d)). */
22
+ safetySteps?: string;
23
+ /** The personal data exposed, as data map keys: `"users.phone"`, or `"users"` for a whole table. */
24
+ fields?: readonly string[];
25
+ }
26
+ /** The detailed report's parts, Rule 7(2)(b)(i)–(v). Part (vi) is built from the notice records. */
27
+ export interface BoardReportInput {
28
+ /** (i) Updated and detailed information about the breach. */
29
+ details?: string;
30
+ /** (ii) The broad facts: events, circumstances and reasons leading to the breach. */
31
+ facts?: string;
32
+ /** (iii) Measures implemented or proposed to mitigate the risk. */
33
+ mitigation?: string;
34
+ /** (iv) Findings about the person who caused the breach. */
35
+ findings?: string;
36
+ /** (v) Remedial measures taken to prevent it happening again. */
37
+ remedial?: string;
38
+ }
39
+ export interface Breach extends Omit<BreachInput, "awareAt" | "fields"> {
40
+ id: string;
41
+ awareAt: string;
42
+ fields: string[];
43
+ /** When the detailed report to the Board is due: 72 hours after `awareAt`, or the extension. */
44
+ reportDueAt: string;
45
+ /** A longer period the Board allowed on a written request (Rule 7(2)(b)). */
46
+ extension?: {
47
+ until: string;
48
+ reference: string;
49
+ recordedAt: string;
50
+ };
51
+ /** When you told the Board, without delay (Rule 7(2)(a)). */
52
+ boardNotifiedAt?: string;
53
+ /** The detailed report's parts so far. */
54
+ report: BoardReportInput;
55
+ /** When you sent the detailed report (Rule 7(2)(b)). */
56
+ reportSentAt?: string;
57
+ status: "open" | "closed";
58
+ closedAt?: string;
59
+ history: Array<{
60
+ at: string;
61
+ event: string;
62
+ note?: string;
63
+ }>;
64
+ }
65
+ /** One affected person, and whether they've been told (Rule 7(1)). */
66
+ export interface BreachNotice {
67
+ breachId: string;
68
+ subjectId: string;
69
+ status: "pending" | "sent";
70
+ addedAt: string;
71
+ sentAt?: string;
72
+ /** How they were told, e.g. `"email"`, `"sms"`, `"in-app"`. */
73
+ channel?: string;
74
+ }
75
+ /** Storage for breach records and notices. Both built-in stores implement it. */
76
+ export interface BreachStore {
77
+ insertBreach(breach: Breach): Promise<void>;
78
+ getBreach(id: string): Promise<Breach | undefined>;
79
+ /**
80
+ * Replace a stored breach, but only if no one changed it since it was read. Each change adds one
81
+ * history entry, so save only when the stored history is one entry shorter than `breach.history`.
82
+ * Returns false when it isn't; dpdp-kit then reads it again and retries.
83
+ */
84
+ updateBreach(breach: Breach): Promise<boolean>;
85
+ /** Breaches, newest first. */
86
+ listBreaches(filter: {
87
+ status?: Breach["status"];
88
+ }): Promise<Breach[]>;
89
+ /** Add affected people; people already on the breach are left as they are. Returns how many were new. */
90
+ addNotices(notices: readonly BreachNotice[]): Promise<number>;
91
+ /** Mark these people as told. Returns how many changed. */
92
+ markNotices(breachId: string, subjectIds: readonly string[], sentAt: string, channel?: string): Promise<number>;
93
+ listNotices(breachId: string, filter: {
94
+ status?: BreachNotice["status"];
95
+ limit?: number;
96
+ }): Promise<BreachNotice[]>;
97
+ /** How many people are on the breach and how many were told, with the first and last time anyone was. */
98
+ countNotices(breachId: string): Promise<NoticeCounts>;
99
+ }
100
+ export interface NoticeCounts {
101
+ total: number;
102
+ sent: number;
103
+ firstSentAt?: string;
104
+ lastSentAt?: string;
105
+ }
106
+ export declare function isBreachStore(store: object): store is BreachStore;
107
+ export interface BreachStatus {
108
+ id: string;
109
+ status: Breach["status"];
110
+ awareAt: string;
111
+ /** Rule 7(2)(a): tell the Board without delay. */
112
+ boardNotified: boolean;
113
+ /** Rule 7(2)(b). */
114
+ report: {
115
+ dueAt: string;
116
+ sent: boolean;
117
+ overdue: boolean;
118
+ hoursLeft: number;
119
+ missing: Array<keyof BoardReportInput>;
120
+ };
121
+ /** Rule 7(1): each affected person, without delay. */
122
+ people: {
123
+ total: number;
124
+ sent: number;
125
+ pending: number;
126
+ };
127
+ /** What still needs doing, in plain words. */
128
+ todo: string[];
129
+ }
130
+ export declare function breachStatus(breach: Breach, counts: NoticeCounts, now: string): BreachStatus;
131
+ /** The notice for an affected person, Rule 7(1)(a)–(e). Translate it for their language before sending. */
132
+ export interface PersonNotice {
133
+ /** (a) What happened, how much, and when. */
134
+ description: string;
135
+ /** (b) The consequences likely for them. */
136
+ consequences: string;
137
+ /** (c) What you're doing about it. */
138
+ measures: string;
139
+ /** (d) What they can do to protect themselves. */
140
+ safetySteps: string;
141
+ /** (e) Who can answer their questions. */
142
+ contact: string;
143
+ /** All of the above as plain text. */
144
+ text: string;
145
+ /** Parts not filled in yet: send only when this is empty. */
146
+ missing: Array<"consequences" | "measures" | "safetySteps" | "contact">;
147
+ }
148
+ export declare function personNotice(config: DpdpConfig<string>, breach: Breach): PersonNotice;
149
+ /** The detailed report for the Board, Rule 7(2)(b)(i)–(vi). */
150
+ export interface BoardReport {
151
+ breachId: string;
152
+ awareAt: string;
153
+ dueAt: string;
154
+ /** (i)–(v), as recorded. */
155
+ details: string;
156
+ facts: string;
157
+ mitigation: string;
158
+ findings: string;
159
+ remedial: string;
160
+ /** (vi) The notices given to affected people. */
161
+ intimations: {
162
+ total: number;
163
+ sent: number;
164
+ pending: number;
165
+ firstSentAt?: string;
166
+ lastSentAt?: string;
167
+ };
168
+ /** Parts (i)–(v) not filled in yet. */
169
+ missing: Array<keyof BoardReportInput>;
170
+ }
@@ -0,0 +1,94 @@
1
+ // src/ddl.ts
2
+ var CONSENT_EVENTS_DDL = `CREATE TABLE IF NOT EXISTS dpdp_consent_events (
3
+ subject_id text NOT NULL,
4
+ seq integer NOT NULL,
5
+ action text NOT NULL CHECK (action IN ('grant', 'withdraw')),
6
+ purposes jsonb NOT NULL,
7
+ notice_version text,
8
+ language text,
9
+ channel text,
10
+ evidence jsonb,
11
+ at timestamptz NOT NULL,
12
+ prev_hash text,
13
+ hash text NOT NULL,
14
+ PRIMARY KEY (subject_id, seq)
15
+ );`;
16
+ var RECORDS_DDL = `CREATE TABLE IF NOT EXISTS dpdp_requests (
17
+ id text PRIMARY KEY,
18
+ subject_id text NOT NULL,
19
+ type text NOT NULL,
20
+ status text NOT NULL,
21
+ opened_at timestamptz NOT NULL,
22
+ due_at timestamptz NOT NULL,
23
+ closed_at timestamptz,
24
+ details jsonb,
25
+ history jsonb NOT NULL
26
+ );
27
+ CREATE INDEX IF NOT EXISTS dpdp_requests_subject_idx ON dpdp_requests (subject_id);
28
+ CREATE INDEX IF NOT EXISTS dpdp_requests_status_due_idx ON dpdp_requests (status, due_at);
29
+ CREATE TABLE IF NOT EXISTS dpdp_erasure_tasks (
30
+ id text PRIMARY KEY,
31
+ subject_id text NOT NULL,
32
+ reason text NOT NULL,
33
+ kind text NOT NULL,
34
+ table_key text,
35
+ fields jsonb,
36
+ processor text,
37
+ purposes jsonb,
38
+ created_at timestamptz NOT NULL,
39
+ due_at timestamptz NOT NULL,
40
+ status text NOT NULL,
41
+ attempts integer NOT NULL,
42
+ claimed_at timestamptz,
43
+ done_at timestamptz,
44
+ affected integer,
45
+ last_error text,
46
+ note text
47
+ );
48
+ CREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_subject_idx ON dpdp_erasure_tasks (subject_id);
49
+ CREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_status_due_idx ON dpdp_erasure_tasks (status, due_at);`;
50
+ var ACCESS_LOG_DDL = `CREATE TABLE IF NOT EXISTS dpdp_access_log (
51
+ id text PRIMARY KEY,
52
+ at timestamptz NOT NULL,
53
+ actor text NOT NULL,
54
+ subject_id text NOT NULL,
55
+ action text NOT NULL,
56
+ purpose text NOT NULL,
57
+ fields jsonb,
58
+ out_of_purpose jsonb,
59
+ reason text,
60
+ evidence jsonb
61
+ );
62
+ CREATE INDEX IF NOT EXISTS dpdp_access_log_at_idx ON dpdp_access_log (at);
63
+ CREATE INDEX IF NOT EXISTS dpdp_access_log_subject_idx ON dpdp_access_log (subject_id, at);
64
+ CREATE INDEX IF NOT EXISTS dpdp_access_log_actor_idx ON dpdp_access_log (actor, at);`;
65
+ var BREACH_DDL = `CREATE TABLE IF NOT EXISTS dpdp_breaches (
66
+ id text PRIMARY KEY,
67
+ status text NOT NULL,
68
+ aware_at timestamptz NOT NULL,
69
+ report_due_at timestamptz NOT NULL,
70
+ data jsonb NOT NULL
71
+ );
72
+ CREATE INDEX IF NOT EXISTS dpdp_breaches_status_idx ON dpdp_breaches (status, aware_at);
73
+ CREATE TABLE IF NOT EXISTS dpdp_breach_notices (
74
+ breach_id text NOT NULL,
75
+ subject_id text NOT NULL,
76
+ status text NOT NULL,
77
+ added_at timestamptz NOT NULL,
78
+ sent_at timestamptz,
79
+ channel text,
80
+ PRIMARY KEY (breach_id, subject_id)
81
+ );
82
+ CREATE INDEX IF NOT EXISTS dpdp_breach_notices_status_idx ON dpdp_breach_notices (breach_id, status, added_at);`;
83
+ var DPDP_DDL = `${CONSENT_EVENTS_DDL}
84
+ ${RECORDS_DDL}
85
+ ${ACCESS_LOG_DDL}
86
+ ${BREACH_DDL}`;
87
+
88
+ export {
89
+ CONSENT_EVENTS_DDL,
90
+ RECORDS_DDL,
91
+ ACCESS_LOG_DDL,
92
+ BREACH_DDL,
93
+ DPDP_DDL
94
+ };