dpdp-kit 0.1.2 → 0.3.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/CHANGELOG.md +37 -0
- package/README.md +229 -13
- package/dist/access.d.ts +106 -0
- package/dist/audit.d.ts +3 -1
- package/dist/chunk-5TVA2TKG.js +37 -0
- package/dist/chunk-YOEAZX65.js +937 -0
- package/dist/cli.js +48 -10
- package/dist/config.d.ts +79 -0
- package/dist/data-access.d.ts +23 -0
- package/dist/dpdp.d.ts +206 -3
- package/dist/drizzle.d.ts +684 -4
- package/dist/drizzle.js +349 -6
- package/dist/erasure.d.ts +2 -1
- package/dist/errors.d.ts +1 -1
- package/dist/express.d.ts +17 -1
- package/dist/express.js +10 -2
- package/dist/fastify.d.ts +41 -0
- package/dist/fastify.js +25 -0
- package/dist/guard.d.ts +19 -0
- package/dist/hono.d.ts +16 -1
- package/dist/hono.js +11 -2
- package/dist/index.d.ts +11 -5
- package/dist/index.js +482 -51
- package/dist/nestjs.d.ts +65 -0
- package/dist/nestjs.js +41 -0
- package/dist/protect.d.ts +74 -0
- package/dist/protect.js +114 -0
- package/dist/records.d.ts +124 -0
- package/dist/retention.d.ts +47 -0
- package/dist/rights.d.ts +49 -0
- package/dist/run-audit.d.ts +14 -0
- package/dist/safeguards.d.ts +23 -0
- package/dist/schedule.d.ts +37 -0
- package/dist/schedule.js +66 -0
- package/dist/schema-check.d.ts +5 -7
- package/dist/store.d.ts +16 -2
- package/package.json +35 -4
- package/dist/chunk-FGZAH2NF.js +0 -16
- package/dist/chunk-MX5FRZQT.js +0 -455
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
**Security safeguards and access logs (Rule 6 of the DPDP Rules)**, plus Fastify and NestJS guards, events, `NOT NULL` erasure and daily upkeep.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **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.
|
|
10
|
+
- **`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`.
|
|
11
|
+
- **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`.
|
|
12
|
+
- **`npx dpdp-kit safeguards`**: Rule 6(1)(a)–(g), what's recorded and what's missing; `--strict` fails on gaps.
|
|
13
|
+
- **Guards**: `dpdp-kit/fastify` (`requireConsent`, `logAccess` as `preHandler` hooks) and `dpdp-kit/nestjs` (`consentGuard`, `accessLogGuard`), plus `logAccess` for Express and Hono.
|
|
14
|
+
- **Events**: `dpdp.on()` for `consent.granted`, `consent.withdrawn`, `erasure.scheduled`, `retention.ran`, `rights.opened`, `rights.closed`, `access.logged`, `daily.ran`.
|
|
15
|
+
- **`erase` on fields**: `"null"` (default), `"redact"` or `{ value }` (fixed or a function), so `NOT NULL` and `UNIQUE` columns can be erased.
|
|
16
|
+
- **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.
|
|
17
|
+
- **`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.
|
|
18
|
+
- 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.
|
|
19
|
+
|
|
20
|
+
### Upgrading from 0.2.x
|
|
21
|
+
|
|
22
|
+
1. **New table.** Add `accessLog` to your Drizzle schema (`export { accessLog } from "dpdp-kit/drizzle"`) and generate a migration, or run `ACCESS_LOG_DDL`.
|
|
23
|
+
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).
|
|
24
|
+
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.
|
|
25
|
+
4. **Custom stores.** The access log needs `AccessLogStore` (`insertAccess`, `listAccess`, `pruneAccess`). Without it, `dpdp.access` throws `store-unsupported` and `daily()` skips it.
|
|
26
|
+
|
|
27
|
+
## 0.2.0
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
|
|
31
|
+
## 0.1.2
|
|
32
|
+
|
|
33
|
+
Schema drift check: `audit --schema`, `checkSchema`, `drizzleSchema`, `notPersonal`.
|
|
34
|
+
|
|
35
|
+
## 0.1.0
|
|
36
|
+
|
|
37
|
+
Typed config, `audit` and the CLI, hash-chained consent records, erasure plans, the Drizzle store, Express and Hono guards.
|
package/README.md
CHANGED
|
@@ -4,10 +4,15 @@
|
|
|
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/)**
|
|
8
|
+
|
|
9
|
+

