dpdp-kit 0.4.0 → 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 +45 -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
@@ -0,0 +1,294 @@
1
+ import {
2
+ REQUEST_TYPES
3
+ } from "./chunk-NBVJQDDP.js";
4
+ import {
5
+ DpdpError
6
+ } from "./chunk-67Q5GFD6.js";
7
+
8
+ // src/http.ts
9
+ var STATUS = {
10
+ "request-not-found": 404,
11
+ "nominee-not-found": 404,
12
+ "no-matching-rows": 404,
13
+ "notice-not-configured": 404,
14
+ "notice-language-unavailable": 404,
15
+ "request-closed": 409,
16
+ "write-conflict": 409,
17
+ "notice-version-conflict": 409,
18
+ "request-not-verified": 403,
19
+ "store-unsupported": 501,
20
+ "no-data-access": 501,
21
+ "data-access-unsupported": 501
22
+ };
23
+ var fail = (status, error) => ({ status, body: { error } });
24
+ var ok = (body, status = 200) => ({ status, body });
25
+ var HttpError = class extends Error {
26
+ constructor(response) {
27
+ super(String(response.body.error));
28
+ this.response = response;
29
+ }
30
+ response;
31
+ };
32
+ var refuse = (status, error) => {
33
+ throw new HttpError(fail(status, error));
34
+ };
35
+ var isJson = (contentType) => /^application\/(?:[\w.+-]+\+)?json\b/i.test(contentType ?? "");
36
+ function strings(value, name) {
37
+ if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string")) {
38
+ refuse(400, `invalid-${name}`);
39
+ }
40
+ return value;
41
+ }
42
+ var text = (value, name) => typeof value === "string" && value.trim() ? value : refuse(400, `invalid-${name}`);
43
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
44
+ function forPerson(r) {
45
+ return {
46
+ id: r.id,
47
+ type: r.type,
48
+ status: r.status,
49
+ openedAt: r.openedAt,
50
+ dueAt: r.dueAt,
51
+ ...r.closedAt ? { closedAt: r.closedAt } : {},
52
+ ...r.details ? { details: r.details } : {},
53
+ history: r.history.map(({ by: _by, method: _method, ...entry }) => entry)
54
+ };
55
+ }
56
+ async function handle(dpdp, req, options = {}) {
57
+ try {
58
+ return await route(dpdp, req, options);
59
+ } catch (err) {
60
+ if (err instanceof HttpError) return err.response;
61
+ if (err instanceof DpdpError) return fail(STATUS[err.code] ?? 400, err.code);
62
+ (options.onError ?? console.error)(err);
63
+ return fail(500, "internal");
64
+ }
65
+ }
66
+ var PUBLIC_ROUTES = ["GET notice", "GET rights"];
67
+ var PERSON_ROUTES = [
68
+ "GET consents",
69
+ "POST consents",
70
+ "POST consents/withdraw",
71
+ "POST objections",
72
+ "DELETE objections",
73
+ "GET data",
74
+ "GET requests",
75
+ "GET requests/:id",
76
+ "POST requests",
77
+ "GET nominees",
78
+ "POST nominees",
79
+ "DELETE nominees/:id"
80
+ ];
81
+ var ADMIN_ROUTES = [
82
+ "GET admin/requests",
83
+ "GET admin/requests/:id",
84
+ "GET admin/requests/:id/data",
85
+ "POST admin/requests/:id/verify",
86
+ "POST admin/requests/:id/resolve",
87
+ "POST admin/requests/:id/reject",
88
+ "POST admin/requests/:id/correct",
89
+ "POST admin/requests/:id/erase"
90
+ ];
91
+ function segments(path) {
92
+ try {
93
+ return path.split("/").filter(Boolean).map(decodeURIComponent);
94
+ } catch {
95
+ return void 0;
96
+ }
97
+ }
98
+ var matches = (route2, method, parts) => {
99
+ const [m, pattern = ""] = route2.split(" ");
100
+ const want = pattern.split("/");
101
+ return m === method && want.length === parts.length && want.every((p, i) => p.startsWith(":") || p === parts[i]);
102
+ };
103
+ function isApiRoute(method, path, options = {}) {
104
+ const parts = segments(path);
105
+ if (!parts) return false;
106
+ const m = method.toUpperCase();
107
+ const routes = options.admin ? [...PUBLIC_ROUTES, ...PERSON_ROUTES, ...ADMIN_ROUTES] : [...PUBLIC_ROUTES, ...PERSON_ROUTES];
108
+ return routes.some((r) => matches(r, m, parts));
109
+ }
110
+ async function route(dpdp, req, options) {
111
+ const method = req.method.toUpperCase();
112
+ if (!isApiRoute(method, req.path, options)) return fail(404, "not-found");
113
+ const parts = segments(req.path);
114
+ const query = req.query ?? {};
115
+ if (method === "POST" && !isJson(req.contentType)) return fail(415, "unsupported-media-type");
116
+ const body = object(req.body);
117
+ const is = (m, ...pattern) => method === m && parts.length === pattern.length && pattern.every((p, i) => p.startsWith(":") || p === parts[i]);
118
+ if (is("GET", "notice")) {
119
+ const language = query.language;
120
+ return ok(await dpdp.notice.show({ ...language ? { language } : {}, ...query.kind ? { kind: query.kind } : {} }));
121
+ }
122
+ if (is("GET", "rights")) return ok(dpdp.rights.how());
123
+ if (parts[0] === "admin") return admin(dpdp, req, parts.slice(1), method, body, options);
124
+ const subjectId = req.subjectId;
125
+ if (!subjectId) return fail(401, "unauthenticated");
126
+ const write = method !== "GET";
127
+ if (write && options.limitWrites && !await options.limitWrites(subjectId)) return fail(429, "too-many-requests");
128
+ const meta = {
129
+ channel: options.channel ?? "web",
130
+ ...req.ip || req.userAgent ? { evidence: { ...req.ip ? { ip: req.ip } : {}, ...req.userAgent ? { userAgent: req.userAgent } : {} } } : {}
131
+ };
132
+ const purposes = () => strings(body.purposes, "purposes");
133
+ if (is("GET", "consents")) {
134
+ const [consents, objections] = await Promise.all([dpdp.consent.active(subjectId), dpdp.consent.objections(subjectId)]);
135
+ const list = Object.entries(dpdp.config.purposes).map(
136
+ ([purpose, def]) => ({
137
+ purpose,
138
+ basis: def.basis,
139
+ ...def.description ? { description: def.description } : {},
140
+ ...def.legitimateUse ? { legitimateUse: def.legitimateUse } : {},
141
+ active: def.basis === "consent" ? consents.includes(purpose) : !objections.includes(purpose)
142
+ })
143
+ );
144
+ return ok({ consents, objections, purposes: list });
145
+ }
146
+ if (is("POST", "consents")) {
147
+ const language = typeof body.language === "string" ? body.language : void 0;
148
+ const event = await dpdp.consent.grant(subjectId, purposes(), { ...meta, ...language ? { language } : {} });
149
+ return ok({ event }, 201);
150
+ }
151
+ if (is("POST", "consents", "withdraw")) {
152
+ const { event, tasks } = await dpdp.consent.withdraw(subjectId, purposes(), meta);
153
+ return ok({ event, scheduled: tasks.length });
154
+ }
155
+ if (is("POST", "objections")) {
156
+ const { event, tasks } = await dpdp.consent.object(subjectId, purposes(), meta);
157
+ return ok({ event, scheduled: tasks.length }, 201);
158
+ }
159
+ if (is("DELETE", "objections")) {
160
+ const list = body.purposes ?? query.purposes?.split(",").filter(Boolean);
161
+ const { event, cancelled } = await dpdp.consent.liftObjection(subjectId, strings(list, "purposes"), meta);
162
+ return ok({ event, cancelled: cancelled.length });
163
+ }
164
+ if (is("GET", "data")) return ok(await dpdp.rights.summary(subjectId));
165
+ if (is("GET", "requests")) return ok({ requests: (await dpdp.rights.list({ subjectId })).map(forPerson) });
166
+ if (is("GET", "requests", ":id")) {
167
+ const r = await dpdp.rights.get(parts[1]);
168
+ return r && r.subjectId === subjectId ? ok(forPerson(r)) : fail(404, "request-not-found");
169
+ }
170
+ if (is("POST", "requests")) {
171
+ const type = body.type;
172
+ if (!REQUEST_TYPES.includes(type)) return fail(400, "invalid-request-type");
173
+ const details = body.details === void 0 ? void 0 : object(body.details);
174
+ const request = await dpdp.rights.open(subjectId, type, details);
175
+ return ok({ request: forPerson(request), acknowledgement: await dpdp.rights.acknowledgement(request.id) }, 201);
176
+ }
177
+ if (is("GET", "nominees")) return ok({ nominees: await dpdp.rights.nominees(subjectId) });
178
+ if (is("POST", "nominees")) {
179
+ const nominee = await dpdp.rights.nominate(subjectId, {
180
+ name: text(body.name, "name"),
181
+ contact: text(body.contact, "contact"),
182
+ ...typeof body.relation === "string" ? { relation: body.relation } : {}
183
+ });
184
+ return ok({ nominee }, 201);
185
+ }
186
+ if (is("DELETE", "nominees", ":id")) {
187
+ await dpdp.rights.revokeNominee(subjectId, parts[1]);
188
+ return ok({ revoked: true });
189
+ }
190
+ return fail(404, "not-found");
191
+ }
192
+ async function admin(dpdp, req, parts, method, body, options) {
193
+ if (!options.admin) return fail(404, "not-found");
194
+ const by = req.actor;
195
+ if (!by) return fail(403, "forbidden");
196
+ const is = (m, ...pattern) => method === m && parts.length === pattern.length && pattern.every((p, i) => p.startsWith(":") || p === parts[i]);
197
+ const id = parts[1];
198
+ const query = req.query ?? {};
199
+ if (is("GET", "requests")) {
200
+ const status = query.status;
201
+ return ok({
202
+ requests: await dpdp.rights.list({
203
+ ...query.subjectId ? { subjectId: query.subjectId } : {},
204
+ ...status ? { status } : {},
205
+ ...query.overdue === "true" ? { overdue: true } : {}
206
+ })
207
+ });
208
+ }
209
+ if (is("GET", "requests", ":id")) {
210
+ const r = await dpdp.rights.get(id);
211
+ return r ? ok(r) : fail(404, "request-not-found");
212
+ }
213
+ if (is("GET", "requests", ":id", "data")) {
214
+ const r = await dpdp.rights.get(id) ?? refuse(404, "request-not-found");
215
+ return ok(await dpdp.rights.summary(r.subjectId, { requestId: id }));
216
+ }
217
+ if (is("POST", "requests", ":id", "verify")) return ok(await dpdp.rights.verifyIdentity(id, { method: text(body.method, "method"), by }));
218
+ if (is("POST", "requests", ":id", "resolve")) return ok(await dpdp.rights.resolve(id, typeof body.note === "string" ? body.note : void 0, { by }));
219
+ if (is("POST", "requests", ":id", "reject")) return ok(await dpdp.rights.reject(id, text(body.reason, "reason"), { by }));
220
+ if (is("POST", "requests", ":id", "correct")) {
221
+ const where = body.where === void 0 ? void 0 : object(body.where);
222
+ const result = await dpdp.rights.correct(id, object(body.changes), { by, ...where ? { where } : {}, ...body.resolve === false ? { resolve: false } : {} });
223
+ return ok(result);
224
+ }
225
+ if (is("POST", "requests", ":id", "erase")) {
226
+ const r = await dpdp.rights.get(id) ?? refuse(404, "request-not-found");
227
+ const keepFor = body.keepFor === void 0 ? [] : strings(body.keepFor, "keepFor");
228
+ const { tasks } = await dpdp.rights.erase(r.subjectId, { requestId: id, keepFor, by });
229
+ return ok({ scheduled: tasks.length });
230
+ }
231
+ return fail(404, "not-found");
232
+ }
233
+ function parseJsonBody(raw, limit) {
234
+ if (new TextEncoder().encode(raw).length > limit) throw new HttpError(fail(413, "payload-too-large"));
235
+ if (raw.trim() === "") return void 0;
236
+ try {
237
+ return JSON.parse(raw);
238
+ } catch {
239
+ throw new HttpError(fail(400, "invalid-json"));
240
+ }
241
+ }
242
+ var DEFAULT_BODY_LIMIT = 16 * 1024;
243
+ function bodyOrResponse(raw, limit) {
244
+ try {
245
+ return { body: parseJsonBody(raw, limit) };
246
+ } catch (err) {
247
+ if (err instanceof HttpError) return { response: err.response };
248
+ throw err;
249
+ }
250
+ }
251
+ async function handleWeb(dpdp, request, ctx, options) {
252
+ const url = new URL(request.url);
253
+ const base = (options.base ?? "").replace(/\/+$/, "");
254
+ const path = base && url.pathname.startsWith(base) ? url.pathname.slice(base.length) || "/" : url.pathname;
255
+ const json = (r) => Response.json(r.body, { status: r.status, headers: { "cache-control": "no-store" } });
256
+ let body;
257
+ if (request.method !== "GET" && request.method !== "HEAD") {
258
+ const declared = Number(request.headers.get("content-length") ?? 0);
259
+ const limit = options.bodyLimit ?? DEFAULT_BODY_LIMIT;
260
+ if (declared > limit) return json(fail(413, "payload-too-large"));
261
+ const parsed = bodyOrResponse(await (options.readBody ? options.readBody() : request.text()), limit);
262
+ if ("response" in parsed) return json(parsed.response);
263
+ body = parsed.body;
264
+ }
265
+ const [subjectId, actor] = await Promise.all([options.subject(ctx), options.admin?.(ctx)]);
266
+ const ip = options.ip?.(ctx);
267
+ const userAgent = request.headers.get("user-agent") ?? void 0;
268
+ const contentType = request.headers.get("content-type") ?? void 0;
269
+ return json(
270
+ await handle(
271
+ dpdp,
272
+ {
273
+ method: request.method,
274
+ path,
275
+ query: Object.fromEntries(url.searchParams),
276
+ body,
277
+ ...contentType ? { contentType } : {},
278
+ ...subjectId ? { subjectId } : {},
279
+ ...actor ? { actor } : {},
280
+ ...ip ? { ip } : {},
281
+ ...userAgent ? { userAgent } : {}
282
+ },
283
+ { ...options, admin: options.admin !== void 0 }
284
+ )
285
+ );
286
+ }
287
+
288
+ export {
289
+ handle,
290
+ isApiRoute,
291
+ DEFAULT_BODY_LIMIT,
292
+ bodyOrResponse,
293
+ handleWeb
294
+ };
@@ -1,3 +1,15 @@
1
+ import {
2
+ columnValue
3
+ } from "./chunk-EMNABUCL.js";
4
+ import {
5
+ ACTIONS_SQL,
6
+ NOW_SQL,
7
+ PERIOD_SQL,
8
+ TASKS_SQL,
9
+ TOTALS_SQL,
10
+ statsFromRows,
11
+ taskCountsFromRows
12
+ } from "./chunk-M2PDT6DD.js";
1
13
  import {
2
14
  SeqConflictError
3
15
  } from "./chunk-67Q5GFD6.js";
