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/dist/mongodb.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { AccessLogStore } from "./access.js";
2
2
  import type { BreachStore } from "./breach.js";
3
3
  import type { DataAccess } from "./data-access.js";
4
+ import type { NoticeStore } from "./notice.js";
5
+ import type { StatsStore } from "./stats.js";
4
6
  import type { Schema } from "./schema-check.js";
5
7
  import type { DpdpStore } from "./store.js";
6
8
  type Doc = Record<string, any>;
@@ -55,7 +57,7 @@ export declare function isDuplicateKey(err: unknown): boolean;
55
57
  * const store = mongoStore(() => mongoose.connection.db); // Mongoose, before or after connecting
56
58
  * ```
57
59
  */
58
- export declare function mongoStore(source: MongoDbSource): DpdpStore & AccessLogStore & BreachStore;
60
+ export declare function mongoStore(source: MongoDbSource): DpdpStore & AccessLogStore & BreachStore & NoticeStore & StatsStore;
59
61
  /** Builds the driver's ObjectId from a hex string: `mongodb`'s `ObjectId`, or `mongoose.Types.ObjectId`. */
60
62
  export type ObjectIdClass = new (hex: string) => unknown;
61
63
  export interface MongoDataOptions {
package/dist/mongodb.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ DpdpError,
2
3
  SeqConflictError
3
4
  } from "./chunk-67Q5GFD6.js";
4
5
 
@@ -9,7 +10,8 @@ var COLLECTIONS = {
9
10
  tasks: "dpdp_erasure_tasks",
10
11
  access: "dpdp_access_log",
11
12
  breaches: "dpdp_breaches",
12
- notices: "dpdp_breach_notices"
13
+ notices: "dpdp_breach_notices",
14
+ privacyNotices: "dpdp_privacy_notices"
13
15
  };
14
16
  var INDEXES = {
15
17
  // The unique key keeps each person's consent chain from forking (see SeqConflictError).
@@ -28,6 +30,7 @@ var INDEXES = {
28
30
  { key: { actor: 1, at: 1 }, name: "dpdp_actor_at" }
29
31
  ],
30
32
  breaches: [{ key: { status: 1, awareAt: -1 }, name: "dpdp_status_aware" }],
33
+ privacyNotices: [{ key: { firstShownAt: 1, _id: 1 }, name: "dpdp_first_shown" }],
31
34
  notices: [
32
35
  { key: { breachId: 1, subjectId: 1 }, name: "dpdp_breach_subject", unique: true },
33
36
  { key: { breachId: 1, status: 1, addedAt: 1, subjectId: 1 }, name: "dpdp_breach_status" }
@@ -93,7 +96,80 @@ function mongoStore(source) {
93
96
  await ready;
94
97
  return resolveDb(source).collection(COLLECTIONS[name]);
95
98
  };
99
+ const noticeId = (version, language, kind) => `${version}\0${language}\0${kind}`;
100
+ const savedNotice = (d) => ({ notice: d.notice, firstShownAt: toIso(d.firstShownAt) });
96
101
  return {
102
+ async consentStats(from, to) {
103
+ const inPeriod = { at: { $gte: new Date(from), $lt: new Date(to) } };
104
+ const events = await col("events");
105
+ const [[facet], now] = await Promise.all([
106
+ events.aggregate([
107
+ { $match: inPeriod },
108
+ {
109
+ $facet: {
110
+ totals: [{ $group: { _id: null, events: { $sum: 1 } } }],
111
+ people: [{ $group: { _id: "$subjectId" } }, { $count: "n" }],
112
+ actions: [{ $group: { _id: "$action", n: { $sum: 1 } } }],
113
+ period: [{ $unwind: "$purposes" }, { $group: { _id: { action: "$action", purpose: "$purposes" }, n: { $sum: 1 } } }]
114
+ }
115
+ }
116
+ ]).toArray(),
117
+ events.aggregate([
118
+ { $unwind: "$purposes" },
119
+ { $addFields: { kind: { $cond: [{ $in: ["$action", ["grant", "withdraw"]] }, "consent", "objection"] } } },
120
+ { $sort: { subjectId: 1, seq: -1 } },
121
+ { $group: { _id: { s: "$subjectId", p: "$purposes", k: "$kind" }, action: { $first: "$action" } } },
122
+ { $match: { action: { $in: ["grant", "object"] } } },
123
+ { $group: { _id: { purpose: "$_id.p", kind: "$_id.k" }, n: { $sum: 1 } } }
124
+ ]).toArray()
125
+ ]);
126
+ const stats = {
127
+ from,
128
+ to,
129
+ events: facet?.totals[0]?.events ?? 0,
130
+ people: facet?.people[0]?.n ?? 0,
131
+ byAction: Object.fromEntries((facet?.actions ?? []).map((r) => [r._id, r.n])),
132
+ byPurpose: {},
133
+ grantedNow: {},
134
+ objectedNow: {}
135
+ };
136
+ for (const r of facet?.period ?? []) (stats.byPurpose[r._id.purpose] ??= {})[r._id.action] = r.n;
137
+ for (const r of now) (r._id.kind === "consent" ? stats.grantedNow : stats.objectedNow)[r._id.purpose] = r.n;
138
+ return stats;
139
+ },
140
+ async taskCounts(now) {
141
+ const rows = await (await col("tasks")).aggregate([
142
+ {
143
+ $group: {
144
+ _id: "$status",
145
+ n: { $sum: 1 },
146
+ late: { $sum: { $cond: [{ $and: [{ $in: ["$status", ["pending", "failed"]] }, { $lt: ["$dueAt", new Date(now)] }] }, 1, 0] } }
147
+ }
148
+ }
149
+ ]).toArray();
150
+ const counts = { byStatus: {}, late: 0 };
151
+ for (const r of rows) {
152
+ counts.byStatus[r._id] = r.n;
153
+ counts.late += r.late;
154
+ }
155
+ return counts;
156
+ },
157
+ async savePrivacyNotice(n, at) {
158
+ try {
159
+ await (await col("privacyNotices")).insertOne({ _id: noticeId(n.version, n.language, n.kind), notice: n, firstShownAt: new Date(at) });
160
+ return true;
161
+ } catch (err) {
162
+ if (isDuplicateKey(err)) return false;
163
+ throw err;
164
+ }
165
+ },
166
+ async getPrivacyNotice(version, language, kind) {
167
+ const doc = await (await col("privacyNotices")).findOne({ _id: noticeId(version, language, kind) });
168
+ return doc ? savedNotice(doc) : void 0;
169
+ },
170
+ async listPrivacyNotices() {
171
+ return (await (await col("privacyNotices")).find({}, { sort: { firstShownAt: 1, _id: 1 } }).toArray()).map(savedNotice);
172
+ },
97
173
  async lastEvent(subjectId) {
98
174
  const [doc] = await (await col("events")).find({ subjectId }, { sort: { seq: -1 }, limit: 1 }).toArray();
99
175
  return doc ? fromDoc(doc, EVENT_DATES, void 0, ["prevHash"]) : void 0;
@@ -293,6 +369,28 @@ function mongoData(source, options = {}) {
293
369
  const result = await collection(table).updateMany(filter(table, subjectColumn, subjectId), clean({ $set: Object.keys($set).length ? $set : void 0, $unset: Object.keys($unset).length ? $unset : void 0 }));
294
370
  return result.matchedCount;
295
371
  },
372
+ async updateFields(table, subjectColumn, subjectId, changes, only = {}) {
373
+ const $set = {};
374
+ for (const [c, v] of Object.entries(changes)) {
375
+ const path = field(table, c);
376
+ if (writePath(table, path) !== path) {
377
+ throw new DpdpError("not-correctable", `${table}.${c} is inside an array: correct it in your own code, where you know which element is meant`);
378
+ }
379
+ $set[path] = v ?? null;
380
+ }
381
+ if (Object.keys($set).length === 0) return 0;
382
+ const narrow = {};
383
+ for (const [c, v] of Object.entries(only)) {
384
+ const stored = field(table, c);
385
+ narrow[stored] = typeof v === "string" ? { $in: values(v, table, stored) } : v;
386
+ }
387
+ const result = await collection(table).updateMany(
388
+ { ...narrow, ...filter(table, subjectColumn, subjectId) },
389
+ // the person's filter last: nothing in where replaces it
390
+ { $set }
391
+ );
392
+ return result.matchedCount;
393
+ },
296
394
  async deleteRows(table, subjectColumn, subjectId) {
297
395
  return (await collection(table).deleteMany(filter(table, subjectColumn, subjectId))).deletedCount;
298
396
  }
package/dist/nestjs.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  checkConsent,
3
3
  recordAccess
4
- } from "./chunk-5TVA2TKG.js";
4
+ } from "./chunk-3DOVLBUB.js";
5
5
  import {
6
6
  DpdpError
7
7
  } from "./chunk-67Q5GFD6.js";
package/dist/next.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { Dpdp } from "./dpdp.js";
2
+ import { type ApiOptions } from "./http.js";
3
+ export type { ApiOptions } from "./http.js";
4
+ /**
5
+ * Route handlers for `app/api/privacy/[...path]/route.ts`:
6
+ *
7
+ * ```ts
8
+ * import { createHandlers } from "dpdp-kit/next";
9
+ * export const { GET, POST, DELETE } = createHandlers(dpdp, {
10
+ * base: "/api/privacy",
11
+ * subject: async () => (await auth())?.user?.id,
12
+ * });
13
+ * ```
14
+ *
15
+ * `subject` and `admin` get the Web `Request`. Pass `ip` to record the client address with
16
+ * consent; behind a proxy, read it from the header your proxy sets.
17
+ */
18
+ export declare function createHandlers<P extends string>(dpdp: Dpdp<P>, options: ApiOptions<Request> & {
19
+ base: string;
20
+ ip?: (req: Request) => string | undefined;
21
+ }): {
22
+ GET: (req: Request) => Promise<Response>;
23
+ POST: (req: Request) => Promise<Response>;
24
+ DELETE: (req: Request) => Promise<Response>;
25
+ };
package/dist/next.js ADDED
@@ -0,0 +1,14 @@
1
+ import {
2
+ handleWeb
3
+ } from "./chunk-HGN6TO6R.js";
4
+ import "./chunk-NBVJQDDP.js";
5
+ import "./chunk-67Q5GFD6.js";
6
+
7
+ // src/next.ts
8
+ function createHandlers(dpdp, options) {
9
+ const handler = (req) => handleWeb(dpdp, req, req, options);
10
+ return { GET: handler, POST: handler, DELETE: handler };
11
+ }
12
+ export {
13
+ createHandlers
14
+ };
@@ -0,0 +1,139 @@
1
+ import type { DpdpConfig } from "./config.js";
2
+ import { type NoticeLanguage } from "./languages.js";
3
+ /**
4
+ * - `"consent"`: shown with, or before, a request for consent (Section 5(1)).
5
+ * - `"existing-users"`: for people who consented before the Act came into force (Section 5(2)).
6
+ */
7
+ export type NoticeKind = "consent" | "existing-users";
8
+ export declare const NOTICE_KINDS: readonly NoticeKind[];
9
+ /**
10
+ * Where people can act on the notice. Rule 3(c) requires the link to your website or app, and a
11
+ * description of the other means to withdraw consent, exercise rights and complain to the Board.
12
+ * Each value is a URL or a short description, e.g. `"https://chai.example/privacy"` or
13
+ * `"Settings → Privacy in the app"`.
14
+ */
15
+ export interface NoticeLinks {
16
+ /** Your website or app (Rule 3(c)). */
17
+ website: string;
18
+ /** Where to withdraw consent, as easily as it was given (Rule 3(c)(i), Section 6(4)). */
19
+ withdraw: string;
20
+ /** Where to exercise rights: access, correction, erasure, nomination, grievances (Rule 3(c)(ii)). */
21
+ rights: string;
22
+ /**
23
+ * How to complain to the Data Protection Board (Rule 3(c)(iii)). Optional: without it the
24
+ * notice says people can complain to the Board once they've raised a grievance with you.
25
+ */
26
+ complaint?: string;
27
+ }
28
+ /**
29
+ * The fixed sentences of a notice, with placeholders: `{fiduciary}`, `{withdraw}`, `{rights}`,
30
+ * `{contact}`, `{complaint}`, `{website}`. dpdp-kit ships English; supply the rest per language.
31
+ */
32
+ export interface NoticeWording {
33
+ /** e.g. "Privacy notice: {fiduciary}" */
34
+ title: string;
35
+ /** Opening for a consent request. */
36
+ introConsent: string;
37
+ /** Opening for people who consented before the Act came into force. */
38
+ introExisting: string;
39
+ /** Introduces the list of data for each purpose, e.g. "Data used:". */
40
+ data: string;
41
+ /** Must contain `{withdraw}`. */
42
+ withdraw: string;
43
+ /** Must contain `{rights}`. */
44
+ rights: string;
45
+ /** Must contain `{contact}`. Left out when there is no `fiduciary.dpo`. */
46
+ contact: string;
47
+ /** Used when there is no `links.complaint`. */
48
+ complaint: string;
49
+ /** Used with `links.complaint`; must contain `{complaint}`. */
50
+ complaintWithLink: string;
51
+ /** Must contain `{website}`. */
52
+ website: string;
53
+ }
54
+ export declare const ENGLISH_WORDING: NoticeWording;
55
+ /** Placeholders each wording must keep, so the notice still has what Rule 3(c) requires. */
56
+ export declare const REQUIRED_PLACEHOLDERS: Partial<Record<keyof NoticeWording, string>>;
57
+ /** One language's text, supplied by you. dpdp-kit doesn't translate. */
58
+ export interface NoticeTranslation<P extends string = string> {
59
+ /** Your name as written in this language. Default `fiduciary.name`. */
60
+ fiduciary?: string;
61
+ /** Each consent purpose's description. */
62
+ purposes: Partial<Record<P, string>>;
63
+ /** Each field's label, keyed `"<data key>.<field>"`, e.g. `"users.phone"`. */
64
+ fields: Record<string, string>;
65
+ wording: NoticeWording;
66
+ /** Pages in this language, if you have them. Default `notice.links`. */
67
+ links?: Partial<NoticeLinks>;
68
+ }
69
+ export interface NoticeConfig<P extends string = string> {
70
+ links: NoticeLinks;
71
+ /**
72
+ * Notices in other languages than English (Section 5(3)), keyed by language code
73
+ * (`"hi"`, `"ta"`…). The audit checks each one is complete.
74
+ */
75
+ translations?: Partial<Record<NoticeLanguage, NoticeTranslation<P>>>;
76
+ /**
77
+ * Your own version label, e.g. `"2026-11"`. By default each notice's version is a hash of its
78
+ * content, so it changes exactly when the text does. With your own label, change it whenever you
79
+ * change the notice: granting consent fails with `notice-version-conflict` if a different
80
+ * notice was already saved under the same label.
81
+ */
82
+ version?: string;
83
+ }
84
+ export interface NoticeItem {
85
+ purpose: string;
86
+ /** The specified purpose, and what it provides (Rule 3(b)(ii)). */
87
+ description: string;
88
+ /** The itemised personal data (Rule 3(b)(i)): one entry per label, with the fields behind it. */
89
+ data: Array<{
90
+ label: string;
91
+ category: string;
92
+ fields: string[];
93
+ }>;
94
+ }
95
+ /** A notice as shown to people, and as saved as proof. */
96
+ export interface PrivacyNotice {
97
+ version: string;
98
+ language: NoticeLanguage;
99
+ kind: NoticeKind;
100
+ fiduciary: string;
101
+ items: NoticeItem[];
102
+ links: NoticeLinks;
103
+ contact?: string;
104
+ /** The whole notice as plain text, ready to show or send. */
105
+ text: string;
106
+ }
107
+ export interface SavedNotice {
108
+ notice: PrivacyNotice;
109
+ /** When it was first shown (saved). */
110
+ firstShownAt: string;
111
+ }
112
+ /**
113
+ * Where notice snapshots are kept. The built-in stores are all one (table or collection
114
+ * `dpdp_privacy_notices`).
115
+ */
116
+ export interface NoticeStore {
117
+ /** Save a notice unless one with the same version, language and kind exists. True when saved. */
118
+ savePrivacyNotice(notice: PrivacyNotice, at: string): Promise<boolean>;
119
+ getPrivacyNotice(version: string, language: NoticeLanguage, kind: NoticeKind): Promise<SavedNotice | undefined>;
120
+ /** Every saved notice, oldest first. */
121
+ listPrivacyNotices(): Promise<SavedNotice[]>;
122
+ }
123
+ export declare function isNoticeStore(store: object): store is NoticeStore;
124
+ /** Languages a config has a notice in: English, then each translation. */
125
+ export declare function noticeLanguages(config: DpdpConfig<string>): NoticeLanguage[];
126
+ /** `"phoneNumber"` and `"phone_number"` → `"Phone number"`. Fields should set `label`; this is the fallback. */
127
+ export declare function humanise(name: string): string;
128
+ /**
129
+ * Build the notice for a language. Items are the consent purposes, in config order, each with the
130
+ * data held for it. Pure: the same config always gives the same notice and version.
131
+ */
132
+ export declare function buildNotice(config: DpdpConfig<string>, options?: {
133
+ language?: NoticeLanguage;
134
+ kind?: NoticeKind;
135
+ }): PrivacyNotice;
136
+ /** Twelve hex characters of a SHA-256 over the notice's content (everything but the version). */
137
+ export declare function noticeHash(content: Omit<PrivacyNotice, "version">): string;
138
+ /** Whether two notices say exactly the same thing. */
139
+ export declare const sameNotice: (a: PrivacyNotice, b: PrivacyNotice) => boolean;
@@ -1,9 +1,11 @@
1
1
  import type { AccessLogStore } from "./access.js";
2
2
  import type { BreachStore } from "./breach.js";
3
- import type { DataAccess } from "./data-access.js";
3
+ import { type DataAccess } from "./data-access.js";
4
+ import type { NoticeStore } from "./notice.js";
5
+ import { type StatsStore } from "./stats.js";
4
6
  import type { Schema } from "./schema-check.js";
5
7
  import type { DpdpStore } from "./store.js";
6
- export { ACCESS_LOG_DDL, BREACH_DDL, CONSENT_EVENTS_DDL, DPDP_DDL, RECORDS_DDL } from "./ddl.js";
8
+ export { ACCESS_LOG_DDL, BREACH_DDL, CONSENT_EVENTS_DDL, DPDP_DDL, MIGRATE_0_5_DDL, PRIVACY_NOTICES_DDL, RECORDS_DDL } from "./ddl.js";
7
9
  /**
8
10
  * Runs one parameterised SQL statement (`$1`, `$2`… placeholders) and resolves with its rows.
9
11
  *
@@ -27,7 +29,7 @@ export declare function isUniqueViolation(err: unknown): boolean;
27
29
  * const store = postgresStore(async (text, params) => (await pool.query(text, [...params])).rows);
28
30
  * ```
