dpdp-kit 0.4.1 → 0.5.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 (47) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +12 -9
  3. package/dist/access.d.ts +3 -2
  4. package/dist/audit.d.ts +7 -2
  5. package/dist/{chunk-5TVA2TKG.js → chunk-3DOVLBUB.js} +12 -2
  6. package/dist/chunk-EMNABUCL.js +34 -0
  7. package/dist/{chunk-HXVP446N.js → chunk-FEGA6SOM.js} +817 -149
  8. package/dist/chunk-HGN6TO6R.js +294 -0
  9. package/dist/{chunk-KLMR7S7I.js → chunk-LVT4OKBC.js} +65 -0
  10. package/dist/chunk-M2PDT6DD.js +88 -0
  11. package/dist/chunk-NBVJQDDP.js +16 -0
  12. package/dist/{chunk-2ELTZSW3.js → chunk-VWGKAQCM.js} +18 -3
  13. package/dist/cli.js +48 -5
  14. package/dist/config.d.ts +67 -0
  15. package/dist/data-access.d.ts +8 -0
  16. package/dist/ddl.d.ts +13 -2
  17. package/dist/dpdp.d.ts +155 -9
  18. package/dist/drizzle.d.ts +108 -6
  19. package/dist/drizzle.js +85 -4
  20. package/dist/erasure.d.ts +1 -1
  21. package/dist/errors.d.ts +1 -1
  22. package/dist/evidence.d.ts +91 -0
  23. package/dist/express.d.ts +30 -0
  24. package/dist/express.js +70 -3
  25. package/dist/fastify.js +3 -3
  26. package/dist/guard.d.ts +23 -2
  27. package/dist/hono.d.ts +21 -0
  28. package/dist/hono.js +11 -3
  29. package/dist/http.d.ts +78 -0
  30. package/dist/index.d.ts +7 -3
  31. package/dist/index.js +375 -125
  32. package/dist/mongodb.d.ts +3 -1
  33. package/dist/mongodb.js +99 -1
  34. package/dist/nestjs.js +1 -1
  35. package/dist/next.d.ts +25 -0
  36. package/dist/next.js +14 -0
  37. package/dist/notice.d.ts +139 -0
  38. package/dist/postgres.d.ts +5 -3
  39. package/dist/postgres.js +8 -2
  40. package/dist/prisma.d.ts +4 -2
  41. package/dist/prisma.js +16 -2
  42. package/dist/records.d.ts +24 -1
  43. package/dist/rights.d.ts +35 -2
  44. package/dist/run-audit.d.ts +8 -0
  45. package/dist/stats.d.ts +41 -0
  46. package/dist/store.d.ts +15 -2
  47. package/package.json +5 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ **Notices, objections, complete rights requests, transfers, an HTTP API and an evidence report.** A 0.4 app that changes nothing keeps working: everything new is opt-in, and new audit warnings don't fail `--strict` until 0.6.