@@ -231,7 +243,43 @@ var ACCESS_WHERE = `($1::text IS NULL OR subject_id = $1::text) AND ($2::text IS
231
243
  AND ($4::timestamptz IS NULL OR at >= $4::timestamptz) AND ($5::timestamptz IS NULL OR at < $5::timestamptz)`;
232
244
  var accessParams = (f) => [f.subjectId ?? null, f.actor ?? null, f.purpose ?? null, f.from ?? null, f.to ?? null];
233
245
  function postgresStore(query) {
246
+ const NOTICE_ROW = `content, ${utc("first_shown_at")} AS first_shown_at`;
247
+ const savedNotice = (r) => ({
248
+ notice: typeof r.content === "string" ? JSON.parse(r.content) : r.content,
249
+ firstShownAt: iso(r.first_shown_at)
250
+ });
234
251
  return {
252
+ async consentStats(from, to) {
253
+ const [totals, actions, period, now] = await Promise.all([
254
+ query(TOTALS_SQL, [from, to]),
255
+ query(ACTIONS_SQL, [from, to]),
256
+ query(PERIOD_SQL, [from, to]),
257
+ query(NOW_SQL, [])
258
+ ]);
259
+ return statsFromRows(from, to, totals[0], actions, period, now);
260
+ },
261
+ async taskCounts(now) {
262
+ return taskCountsFromRows(await query(TASKS_SQL, [now]));
263
+ },
264
+ async savePrivacyNotice(n, at) {
265
+ const rows = await query(
266
+ `INSERT INTO dpdp_privacy_notices (version, language, kind, content, first_shown_at)
267
+ VALUES ($1::text, $2::text, $3::text, $4::jsonb, $5::timestamptz) ON CONFLICT (version, language, kind) DO NOTHING RETURNING 1 AS one`,
268
+ [n.version, n.language, n.kind, JSON.stringify(n), at]
269
+ );
270
+ return rows.length > 0;
271
+ },
272
+ async getPrivacyNotice(version, language, kind) {
273
+ const [row] = await query(
274
+ `SELECT ${NOTICE_ROW} FROM dpdp_privacy_notices WHERE version = $1::text AND language = $2::text AND kind = $3::text`,
275
+ [version, language, kind]
276
+ );
277
+ return row ? savedNotice(row) : void 0;
278
+ },
279
+ async listPrivacyNotices() {
280
+ const rows = await query(`SELECT ${NOTICE_ROW} FROM dpdp_privacy_notices ORDER BY first_shown_at, version, language, kind`, []);
281
+ return rows.map(savedNotice);
282
+ },
235
283
  async lastEvent(subjectId) {
236
284
  const [row] = await query(`SELECT ${EVENT_SELECT} FROM dpdp_consent_events WHERE subject_id = $1::text ORDER BY seq DESC LIMIT 1`, [subjectId]);
237
285
  return row ? eventFromRow(row) : void 0;
@@ -422,6 +470,23 @@ function postgresData(query, options = {}) {
422
470
  const rows = await query(`UPDATE ${from(table)} SET ${set} WHERE ${where(table, subjectColumn)} RETURNING 1 AS one`, params);
423
471
  return rows.length;
424
472
  },
473
+ async updateFields(table, subjectColumn, subjectId, values, only = {}) {
474
+ const entries = Object.entries(values);
475
+ if (entries.length === 0) return 0;
476
+ const params = [subjectId];
477
+ const isArrayColumn = (c) => /\[\]$|^_/.test(column(table, c)?.sqlType ?? "");
478
+ const set = entries.map(([c, v]) => {
479
+ if (v === null || v === void 0) return `${col(table, c)} = NULL`;
480
+ params.push(Array.isArray(v) && isArrayColumn(c) ? v : columnValue(v));
481
+ return `${col(table, c)} = ${param(params.length, table, c)}`;
482
+ }).join(", ");
483
+ const narrow = Object.entries(only).map(([c, v]) => {
484
+ params.push(v);
485
+ return ` AND ${col(table, c)} = ${param(params.length, table, c)}`;
486
+ });
487
+ const rows = await query(`UPDATE ${from(table)} SET ${set} WHERE ${where(table, subjectColumn)}${narrow.join("")} RETURNING 1 AS one`, params);
488
+ return rows.length;
489
+ },
425
490
  async deleteRows(table, subjectColumn, subjectId) {
426
491
  const rows = await query(`DELETE FROM ${from(table)} WHERE ${where(table, subjectColumn)} RETURNING 1 AS one`, [subjectId]);
427
492
  return rows.length;
@@ -0,0 +1,88 @@
1
+ // src/stats.ts
2
+ function isStatsStore(store) {
3
+ const s = store;
4
+ return typeof s.consentStats === "function" && typeof s.taskCounts === "function";
5
+ }
6
+ var CONSENT_ACTIONS = /* @__PURE__ */ new Set(["grant", "withdraw"]);
7
+ function statsFromEvents(all, from, to) {
8
+ const stats = { from, to, events: 0, people: 0, byAction: {}, byPurpose: {}, grantedNow: {}, objectedNow: {} };
9
+ for (const events of all) {
10
+ let counted = false;
11
+ const latest = /* @__PURE__ */ new Map();
12
+ for (const e of events) {
13
+ if (e.at >= from && e.at < to) {
14
+ stats.events++;
15
+ if (!counted) stats.people++;
16
+ counted = true;
17
+ stats.byAction[e.action] = (stats.byAction[e.action] ?? 0) + 1;
18
+ for (const p of e.purposes) {
19
+ const row = stats.byPurpose[p] ??= {};
20
+ row[e.action] = (row[e.action] ?? 0) + 1;
21
+ }
22
+ }
23
+ for (const p of e.purposes) latest.set(`${CONSENT_ACTIONS.has(e.action) ? "c" : "o"}:${p}`, e.action);
24
+ }
25
+ for (const [key, action] of latest) {
26
+ const p = key.slice(2);
27
+ if (action === "grant") stats.grantedNow[p] = (stats.grantedNow[p] ?? 0) + 1;
28
+ if (action === "object") stats.objectedNow[p] = (stats.objectedNow[p] ?? 0) + 1;
29
+ }
30
+ }
31
+ return stats;
32
+ }
33
+ var PERIOD_SQL = `SELECT action, p AS purpose, count(*) AS n
34
+ FROM dpdp_consent_events, jsonb_array_elements_text(purposes) AS p
35
+ WHERE at >= $1::timestamptz AND at < $2::timestamptz GROUP BY action, p`;
36
+ var TOTALS_SQL = `SELECT count(*) AS events, count(DISTINCT subject_id) AS people
37
+ FROM dpdp_consent_events WHERE at >= $1::timestamptz AND at < $2::timestamptz`;
38
+ var ACTIONS_SQL = `SELECT action, count(*) AS n
39
+ FROM dpdp_consent_events WHERE at >= $1::timestamptz AND at < $2::timestamptz GROUP BY action`;
40
+ var NOW_SQL = `SELECT kind, p AS purpose, count(*) AS n FROM (
41
+ SELECT DISTINCT ON (subject_id, p, kind) action, p, kind
42
+ FROM (SELECT subject_id, seq, action, p, CASE WHEN action IN ('grant', 'withdraw') THEN 'consent' ELSE 'objection' END AS kind
43
+ FROM dpdp_consent_events, jsonb_array_elements_text(purposes) AS p) e
44
+ ORDER BY subject_id, p, kind, seq DESC
45
+ ) latest WHERE action IN ('grant', 'object') GROUP BY kind, p`;
46
+ var TASKS_SQL = `SELECT status, count(*) AS n, count(*) FILTER (WHERE status IN ('pending', 'failed') AND due_at < $1::timestamptz) AS late
47
+ FROM dpdp_erasure_tasks GROUP BY status`;
48
+ function statsFromRows(from, to, totals, actions, period, now) {
49
+ const stats = {
50
+ from,
51
+ to,
52
+ events: Number(totals?.events ?? 0),
53
+ people: Number(totals?.people ?? 0),
54
+ byAction: {},
55
+ byPurpose: {},
56
+ grantedNow: {},
57
+ objectedNow: {}
58
+ };
59
+ for (const r of actions) stats.byAction[String(r.action)] = Number(r.n);
60
+ for (const r of period) {
61
+ const action = String(r.action);
62
+ const n = Number(r.n);
63
+ const row = stats.byPurpose[String(r.purpose)] ??= {};
64
+ row[action] = (row[action] ?? 0) + n;
65
+ }
66
+ for (const r of now) (r.kind === "consent" ? stats.grantedNow : stats.objectedNow)[String(r.purpose)] = Number(r.n);
67
+ return stats;
68
+ }
69
+ function taskCountsFromRows(rows) {
70
+ const counts = { byStatus: {}, late: 0 };
71
+ for (const r of rows) {
72
+ counts.byStatus[String(r.status)] = Number(r.n);
73
+ counts.late += Number(r.late ?? 0);
74
+ }
75
+ return counts;
76
+ }
77
+
78
+ export {
79
+ isStatsStore,
80
+ statsFromEvents,
81
+ PERIOD_SQL,
82
+ TOTALS_SQL,
83
+ ACTIONS_SQL,
84
+ NOW_SQL,
85
+ TASKS_SQL,
86
+ statsFromRows,
87
+ taskCountsFromRows
88
+ };
@@ -0,0 +1,16 @@
1
+ // src/records.ts
2
+ var REQUEST_TYPES = ["access", "correction", "erasure", "grievance", "nomination"];
3
+ var isVerified = (request) => request.history.some((e) => e.event === "verified");
4
+ function isRunnable(task, { now, staleBefore, maxAttempts }) {
5
+ if (task.dueAt > now) return false;
6
+ if (task.status === "pending") return true;
7
+ if (task.status === "failed") return task.attempts < maxAttempts;
8
+ if (task.status === "running") return (task.claimedAt ?? "") < staleBefore;
9
+ return false;
10
+ }
11
+
12
+ export {
13
+ REQUEST_TYPES,
14
+ isVerified,
15
+ isRunnable
16
+ };
@@ -2,7 +2,7 @@
2
2
  var CONSENT_EVENTS_DDL = `CREATE TABLE IF NOT EXISTS dpdp_consent_events (
3
3
  subject_id text NOT NULL,
4
4
  seq integer NOT NULL,
5
- action text NOT NULL CHECK (action IN ('grant', 'withdraw')),
5
+ action text NOT NULL CONSTRAINT dpdp_consent_events_action_check CHECK (action IN ('grant', 'withdraw', 'object', 'lift-objection')),
6
6
  purposes jsonb NOT NULL,
7
7
  notice_version text,
8
8
  language text,
@@ -80,15 +80,30 @@ CREATE TABLE IF NOT EXISTS dpdp_breach_notices (
80
80
  PRIMARY KEY (breach_id, subject_id)
81
81
  );
82
82
  CREATE INDEX IF NOT EXISTS dpdp_breach_notices_status_idx ON dpdp_breach_notices (breach_id, status, added_at);`;
83
+ var PRIVACY_NOTICES_DDL = `CREATE TABLE IF NOT EXISTS dpdp_privacy_notices (
84
+ version text NOT NULL,
85
+ language text NOT NULL,
86
+ kind text NOT NULL,
87
+ content jsonb NOT NULL,
88
+ first_shown_at timestamptz NOT NULL,
89
+ PRIMARY KEY (version, language, kind)
90
+ );`;
83
91
  var DPDP_DDL = `${CONSENT_EVENTS_DDL}
84
92
  ${RECORDS_DDL}
85
93
  ${ACCESS_LOG_DDL}
86
- ${BREACH_DDL}`;
94
+ ${BREACH_DDL}
95
+ ${PRIVACY_NOTICES_DDL}`;
96
+ var MIGRATE_0_5_DDL = `ALTER TABLE dpdp_consent_events DROP CONSTRAINT IF EXISTS dpdp_consent_events_action_check;
97
+ ALTER TABLE dpdp_consent_events ADD CONSTRAINT dpdp_consent_events_action_check CHECK (action IN ('grant', 'withdraw', 'object', 'lift-objection')) NOT VALID;
98
+ ALTER TABLE dpdp_consent_events VALIDATE CONSTRAINT dpdp_consent_events_action_check;
99
+ ${PRIVACY_NOTICES_DDL}`;
87
100
 
88
101
  export {
89
102
  CONSENT_EVENTS_DDL,
90
103
  RECORDS_DDL,
91
104
  ACCESS_LOG_DDL,
92
105
  BREACH_DDL,
93
- DPDP_DDL
106
+ PRIVACY_NOTICES_DDL,
107
+ DPDP_DDL,
108
+ MIGRATE_0_5_DDL
94
109
  };
package/dist/cli.js CHANGED
@@ -2,13 +2,17 @@
2
2
  import {
3
3
  audit,
4
4
  checkSchema,
5
+ formatEvidence,
5
6
  formatSafeguards,
6
- safeguardsReport
7
- } from "./chunk-HXVP446N.js";
7
+ safeguardsReport,
8
+ staticEvidence
9
+ } from "./chunk-FEGA6SOM.js";
10
+ import "./chunk-M2PDT6DD.js";
11
+ import "./chunk-NBVJQDDP.js";
8
12
  import "./chunk-67Q5GFD6.js";
9
13
 
10
14
  // src/run-audit.ts
11
- import { existsSync, readdirSync, readFileSync, statSync } from "fs";
15
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "fs";
12
16
  import { join, relative, resolve } from "path";
13
17
  import { pathToFileURL } from "url";
14
18
  var CONFIG_FILES = ["dpdp.config.ts", "dpdp.config.mts", "dpdp.config.js", "dpdp.config.mjs"];
@@ -112,9 +116,24 @@ async function runAudit(argv, cwd, log) {
112
116
  log(formatGithubAnnotations(issues, { config: file, schema: schemaFile }, process.env.GITHUB_WORKSPACE ?? cwd));
113
117
  }
114
118
  log(formatIssues(issues));
115
- const failing = issues.filter((i) => i.level === "error" || strict && i.level === "warning");
119
+ const minor = currentMinor();
120
+ const isNew = (i) => i.level === "warning" && i.since !== void 0 && compareMinor(i.since, minor) >= 0;
121
+ const grace = issues.filter(isNew);
122
+ if (strict && grace.length > 0) {
123
+ log(`${grace.length} warning(s) are from checks new in this version: they don't fail --strict until the next minor version.`);
124
+ }
125
+ const failing = issues.filter((i) => i.level === "error" || strict && i.level === "warning" && !isNew(i));
116
126
  return failing.length > 0 ? 1 : 0;
117
127
  }
128
+ function currentMinor() {
129
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
130
+ return version.split(".").slice(0, 2).join(".");
131
+ }
132
+ function compareMinor(a, b) {
133
+ const [a0 = 0, a1 = 0] = a.split(".").map(Number);
134
+ const [b0 = 0, b1 = 0] = b.split(".").map(Number);
135
+ return a0 - b0 || a1 - b1;
136
+ }
118
137
  async function runSafeguards(argv, cwd, log) {
119
138
  const file = configFile(argv, cwd, log);
120
139
  if (!file) return 1;
@@ -123,6 +142,24 @@ async function runSafeguards(argv, cwd, log) {
123
142
  const gaps = report.some((s) => s.status === "missing" || s.status === "partly");
124
143
  return argv.includes("--strict") && gaps ? 1 : 0;
125
144
  }
145
+ async function runEvidence(argv, cwd, log) {
146
+ const format = flagValue(argv, "--format") ?? "markdown";
147
+ if (format !== "markdown" && format !== "json") {
148
+ log(`Unknown --format ${JSON.stringify(format)}. Use "markdown" or "json".`);
149
+ return 1;
150
+ }
151
+ const file = configFile(argv, cwd, log);
152
+ if (!file) return 1;
153
+ const report = staticEvidence(await loadConfig(file));
154
+ const text = format === "json" ? `${JSON.stringify(report, null, 2)}
155
+ ` : formatEvidence(report);
156
+ const out = flagValue(argv, "--out");
157
+ if (out) {
158
+ writeFileSync(resolve(cwd, out), text);
159
+ log(`Wrote ${out}. It covers the config only; call dpdp.evidence() in your app for the records too.`);
160
+ } else log(text.trimEnd());
161
+ return report.audit.some((i) => i.level === "error") ? 1 : 0;
162
+ }
126
163
 
127
164
  // src/cli.ts
128
165
  var HELP = `dpdp-kit \u2014 DPDP Act tooling for Node.js
@@ -130,6 +167,7 @@ var HELP = `dpdp-kit \u2014 DPDP Act tooling for Node.js
130
167
  Usage:
131
168
  dpdp-kit audit [--config <file>] [--schema <file>] [--strict] [--format text|github]
132
169
  dpdp-kit safeguards [--config <file>] [--strict]
170
+ dpdp-kit evidence [--config <file>] [--static] [--format markdown|json] [--out <file>]
133
171
 
134
172
  Checks your data map and purposes. With --schema, also compares the data map with your
135
173
  Drizzle, Prisma or Mongoose schema: personal-looking columns missing from the map, map entries that no
@@ -145,9 +183,14 @@ Options:
145
183
 
146
184
  safeguards reports each security safeguard of Rule 6(1), (a) to (g): what your config records
147
185
  and what's missing. With --strict, exits 1 when one is missing.
186
+
187
+ evidence writes the parts of the evidence report that come from the config: purposes, the data
188
+ map, processors and countries, Rule 6 safeguards, Rule 14 information, the audit and what needs
189
+ attention. For consent counts, requests, erasure, the access review and breaches, call
190
+ dpdp.evidence() in your app and pass it to formatEvidence().
148
191
  `;
149
192
  var [command, ...rest] = process.argv.slice(2);
150
- var commands = { audit: runAudit, safeguards: runSafeguards };
193
+ var commands = { audit: runAudit, safeguards: runSafeguards, evidence: runEvidence };
151
194
  var run = command !== void 0 && Object.hasOwn(commands, command) ? commands[command] : void 0;
152
195
  if (run) {
153
196
  run(rest, process.cwd(), (line) => console.log(line)).then(