dpdp-kit 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dpdp-kit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,206 @@
1
- # Temporary Holding Version
1
+ # dpdp-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/yogesh2902/dpdp-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/yogesh2902/dpdp-kit/actions/workflows/ci.yml)
4
+
5
+ Build India's **Digital Personal Data Protection Act, 2023** into your Node.js backend.
6
+
7
+ - **Declare why you hold each piece of personal data**, in one typed config file. A misspelt purpose is a type error.
8
+ - **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
+ - **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
+ - **Check it in CI.** `dpdp-kit audit` fails the build when the data map is inconsistent.
11
+
12
+ It runs inside your app and writes to your own Postgres. There's no hosted service and no account.
13
+
14
+ > **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.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install dpdp-kit
20
+ ```
21
+
22
+ Node.js 20.19 or later. The package is ESM-only; `require("dpdp-kit")` also works on those Node versions.
23
+
24
+ ## 1. Declare your data
25
+
26
+ ```ts
27
+ // dpdp.config.ts
28
+ import { defineConfig } from "dpdp-kit";
29
+
30
+ export default defineConfig({
31
+ fiduciary: { name: "Acme Pvt Ltd", grievanceUrl: "https://acme.in/privacy/grievance" },
32
+
33
+ purposes: {
34
+ account: { basis: "legitimate-use", retain: "while-active" },
35
+ order_updates: { basis: "consent", retain: "while-active" },
36
+ marketing_sms: { basis: "consent", retain: { afterWithdrawal: "0d" } },
37
+ analytics: { basis: "consent", retain: { afterWithdrawal: "7d" } }, // time for the batch job to run
38
+ },
39
+
40
+ data: {
41
+ users: {
42
+ table: "users",
43
+ subject: "id",
44
+ fields: {
45
+ phone: { category: "contact", purposes: ["account", "order_updates", "marketing_sms"] },
46
+ name: { category: "identity", purposes: ["account"] },
47
+ interests: { category: "behavioural", purposes: ["marketing_sms", "analytics"] },
48
+ },
49
+ },
50
+ orders: {
51
+ table: "orders",
52
+ subject: "user_id",
53
+ fields: { address: { category: "contact", purposes: ["account"] } },
54
+ legalHold: { reason: "GST records", keep: "8y", then: "anonymise" },
55
+ },
56
+ },
57
+
58
+ processors: {
59
+ msg91: { purposes: ["order_updates", "marketing_sms"] },
60
+ posthog: { purposes: ["analytics"] },
61
+ },
62
+
63
+ minimumRetention: "1y", // Rule 8(3): keep data and logs of each processing at least one year
64
+ });
65
+ ```
66
+
67
+ - **`basis`**: `"consent"` (Section 6) or `"legitimate-use"` (Section 7). For most apps a legitimate use means Section 7(a): data the person voluntarily gave you for a specified purpose, until they tell you they don't want it used. Keeping data because a law requires it is not a legitimate use; use `legalHold`.
68
+ - **`retain`**: `"while-active"`, a duration such as `"1y"`, or `{ afterWithdrawal: "7d" }` for consent purposes. Durations use `h`, `d` or `y`. Section 8(7)(a) says to erase upon withdrawal, so keep `afterWithdrawal` to the delay your systems really need.
69
+ - **`legalHold`**: another law makes you keep these rows (tax, KYC). Section 8(7) requires erasure "unless retention is necessary for compliance with any law". They are held, not erased.
70
+ - **`minimumRetention`**: Rule 8(3) requires keeping the personal data, traffic data and logs of each processing for at least one year from that processing, even after the account is deleted, but only for the purposes in the Seventh Schedule (requests from the State). The audit fails if this is under `"1y"`.
71
+
72
+ ## 2. Check it
73
+
74
+ ```bash
75
+ npx dpdp-kit audit # exit code 1 on errors
76
+ npx dpdp-kit audit --strict # also fail on warnings
77
+ ```
78
+
79
+ ```
80
+ ✖ error data.users.fields.phone.purposes
81
+ Unknown purpose "acount". Declare it under `purposes` or fix the spelling.
82
+ ⚠ warning fiduciary.grievanceUrl
83
+ Add where people can raise a grievance. Section 8(10) requires a grievance mechanism, and Section 5(1)(ii) requires the notice to say how to use it.
84
+ ```
85
+
86
+ The same checks run when the app starts: `createDpdp` throws if the config has errors.
87
+
88
+ ## 3. Record consent
89
+
90
+ ```ts
91
+ import { createDpdp } from "dpdp-kit";
92
+ import { drizzleStore } from "dpdp-kit/drizzle";
93
+ import config from "./dpdp.config";
94
+
95
+ export const dpdp = createDpdp({ config, store: drizzleStore(db) });
96
+
97
+ await dpdp.consent.grant(userId, ["marketing_sms", "analytics"], {
98
+ noticeVersion: "2026-11",
99
+ language: "hi", // English or any of the 22 Eighth Schedule languages (Sections 5(3), 6(3))
100
+ channel: "android",
101
+ evidence: { ip: req.ip },
102
+ });
103
+
104
+ await dpdp.consent.has(userId, "marketing_sms"); // true
105
+ await dpdp.consent.active(userId); // ["marketing_sms", "analytics"]
106
+ await dpdp.consent.history(userId); // every event, oldest first
107
+ await dpdp.consent.verify(userId); // { ok: true, events: 1 }
108
+ ```
109
+
110
+ `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.
111
+
112
+ ## 4. Withdrawals and deletions
113
+
114
+ ```ts
115
+ const { erasure } = await dpdp.consent.withdraw(userId, ["analytics"]);
116
+ ```
117
+
118
+ ```jsonc
119
+ {
120
+ "tables": [
121
+ { "table": "users", "action": "erase-fields",
122
+ "fields": [{ "field": "interests", "action": "erase", "after": "7d" }] }
123
+ ],
124
+ "processors": [{ "name": "posthog", "action": "erase", "ended": ["analytics"] }]
125
+ }
126
+ ```
127
+
128
+ A field is erased only when **none** of its purposes remain. `phone` above stays because `account` and `order_updates` still need it, and the plan says so (`action: "keep", keptFor: [...]`).
129
+
130
+ ```ts
131
+ await dpdp.erasure.plan(userId, { reason: "account-deletion" });
132
+ // users → delete-rows, orders → hold (GST records, 8y, then anonymise), processors → erase
133
+ ```
134
+
135
+ **"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".
136
+
137
+ **In v0.1 the plan only describes what to do; nothing is deleted for you.** Applying it (with your own `onErase` hooks for third parties) arrives in v0.2.
138
+
139
+ ## 5. Guard routes
140
+
141
+ ```ts
142
+ // Express
143
+ import { requireConsent } from "dpdp-kit/express";
144
+ app.post("/promo", requireConsent(dpdp, "marketing_sms", { subject: (req) => req.user?.id }), handler);
145
+
146
+ // Hono
147
+ import { requireConsent } from "dpdp-kit/hono";
148
+ app.post("/promo", requireConsent(dpdp, "marketing_sms", { subject: (c) => c.get("userId") }), handler);
149
+ ```
150
+
151
+ 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.
152
+
153
+ ## Storage
154
+
155
+ ### Drizzle (Postgres)
156
+
157
+ Add the table to your schema so drizzle-kit creates it:
158
+
159
+ ```ts
160
+ // schema.ts
161
+ export { consentEvents } from "dpdp-kit/drizzle";
162
+ ```
163
+
164
+ If you don't use drizzle-kit, run `CONSENT_EVENTS_DDL` (exported from `dpdp-kit/drizzle`). This works with any Drizzle Postgres driver: node-postgres, postgres.js, Neon, PGlite.
165
+
166
+ ### Anything else
167
+
168
+ Implement `ConsentStore`: three methods (`lastEvent`, `insert`, `events`). `insert` must throw `SeqConflictError` on a duplicate `(subjectId, seq)`; a primary key on those columns does that. `memoryStore()` is included for tests.
169
+
170
+ ## How the consent record works
171
+
172
+ Section 6(10) puts the burden on you: if consent is questioned in a proceeding, the Data Fiduciary must prove that a notice was given and consent was given. That's why each event stores the notice version, language, channel and evidence, and why the record shows edits.
173
+
174
+ - Events are only ever added. Each has `seq` (1, 2, 3… per person), `prevHash` and `hash`, a sha256 over the event's fields and the previous hash.
175
+ - Two writes for the same person at once can't fork the chain. The second hits the `(subjectId, seq)` key and retries on top of the first.
176
+ - `verify()` recomputes every hash. It catches an edited event, a deleted event in the middle, and reordering.
177
+ - **Limitation:** deleting the *latest* events leaves a shorter chain that still verifies. To catch that, save `history().at(-1).hash` somewhere the database admin can't change, such as your logs or another system, and compare.
178
+
179
+ ## Roadmap
180
+
181
+ | Version | Adds |
182
+ |---|---|
183
+ | **v0.1** (this) | Config and types, `audit` + CLI, consent records, erasure plans, Drizzle store, Express/Hono guards |
184
+ | v0.2 | User rights requests (Sections 11–14, Rule 14; grievances answered within 90 days, Rule 14(3)), recording objections to a Section 7(a) use, applying erasure plans, processor hooks, React notice that meets Rule 3 + privacy centre |
185
+ | v0.3 | Breach records with deadlines (Section 8(6), Rule 7: people and the Board without delay, detailed report to the Board within 72 hours), children and guardian consent (Section 9, Rule 10), inactivity erasure with 48 hours' warning for large e-commerce, gaming and social media platforms (Rule 8(1)–(2), Third Schedule), Consent Manager interop (Sections 6(7)–6(9), Rule 4), Prisma store |
186
+
187
+ ## When the Rules apply
188
+
189
+ The DPDP Rules, 2025 were published on 13 November 2025 and start in phases (Rule 1):
190
+
191
+ - **Rule 4** (Consent Managers): one year after publication, November 2026.
192
+ - **Rules 3, 5 to 16, 22 and 23**, including notices, security safeguards, breaches, retention and erasure, children, and rights requests: **18 months after publication, May 2027.**
193
+
194
+ Building this in now gives you time to test before those obligations start.
195
+
196
+ ## Legal sources
197
+
198
+ - **The Digital Personal Data Protection Act, 2023** (No. 22 of 2023), Gazette of India Extraordinary, Part II Section 1, 11 August 2023 (CG-DL-E-12082023-248045). Every Section reference here has been checked against this text.
199
+ - **The Digital Personal Data Protection Rules, 2025**, G.S.R. 846(E), 13 November 2025 (MeitY copy). Every Rule reference here has been checked against this text.
200
+ - **Corrigendum G.S.R. 892(E)**, 10 December 2025, published 11 December 2025 (CG-DL-E-12122025-268455). It makes 8 wording corrections, to Rule 1(3)–(4), Rule 11, Rule 19, the First Schedule and the Fourth Schedule. None changes anything cited here. Rule 1's "of this Gazette" becoming "in the Official Gazette" leaves the start dates unchanged.
201
+
202
+ Report a wrong or outdated reference as an issue. It's treated as a bug.
203
+
204
+ ## Licence
205
+
206
+ MIT
@@ -0,0 +1,15 @@
1
+ import type { DpdpConfig } from "./config.js";
2
+ export type IssueLevel = "error" | "warning";
3
+ export interface Issue {
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";
6
+ /** Where in the config, e.g. `data.users.fields.phone`. */
7
+ path: string;
8
+ message: string;
9
+ }
10
+ /**
11
+ * Check a config for mistakes. Errors mean the config can't be used; warnings are things a
12
+ * reviewer should look at. This checks the config's own consistency, not legal compliance.
13
+ */
14
+ export declare function audit(config: DpdpConfig<string>): Issue[];
15
+ export declare function hasErrors(issues: readonly Issue[]): boolean;
@@ -0,0 +1,26 @@
1
+ // src/errors.ts
2
+ var DpdpError = class extends Error {
3
+ constructor(code, message, issues) {
4
+ super(message);
5
+ this.code = code;
6
+ this.issues = issues;
7
+ }
8
+ code;
9
+ issues;
10
+ name = "DpdpError";
11
+ };
12
+ var SeqConflictError = class extends Error {
13
+ constructor(subjectId, seq) {
14
+ super(`A consent event for this subject with seq ${seq} already exists`);
15
+ this.subjectId = subjectId;
16
+ this.seq = seq;
17
+ }
18
+ subjectId;
19
+ seq;
20
+ name = "SeqConflictError";
21
+ };
22
+
23
+ export {
24
+ DpdpError,
25
+ SeqConflictError
26
+ };
@@ -0,0 +1,16 @@
1
+ // src/guard.ts
2
+ var CONSENT_REQUIRED_BODY = (purpose) => ({
3
+ error: "consent_required",
4
+ purpose,
5
+ message: "You haven't agreed to this yet. You can turn it on in your privacy settings."
6
+ });
7
+ async function checkConsent(dpdp, purpose, options, ctx) {
8
+ const subjectId = await options.subject(ctx);
9
+ if (!subjectId) return false;
10
+ return dpdp.consent.has(subjectId, purpose);
11
+ }
12
+
13
+ export {
14
+ CONSENT_REQUIRED_BODY,
15
+ checkConsent
16
+ };
@@ -0,0 +1,185 @@
1
+ // src/duration.ts
2
+ var PATTERN = /^(\d+)(h|d|y)$/;
3
+ var HOUR_MS = 60 * 60 * 1e3;
4
+ var UNIT_MS = { h: HOUR_MS, d: 24 * HOUR_MS, y: 365 * 24 * HOUR_MS };
5
+ function isDuration(value) {
6
+ return typeof value === "string" && PATTERN.test(value);
7
+ }
8
+ function durationMs(value) {
9
+ const match = PATTERN.exec(value);
10
+ if (!match) throw new TypeError(`Not a duration: ${JSON.stringify(value)} (use e.g. "48h", "30d", "1y")`);
11
+ const [, amount, unit] = match;
12
+ return Number(amount) * UNIT_MS[unit];
13
+ }
14
+ function maxDuration(a, b) {
15
+ return durationMs(b) > durationMs(a) ? b : a;
16
+ }
17
+
18
+ // src/audit.ts
19
+ var ONE_YEAR_MS = durationMs("1y");
20
+ function checkRetention(retain, path, issues) {
21
+ if (retain === "while-active" || isDuration(retain)) return;
22
+ if (retain && typeof retain === "object" && "afterWithdrawal" in retain) {
23
+ if (!isDuration(retain.afterWithdrawal)) {
24
+ issues.push({
25
+ level: "error",
26
+ code: "invalid-duration",
27
+ path: `${path}.afterWithdrawal`,
28
+ message: `${JSON.stringify(retain.afterWithdrawal)} is not a duration. Use e.g. "0d", "30d", "1y".`
29
+ });
30
+ }
31
+ return;
32
+ }
33
+ issues.push({
34
+ level: "error",
35
+ code: "invalid-retention",
36
+ path,
37
+ message: `Retention must be "while-active", a duration like "1y", or { afterWithdrawal: "30d" }.`
38
+ });
39
+ }
40
+ function checkPurposeList(purposes, known, used, path, issues) {
41
+ if (!purposes || purposes.length === 0) {
42
+ issues.push({
43
+ level: "error",
44
+ code: "field-without-purpose",
45
+ path: `${path}.purposes`,
46
+ message: "List at least one purpose. Personal data with no purpose must not be collected."
47
+ });
48
+ return;
49
+ }
50
+ for (const p of purposes) {
51
+ used.add(p);
52
+ if (!known.has(p)) {
53
+ issues.push({
54
+ level: "error",
55
+ code: "unknown-purpose",
56
+ path: `${path}.purposes`,
57
+ message: `Unknown purpose ${JSON.stringify(p)}. Declare it under \`purposes\` or fix the spelling.`
58
+ });
59
+ }
60
+ }
61
+ }
62
+ function audit(config) {
63
+ const issues = [];
64
+ const purposes = config.purposes ?? {};
65
+ const known = new Set(Object.keys(purposes));
66
+ const used = /* @__PURE__ */ new Set();
67
+ if (!config.fiduciary?.name) {
68
+ issues.push({
69
+ level: "error",
70
+ code: "fiduciary-missing",
71
+ path: "fiduciary.name",
72
+ message: "Name the Data Fiduciary (your organisation). It appears on every notice."
73
+ });
74
+ }
75
+ if (!config.fiduciary?.grievanceUrl) {
76
+ issues.push({
77
+ level: "warning",
78
+ code: "grievance-missing",
79
+ path: "fiduciary.grievanceUrl",
80
+ message: "Add where people can raise a grievance. Section 8(10) requires a grievance mechanism, and Section 5(1)(ii) requires the notice to say how to use it."
81
+ });
82
+ }
83
+ if (known.size === 0) {
84
+ issues.push({ level: "error", code: "no-purposes", path: "purposes", message: "Declare at least one purpose." });
85
+ }
86
+ for (const [name, def] of Object.entries(purposes)) {
87
+ const path = `purposes.${name}`;
88
+ if (def.basis !== "consent" && def.basis !== "legitimate-use") {
89
+ issues.push({
90
+ level: "error",
91
+ code: "invalid-basis",
92
+ path: `${path}.basis`,
93
+ message: `Basis must be "consent" or "legitimate-use".`
94
+ });
95
+ }
96
+ checkRetention(def.retain, `${path}.retain`, issues);
97
+ if (def.basis === "legitimate-use" && typeof def.retain === "object") {
98
+ issues.push({
99
+ level: "error",
100
+ code: "invalid-retention",
101
+ path: `${path}.retain`,
102
+ message: 'afterWithdrawal only applies to consent purposes (Section 6(4)). Use "while-active" or a duration for a legitimate use.'
103
+ });
104
+ }
105
+ }
106
+ for (const [key, table] of Object.entries(config.data ?? {})) {
107
+ const path = `data.${key}`;
108
+ if (!table.subject) {
109
+ issues.push({
110
+ level: "error",
111
+ code: "missing-subject-column",
112
+ path: `${path}.subject`,
113
+ message: "Name the column that holds the person's id, so their rows can be found."
114
+ });
115
+ }
116
+ const fields = Object.entries(table.fields ?? {});
117
+ if (fields.length === 0) {
118
+ issues.push({
119
+ level: "warning",
120
+ code: "table-without-fields",
121
+ path: `${path}.fields`,
122
+ message: "No personal fields listed. Remove the table from the map, or list its fields."
123
+ });
124
+ }
125
+ for (const [field, def] of fields) {
126
+ checkPurposeList(def.purposes, known, used, `${path}.fields.${field}`, issues);
127
+ }
128
+ if (table.legalHold && !isDuration(table.legalHold.keep)) {
129
+ issues.push({
130
+ level: "error",
131
+ code: "invalid-duration",
132
+ path: `${path}.legalHold.keep`,
133
+ message: `${JSON.stringify(table.legalHold.keep)} is not a duration. Use e.g. "8y".`
134
+ });
135
+ }
136
+ }
137
+ for (const [name, processor] of Object.entries(config.processors ?? {})) {
138
+ checkPurposeList(processor.purposes, known, used, `processors.${name}`, issues);
139
+ }
140
+ for (const name of known) {
141
+ if (!used.has(name)) {
142
+ issues.push({
143
+ level: "warning",
144
+ code: "unused-purpose",
145
+ path: `purposes.${name}`,
146
+ message: "No field or processor uses this purpose. Remove it, or map the data it covers."
147
+ });
148
+ }
149
+ }
150
+ const minimum = config.minimumRetention;
151
+ if (minimum === void 0) {
152
+ issues.push({
153
+ level: "warning",
154
+ code: "minimum-retention-missing",
155
+ path: "minimumRetention",
156
+ message: 'Set minimumRetention. Rule 8(3) of the DPDP Rules requires keeping personal data, traffic data and logs of each processing for at least one year from the processing ("1y").'
157
+ });
158
+ } else if (!isDuration(minimum)) {
159
+ issues.push({
160
+ level: "error",
161
+ code: "invalid-duration",
162
+ path: "minimumRetention",
163
+ message: `${JSON.stringify(minimum)} is not a duration. Use e.g. "1y".`
164
+ });
165
+ } else if (durationMs(minimum) < ONE_YEAR_MS) {
166
+ issues.push({
167
+ level: "error",
168
+ code: "minimum-retention-too-short",
169
+ path: "minimumRetention",
170
+ message: 'Rule 8(3) of the DPDP Rules requires keeping personal data, traffic data and logs of each processing for at least one year. Use at least "1y".'
171
+ });
172
+ }
173
+ return issues;
174
+ }
175
+ function hasErrors(issues) {
176
+ return issues.some((i) => i.level === "error");
177
+ }
178
+
179
+ export {
180
+ isDuration,
181
+ durationMs,
182
+ maxDuration,
183
+ audit,
184
+ hasErrors
185
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ audit
4
+ } from "./chunk-HRKHRKV4.js";
5
+
6
+ // src/run-audit.ts
7
+ import { existsSync } from "fs";
8
+ import { resolve } from "path";
9
+ import { pathToFileURL } from "url";
10
+ var CONFIG_FILES = ["dpdp.config.ts", "dpdp.config.mts", "dpdp.config.js", "dpdp.config.mjs"];
11
+ function findConfig(cwd, explicit) {
12
+ if (explicit) return resolve(cwd, explicit);
13
+ return CONFIG_FILES.map((f) => resolve(cwd, f)).find((f) => existsSync(f));
14
+ }
15
+ async function loadConfig(file) {
16
+ const { createJiti } = await import("jiti");
17
+ const jiti = createJiti(pathToFileURL(file).href);
18
+ const mod = await jiti.import(file);
19
+ const config = [mod.default, mod.config, mod.default?.config].find(
20
+ (c) => typeof c === "object" && c !== null && "purposes" in c
21
+ );
22
+ if (!config) {
23
+ throw new Error(`${file} must export a config: \`export default defineConfig({ ... })\``);
24
+ }
25
+ return config;
26
+ }
27
+ function formatIssues(issues) {
28
+ if (issues.length === 0) return "\u2714 No problems found.";
29
+ const errors = issues.filter((i) => i.level === "error");
30
+ const warnings = issues.filter((i) => i.level === "warning");
31
+ const lines = [...errors, ...warnings].map(
32
+ (i) => `${i.level === "error" ? "\u2716 error " : "\u26A0 warning"} ${i.path}
33
+ ${i.message}`
34
+ );
35
+ lines.push("", `${errors.length} error(s), ${warnings.length} warning(s)`);
36
+ return lines.join("\n");
37
+ }
38
+ async function runAudit(argv, cwd, log) {
39
+ const configFlag = argv.indexOf("--config");
40
+ const explicit = configFlag >= 0 ? argv[configFlag + 1] : void 0;
41
+ const strict = argv.includes("--strict");
42
+ const file = findConfig(cwd, explicit);
43
+ if (!file || !existsSync(file)) {
44
+ log(explicit ? `Config file not found: ${explicit}` : `No config found. Create one of: ${CONFIG_FILES.join(", ")}`);
45
+ return 1;
46
+ }
47
+ const issues = audit(await loadConfig(file));
48
+ log(formatIssues(issues));
49
+ const failing = issues.filter((i) => i.level === "error" || strict && i.level === "warning");
50
+ return failing.length > 0 ? 1 : 0;
51
+ }
52
+
53
+ // src/cli.ts
54
+ var HELP = `dpdp-kit \u2014 DPDP Act tooling for Node.js
55
+
56
+ Usage:
57
+ dpdp-kit audit [--config <file>] [--strict] Check your data map and purposes
58
+
59
+ Options:
60
+ --config <file> Config file (default: dpdp.config.ts / .mts / .js / .mjs)
61
+ --strict Fail on warnings too
62
+ `;
63
+ var [command, ...rest] = process.argv.slice(2);
64
+ if (command === "audit") {
65
+ runAudit(rest, process.cwd(), (line) => console.log(line)).then(
66
+ (code) => {
67
+ process.exitCode = code;
68
+ },
69
+ (err) => {
70
+ console.error(err instanceof Error ? err.message : err);
71
+ process.exitCode = 1;
72
+ }
73
+ );
74
+ } else {
75
+ console.log(HELP);
76
+ process.exitCode = command === void 0 || command === "--help" || command === "-h" ? 0 : 1;
77
+ }
@@ -0,0 +1,103 @@
1
+ import type { Duration } from "./duration.js";
2
+ /**
3
+ * Why you may process data for a purpose.
4
+ * - `"consent"`: the person agreed (Section 6(1)). They can withdraw at any time, as easily as
5
+ * they gave it (Section 6(4)).
6
+ * - `"legitimate-use"`: one of the uses listed in Section 7, which need no consent. For most apps
7
+ * that means Section 7(a): data the person voluntarily gave you for a specified purpose (a
8
+ * receipt by SMS, an order delivery). Section 7(a) applies only while they haven't told you they
9
+ * don't want it used, so it isn't permanent. Section 7(i) covers employment. The other clauses
10
+ * are for the State, legal orders, medical emergencies and disasters.
11
+ *
12
+ * Keeping data because another law requires it (tax, KYC) is not a legitimate use. Model it as a
13
+ * `legalHold` on the table instead (Section 8(7)).
14
+ */
15
+ export type Basis = "consent" | "legitimate-use";
16
+ /**
17
+ * How long data held for a purpose is kept.
18
+ * - `"while-active"`: for as long as the purpose is still being served (e.g. the account is open).
19
+ * - a duration, e.g. `"1y"`: at most this long after it was collected.
20
+ * - `{ afterWithdrawal }`: for consent purposes, how long after withdrawal before it's erased
21
+ * (default `"0d"`). Section 8(7)(a) says to erase upon withdrawal, and Section 6(6) to stop
22
+ * processing within a reasonable time, so keep this to the delay your systems really need
23
+ * (batch jobs, backups).
24
+ */
25
+ export type Retention = "while-active" | Duration | {
26
+ afterWithdrawal: Duration;
27
+ };
28
+ export interface PurposeDef {
29
+ basis: Basis;
30
+ retain: Retention;
31
+ /** Plain-language description, as shown to people in the notice. */
32
+ description?: string;
33
+ }
34
+ /** Kind of personal data. Free text is allowed; these are the common ones. */
35
+ export type Category = "contact" | "identity" | "financial" | "health" | "location" | "device" | "biometric" | "behavioural" | (string & {});
36
+ export interface PersonalField<P extends string = string> {
37
+ category: Category;
38
+ /** Every purpose this field is held for. When all of them end, the field must go. */
39
+ purposes: readonly P[];
40
+ /** This field can tell you the person is under 18 (e.g. date of birth). Used from v0.3. */
41
+ childSignal?: boolean;
42
+ }
43
+ /**
44
+ * Another law says you must keep these rows (e.g. tax or KYC records). Section 8(7) requires
45
+ * erasure "unless retention is necessary for compliance with any law".
46
+ */
47
+ export interface LegalHold {
48
+ reason: string;
49
+ keep: Duration;
50
+ /** What happens to the personal fields once the hold ends. */
51
+ then: "anonymise" | "delete";
52
+ }
53
+ export interface TableDef<P extends string = string> {
54
+ /** Table (or collection) name in your database. */
55
+ table: string;
56
+ /** Column that holds the person's id. */
57
+ subject: string;
58
+ fields: Record<string, PersonalField<P>>;
59
+ legalHold?: LegalHold;
60
+ }
61
+ /** A third party you share data with (SMS gateway, analytics, payment provider…). */
62
+ export interface ProcessorDef<P extends string = string> {
63
+ purposes: readonly P[];
64
+ description?: string;
65
+ }
66
+ export interface FiduciaryDef {
67
+ name: string;
68
+ /**
69
+ * Where people raise a grievance. Section 8(10) requires a grievance mechanism, Section 13 gives
70
+ * people the right to use it, and Section 5(1)(ii) requires the notice to say how.
71
+ */
72
+ grievanceUrl?: string;
73
+ /**
74
+ * Data Protection Officer, or a person who can answer questions about the data. Section 8(9)
75
+ * and Rule 9 require publishing their business contact details prominently and in every reply
76
+ * to a rights request; Section 6(3) requires them in every consent request.
77
+ */
78
+ dpo?: string;
79
+ }
80
+ export interface DpdpConfig<P extends string = string> {
81
+ fiduciary: FiduciaryDef;
82
+ purposes: {
83
+ readonly [K in P]: PurposeDef;
84
+ };
85
+ data: Record<string, TableDef<NoInfer<P>>>;
86
+ processors?: Record<string, ProcessorDef<NoInfer<P>>>;
87
+ /**
88
+ * How long personal data, traffic data and logs of each processing are kept, at minimum, from the
89
+ * date of that processing, even after erasure is otherwise due (e.g. the account is deleted).
90
+ * Rule 8(3) of the DPDP Rules requires at least one year (`"1y"`), only for the purposes in the
91
+ * Seventh Schedule (requests from the State); Rule 6(1)(e) also requires a year of logs for
92
+ * security investigations.
93
+ */
94
+ minimumRetention?: Duration;
95
+ }
96
+ /** Purpose names of a config, e.g. `"account" | "marketing_sms"`. */
97
+ export type PurposeOf<C> = C extends DpdpConfig<infer P> ? P : never;
98
+ /**
99
+ * Declare what personal data you hold, where, and why. Purpose names used in `data` and
100
+ * `processors` are checked against `purposes` by the type checker, and again by `audit()`.
101
+ */
102
+ export declare function defineConfig<const P extends string>(config: DpdpConfig<P>): DpdpConfig<P>;
103
+ export declare function purposeNames<P extends string>(config: DpdpConfig<P>): P[];