29
31
  */
30
- export declare function postgresStore(query: SqlQuery): DpdpStore & AccessLogStore & BreachStore;
32
+ export declare function postgresStore(query: SqlQuery): DpdpStore & AccessLogStore & BreachStore & NoticeStore & StatsStore;
31
33
  /**
32
34
  * The type to cast a parameter to for a column. Length limits are dropped, because a cast to
33
35
  * `varchar(3)` cuts the value short and would match the wrong rows; serials are plain integers.
package/dist/postgres.js CHANGED
@@ -4,20 +4,26 @@ import {
4
4
  isUniqueViolation,
5
5
  postgresData,
6
6
  postgresStore
7
- } from "./chunk-KLMR7S7I.js";
7
+ } from "./chunk-LVT4OKBC.js";
8
8
  import {
9
9
  ACCESS_LOG_DDL,
10
10
  BREACH_DDL,
11
11
  CONSENT_EVENTS_DDL,
12
12
  DPDP_DDL,
13
+ MIGRATE_0_5_DDL,
14
+ PRIVACY_NOTICES_DDL,
13
15
  RECORDS_DDL
14
- } from "./chunk-2ELTZSW3.js";
16
+ } from "./chunk-VWGKAQCM.js";
17
+ import "./chunk-EMNABUCL.js";
18
+ import "./chunk-M2PDT6DD.js";
15
19
  import "./chunk-67Q5GFD6.js";
16
20
  export {
17
21
  ACCESS_LOG_DDL,
18
22
  BREACH_DDL,
19
23
  CONSENT_EVENTS_DDL,
20
24
  DPDP_DDL,
25
+ MIGRATE_0_5_DDL,
26
+ PRIVACY_NOTICES_DDL,
21
27
  RECORDS_DDL,
22
28
  castType,
23
29
  ident,
package/dist/prisma.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { AccessLogStore } from "./access.js";
2
2
  import type { BreachStore } from "./breach.js";
3
+ import type { NoticeStore } from "./notice.js";
4
+ import type { StatsStore } from "./stats.js";
3
5
  import type { DataAccess } from "./data-access.js";
4
6
  import { type SqlQuery } from "./postgres.js";
5
7
  import type { Schema } from "./schema-check.js";
@@ -19,7 +21,7 @@ export declare const prismaQuery: (prisma: PrismaLike) => SqlQuery;
19
21
  * const dpdp = createDpdp({ config, store: prismaStore(prisma), data: prismaData(prisma, { schema }) });
20
22
  * ```
21
23
  */
