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/dist/index.js ADDED
@@ -0,0 +1,320 @@
1
+ import {
2
+ DpdpError,
3
+ SeqConflictError
4
+ } from "./chunk-67Q5GFD6.js";
5
+ import {
6
+ CONSENT_REQUIRED_BODY
7
+ } from "./chunk-FGZAH2NF.js";
8
+ import {
9
+ audit,
10
+ durationMs,
11
+ hasErrors,
12
+ isDuration,
13
+ maxDuration
14
+ } from "./chunk-HRKHRKV4.js";
15
+
16
+ // src/config.ts
17
+ function defineConfig(config) {
18
+ return config;
19
+ }
20
+ function purposeNames(config) {
21
+ return Object.keys(config.purposes);
22
+ }
23
+
24
+ // src/erasure.ts
25
+ function erasureDelay(config, ended) {
26
+ let delay = "0d";
27
+ for (const name of ended) {
28
+ const retain = config.purposes[name]?.retain;
29
+ if (retain && typeof retain === "object") delay = maxDuration(delay, retain.afterWithdrawal);
30
+ }
31
+ return delay;
32
+ }
33
+ function planErasure(config, input) {
34
+ const ended = new Set(input.ended);
35
+ const remaining = new Set(input.remaining.filter((p) => !ended.has(p)));
36
+ const tables = [];
37
+ for (const [key, table] of Object.entries(config.data)) {
38
+ const fields = [];
39
+ for (const [field, def] of Object.entries(table.fields)) {
40
+ const endedHere = def.purposes.filter((p) => ended.has(p));
41
+ if (endedHere.length === 0) continue;
42
+ const keptFor = def.purposes.filter((p) => remaining.has(p));
43
+ if (keptFor.length > 0) {
44
+ fields.push({ field, action: "keep", keptFor });
45
+ } else if (table.legalHold) {
46
+ fields.push({ field, action: "hold" });
47
+ } else {
48
+ fields.push({ field, action: "erase", after: erasureDelay(config, endedHere) });
49
+ }
50
+ }
51
+ if (fields.length === 0) continue;
52
+ const allFieldsGo = fields.length === Object.keys(table.fields).length && fields.every((f) => f.action !== "keep");
53
+ let action;
54
+ if (fields.some((f) => f.action === "hold")) action = "hold";
55
+ else if (input.reason === "account-deletion" && allFieldsGo) action = "delete-rows";
56
+ else if (fields.some((f) => f.action === "erase")) action = "erase-fields";
57
+ else action = "keep";
58
+ tables.push({
59
+ key,
60
+ table: table.table,
61
+ subject: table.subject,
62
+ action,
63
+ fields,
64
+ ...action === "hold" && table.legalHold ? { hold: table.legalHold } : {}
65
+ });
66
+ }
67
+ const processors = [];
68
+ for (const [name, processor] of Object.entries(config.processors ?? {})) {
69
+ const endedHere = processor.purposes.filter((p) => ended.has(p));
70
+ if (endedHere.length === 0) continue;
71
+ const stillUsed = processor.purposes.some((p) => remaining.has(p));
72
+ processors.push({ name, action: stillUsed ? "restrict" : "erase", ended: endedHere });
73
+ }
74
+ return {
75
+ subjectId: input.subjectId,
76
+ reason: input.reason,
77
+ ended: [...ended],
78
+ remaining: [...remaining],
79
+ tables,
80
+ processors,
81
+ ...config.minimumRetention !== void 0 ? { minimumRetention: config.minimumRetention } : {}
82
+ };
83
+ }
84
+
85
+ // src/hash.ts
86
+ import { createHash } from "crypto";
87
+ function canonicalJson(value) {
88
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
89
+ if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
90
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
91
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
92
+ }
93
+ function sha256(text) {
94
+ return createHash("sha256").update(text).digest("hex");
95
+ }
96
+
97
+ // src/languages.ts
98
+ var NOTICE_LANGUAGES = {
99
+ en: "English",
100
+ as: "Assamese",
101
+ bn: "Bengali",
102
+ brx: "Bodo",
103
+ doi: "Dogri",
104
+ gu: "Gujarati",
105
+ hi: "Hindi",
106
+ kn: "Kannada",
107
+ ks: "Kashmiri",
108
+ kok: "Konkani",
109
+ mai: "Maithili",
110
+ ml: "Malayalam",
111
+ mni: "Manipuri",
112
+ mr: "Marathi",
113
+ ne: "Nepali",
114
+ or: "Odia",
115
+ pa: "Punjabi",
116
+ sa: "Sanskrit",
117
+ sat: "Santali",
118
+ sd: "Sindhi",
119
+ ta: "Tamil",
120
+ te: "Telugu",
121
+ ur: "Urdu"
122
+ };
123
+ function isNoticeLanguage(value) {
124
+ return typeof value === "string" && Object.hasOwn(NOTICE_LANGUAGES, value);
125
+ }
126
+
127
+ // src/dpdp.ts
128
+ function hashEvent(event) {
129
+ return sha256(
130
+ canonicalJson({
131
+ subjectId: event.subjectId,
132
+ seq: event.seq,
133
+ action: event.action,
134
+ purposes: event.purposes,
135
+ noticeVersion: event.noticeVersion,
136
+ language: event.language,
137
+ channel: event.channel,
138
+ evidence: event.evidence,
139
+ at: event.at,
140
+ prevHash: event.prevHash
141
+ })
142
+ );
143
+ }
144
+ function grantedFrom(events) {
145
+ const granted = /* @__PURE__ */ new Set();
146
+ for (const e of events) {
147
+ for (const p of e.purposes) {
148
+ if (e.action === "grant") granted.add(p);
149
+ else granted.delete(p);
150
+ }
151
+ }
152
+ return granted;
153
+ }
154
+ function createDpdp(options) {
155
+ const { config, store } = options;
156
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
157
+ const maxRetries = options.maxRetries ?? 5;
158
+ const issues = audit(config);
159
+ if (hasErrors(issues)) {
160
+ const lines = issues.filter((i) => i.level === "error").map((i) => ` ${i.path}: ${i.message}`);
161
+ throw new DpdpError("invalid-config", `dpdp-kit config has errors:
162
+ ${lines.join("\n")}`, issues);
163
+ }
164
+ const purposes = config.purposes;
165
+ const legitimate = Object.keys(purposes).filter((p) => purposes[p]?.basis === "legitimate-use");
166
+ function checkSubject(subjectId) {
167
+ if (typeof subjectId !== "string" || subjectId.length === 0) {
168
+ throw new DpdpError("invalid-subject", "subjectId must be a non-empty string");
169
+ }
170
+ }
171
+ function checkConsentPurposes(list) {
172
+ if (list.length === 0) throw new DpdpError("no-purposes", "Pass at least one purpose");
173
+ for (const p of list) {
174
+ const def = purposes[p];
175
+ if (!def) throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(p)}`);
176
+ if (def.basis !== "consent") {
177
+ throw new DpdpError(
178
+ "not-a-consent-purpose",
179
+ `${JSON.stringify(p)} is a legitimate-use purpose; consent isn't granted or withdrawn for it`
180
+ );
181
+ }
182
+ }
183
+ }
184
+ async function append(subjectId, action, list, meta = {}) {
185
+ checkSubject(subjectId);
186
+ checkConsentPurposes(list);
187
+ if (meta.language !== void 0 && !isNoticeLanguage(meta.language)) {
188
+ throw new DpdpError("invalid-language", `Unknown notice language ${JSON.stringify(meta.language)}`);
189
+ }
190
+ const unique = [...new Set(list)];
191
+ for (let attempt = 1; ; attempt++) {
192
+ const last = await store.lastEvent(subjectId);
193
+ const fields = {
194
+ subjectId,
195
+ seq: (last?.seq ?? 0) + 1,
196
+ action,
197
+ purposes: unique,
198
+ ...meta.noticeVersion !== void 0 ? { noticeVersion: meta.noticeVersion } : {},
199
+ ...meta.language !== void 0 ? { language: meta.language } : {},
200
+ ...meta.channel !== void 0 ? { channel: meta.channel } : {},
201
+ ...meta.evidence !== void 0 ? { evidence: { ...meta.evidence } } : {},
202
+ at: now().toISOString(),
203
+ prevHash: last?.hash ?? null
204
+ };
205
+ const event = { ...fields, hash: hashEvent(fields) };
206
+ try {
207
+ await store.insert(event);
208
+ return event;
209
+ } catch (err) {
210
+ if (err instanceof SeqConflictError && attempt < maxRetries) continue;
211
+ if (err instanceof SeqConflictError) {
212
+ throw new DpdpError("write-conflict", `Gave up after ${maxRetries} conflicting writes for one subject`);
213
+ }
214
+ throw err;
215
+ }
216
+ }
217
+ }
218
+ async function activeFor(subjectId) {
219
+ checkSubject(subjectId);
220
+ return [...grantedFrom(await store.events(subjectId))];
221
+ }
222
+ return {
223
+ config,
224
+ consent: {
225
+ grant: (subjectId, list, meta) => append(subjectId, "grant", list, meta),
226
+ async withdraw(subjectId, list, meta) {
227
+ const event = await append(subjectId, "withdraw", list, meta);
228
+ const stillGranted = await activeFor(subjectId);
229
+ const erasure = planErasure(config, {
230
+ subjectId,
231
+ reason: "withdrawal",
232
+ ended: event.purposes,
233
+ remaining: [...legitimate, ...stillGranted]
234
+ });
235
+ return { event, erasure };
236
+ },
237
+ async has(subjectId, purpose) {
238
+ checkSubject(subjectId);
239
+ const def = purposes[purpose];
240
+ if (!def) throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(purpose)}`);
241
+ if (def.basis === "legitimate-use") return true;
242
+ return grantedFrom(await store.events(subjectId)).has(purpose);
243
+ },
244
+ active: activeFor,
245
+ async history(subjectId) {
246
+ checkSubject(subjectId);
247
+ return store.events(subjectId);
248
+ },
249
+ async verify(subjectId) {
250
+ checkSubject(subjectId);
251
+ const events = await store.events(subjectId);
252
+ let prev;
253
+ for (const e of events) {
254
+ if (e.seq !== (prev?.seq ?? 0) + 1) {
255
+ return { ok: false, events: events.length, brokenAt: e.seq, reason: "seq-gap" };
256
+ }
257
+ if (e.prevHash !== (prev?.hash ?? null)) {
258
+ return { ok: false, events: events.length, brokenAt: e.seq, reason: "chain-broken" };
259
+ }
260
+ const { hash, ...fields } = e;
261
+ if (hashEvent(fields) !== hash) {
262
+ return { ok: false, events: events.length, brokenAt: e.seq, reason: "hash-mismatch" };
263
+ }
264
+ prev = e;
265
+ }
266
+ return { ok: true, events: events.length };
267
+ }
268
+ },
269
+ erasure: {
270
+ async plan(subjectId, input) {
271
+ checkSubject(subjectId);
272
+ return planErasure(config, {
273
+ subjectId,
274
+ reason: input.reason,
275
+ ended: Object.keys(purposes),
276
+ remaining: []
277
+ });
278
+ }
279
+ }
280
+ };
281
+ }
282
+
283
+ // src/store.ts
284
+ function memoryStore() {
285
+ const all = /* @__PURE__ */ new Map();
286
+ return {
287
+ all,
288
+ async lastEvent(subjectId) {
289
+ const list = all.get(subjectId);
290
+ return list?.[list.length - 1];
291
+ },
292
+ async insert(event) {
293
+ const list = all.get(event.subjectId) ?? [];
294
+ if (list.some((e) => e.seq === event.seq)) throw new SeqConflictError(event.subjectId, event.seq);
295
+ list.push(structuredClone(event));
296
+ list.sort((a, b) => a.seq - b.seq);
297
+ all.set(event.subjectId, list);
298
+ },
299
+ async events(subjectId) {
300
+ return structuredClone(all.get(subjectId) ?? []);
301
+ }
302
+ };
303
+ }
304
+ export {
305
+ CONSENT_REQUIRED_BODY,
306
+ DpdpError,
307
+ NOTICE_LANGUAGES,
308
+ SeqConflictError,
309
+ audit,
310
+ createDpdp,
311
+ defineConfig,
312
+ durationMs,
313
+ hasErrors,
314
+ hashEvent,
315
+ isDuration,
316
+ isNoticeLanguage,
317
+ memoryStore,
318
+ planErasure,
319
+ purposeNames
320
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Languages a notice can be given in. Section 5(3) of the DPDP Act gives people the option to
3
+ * read the notice in English or any language in the Eighth Schedule to the Constitution (22
4
+ * languages), and Section 6(3) gives the same option for the consent request itself.
5
+ * Codes are ISO 639 (639-2/3 where a language has no two-letter code).
6
+ */
7
+ export declare const NOTICE_LANGUAGES: {
8
+ readonly en: "English";
9
+ readonly as: "Assamese";
10
+ readonly bn: "Bengali";
11
+ readonly brx: "Bodo";
12
+ readonly doi: "Dogri";
13
+ readonly gu: "Gujarati";
14
+ readonly hi: "Hindi";
15
+ readonly kn: "Kannada";
16
+ readonly ks: "Kashmiri";
17
+ readonly kok: "Konkani";
18
+ readonly mai: "Maithili";
19
+ readonly ml: "Malayalam";
20
+ readonly mni: "Manipuri";
21
+ readonly mr: "Marathi";
22
+ readonly ne: "Nepali";
23
+ readonly or: "Odia";
24
+ readonly pa: "Punjabi";
25
+ readonly sa: "Sanskrit";
26
+ readonly sat: "Santali";
27
+ readonly sd: "Sindhi";
28
+ readonly ta: "Tamil";
29
+ readonly te: "Telugu";
30
+ readonly ur: "Urdu";
31
+ };
32
+ export type NoticeLanguage = keyof typeof NOTICE_LANGUAGES;
33
+ export declare function isNoticeLanguage(value: unknown): value is NoticeLanguage;
@@ -0,0 +1,9 @@
1
+ import { type Issue } from "./audit.js";
2
+ import type { DpdpConfig } from "./config.js";
3
+ export declare const CONFIG_FILES: string[];
4
+ export declare function findConfig(cwd: string, explicit?: string): string | undefined;
5
+ /** Load a config file (TypeScript or JavaScript). Accepts a default export or `export const config`. */
6
+ export declare function loadConfig(file: string): Promise<DpdpConfig<string>>;
7
+ export declare function formatIssues(issues: readonly Issue[]): string;
8
+ /** Run `dpdp-kit audit`. Returns the exit code: 1 when there are errors (or `--strict` and warnings). */
9
+ export declare function runAudit(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
@@ -0,0 +1,38 @@
1
+ import type { NoticeLanguage } from "./languages.js";
2
+ export type ConsentAction = "grant" | "withdraw";
3
+ /** One entry in a person's consent record. Entries are only ever added, never changed. */
4
+ export interface ConsentEvent {
5
+ subjectId: string;
6
+ /** 1, 2, 3… per subject. */
7
+ seq: number;
8
+ action: ConsentAction;
9
+ purposes: string[];
10
+ /** Version of the notice the person saw, e.g. `"2026-11"`. */
11
+ noticeVersion?: string;
12
+ language?: NoticeLanguage;
13
+ /** Where it happened, e.g. `"web"`, `"android"`, `"call-centre"`. */
14
+ channel?: string;
15
+ /** Proof of the action, e.g. IP address, user agent, form id. */
16
+ evidence?: Record<string, string>;
17
+ /** ISO 8601 timestamp. */
18
+ at: string;
19
+ /** Hash of the previous event for this subject (`null` for the first). */
20
+ prevHash: string | null;
21
+ /** sha256 over this event's fields and `prevHash`. */
22
+ hash: string;
23
+ }
24
+ /**
25
+ * Where consent events are kept. Implement this to use any database.
26
+ * `insert` must reject a duplicate (subjectId, seq) by throwing `SeqConflictError`, usually via
27
+ * a primary key or unique index on those two columns.
28
+ */
29
+ export interface ConsentStore {
30
+ lastEvent(subjectId: string): Promise<ConsentEvent | undefined>;
31
+ insert(event: ConsentEvent): Promise<void>;
32
+ /** All events for a subject, oldest first. */
33
+ events(subjectId: string): Promise<ConsentEvent[]>;
34
+ }
35
+ /** Keeps events in memory. For tests and trying the library out; everything is lost on restart. */
36
+ export declare function memoryStore(): ConsentStore & {
37
+ readonly all: Map<string, ConsentEvent[]>;
38
+ };
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "dpdp-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Build India's DPDP Act 2023 into your Node.js backend: declared purposes, tamper-evident consent records, erasure plans and an audit you can run in CI.",
5
+ "keywords": [
6
+ "dpdp",
7
+ "dpdpa",
8
+ "dpdp-act",
9
+ "india",
10
+ "privacy",
11
+ "consent",
12
+ "data-protection",
13
+ "erasure",
14
+ "compliance",
15
+ "drizzle"
16
+ ],
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/yogesh2902/dpdp-kit.git"
21
+ },
22
+ "homepage": "https://github.com/yogesh2902/dpdp-kit#readme",
23
+ "bugs": {
24
+ "url": "https://github.com/yogesh2902/dpdp-kit/issues"
25
+ },
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=20.19"
30
+ },
31
+ "packageManager": "pnpm@12.15.0",
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "bin": {
36
+ "dpdp-kit": "dist/cli.js"
37
+ },
38
+ "exports": {
39
+ ".": {
40
+ "types": "./dist/index.d.ts",
41
+ "default": "./dist/index.js"
42
+ },
43
+ "./drizzle": {
44
+ "types": "./dist/drizzle.d.ts",
45
+ "default": "./dist/drizzle.js"
46
+ },
47
+ "./express": {
48
+ "types": "./dist/express.d.ts",
49
+ "default": "./dist/express.js"
50
+ },
51
+ "./hono": {
52
+ "types": "./dist/hono.d.ts",
53
+ "default": "./dist/hono.js"
54
+ },
55
+ "./package.json": "./package.json"
56
+ },
57
+ "scripts": {
58
+ "build": "tsup && tsc -p tsconfig.build.json",
59
+ "typecheck": "tsc --noEmit",
60
+ "test": "vitest run",
61
+ "prepublishOnly": "pnpm typecheck && pnpm test && pnpm build"
62
+ },
63
+ "peerDependencies": {
64
+ "drizzle-orm": ">=0.38"
65
+ },
66
+ "peerDependenciesMeta": {
67
+ "drizzle-orm": {
68
+ "optional": true
69
+ }
70
+ },
71
+ "dependencies": {
72
+ "jiti": "^2.7.0"
73
+ },
74
+ "devDependencies": {
75
+ "@electric-sql/pglite": "^0.5.16",
76
+ "@types/node": "^26.6.6",
77
+ "drizzle-orm": "^0.45.4",
78
+ "tsup": "^9.0.0",
79
+ "typescript": "^7.0.2",
80
+ "vitest": "^5.1.0"
81
+ }
82
+ }