6
+
7
+ ### Added
8
+
9
+ - **Privacy notices** (Section 5, Rule 3), with `notice` in the config:
10
+ - `dpdp.notice.build()` / `show()` build the notice from the config: each consent purpose with its description, the itemised data (`label` on fields), the links Rule 3(c) requires and how to complain to the Board.
11
+ - English is built in; other languages come from `notice.translations`, which you supply. The audit checks each translation is complete.
12
+ - Each notice is versioned by its content, per language and kind (`"consent"` or `"existing-users"`), and saved the first time it's shown (`dpdp_privacy_notices`), as proof under Section 6(10). Reusing a version label for different text throws `notice-version-conflict`.
13
+ - `consent.grant()` records the version and language shown, when `config.notice` is set and you don't pass a `noticeVersion`.
14
+ - **Objections** (Section 7(a)): `legitimateUse: "7(a)"` … `"7(i)"` on legitimate-use purposes.
15
+ - `consent.object()` and `consent.liftObjection()` add `object` and `lift-objection` events to the same hash chain.
16
+ - `has()` is false for an objected 7(a) purpose; guards answer `reason: "objected"`; `access.review()` reports `objected` reads; `rights.summary()` lists `objections`.
17
+ - An objection plans erasure like a withdrawal (fields, never rows). Lifting it cancels the tasks it scheduled that haven't run (new task status `cancelled`).
18
+ - **Rights requests, completed** (Sections 11 to 14, Rule 14):
19
+ - `rights.correct(requestId, { "users.phone": "…" }, { where })` writes a correction through the new optional `DataAccess.updateFields` (all built-in data access have it) and records which fields changed, never the values.
20
+ - `rights.verifyIdentity()` records the identity check; `rights: { verify: "required" }` makes summaries, erasure and corrections for a request wait for it.
21
+ - `rights.acknowledgement()` gives the reference, due date and contact to send; `rights.how()` and `rights.how` / `rights.identifiers` in the config publish Rule 14(1) information.
22
+ - `rights.nominate()`, `nominees()` and `revokeNominee()` (Section 14). `resolve`, `reject`, `erase` and `correct` take `by`, recorded in the history.
23
+ - New events: `rights.verified`, `rights.corrected`, `rights.nominated`.
24
+ - **Cross-border transfers** (Section 16, Rule 15): `countries` and `foreignState` on processors, and `transfers: { restricted, keepInIndia }`. The audit errors on a processor in a restricted country, or abroad for a purpose that must stay in India. `rights.summary().sharedWith` lists countries.
25
+ - **HTTP API** for a privacy centre, a consent screen or a mobile app: `dpdpRouter` (`dpdp-kit/express`), `dpdpRoutes` (`dpdp-kit/hono`) and `createHandlers` (new `dpdp-kit/next`, Web `Request`/`Response` only), over `handle()`.
26
+ - Routes for the notice, consents, objections, the person's data, rights requests and nominees, plus optional `/admin` routes for your privacy team.
27
+ - The person comes only from your authentication; POST must be JSON; bodies are limited; `limitWrites` can refuse floods; errors answer `{ error: code }` only. Paths it doesn't serve go on to your own handlers.
28
+ - **Evidence report**: `dpdp.evidence({ from, to })` and `formatEvidence()`: the data map, processors and countries, Rule 6 safeguards, Rule 14 information, notices shown, consent counts, rights requests, erasure, the access review and breaches, ending with what needs attention. The built-in stores count consent events and tasks in the database. `npx dpdp-kit evidence` writes the config-only parts.
29
+ - **New audit checks**: errors for invalid clauses, countries, notice links, descriptions and translations (only when you use those settings); warnings `legitimate-use-clause-missing`, `rights-how-missing`, `processor-countries-missing`, `foreign-state-transfer` and `notice-label-missing`. Warnings new in 0.5 are reported but don't fail `--strict` until 0.6 (`Issue.since`).
30
+ - **Releases from GitHub Actions** with npm provenance.
31
+
32
+ ### Upgrading from 0.4.x
33
+
34
+ 1. **Storage.**
35
+ - Plain SQL or Drizzle tables from `DPDP_DDL`: run `MIGRATE_0_5_DDL` once (from `dpdp-kit/postgres` or `dpdp-kit/drizzle`). It lets the consent table accept objections and creates `dpdp_privacy_notices`. It's safe to run twice. Drizzle users can instead add `privacyNotices` to their schema and generate a migration.
36
+ - Prisma: add the new `DpdpPrivacyNotice` model from `PRISMA_MODELS` and run `prisma migrate dev`.
37
+ - MongoDB: nothing to do.
38
+ 2. **Types that grew.** `ConsentAction` adds `"object" | "lift-objection"`, `ErasureReason` adds `"objection"`, `TaskStatus` adds `"cancelled"`, and there are new events and error codes. A `switch` that lists every case needs the new ones. `consent.history()` now includes objections when there are any.
39
+ 3. **Guards** may answer `{ error: "consent_required", reason: "objected" }` for a 7(a) purpose the person objected to.
40
+ 4. **`rights.erase({ requestId })`** now needs an open `erasure` request for that person, checked before anything is scheduled. `summary(subjectId, { requestId })` checks that the request is the person's and open. With `verify: "required"`, both also need the identity check.
41
+ 5. **Custom stores and data access.** `NoticeStore`, `StatsStore` and `DataAccess.updateFields` are optional: without them, saved notices, database counts in the evidence report and corrections aren't available, and everything else works.
42
+ 6. **Audit.** Run `npx dpdp-kit audit` and fill in what the new warnings ask for (`legitimateUse` on each legitimate use, `rights.how`, `countries` on processors) before 0.6, when they start failing `--strict`.
43
+
3
44
  ## 0.4.1