22
- export declare function prismaStore(prisma: PrismaLike): DpdpStore & AccessLogStore & BreachStore;
24
+ export declare function prismaStore(prisma: PrismaLike): DpdpStore & AccessLogStore & BreachStore & NoticeStore & StatsStore;
23
25
  /**
24
26
  * Data access for your own tables through Prisma, for access summaries and erasure. Pass the
25
27
  * schema (`prismaSchema(text)`) so the data map can use model and field names (`User`,
@@ -40,4 +42,4 @@ export declare function prismaSchema(text: string): Schema;
40
42
  * `prisma/schema/dpdp.prisma` with a multi-file schema) and run `prisma migrate dev`. They match
41
43
  * `DPDP_DDL` from `dpdp-kit/drizzle`, so either can create the tables.
42
44
  */
43
- export declare const PRISMA_MODELS = "/// dpdp-kit: consent events, a hash chain per person (Section 6).\nmodel DpdpConsentEvent {\n subjectId String @map(\"subject_id\")\n seq Int\n action String\n purposes Json\n noticeVersion String? @map(\"notice_version\")\n language String?\n channel String?\n evidence Json?\n at DateTime @db.Timestamptz(6)\n prevHash String? @map(\"prev_hash\")\n hash String\n\n @@id([subjectId, seq])\n @@map(\"dpdp_consent_events\")\n}\n\n/// dpdp-kit: rights requests and grievances (Sections 11 to 14).\nmodel DpdpRequest {\n id String @id\n subjectId String @map(\"subject_id\")\n type String\n status String\n openedAt DateTime @map(\"opened_at\") @db.Timestamptz(6)\n dueAt DateTime @map(\"due_at\") @db.Timestamptz(6)\n closedAt DateTime? @map(\"closed_at\") @db.Timestamptz(6)\n details Json?\n history Json\n\n @@index([subjectId], map: \"dpdp_requests_subject_idx\")\n @@index([status, dueAt], map: \"dpdp_requests_status_due_idx\")\n @@map(\"dpdp_requests\")\n}\n\n/// dpdp-kit: erasure and processor tasks (Section 8(7), Rule 8).\nmodel DpdpErasureTask {\n id String @id\n subjectId String @map(\"subject_id\")\n reason String\n kind String\n tableKey String? @map(\"table_key\")\n fields Json?\n processor String?\n purposes Json?\n createdAt DateTime @map(\"created_at\") @db.Timestamptz(6)\n dueAt DateTime @map(\"due_at\") @db.Timestamptz(6)\n status String\n attempts Int\n claimedAt DateTime? @map(\"claimed_at\") @db.Timestamptz(6)\n doneAt DateTime? @map(\"done_at\") @db.Timestamptz(6)\n affected Int?\n lastError String? @map(\"last_error\")\n note String?\n\n @@index([subjectId], map: \"dpdp_erasure_tasks_subject_idx\")\n @@index([status, dueAt], map: \"dpdp_erasure_tasks_status_due_idx\")\n @@map(\"dpdp_erasure_tasks\")\n}\n\n/// dpdp-kit: who accessed whose data, and why (Rule 6(1)(c), (e)).\nmodel DpdpAccessLog {\n id String @id\n at DateTime @db.Timestamptz(6)\n actor String\n subjectId String @map(\"subject_id\")\n action String\n purpose String\n fields Json?\n outOfPurpose Json? @map(\"out_of_purpose\")\n reason String?\n evidence Json?\n\n @@index([at], map: \"dpdp_access_log_at_idx\")\n @@index([subjectId, at], map: \"dpdp_access_log_subject_idx\")\n @@index([actor, at], map: \"dpdp_access_log_actor_idx\")\n @@map(\"dpdp_access_log\")\n}\n\n/// dpdp-kit: personal data breaches (Section 8(6), Rule 7).\nmodel DpdpBreach {\n id String @id\n status String\n awareAt DateTime @map(\"aware_at\") @db.Timestamptz(6)\n reportDueAt DateTime @map(\"report_due_at\") @db.Timestamptz(6)\n data Json\n\n @@index([status, awareAt], map: \"dpdp_breaches_status_idx\")\n @@map(\"dpdp_breaches\")\n}\n\n/// dpdp-kit: each person affected by a breach, and whether they've been told (Rule 7(1)).\nmodel DpdpBreachNotice {\n breachId String @map(\"breach_id\")\n subjectId String @map(\"subject_id\")\n status String\n addedAt DateTime @map(\"added_at\") @db.Timestamptz(6)\n sentAt DateTime? @map(\"sent_at\") @db.Timestamptz(6)\n channel String?\n\n @@id([breachId, subjectId])\n @@index([breachId, status, addedAt], map: \"dpdp_breach_notices_status_idx\")\n @@map(\"dpdp_breach_notices\")\n}\n";
45
+ export declare const PRISMA_MODELS = "/// dpdp-kit: consent events, a hash chain per person (Section 6).\nmodel DpdpConsentEvent {\n subjectId String @map(\"subject_id\")\n seq Int\n action String\n purposes Json\n noticeVersion String? @map(\"notice_version\")\n language String?\n channel String?\n evidence Json?\n at DateTime @db.Timestamptz(6)\n prevHash String? @map(\"prev_hash\")\n hash String\n\n @@id([subjectId, seq])\n @@map(\"dpdp_consent_events\")\n}\n\n/// dpdp-kit: rights requests and grievances (Sections 11 to 14).\nmodel DpdpRequest {\n id String @id\n subjectId String @map(\"subject_id\")\n type String\n status String\n openedAt DateTime @map(\"opened_at\") @db.Timestamptz(6)\n dueAt DateTime @map(\"due_at\") @db.Timestamptz(6)\n closedAt DateTime? @map(\"closed_at\") @db.Timestamptz(6)\n details Json?\n history Json\n\n @@index([subjectId], map: \"dpdp_requests_subject_idx\")\n @@index([status, dueAt], map: \"dpdp_requests_status_due_idx\")\n @@map(\"dpdp_requests\")\n}\n\n/// dpdp-kit: erasure and processor tasks (Section 8(7), Rule 8).\nmodel DpdpErasureTask {\n id String @id\n subjectId String @map(\"subject_id\")\n reason String\n kind String\n tableKey String? @map(\"table_key\")\n fields Json?\n processor String?\n purposes Json?\n createdAt DateTime @map(\"created_at\") @db.Timestamptz(6)\n dueAt DateTime @map(\"due_at\") @db.Timestamptz(6)\n status String\n attempts Int\n claimedAt DateTime? @map(\"claimed_at\") @db.Timestamptz(6)\n doneAt DateTime? @map(\"done_at\") @db.Timestamptz(6)\n affected Int?\n lastError String? @map(\"last_error\")\n note String?\n\n @@index([subjectId], map: \"dpdp_erasure_tasks_subject_idx\")\n @@index([status, dueAt], map: \"dpdp_erasure_tasks_status_due_idx\")\n @@map(\"dpdp_erasure_tasks\")\n}\n\n/// dpdp-kit: who accessed whose data, and why (Rule 6(1)(c), (e)).\nmodel DpdpAccessLog {\n id String @id\n at DateTime @db.Timestamptz(6)\n actor String\n subjectId String @map(\"subject_id\")\n action String\n purpose String\n fields Json?\n outOfPurpose Json? @map(\"out_of_purpose\")\n reason String?\n evidence Json?\n\n @@index([at], map: \"dpdp_access_log_at_idx\")\n @@index([subjectId, at], map: \"dpdp_access_log_subject_idx\")\n @@index([actor, at], map: \"dpdp_access_log_actor_idx\")\n @@map(\"dpdp_access_log\")\n}\n\n/// dpdp-kit: personal data breaches (Section 8(6), Rule 7).\nmodel DpdpBreach {\n id String @id\n status String\n awareAt DateTime @map(\"aware_at\") @db.Timestamptz(6)\n reportDueAt DateTime @map(\"report_due_at\") @db.Timestamptz(6)\n data Json\n\n @@index([status, awareAt], map: \"dpdp_breaches_status_idx\")\n @@map(\"dpdp_breaches\")\n}\n\n/// dpdp-kit: privacy notices as shown, kept as proof (Section 6(10)).\nmodel DpdpPrivacyNotice {\n version String\n language String\n kind String\n content Json\n firstShownAt DateTime @map(\"first_shown_at\") @db.Timestamptz(6)\n\n @@id([version, language, kind])\n @@map(\"dpdp_privacy_notices\")\n}\n\n/// dpdp-kit: each person affected by a breach, and whether they've been told (Rule 7(1)).\nmodel DpdpBreachNotice {\n breachId String @map(\"breach_id\")\n subjectId String @map(\"subject_id\")\n status String\n addedAt DateTime @map(\"added_at\") @db.Timestamptz(6)\n sentAt DateTime? @map(\"sent_at\") @db.Timestamptz(6)\n channel String?\n\n @@id([breachId, subjectId])\n @@index([breachId, status, addedAt], map: \"dpdp_breach_notices_status_idx\")\n @@map(\"dpdp_breach_notices\")\n}\n";
package/dist/prisma.js CHANGED
@@ -3,10 +3,12 @@ import {
3
3
  isUniqueViolation,
4
4
  postgresData,
5
5
  postgresStore
6
- } from "./chunk-KLMR7S7I.js";
6
+ } from "./chunk-LVT4OKBC.js";
7
7
  import {
8
8
  DPDP_DDL
9
- } from "./chunk-2ELTZSW3.js";
9
+ } from "./chunk-VWGKAQCM.js";
10
+ import "./chunk-EMNABUCL.js";
11
+ import "./chunk-M2PDT6DD.js";
10
12
  import "./chunk-67Q5GFD6.js";