|
|
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.
|
|
10
|
-
- **
|
|
14
|
+
- **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
|
+
- **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
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.
|
|
12
17
|
|
|
13
18
|
## Node-native
|
|
@@ -17,7 +22,7 @@ dpdp-kit is a TypeScript library that runs **inside your Node.js process**, not
|
|
|
17
22
|
- **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
23
|
- **No hosted service.** No account, no API key, and no network calls. Personal data never leaves your infrastructure.
|
|
19
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.
|
|
20
|
-
- **Fits your Node stack.** Typed config,
|
|
25
|
+
- **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
26
|
|
|
22
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.
|
|
23
28
|
|
|
@@ -124,14 +129,49 @@ notPersonal: ["products.name", "branches.*"], // database table and column names
|
|
|
124
129
|
|
|
125
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.
|
|
126
131
|
|
|
132
|
+
### In GitHub Actions
|
|
133
|
+
|
|
134
|
+
Add the audit to any workflow. Problems show up as annotations on the pull request, plus a summary on the run page:
|
|
135
|
+
|
|
136
|
+
```yaml
|
|
137
|
+
# .github/workflows/dpdp.yml
|
|
138
|
+
name: DPDP
|
|
139
|
+
on: [pull_request]
|
|
140
|
+
jobs:
|
|
141
|
+
audit:
|
|
142
|
+
runs-on: ubuntu-latest
|
|
143
|
+
steps:
|
|
144
|
+
- uses: actions/checkout@v4
|
|
145
|
+
- uses: actions/setup-node@v4
|
|
146
|
+
with:
|
|
147
|
+
node-version: 22
|
|
148
|
+
- run: npm ci # so your config can import dpdp-kit
|
|
149
|
+
- uses: yogesh2902/dpdp-kit@main
|
|
150
|
+
with:
|
|
151
|
+
schema: src/db/schema.ts # optional: also check for drift
|
|
152
|
+
# config: dpdp.config.ts # default: found automatically
|
|
153
|
+
# strict: true # fail on warnings too
|
|
154
|
+
# working-directory: apps/api # for monorepos
|
|
155
|
+
```
|
|
156
|
+
|
|
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.
|
|
158
|
+
|
|
127
159
|
## 3. Record consent
|
|
128
160
|
|
|
129
161
|
```ts
|
|
130
162
|
import { createDpdp } from "dpdp-kit";
|
|
131
|
-
import { drizzleStore } from "dpdp-kit/drizzle";
|
|
163
|
+
import { drizzleData, drizzleStore } from "dpdp-kit/drizzle";
|
|
164
|
+
import * as schema from "./db/schema";
|
|
132
165
|
import config from "./dpdp.config";
|
|
133
166
|
|
|
134
|
-
export const dpdp = createDpdp({
|
|
167
|
+
export const dpdp = createDpdp({
|
|
168
|
+
config,
|
|
169
|
+
store: drizzleStore(db), // consent records, rights requests, erasure tasks
|
|
170
|
+
data: drizzleData(db, { schema }), // reads and erases personal data in your own tables
|
|
171
|
+
processors: { // optional: tell third parties to stop or erase
|
|
172
|
+
msg91: { stop: ({ subjectId }) => msg91.optOut(subjectId), erase: ({ subjectId }) => msg91.deleteContact(subjectId) },
|
|
173
|
+
},
|
|
174
|
+
});
|
|
135
175
|
|
|
136
176
|
await dpdp.consent.grant(userId, ["marketing_sms", "analytics"], {
|
|
137
177
|
noticeVersion: "2026-11",
|
|
@@ -173,9 +213,136 @@ await dpdp.erasure.plan(userId, { reason: "account-deletion" });
|
|
|
173
213
|
|
|
174
214
|
**"Erase" is not "delete this second".** Every plan carries `minimumRetention` from your config. Under Rule 8(3), stop using the data now, keep a restricted copy only for the Seventh Schedule purposes, and delete it once a year has passed since its last processing. The Rule's own example is an e-book platform that keeps order details and logs for a year "even if X deletes her account".
|
|
175
215
|
|
|
176
|
-
|
|
216
|
+
### Carrying it out
|
|
217
|
+
|
|
218
|
+
`withdraw()` schedules the plan as dated tasks, and `erasure.deleteAccount(userId)` plans and schedules an account deletion. Then run the retention runner on a schedule; once a day is plenty:
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
const report = await dpdp.retention.run(); // { done, failed, manual }
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
| Task | When it runs | What it does |
|
|
225
|
+
|---|---|---|
|
|
226
|
+
| `processor-stop` | straight away | calls the processor's `stop` hook (Section 6(6)) |
|
|
227
|
+
| `erase-fields` | after `minimumRetention` (and `afterWithdrawal`) | sets the fields to `NULL` in the person's rows |
|
|
228
|
+
| `delete-rows` | after `minimumRetention` | deletes the person's rows (account deletion) |
|
|
229
|
+
| held table | after the legal hold (`keep`) | then anonymises (`NULL`s) or deletes, as `then` says |
|
|
230
|
+
| `processor-erase` | after `minimumRetention` | calls the processor's `erase` hook (Section 8(7)(b)) |
|
|
231
|
+
|
|
232
|
+
- **Safe to run from several servers.** Each task is claimed atomically, so it runs once.
|
|
233
|
+
- **Failures are retried**, up to 5 times. `lastError` keeps the database's message for developers, for example when a column is `NOT NULL`.
|
|
234
|
+
- **A processor with no hook** gives a `manual` task. Handle it yourself (email their support), then `retention.markDone(taskId, "ticket 4411")`.
|
|
235
|
+
- **Consent records are never erased.** Section 6(10) makes you prove consent, and Rule 8(3) requires keeping records of processing.
|
|
236
|
+
- **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.
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
fields: {
|
|
240
|
+
nickname: { category: "identity", purposes: ["newsletter"], erase: "redact" }, // "[erased]"
|
|
241
|
+
points: { category: "behavioural", purposes: ["newsletter"], erase: { value: 0 } },
|
|
242
|
+
email: { category: "contact", purposes: ["newsletter"], erase: { value: ({ subjectId }) => `erased-${subjectId}@invalid` } }, // NOT NULL UNIQUE
|
|
243
|
+
},
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
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.
|
|
247
|
+
|
|
248
|
+
## 5. Rights requests
|
|
249
|
+
|
|
250
|
+
People can ask to see their data (Section 11), correct or erase it (Section 12), raise a grievance (Section 13) or name a nominee (Section 14). Each request is recorded with a due date:
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
const request = await dpdp.rights.open(userId, "grievance", { text: "I keep getting promo SMS" });
|
|
254
|
+
// request.dueAt is 90 days out: Rule 14(3) caps grievance responses at ninety days
|
|
255
|
+
|
|
256
|
+
await dpdp.rights.list({ overdue: true }); // your inbox of late answers
|
|
257
|
+
await dpdp.rights.resolve(request.id, "Promo SMS turned off");
|
|
258
|
+
await dpdp.rights.reject(otherId, "Duplicate of an earlier grievance");
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
**Access (Section 11):** `summary()` reads the person's personal fields from your tables, with the purposes each is held for, their consents, and the processors their data goes to:
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
const summary = await dpdp.rights.summary(userId);
|
|
265
|
+
// { data: [{ table: "users", fields: [...], rows: [{ phone: "98…", name: "Asha" }] }],
|
|
266
|
+
// consents: ["order_updates"], legitimateUses: ["account"],
|
|
267
|
+
// sharedWith: [{ name: "msg91", purposes: ["order_updates"] }] }
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
**Erasure (Section 12(3)):** every purpose ends except those you still need for the specified purpose. Legal holds and `minimumRetention` still apply:
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
await dpdp.rights.erase(userId, { keepFor: ["account"], requestId: request.id }); // schedules, resolves the request
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
Corrections and nominations are recorded with the request (`details`); your app applies them, then calls `resolve()`. Set your own answer times in the config. The Rules set ninety days for grievances only, and the audit fails above that:
|
|
277
|
+
|
|
278
|
+
```ts
|
|
279
|
+
rights: { responseWithin: { grievance: "30d", access: "30d" } },
|
|
280
|
+
```
|
|
177
281
|
|
|
178
|
-
##
|
|
282
|
+
## 6. Security safeguards and access logs
|
|
283
|
+
|
|
284
|
+
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.
|
|
285
|
+
|
|
286
|
+
**Access log (Rule 6(1)(c) and (e)).** Record who accessed whose data, why, and which fields:
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
await dpdp.access.log({
|
|
290
|
+
actor: "support:priya", // who
|
|
291
|
+
subjectId: userId, // whose data
|
|
292
|
+
purpose: "account", // why: one of your purposes
|
|
293
|
+
fields: ["users.phone", "orders"], // what: "table.field", or a whole table
|
|
294
|
+
reason: "ticket 4411",
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
await dpdp.access.list({ subjectId: userId }); // investigate one person, an actor, or a period
|
|
298
|
+
await dpdp.access.review(); // daily: find unauthorised access
|
|
299
|
+
await dpdp.access.prune(); // keeps at least a year, as Rule 6(1)(e) requires
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
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:
|
|
303
|
+
|
|
304
|
+
```ts
|
|
305
|
+
import { logAccess } from "dpdp-kit/express"; // or "dpdp-kit/hono"
|
|
306
|
+
app.get("/admin/users/:id", logAccess(dpdp, {
|
|
307
|
+
purpose: "account",
|
|
308
|
+
fields: ["users"],
|
|
309
|
+
actor: (req) => req.staff?.id,
|
|
310
|
+
subject: (req) => req.params.id,
|
|
311
|
+
}), handler);
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
**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:
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
import { createEncryptor, createTokenizer, maskAadhaar } from "dpdp-kit/protect";
|
|
318
|
+
|
|
319
|
+
const enc = createEncryptor({ keys: { k1: process.env.DPDP_KEY_1! }, current: "k1" });
|
|
320
|
+
const stored = enc.encrypt(aadhaar, `users.aadhaar:${user.id}`); // bound to this row
|
|
321
|
+
enc.decrypt(stored, `users.aadhaar:${user.id}`);
|
|
322
|
+
|
|
323
|
+
const tokens = createTokenizer({ key: process.env.DPDP_TOKEN_KEY! });
|
|
324
|
+
tokens.token(email); // same email → same token, so you can look rows up without storing the email in the clear
|
|
325
|
+
|
|
326
|
+
maskAadhaar("1234 5678 9012"); // "XXXX XXXX 9012"
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
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.
|
|
330
|
+
|
|
331
|
+
**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:
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
data: { users: { /* … */ fields: { aadhaar: { category: "identity", purposes: ["kyc"], protect: "encrypted" } } } },
|
|
335
|
+
processors: { msg91: { purposes: ["marketing_sms"], contract: "DPA signed 2026-03-01, clause 7" } },
|
|
336
|
+
security: {
|
|
337
|
+
accessControl: "SSO with least-privilege roles", // Rule 6(1)(b)
|
|
338
|
+
backups: "Encrypted daily backups, restore tested monthly", // Rule 6(1)(d)
|
|
339
|
+
measures: "Annual security training, quarterly access reviews", // Rule 6(1)(g)
|
|
340
|
+
},
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
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).
|
|
344
|
+
|
|
345
|
+
## 7. Guard routes
|
|
179
346
|
|
|
180
347
|
```ts
|
|
181
348
|
// Express
|
|
@@ -187,24 +354,69 @@ import { requireConsent } from "dpdp-kit/hono";
|
|
|
187
354
|
app.post("/promo", requireConsent(dpdp, "marketing_sms", { subject: (c) => c.get("userId") }), handler);
|
|
188
355
|
```
|
|
189
356
|
|
|
190
|
-
|
|
357
|
+
```ts
|
|
358
|
+
// Fastify
|
|
359
|
+
import { requireConsent } from "dpdp-kit/fastify";
|
|
360
|
+
app.post("/promo", { preHandler: requireConsent(dpdp, "marketing_sms", { subject: (req) => req.user?.id }) }, handler);
|
|
361
|
+
|
|
362
|
+
// NestJS
|
|
363
|
+
import { consentGuard } from "dpdp-kit/nestjs";
|
|
364
|
+
@UseGuards(consentGuard(dpdp, "marketing_sms", { subject: (req) => req.user?.id }))
|
|
365
|
+
@Post("promo")
|
|
366
|
+
sendPromo() {}
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
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.
|
|
370
|
+
|
|
371
|
+
## 8. Events
|
|
372
|
+
|
|
373
|
+
Listen for changes to feed your own audit trail, alerts or analytics:
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
const off = dpdp.on("consent.withdrawn", ({ event }) => analytics.forget(event.subjectId, event.purposes));
|
|
377
|
+
dpdp.on("access.logged", ({ entries }) => {
|
|
378
|
+
if (entries.some((e) => e.outOfPurpose)) slack.alert("Out-of-purpose read", entries);
|
|
379
|
+
});
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
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.
|
|
383
|
+
|
|
384
|
+
## 9. Daily upkeep
|
|
385
|
+
|
|
386
|
+
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.
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
const report = await dpdp.daily(); // { retention, accessPruned, review, overdueRequests, skipped }
|
|
390
|
+
|
|
391
|
+
// schedule it in-process, with no dependencies:
|
|
392
|
+
import { startDaily } from "dpdp-kit/schedule";
|
|
393
|
+
startDaily(dpdp, { at: "03:00", onReport: (r) => r.retention?.failed.length && alert(r) });
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
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.
|
|
191
397
|
|
|
192
398
|
## Storage
|
|
193
399
|
|
|
194
400
|
### Drizzle (Postgres)
|
|
195
401
|
|
|
196
|
-
Add the
|
|
402
|
+
Add the tables to your schema so drizzle-kit creates them:
|
|
197
403
|
|
|
198
404
|
```ts
|
|
199
405
|
// schema.ts
|
|
200
|
-
export { consentEvents } from "dpdp-kit/drizzle";
|
|
406
|
+
export { accessLog, consentEvents, erasureTasks, rightsRequests } from "dpdp-kit/drizzle";
|
|
201
407
|
```
|
|
202
408
|
|
|
203
|
-
If you don't use drizzle-kit, run `
|
|
409
|
+
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
|
+
|
|
411
|
+
> **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
|
+
>
|
|
413
|
+
> **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
|
+
|
|
415
|
+
`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`).
|
|
204
416
|
|
|
205
417
|
### Anything else
|
|
206
418
|
|
|
207
|
-
Implement `
|
|
419
|
+
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.
|
|
208
420
|
|
|
209
421
|
## How the consent record works
|
|
210
422
|
|
|
@@ -221,8 +433,12 @@ Section 6(10) puts the burden on you: if consent is questioned in a proceeding,
|
|
|
221
433
|
|---|---|
|
|
222
434
|
| **v0.1** | Config and types, `audit` + CLI, consent records, erasure plans, Drizzle store, Express/Hono guards |
|
|
223
435
|
| **v0.1.2** | Schema drift check: `audit --schema`, `checkSchema`, `drizzleSchema`, `notPersonal` |
|
|
224
|
-
| v0.2 |
|
|
225
|
-
| v0.3 |
|
|
436
|
+
| **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
|
+
| **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 |
|
|
441
|
+
| 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) |
|
|
226
442
|
|
|
227
443
|
## When the Rules apply
|
|
228
444
|
|
package/dist/access.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
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
|
+
export declare function isAccessLogStore(store: object): store is AccessLogStore;
|
|
50
|
+
/**
|
|
51
|
+
* An id that sorts in the order entries were written: the time, then a per-process counter for
|
|
52
|
+
* entries in the same millisecond, then random bits so ids from different servers never collide.
|
|
53
|
+
*/
|
|
54
|
+
export declare function accessId(at: string): string;
|
|
55
|
+
/** Default and minimum time to keep the access log (Rule 6(1)(e)). */
|
|
56
|
+
export declare const DEFAULT_ACCESS_LOG_RETENTION = "1y";
|
|
57
|
+
/**
|
|
58
|
+
* Expand field keys against the data map: `"users.phone"` stays as it is; `"users.*"` and
|
|
59
|
+
* `"users"` become every personal field of that table. Returns the keys it doesn't know too.
|
|
60
|
+
*/
|
|
61
|
+
export declare function resolveFields(config: DpdpConfig<string>, keys: readonly string[]): {
|
|
62
|
+
fields: string[];
|
|
63
|
+
unknown: string[];
|
|
64
|
+
};
|
|
65
|
+
/** The fields that aren't held for `purpose` according to the data map. */
|
|
66
|
+
export declare function fieldsOutsidePurpose(config: DpdpConfig<string>, fields: readonly string[], purpose: string): string[];
|
|
67
|
+
export type AccessFindingKind = "out-of-purpose" | "no-consent" | "bulk-access";
|
|
68
|
+
export interface AccessFinding {
|
|
69
|
+
kind: AccessFindingKind;
|
|
70
|
+
actor: string;
|
|
71
|
+
/** Plain-language explanation, for whoever reviews the log. */
|
|
72
|
+
message: string;
|
|
73
|
+
/** Ids of the log entries involved. */
|
|
74
|
+
entries: string[];
|
|
75
|
+
subjectId?: string;
|
|
76
|
+
purpose?: string;
|
|
77
|
+
/** For `bulk-access`: distinct people accessed within one window. */
|
|
78
|
+
subjects?: number;
|
|
79
|
+
}
|
|
80
|
+
export interface AccessReview {
|
|
81
|
+
from: string;
|
|
82
|
+
to: string;
|
|
83
|
+
/** Entries looked at. */
|
|
84
|
+
scanned: number;
|
|
85
|
+
findings: AccessFinding[];
|
|
86
|
+
}
|
|
87
|
+
export interface ReviewInput {
|
|
88
|
+
config: DpdpConfig<string>;
|
|
89
|
+
entries: readonly AccessEntry[];
|
|
90
|
+
from: string;
|
|
91
|
+
to: string;
|
|
92
|
+
/** Consent events for a person, oldest first. */
|
|
93
|
+
history: (subjectId: string) => Promise<readonly ConsentEvent[]>;
|
|
94
|
+
/** Window for bulk-access detection, e.g. `"1h"`. */
|
|
95
|
+
window: Duration;
|
|
96
|
+
/** More distinct people than this within one window is reported as bulk access. */
|
|
97
|
+
maxSubjects: number;
|
|
98
|
+
/** Actors exempt from bulk-access findings (batch jobs). */
|
|
99
|
+
ignoreActors?: readonly string[];
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Look through access log entries for signs of unauthorised access (Rule 6(1)(c)): fields read for
|
|
103
|
+
* a purpose they aren't held for, consent purposes used without consent at the time, and one actor
|
|
104
|
+
* reaching an unusual number of people in a short time.
|
|
105
|
+
*/
|
|
106
|
+
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";
|
|
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";
|
|
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;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DpdpError
|
|
3
|
+
} from "./chunk-67Q5GFD6.js";
|
|
4
|
+
|
|
5
|
+
// src/guard.ts
|
|
6
|
+
var CONSENT_REQUIRED_BODY = (purpose) => ({
|
|
7
|
+
error: "consent_required",
|
|
8
|
+
purpose,
|
|
9
|
+
message: "You haven't agreed to this yet. You can turn it on in your privacy settings."
|
|
10
|
+
});
|
|
11
|
+
async function checkConsent(dpdp, purpose, options, ctx) {
|
|
12
|
+
const subjectId = await options.subject(ctx);
|
|
13
|
+
if (!subjectId) return false;
|
|
14
|
+
return dpdp.consent.has(subjectId, purpose);
|
|
15
|
+
}
|
|
16
|
+
async function recordAccess(dpdp, options, ctx) {
|
|
17
|
+
const subject = await options.subject(ctx);
|
|
18
|
+
const subjectIds = typeof subject === "string" ? [subject] : subject ? [...subject] : [];
|
|
19
|
+
if (subjectIds.length === 0) return;
|
|
20
|
+
const actor = await options.actor(ctx);
|
|
21
|
+
if (!actor) throw new DpdpError("invalid-actor", "logAccess: actor() returned nothing; every access to personal data needs a known actor");
|
|
22
|
+
const evidence = options.evidence?.(ctx) ?? void 0;
|
|
23
|
+
await dpdp.access.log({
|
|
24
|
+
actor,
|
|
25
|
+
subjectIds,
|
|
26
|
+
purpose: options.purpose,
|
|
27
|
+
...options.fields ? { fields: options.fields } : {},
|
|
28
|
+
...options.action ? { action: options.action } : {},
|
|
29
|
+
...evidence ? { evidence } : {}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export {
|
|
34
|
+
CONSENT_REQUIRED_BODY,
|
|
35
|
+
checkConsent,
|
|
36
|
+
recordAccess
|
|
37
|
+
};
|