4
45
 
5
46
  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.
package/README.md CHANGED
@@ -10,6 +10,9 @@
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
+ - **Build the privacy notice from the config** (from 0.5). Itemised data, purposes and the links Rule 3 requires, in English and the translations you supply; each consent records the version shown, and the notice is saved as proof.
14
+ - **Serve the privacy routes** (from 0.5). `dpdpRouter` for Express, `dpdpRoutes` for Hono and `dpdp-kit/next` for Next.js: consents, objections, the person's data, rights requests and nominees, for any frontend to call with `fetch`.
15
+ - **Export the evidence** (from 0.5). `dpdp.evidence()` and `formatEvidence()`: one Markdown report of the data map, safeguards, notices shown, consent counts, rights requests, erasure, the access review and breaches, ending with what needs attention. `dpdp-kit evidence --static` does the config-only parts.
13
16
  - **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
17
  - **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
18
  - **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`.
@@ -54,7 +57,7 @@ export default defineConfig({
54
57
  fiduciary: { name: "Acme Pvt Ltd", grievanceUrl: "https://acme.in/privacy/grievance" },
55
58
 
56
59
  purposes: {
57
- account: { basis: "legitimate-use", retain: "while-active" },
60
+ account: { basis: "legitimate-use", legitimateUse: "7(a)", retain: "while-active" },
58
61
  order_updates: { basis: "consent", retain: "while-active" },
59
62
  marketing_sms: { basis: "consent", retain: { afterWithdrawal: "0d" } },
60
63
  analytics: { basis: "consent", retain: { afterWithdrawal: "7d" } }, // time for the batch job to run
@@ -79,8 +82,8 @@ export default defineConfig({
79
82
  },
80
83
 
81
84
  processors: {
82
- msg91: { purposes: ["order_updates", "marketing_sms"] },
83
- posthog: { purposes: ["analytics"] },
85
+ msg91: { purposes: ["order_updates", "marketing_sms"], countries: ["IN"] },
86
+ posthog: { purposes: ["analytics"], countries: ["US"] },
84
87
  },
85
88
 
86
89
  minimumRetention: "1y", // Rule 8(3): keep data and logs of each processing at least one year
@@ -205,7 +208,7 @@ await dpdp.consent.history(userId); // every event, oldest first
205
208
  await dpdp.consent.verify(userId); // { ok: true, events: 1 }
206
209
  ```
207
210
 
208
- `has()` answers "do I hold consent, or not need it, for this purpose?". It is always `true` for legitimate-use purposes. Under Section 7(a) you must still stop once the person tells you they don't want their data used; v0.1 doesn't record that yet.
211
+ `has()` answers "do I hold consent, or not need it, for this purpose?". For a consent purpose it is `true` while the latest choice is a grant. For a Section 7(a) purpose (`legitimateUse: "7(a)"`) it is `true` until the person objects with `consent.object()` (from 0.5). Other legitimate uses are always `true`.
209
212
 
210
213
  ## 4. Withdrawals and deletions
211
214
 
@@ -283,7 +286,7 @@ await dpdp.rights.reject(otherId, "Duplicate of an earlier grievance");
283
286
  const summary = await dpdp.rights.summary(userId);