11
13
 
12
14
  // src/prisma.ts
@@ -255,6 +257,18 @@ model DpdpBreach {
255
257
  @@map("dpdp_breaches")
256
258
  }
257
259
 
260
+ /// dpdp-kit: privacy notices as shown, kept as proof (Section 6(10)).
261
+ model DpdpPrivacyNotice {
262
+ version String
263
+ language String
264
+ kind String
265
+ content Json
266
+ firstShownAt DateTime @map("first_shown_at") @db.Timestamptz(6)
267
+
268
+ @@id([version, language, kind])
269
+ @@map("dpdp_privacy_notices")
270
+ }
271
+
258
272
  /// dpdp-kit: each person affected by a breach, and whether they've been told (Rule 7(1)).
259
273
  model DpdpBreachNotice {
260
274
  breachId String @map("breach_id")
package/dist/records.d.ts CHANGED
@@ -10,6 +10,28 @@ export interface RequestHistoryEntry {
10
10
  at: string;
11
11
  status: RequestStatus;
12
12
  note?: string;
13
+ /** Who did it: a staff user's id, a team, or a service. */
14
+ by?: string;
15
+ /** What happened, for entries that aren't only a status change. */
16
+ event?: "verified" | "corrected" | "revoked";
17
+ /** How the person's identity was checked, for `verified`, e.g. `"OTP to registered mobile"`. */
18
+ method?: string;
19
+ /** Data map keys that were changed, for `corrected`. Never the values. */
20
+ fields?: string[];
21
+ }
22
+ /** Whether someone recorded checking the identity of the person behind a request. */
23
+ export declare const isVerified: (request: RightsRequest) => boolean;
24
+ /** Someone who may exercise the person's rights if they die or can no longer do so (Section 14). */
25
+ export interface Nominee {
26
+ /** The id of the nomination request that recorded them. */
27
+ id: string;
28
+ subjectId: string;
29
+ name: string;
30
+ /** How to reach them, e.g. an email address or phone number. */
31
+ contact: string;
32
+ /** e.g. `"spouse"`, `"daughter"`. */
33
+ relation?: string;
34
+ nominatedAt: string;
13
35
  }
14
36
  /** A rights request or grievance, from the moment it's raised until it's answered. */
15
37
  export interface RightsRequest {
@@ -40,8 +62,9 @@ export type TaskKind = "erase-fields" | "delete-rows" | "processor-stop" | "proc
40
62
  * - `done`: carried out.
41
63
  * - `failed`: the last attempt threw; retried on the next run (up to 5 attempts).
42
64
  * - `manual`: needs a person, e.g. a processor with no `erase` hook. Mark it done when handled.
65
+ * - `cancelled`: no longer needed, e.g. the person lifted the objection that scheduled it.
43
66
  */
44
- export type TaskStatus = "pending" | "running" | "done" | "failed" | "manual";
67
+ export type TaskStatus = "pending" | "running" | "done" | "failed" | "manual" | "cancelled";
45
68
  export interface ErasureTask {
46
69
  id: string;
47
70
  subjectId: string;
package/dist/rights.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { Category, DpdpConfig } from "./config.js";
2
2
  import type { DataAccess } from "./data-access.js";
3
3
  import { type Duration } from "./duration.js";
4
- import type { RequestType } from "./records.js";
4
+ import { type RequestType, type RightsRequest } from "./records.js";
5
5
  /** Default answer time: Rule 14(3) caps grievance responses at ninety days. */
6
6
  export declare const DEFAULT_RESPONSE_WITHIN: Duration;
7
7
  export declare function responseWithin(config: DpdpConfig<string>, type: RequestType): Duration;
@@ -27,8 +27,10 @@ export interface AccessSummary {
27
27
  }>;
28
28
  /** Consent purposes currently granted. */
29
29
  consents: string[];
30
- /** Legitimate-use purposes that apply without consent (Section 7). */
30
+ /** Legitimate-use purposes that apply without consent (Section 7), minus any the person objected to. */
31
31
  legitimateUses: string[];
32
+ /** Section 7(a) purposes the person objected to. Only present when there are any. */
33
+ objections?: string[];
32
34
  /**
33
35
  * Processors that receive data for a purpose that applies to this person (Section 11(1)(b)).
34
36
  * Section 11(2) exempts sharing with authorities for preventing or investigating offences;
@@ -38,6 +40,7 @@ export interface AccessSummary {
38
40
  name: string;
39
41
  description?: string;
40
42
  purposes: string[];
43
+ countries?: string[];
41
44
  }>;
42
45
  }
43
46
  export declare function buildAccessSummary(input: {
@@ -45,5 +48,35 @@ export declare function buildAccessSummary(input: {
45
48
  data: DataAccess;
46
49
  subjectId: string;
47
50
  consents: string[];
51
+ objections?: string[];
48
52
  now: string;
49
53
  }): Promise<AccessSummary>;
54
+ /** What you tell the person when a request arrives. */
55
+ export interface Acknowledgement {
56
+ /** The request id: the person quotes it when following up. */
57
+ reference: string;
58
+ type: RequestType;
59
+ receivedAt: string;
60
+ /** When you'll answer by (`config.rights.responseWithin`). */
61
+ dueAt: string;
62
+ /** Who to ask in the meantime: `fiduciary.dpo`. */
63
+ contact?: string;
64
+ /** The acknowledgement in plain English, ready to send. */
65
+ text: string;
66
+ }
67
+ /** A date as people read it in India, e.g. "19 November 2026". */
68
+ export declare const indianDate: (iso: string) => string;
69
+ export declare function acknowledgement(config: DpdpConfig<string>, request: RightsRequest): Acknowledgement;
70
+ /** What Rule 14(1) and 14(3) ask you to publish about making requests. */
71
+ export interface RightsInfo {
72
+ /** The means of making a request (Rule 14(1)(a)). */
73
+ how?: string;
74
+ /** What identifies the person (Rule 14(1)(b)). */
75
+ identifiers: string[];
76
+ /** How long you take to answer each type (Rule 14(3) for grievances). */
77
+ responseWithin: Record<RequestType, Duration>;
78
+ contact?: string;
79
+ grievanceUrl?: string;
80
+ verify: "required" | "optional";
81
+ }
82
+ export declare function rightsInfo(config: DpdpConfig<string>): RightsInfo;
@@ -26,8 +26,16 @@ export declare function loadPrismaSchema(path: string): Promise<Schema>;
26
26
  export declare function loadSchema(path: string): Promise<Schema>;
27
27
  /** Run `dpdp-kit audit`. Returns the exit code: 1 when there are errors (or `--strict` and warnings). */
28
28
  export declare function runAudit(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
29
+ /** This package's minor version, e.g. `"0.5"`. Warnings with that `since` don't fail `--strict` yet. */
30
+ export declare function currentMinor(): string;
29
31
  /**
30
32
  * Run `dpdp-kit safeguards`: a Rule 6(1) report from the config. Returns 0, or with `--strict` 1
31
33
  * when a safeguard is missing or partly recorded.
32
34
  */
33
35
  export declare function runSafeguards(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
36
+ /**
37
+ * Run `dpdp-kit evidence`: the parts of the evidence report that come from the config (data map,
38
+ * processors, audit, Rule 6 safeguards, Rule 14 information), as Markdown or JSON. The records
39
+ * (consent counts, requests, erasure, access review, breaches) need the app: `dpdp.evidence()`.
40
+ */
41
+ export declare function runEvidence(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
@@ -0,0 +1,41 @@
1
+ import type { TaskStatus } from "./records.js";
2
+ import type { ConsentAction, ConsentEvent } from "./store.js";
3
+ export interface ConsentStats {
4
+ from: string;
5
+ to: string;
6
+ /** Consent events in the period. */
7
+ events: number;
8
+ /** People with at least one event in the period. */
9
+ people: number;
10
+ /** Events in the period by action. */
11
+ byAction: Partial<Record<ConsentAction, number>>;
12
+ /** Events in the period by purpose and action. */
13
+ byPurpose: Record<string, Partial<Record<ConsentAction, number>>>;
14
+ /** Right now: people whose latest choice for each consent purpose is a grant. */
15
+ grantedNow: Record<string, number>;
16
+ /** Right now: people who object to each Section 7(a) purpose. */
17
+ objectedNow: Record<string, number>;
18
+ }
19
+ export interface TaskCounts {
20
+ byStatus: Partial<Record<TaskStatus, number>>;
21
+ /** Pending or failed tasks whose due date has passed: the retention runner is behind. */
22
+ late: number;
23
+ }
24
+ /** A store that can count for the evidence report. The built-in stores all can. */
25
+ export interface StatsStore {
26
+ consentStats(from: string, to: string): Promise<ConsentStats>;
27
+ taskCounts(now: string): Promise<TaskCounts>;
28
+ }
29
+ export declare function isStatsStore(store: object): store is StatsStore;
30
+ /** The same counts from events in memory. */
31
+ export declare function statsFromEvents(all: Iterable<readonly ConsentEvent[]>, from: string, to: string): ConsentStats;
32
+ /** Postgres: events in the period, by action and purpose. $1 from, $2 to. */
33
+ export declare const PERIOD_SQL = "SELECT action, p AS purpose, count(*) AS n\n FROM dpdp_consent_events, jsonb_array_elements_text(purposes) AS p\n WHERE at >= $1::timestamptz AND at < $2::timestamptz GROUP BY action, p";
34
+ export declare const TOTALS_SQL = "SELECT count(*) AS events, count(DISTINCT subject_id) AS people\n FROM dpdp_consent_events WHERE at >= $1::timestamptz AND at < $2::timestamptz";
35
+ export declare const ACTIONS_SQL = "SELECT action, count(*) AS n\n FROM dpdp_consent_events WHERE at >= $1::timestamptz AND at < $2::timestamptz GROUP BY action";
36
+ /** Postgres: each person's latest consent choice and objection per purpose, counted. */
37
+ export declare const NOW_SQL = "SELECT kind, p AS purpose, count(*) AS n FROM (\n SELECT DISTINCT ON (subject_id, p, kind) action, p, kind\n FROM (SELECT subject_id, seq, action, p, CASE WHEN action IN ('grant', 'withdraw') THEN 'consent' ELSE 'objection' END AS kind\n FROM dpdp_consent_events, jsonb_array_elements_text(purposes) AS p) e\n ORDER BY subject_id, p, kind, seq DESC\n ) latest WHERE action IN ('grant', 'object') GROUP BY kind, p";
38
+ export declare const TASKS_SQL = "SELECT status, count(*) AS n, count(*) FILTER (WHERE status IN ('pending', 'failed') AND due_at < $1::timestamptz) AS late\n FROM dpdp_erasure_tasks GROUP BY status";
39
+ /** Turn the rows of the queries above into stats. */
40
+ export declare function statsFromRows(from: string, to: string, totals: Record<string, unknown> | undefined, actions: readonly Record<string, unknown>[], period: readonly Record<string, unknown>[], now: readonly Record<string, unknown>[]): ConsentStats;
41
+ export declare function taskCountsFromRows(rows: readonly Record<string, unknown>[]): TaskCounts;