284
287
  // { data: [{ table: "users", fields: [...], rows: [{ phone: "98…", name: "Asha" }] }],
285
288
  // consents: ["order_updates"], legitimateUses: ["account"],
286
- // sharedWith: [{ name: "msg91", purposes: ["order_updates"] }] }
289
+ // sharedWith: [{ name: "msg91", purposes: ["order_updates"], countries: ["IN"] }] }
287
290
  ```
288
291
 
289
292
  **Erasure (Section 12(3)):** every purpose ends except those you still need for the specified purpose. Legal holds and `minimumRetention` still apply:
@@ -292,7 +295,7 @@ const summary = await dpdp.rights.summary(userId);
292
295
  await dpdp.rights.erase(userId, { keepFor: ["account"], requestId: request.id }); // schedules, resolves the request
293
296
  ```
294
297
 
295
- 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:
298
+ From 0.5, `rights.correct(requestId, { "users.phone": "…" })` writes a correction and records which fields changed, `rights.nominate()` keeps nominees (Section 14), `rights.verifyIdentity()` records the identity check (and `rights: { verify: "required" }` makes it a precondition), and `rights.acknowledgement()` gives the reference and due date to send. Put how people make a request in `rights.how` (Rule 14(1)). Set your own answer times in the config. The Rules set ninety days for grievances only, and the audit fails above that:
296
299
 
297
300
  ```ts
298
301
  rights: { responseWithin: { grievance: "30d", access: "30d" } },
@@ -443,7 +446,7 @@ Add the tables to your schema so drizzle-kit creates them:
443
446
 
444
447
  ```ts
445
448
  // schema.ts
446
- export { accessLog, breachNotices, breaches, consentEvents, erasureTasks, rightsRequests } from "dpdp-kit/drizzle";
449
+ export { accessLog, breachNotices, breaches, consentEvents, erasureTasks, privacyNotices, rightsRequests } from "dpdp-kit/drizzle";
447
450
  ```
448
451
 
449
452
  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.
@@ -537,8 +540,8 @@ Section 6(10) puts the burden on you: if consent is questioned in a proceeding,
537
540
  | **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 |
538
541
  | **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
542
  | **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 |
543
+ | **v0.5.0** | **Notices** that meet Rule 3, built from the config and saved as proof; **objections** to a Section 7(a) use; rights requests completed (corrections, identity checks, nominees, acknowledgements); **cross-border transfers** (Section 16); an **HTTP API** for Express, Hono and Next.js; the **evidence report**; npm releases with provenance |
544
+ | next (0.6) | React and React Native consent screens on the HTTP API, MySQL and SQLite data access, Next.js and Expo example apps |
542
545
  | 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) |
543
546
 
544
547
  ## When the Rules apply
package/dist/access.d.ts CHANGED
@@ -69,7 +69,7 @@ export declare function resolveFields(config: DpdpConfig<string>, keys: readonly
69
69
  };
70
70
  /** The fields that aren't held for `purpose` according to the data map. */
71
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";
72
+ export type AccessFindingKind = "out-of-purpose" | "no-consent" | "objected" | "bulk-access";
73
73
  export interface AccessFinding {
74
74
  kind: AccessFindingKind;
75
75
  actor: string;
@@ -105,7 +105,8 @@ export interface ReviewInput {
105
105
  }
106
106
  /**
107
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
108
+ * a purpose they aren't held for, consent purposes used without consent at the time, Section 7(a)
109
+ * purposes used after the person objected, and one actor
109
110
  * reaching an unusual number of people in a short time.
110
111
  */
111
112
  export declare function reviewAccess(input: ReviewInput): Promise<AccessReview>;
package/dist/audit.d.ts CHANGED
@@ -1,11 +1,16 @@
1
- import type { DpdpConfig } from "./config.js";
1
+ 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" | "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";
5
+ code: "no-purposes" | "invalid-basis" | "invalid-retention" | "invalid-legitimate-use" | "legitimate-use-clause-missing" | "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" | "rights-how-missing" | "invalid-rights-verify" | "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" | "invalid-country" | "transfer-restricted" | "transfer-outside-india" | "processor-countries-missing" | "foreign-state-transfer" | "notice-link-missing" | "notice-description-missing" | "notice-label-missing" | "notice-translation-incomplete" | "invalid-notice-language";
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;
9
+ /**
10
+ * The version that introduced this check, for warnings added after 0.4. `--strict` doesn't fail
11
+ * on a warning in the minor version that introduced it, so upgrading doesn't break CI.
12
+ */
13
+ since?: string;
9
14
  }
10
15
  /**
11
16
  * Check a config for mistakes. Errors mean the config can't be used; warnings are things a
@@ -3,11 +3,20 @@ import {
3
3
  } from "./chunk-67Q5GFD6.js";
4
4
 
5
5
  // src/guard.ts
6
- var CONSENT_REQUIRED_BODY = (purpose) => ({
6
+ var CONSENT_REQUIRED_BODY = (purpose, reason) => reason === "objected" ? {
7
+ error: "consent_required",
8
+ purpose,
9
+ reason,
10
+ message: "You've asked us not to use your data for this. You can change that in your privacy settings."
11
+ } : {
7
12
  error: "consent_required",
8
13
  purpose,
9
14
  message: "You haven't agreed to this yet. You can turn it on in your privacy settings."
10
- });
15
+ };
16
+ function consentDeniedBody(dpdp, purpose) {
17
+ const def = dpdp.config.purposes[purpose];
18
+ return CONSENT_REQUIRED_BODY(purpose, def?.basis === "legitimate-use" ? "objected" : void 0);
19
+ }
11
20
  async function checkConsent(dpdp, purpose, options, ctx) {
12
21
  const subjectId = await options.subject(ctx);
13
22
  if (!subjectId) return false;
@@ -32,6 +41,7 @@ async function recordAccess(dpdp, options, ctx) {
32
41
 
33
42
  export {
34
43
  CONSENT_REQUIRED_BODY,
44
+ consentDeniedBody,
35
45
  checkConsent,
36
46
  recordAccess
37
47
  };
@@ -0,0 +1,34 @@
1
+ // src/data-access.ts
2
+ var columnValue = (v) => v !== null && typeof v === "object" && !(v instanceof Date) ? JSON.stringify(v) : v;
3
+ function memoryData(tables) {
4
+ const rowsOf = (table) => tables[table] ??= [];
5
+ const mine = (subjectColumn, subjectId) => (row) => String(row[subjectColumn]) === subjectId;
6
+ return {
7
+ tables,
8
+ async read(table, subjectColumn, subjectId, columns) {
9
+ return rowsOf(table).filter(mine(subjectColumn, subjectId)).map((row) => Object.fromEntries(columns.map((c) => [c, row[c] ?? null])));
10
+ },
11
+ async eraseFields(table, subjectColumn, subjectId, columns, values = {}) {
12
+ const rows = rowsOf(table).filter(mine(subjectColumn, subjectId));
13
+ for (const row of rows) for (const c of columns) row[c] = Object.hasOwn(values, c) ? values[c] : null;
14
+ return rows.length;
15
+ },
16
+ async updateFields(table, subjectColumn, subjectId, values, where = {}) {
17
+ const rows = rowsOf(table).filter(
18
+ (row) => mine(subjectColumn, subjectId)(row) && Object.entries(where).every(([k, v]) => String(row[k]) === String(v))
19
+ );
20
+ for (const row of rows) Object.assign(row, structuredClone(values));
21
+ return rows.length;
22
+ },
23
+ async deleteRows(table, subjectColumn, subjectId) {
24
+ const before = rowsOf(table).length;
25
+ tables[table] = rowsOf(table).filter((row) => !mine(subjectColumn, subjectId)(row));
26
+ return before - tables[table].length;
27
+ }
28
+ };
29
+ }
30
+
31
+ export {
32
+ columnValue,
33
+ memoryData
34
+ };