dpdp-kit 0.2.0 → 0.4.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 (46) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +240 -17
  3. package/dist/access.d.ts +111 -0
  4. package/dist/audit.d.ts +3 -1
  5. package/dist/breach.d.ts +170 -0
  6. package/dist/chunk-2ELTZSW3.js +94 -0
  7. package/dist/chunk-5TVA2TKG.js +37 -0
  8. package/dist/chunk-HXVP446N.js +1051 -0
  9. package/dist/chunk-KLMR7S7I.js +438 -0
  10. package/dist/cli.js +53 -17
  11. package/dist/config.d.ts +69 -0
  12. package/dist/data-access.d.ts +6 -2
  13. package/dist/ddl.d.ts +10 -0
  14. package/dist/dpdp.d.ts +210 -0
  15. package/dist/drizzle.d.ts +403 -11
  16. package/dist/drizzle.js +209 -56
  17. package/dist/errors.d.ts +1 -1
  18. package/dist/express.d.ts +17 -1
  19. package/dist/express.js +10 -2
  20. package/dist/fastify.d.ts +41 -0
  21. package/dist/fastify.js +25 -0
  22. package/dist/guard.d.ts +19 -0
  23. package/dist/hono.d.ts +16 -1
  24. package/dist/hono.js +11 -2
  25. package/dist/index.d.ts +7 -4
  26. package/dist/index.js +420 -100
  27. package/dist/mongodb.d.ts +87 -0
  28. package/dist/mongodb.js +344 -0
  29. package/dist/nestjs.d.ts +65 -0
  30. package/dist/nestjs.js +41 -0
  31. package/dist/postgres.d.ts +45 -0
  32. package/dist/postgres.js +27 -0
  33. package/dist/prisma.d.ts +43 -0
  34. package/dist/prisma.js +281 -0
  35. package/dist/protect.d.ts +74 -0
  36. package/dist/protect.js +114 -0
  37. package/dist/retention.d.ts +1 -1
  38. package/dist/run-audit.d.ts +13 -1
  39. package/dist/safeguards.d.ts +23 -0
  40. package/dist/schedule.d.ts +37 -0
  41. package/dist/schedule.js +66 -0
  42. package/dist/schema-check.d.ts +25 -8
  43. package/dist/store.d.ts +11 -1
  44. package/package.json +58 -5
  45. package/dist/chunk-FGZAH2NF.js +0 -16
  46. package/dist/chunk-KVTUMHXO.js +0 -491
@@ -0,0 +1,87 @@
1
+ import type { AccessLogStore } from "./access.js";
2
+ import type { BreachStore } from "./breach.js";
3
+ import type { DataAccess } from "./data-access.js";
4
+ import type { Schema } from "./schema-check.js";
5
+ import type { DpdpStore } from "./store.js";
6
+ type Doc = Record<string, any>;
7
+ /** The collection methods dpdp-kit uses, as the official driver has them. */
8
+ export interface MongoCollectionLike {
9
+ insertOne(doc: Doc): Promise<unknown>;
10
+ insertMany(docs: Doc[], options?: Doc): Promise<{
11
+ insertedCount: number;
12
+ }>;
13
+ findOne(filter: Doc, options?: Doc): Promise<Doc | null>;
14
+ find(filter: Doc, options?: Doc): {
15
+ toArray(): Promise<Doc[]>;
16
+ };
17
+ replaceOne(filter: Doc, doc: Doc): Promise<{
18
+ matchedCount: number;
19
+ }>;
20
+ updateOne(filter: Doc, update: Doc): Promise<{
21
+ matchedCount: number;
22
+ modifiedCount: number;
23
+ }>;
24
+ updateMany(filter: Doc, update: Doc): Promise<{
25
+ matchedCount: number;
26
+ modifiedCount: number;
27
+ }>;
28
+ deleteMany(filter: Doc): Promise<{
29
+ deletedCount: number;
30
+ }>;
31
+ aggregate(pipeline: Doc[]): {
32
+ toArray(): Promise<Doc[]>;
33
+ };
34
+ createIndexes(indexes: Doc[]): Promise<unknown>;
35
+ }
36
+ /** A MongoDB database: the driver's `Db`, or Mongoose's `mongoose.connection.db`. */
37
+ export interface MongoDbLike {
38
+ collection(name: string): MongoCollectionLike;
39
+ }
40
+ /** A database, or a function returning one, for Mongoose apps that create dpdp before connecting. */
41
+ export type MongoDbSource = MongoDbLike | (() => MongoDbLike | undefined);
42
+ /**
43
+ * Create the indexes dpdp-kit's collections need. The store does this itself before its first
44
+ * write; call it from a migration or deploy script if your app user can't create indexes.
45
+ */
46
+ export declare function createMongoIndexes(source: MongoDbSource): Promise<void>;
47
+ /** Duplicate key errors: code 11000, on the error or in the server's response. */
48
+ export declare function isDuplicateKey(err: unknown): boolean;
49
+ /**
50
+ * Store on MongoDB: consent events, rights requests, erasure tasks, the access log and breaches,
51
+ * in `dpdp_*` collections. Creates its indexes before the first write.
52
+ *
53
+ * ```ts
54
+ * const store = mongoStore(client.db()); // the official driver
55
+ * const store = mongoStore(() => mongoose.connection.db); // Mongoose, before or after connecting
56
+ * ```
57
+ */
58
+ export declare function mongoStore(source: MongoDbSource): DpdpStore & AccessLogStore & BreachStore;
59
+ /** Builds the driver's ObjectId from a hex string: `mongodb`'s `ObjectId`, or `mongoose.Types.ObjectId`. */
60
+ export type ObjectIdClass = new (hex: string) => unknown;
61
+ export interface MongoDataOptions {
62
+ /** From `mongooseSchema()`: lets the data map use model names (`User`) for collections (`users`). */
63
+ schema?: Schema;
64
+ /**
65
+ * Pass `ObjectId` when subjects are found by an ObjectId field (`subject: "_id"`), so a 24-digit
66
+ * hex subject id matches it. Ids that look like numbers also match number fields.
67
+ */
68
+ ObjectId?: ObjectIdClass;
69
+ /** Full control over how a subject id is matched: return the value (or values) to look for. */
70
+ subjectValues?: (subjectId: string, collection: string, field: string) => unknown[];
71
+ }
72
+ /**
73
+ * Data access for your own collections, for access summaries and erasure. Each data map entry's
74
+ * `table` is a collection (or a Mongoose model name, with `schema`), its fields are document
75
+ * fields (`"address.city"` reaches into nested documents), and `subject` is the field holding the
76
+ * person's id. Erasure sets a field to its `erase` replacement, or removes it ($unset).
77
+ */
78
+ export declare function mongoData(source: MongoDbSource, options?: MongoDataOptions): DataAccess;
79
+ /**
80
+ * Read Mongoose models into the neutral shape `dpdp-kit audit --schema` and `mongoData()` use.
81
+ * Pass the Mongoose instance, `mongoose.models`, an array of models, or a module that exports
82
+ * them. Each model becomes a table named after its collection, with the model name as its `key`;
83
+ * each schema path becomes a column, including fields in nested objects and subdocuments
84
+ * (`address.city`, `addresses.phone`), and `_id` has the key `id`. `__v` is skipped.
85
+ */
86
+ export declare function mongooseSchema(source: unknown): Schema;
87
+ export {};
@@ -0,0 +1,344 @@
1
+ import {
2
+ SeqConflictError
3
+ } from "./chunk-67Q5GFD6.js";
4
+
5
+ // src/mongodb.ts
6
+ var COLLECTIONS = {
7
+ events: "dpdp_consent_events",
8
+ requests: "dpdp_requests",
9
+ tasks: "dpdp_erasure_tasks",
10
+ access: "dpdp_access_log",
11
+ breaches: "dpdp_breaches",
12
+ notices: "dpdp_breach_notices"
13
+ };
14
+ var INDEXES = {
15
+ // The unique key keeps each person's consent chain from forking (see SeqConflictError).
16
+ events: [{ key: { subjectId: 1, seq: 1 }, name: "dpdp_subject_seq", unique: true }],
17
+ requests: [
18
+ { key: { subjectId: 1 }, name: "dpdp_subject" },
19
+ { key: { status: 1, dueAt: 1 }, name: "dpdp_status_due" }
20
+ ],
21
+ tasks: [
22
+ { key: { subjectId: 1 }, name: "dpdp_subject" },
23
+ { key: { status: 1, dueAt: 1 }, name: "dpdp_status_due" }
24
+ ],
25
+ access: [
26
+ { key: { at: 1, _id: 1 }, name: "dpdp_at" },
27
+ { key: { subjectId: 1, at: 1 }, name: "dpdp_subject_at" },
28
+ { key: { actor: 1, at: 1 }, name: "dpdp_actor_at" }
29
+ ],
30
+ breaches: [{ key: { status: 1, awareAt: -1 }, name: "dpdp_status_aware" }],
31
+ notices: [
32
+ { key: { breachId: 1, subjectId: 1 }, name: "dpdp_breach_subject", unique: true },
33
+ { key: { breachId: 1, status: 1, addedAt: 1, subjectId: 1 }, name: "dpdp_breach_status" }
34
+ ]
35
+ };
36
+ var resolveDb = (source) => {
37
+ const db = typeof source === "function" ? source() : source;
38
+ if (!db) throw new Error("dpdp-kit/mongodb: the database isn't connected yet (mongoose.connection.db is undefined).");
39
+ return db;
40
+ };
41
+ async function createMongoIndexes(source) {
42
+ const db = resolveDb(source);
43
+ await Promise.all(Object.entries(INDEXES).map(([k, specs]) => db.collection(COLLECTIONS[k]).createIndexes(specs)));
44
+ }
45
+ function isDuplicateKey(err) {
46
+ const e = err;
47
+ return e?.code === 11e3 || e?.errorResponse?.code === 11e3;
48
+ }
49
+ var toDate = (v) => v === void 0 ? void 0 : new Date(v);
50
+ var toIso = (v) => v instanceof Date ? v.toISOString() : v === null || v === void 0 ? void 0 : new Date(v).toISOString();
51
+ var clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
52
+ function fromDoc(doc, dates, idField, keepNull = []) {
53
+ const out = {};
54
+ for (const [k, v] of Object.entries(doc)) {
55
+ if (k === "_id") {
56
+ if (idField) out[idField] = v;
57
+ continue;
58
+ }
59
+ if (v === null || v === void 0) {
60
+ if (keepNull.includes(k)) out[k] = null;
61
+ continue;
62
+ }
63
+ out[k] = dates.includes(k) ? toIso(v) : v;
64
+ }
65
+ return out;
66
+ }
67
+ var EVENT_DATES = ["at"];
68
+ var REQUEST_DATES = ["openedAt", "dueAt", "closedAt"];
69
+ var TASK_DATES = ["createdAt", "dueAt", "claimedAt", "doneAt"];
70
+ var ACCESS_DATES = ["at"];
71
+ var NOTICE_DATES = ["addedAt", "sentAt"];
72
+ var requestDoc = (r) => {
73
+ const { id, ...rest } = r;
74
+ return clean({ _id: id, ...rest, openedAt: toDate(r.openedAt), dueAt: toDate(r.dueAt), closedAt: toDate(r.closedAt) });
75
+ };
76
+ var taskDoc = (t) => {
77
+ const { id, ...rest } = t;
78
+ return clean({ _id: id, ...rest, createdAt: toDate(t.createdAt), dueAt: toDate(t.dueAt), claimedAt: toDate(t.claimedAt), doneAt: toDate(t.doneAt) });
79
+ };
80
+ var breachDoc = (b) => ({ _id: b.id, status: b.status, awareAt: new Date(b.awareAt), reportDueAt: new Date(b.reportDueAt), data: b });
81
+ var runnable = (now, staleBefore, maxAttempts) => ({
82
+ dueAt: { $lte: new Date(now) },
83
+ $or: [{ status: "pending" }, { status: "failed", attempts: { $lt: maxAttempts } }, { status: "running", claimedAt: { $lt: new Date(staleBefore) } }]
84
+ });
85
+ var BATCH = 1e3;
86
+ function mongoStore(source) {
87
+ let ready;
88
+ const col = async (name) => {
89
+ ready ??= createMongoIndexes(source).catch((err) => {
90
+ ready = void 0;
91
+ throw err;
92
+ });
93
+ await ready;
94
+ return resolveDb(source).collection(COLLECTIONS[name]);
95
+ };
96
+ return {
97
+ async lastEvent(subjectId) {
98
+ const [doc] = await (await col("events")).find({ subjectId }, { sort: { seq: -1 }, limit: 1 }).toArray();
99
+ return doc ? fromDoc(doc, EVENT_DATES, void 0, ["prevHash"]) : void 0;
100
+ },
101
+ async insert(e) {
102
+ try {
103
+ await (await col("events")).insertOne(clean({ ...e, at: new Date(e.at) }));
104
+ } catch (err) {
105
+ if (isDuplicateKey(err)) throw new SeqConflictError(e.subjectId, e.seq);
106
+ throw err;
107
+ }
108
+ },
109
+ async events(subjectId) {
110
+ const docs = await (await col("events")).find({ subjectId }, { sort: { seq: 1 } }).toArray();
111
+ return docs.map((d) => fromDoc(d, EVENT_DATES, void 0, ["prevHash"]));
112
+ },
113
+ async insertRequest(r) {
114
+ await (await col("requests")).insertOne(requestDoc(r));
115
+ },
116
+ async getRequest(id) {
117
+ const doc = await (await col("requests")).findOne({ _id: id });
118
+ return doc ? fromDoc(doc, REQUEST_DATES, "id") : void 0;
119
+ },
120
+ async updateRequest(r) {
121
+ await (await col("requests")).replaceOne({ _id: r.id }, requestDoc(r));
122
+ },
123
+ async listRequests(filter) {
124
+ const docs = await (await col("requests")).find(clean({ subjectId: filter.subjectId, status: filter.status }), { sort: { openedAt: 1, _id: 1 } }).toArray();
125
+ return docs.map((d) => fromDoc(d, REQUEST_DATES, "id"));
126
+ },
127
+ async insertTasks(tasks) {
128
+ if (tasks.length > 0) await (await col("tasks")).insertMany(tasks.map(taskDoc));
129
+ },
130
+ async dueTasks({ limit, now, staleBefore, maxAttempts }) {
131
+ const docs = await (await col("tasks")).find(runnable(now, staleBefore, maxAttempts), { sort: { dueAt: 1, _id: 1 }, limit }).toArray();
132
+ return docs.map((d) => fromDoc(d, TASK_DATES, "id"));
133
+ },
134
+ async claimTask({ id, now, staleBefore, maxAttempts }) {
135
+ const result = await (await col("tasks")).updateOne(
136
+ { _id: id, ...runnable(now, staleBefore, maxAttempts) },
137
+ { $set: { status: "running", claimedAt: new Date(now) } }
138
+ );
139
+ return result.modifiedCount === 1;
140
+ },
141
+ async updateTask(t) {
142
+ await (await col("tasks")).replaceOne({ _id: t.id }, taskDoc(t));
143
+ },
144
+ async getTask(id) {
145
+ const doc = await (await col("tasks")).findOne({ _id: id });
146
+ return doc ? fromDoc(doc, TASK_DATES, "id") : void 0;
147
+ },
148
+ async listTasks(filter) {
149
+ const docs = await (await col("tasks")).find(clean({ subjectId: filter.subjectId, status: filter.status }), { sort: { dueAt: 1, _id: 1 } }).toArray();
150
+ return docs.map((d) => fromDoc(d, TASK_DATES, "id"));
151
+ },
152
+ async insertAccess(entries) {
153
+ if (entries.length === 0) return;
154
+ await (await col("access")).insertMany(entries.map(({ id, ...e }) => clean({ _id: id, ...e, at: new Date(e.at) })));
155
+ },
156
+ async listAccess(f) {
157
+ const at = clean({ $gte: toDate(f.from), $lt: toDate(f.to) });
158
+ const filter = clean({ subjectId: f.subjectId, actor: f.actor, purpose: f.purpose, at: Object.keys(at).length ? at : void 0 });
159
+ const docs = await (await col("access")).find(filter, clean({ sort: { at: 1, _id: 1 }, limit: f.limit })).toArray();
160
+ return docs.map((d) => fromDoc(d, ACCESS_DATES, "id"));
161
+ },
162
+ async pruneAccess(before) {
163
+ return (await (await col("access")).deleteMany({ at: { $lt: new Date(before) } })).deletedCount;
164
+ },
165
+ async accessSubjects(f) {
166
+ const at = clean({ $gte: toDate(f.from), $lt: toDate(f.to) });
167
+ const filter = clean({ subjectId: f.subjectId, actor: f.actor, purpose: f.purpose, at: Object.keys(at).length ? at : void 0 });
168
+ const groups = await (await col("access")).aggregate([{ $match: filter }, { $group: { _id: "$subjectId" } }]).toArray();
169
+ return groups.map((g) => String(g._id));
170
+ },
171
+ async insertBreach(b) {
172
+ await (await col("breaches")).insertOne(breachDoc(b));
173
+ },
174
+ async getBreach(id) {
175
+ const doc = await (await col("breaches")).findOne({ _id: id });
176
+ return doc ? doc.data : void 0;
177
+ },
178
+ async updateBreach(b) {
179
+ const unchanged = { "data.history": { $size: b.history.length - 1 } };
180
+ return (await (await col("breaches")).replaceOne({ _id: b.id, ...unchanged }, breachDoc(b))).matchedCount === 1;
181
+ },
182
+ async listBreaches(filter) {
183
+ const docs = await (await col("breaches")).find(clean({ status: filter.status }), { sort: { awareAt: -1, _id: 1 } }).toArray();
184
+ return docs.map((d) => d.data);
185
+ },
186
+ async addNotices(list) {
187
+ const notices = await col("notices");
188
+ let added = 0;
189
+ for (let i = 0; i < list.length; i += BATCH) {
190
+ const docs = list.slice(i, i + BATCH).map((n) => clean({ ...n, addedAt: new Date(n.addedAt), sentAt: toDate(n.sentAt) }));
191
+ try {
192
+ added += (await notices.insertMany(docs, { ordered: false })).insertedCount;
193
+ } catch (err) {
194
+ const e = err;
195
+ const writeErrors = Array.isArray(e.writeErrors) ? e.writeErrors : e.writeErrors ? [e.writeErrors] : [];
196
+ if (writeErrors.length === 0 || writeErrors.some((w) => w.code !== 11e3)) throw err;
197
+ added += e.insertedCount ?? e.result?.insertedCount ?? 0;
198
+ }
199
+ }
200
+ return added;
201
+ },
202
+ async markNotices(breachId, subjectIds, sentAt, channel) {
203
+ const notices = await col("notices");
204
+ const update = channel === void 0 ? { $set: { status: "sent", sentAt: new Date(sentAt) }, $unset: { channel: "" } } : { $set: { status: "sent", sentAt: new Date(sentAt), channel } };
205
+ let changed = 0;
206
+ for (let i = 0; i < subjectIds.length; i += BATCH) {
207
+ const result = await notices.updateMany({ breachId, status: "pending", subjectId: { $in: subjectIds.slice(i, i + BATCH) } }, update);
208
+ changed += result.modifiedCount;
209
+ }
210
+ return changed;
211
+ },
212
+ async listNotices(breachId, filter) {
213
+ const docs = await (await col("notices")).find(clean({ breachId, status: filter.status }), clean({ sort: { addedAt: 1, subjectId: 1 }, limit: filter.limit, projection: { _id: 0 } })).toArray();
214
+ return docs.map((d) => fromDoc(d, NOTICE_DATES));
215
+ },
216
+ async countNotices(breachId) {
217
+ const [r] = await (await col("notices")).aggregate([
218
+ { $match: { breachId } },
219
+ {
220
+ $group: {
221
+ _id: null,
222
+ total: { $sum: 1 },
223
+ sent: { $sum: { $cond: [{ $eq: ["$status", "sent"] }, 1, 0] } },
224
+ first: { $min: "$sentAt" },
225
+ last: { $max: "$sentAt" }
226
+ }
227
+ }
228
+ ]).toArray();
229
+ return clean({ total: r?.total ?? 0, sent: r?.sent ?? 0, firstSentAt: toIso(r?.first), lastSentAt: toIso(r?.last) });
230
+ }
231
+ };
232
+ }
233
+ var HEX24 = /^[0-9a-f]{24}$/i;
234
+ function mongoData(source, options = {}) {
235
+ const collections = /* @__PURE__ */ new Map();
236
+ const fields = /* @__PURE__ */ new Map();
237
+ const arrays = /* @__PURE__ */ new Map();
238
+ for (const t of options.schema?.tables ?? []) {
239
+ const byKey = new Map(t.columns.filter((c) => c.key).map((c) => [c.key, c.name]));
240
+ const arrayPaths = new Set(t.columns.filter((c) => c.sqlType === "array").map((c) => c.name));
241
+ for (const name of t.key ? [t.name, t.key] : [t.name]) {
242
+ if (!collections.has(name)) collections.set(name, t.name);
243
+ if (!fields.has(name)) fields.set(name, byKey);
244
+ if (!arrays.has(name)) arrays.set(name, arrayPaths);
245
+ }
246
+ }
247
+ const writePath = (table, path) => {
248
+ const inArrays = arrays.get(table);
249
+ if (!inArrays?.size) return path;
250
+ const parts = path.split(".");
251
+ return parts.map((part, i) => i < parts.length - 1 && inArrays.has(parts.slice(0, i + 1).join(".")) ? `${part}.$[]` : part).join(".");
252
+ };
253
+ const collection = (table) => resolveDb(source).collection(collections.get(table) ?? table);
254
+ const field = (table, name) => fields.get(table)?.get(name) ?? name;
255
+ const values = (subjectId, table, field2) => {
256
+ if (options.subjectValues) return options.subjectValues(subjectId, collections.get(table) ?? table, field2);
257
+ const out = [subjectId];
258
+ if (/^-?\d+$/.test(subjectId) && Number.isSafeInteger(Number(subjectId))) out.push(Number(subjectId));
259
+ if (options.ObjectId && HEX24.test(subjectId)) out.push(new options.ObjectId(subjectId));
260
+ return out;
261
+ };
262
+ const filter = (table, subject, subjectId) => {
263
+ const stored = field(table, subject);
264
+ return { [stored]: { $in: values(subjectId, table, stored) } };
265
+ };
266
+ return {
267
+ async read(table, subjectColumn, subjectId, columns) {
268
+ if (columns.length === 0) return [];
269
+ const stored = columns.map((c) => field(table, c));
270
+ const projection = Object.fromEntries(stored.map((c) => [c, 1]));
271
+ if (!stored.includes("_id")) projection._id = 0;
272
+ const docs = await collection(table).find(filter(table, subjectColumn, subjectId), { projection }).toArray();
273
+ return docs.map((doc) => {
274
+ const out = { ...doc };
275
+ columns.forEach((c, i) => {
276
+ const s = stored[i];
277
+ if (s === c) return;
278
+ out[c] = doc[s];
279
+ if (!columns.includes(s)) delete out[s];
280
+ });
281
+ return out;
282
+ });
283
+ },
284
+ async eraseFields(table, subjectColumn, subjectId, columns, replacements = {}) {
285
+ if (columns.length === 0) return 0;
286
+ const $set = {};
287
+ const $unset = {};
288
+ for (const c of columns) {
289
+ const path = writePath(table, field(table, c));
290
+ if (Object.hasOwn(replacements, c) && replacements[c] !== null) $set[path] = replacements[c];
291
+ else $unset[path] = "";
292
+ }
293
+ 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
+ return result.matchedCount;
295
+ },
296
+ async deleteRows(table, subjectColumn, subjectId) {
297
+ return (await collection(table).deleteMany(filter(table, subjectColumn, subjectId))).deletedCount;
298
+ }
299
+ };
300
+ }
301
+ var isModel = (v) => {
302
+ const m = v;
303
+ return (typeof v === "function" || typeof v === "object") && m !== null && typeof m?.modelName === "string" && typeof m.collection?.collectionName === "string" && typeof m.schema?.paths === "object";
304
+ };
305
+ var MONGOOSE_TYPES = { String: "string", Number: "number", Boolean: "boolean" };
306
+ function mongooseSchema(source) {
307
+ const found = /* @__PURE__ */ new Map();
308
+ const visit = (v, depth) => {
309
+ if (isModel(v)) {
310
+ if (!found.has(v.collection.collectionName)) found.set(v.collection.collectionName, v);
311
+ return;
312
+ }
313
+ if (depth > 1 || v === null || typeof v !== "object") return;
314
+ const models = v.models;
315
+ if (models && typeof models === "object" && depth === 0) visit(models, depth + 1);
316
+ for (const value of Array.isArray(v) ? v : Object.values(v)) visit(value, depth + 1);
317
+ };
318
+ visit(source, 0);
319
+ const tables = [];
320
+ for (const model of found.values()) {
321
+ const columns = [];
322
+ const addPaths = (paths, prefix) => {
323
+ for (const [path, type] of Object.entries(paths)) {
324
+ if (path === "__v" || prefix && path === "_id") continue;
325
+ const name2 = `${prefix}${path}`;
326
+ const key = name2 === "_id" && model.schema.virtuals?.id ? { key: "id" } : {};
327
+ const array = type.instance === "Array" ? { sqlType: "array" } : {};
328
+ columns.push({ name: name2, ...key, notNull: name2 === "_id" || type.isRequired === true, type: MONGOOSE_TYPES[type.instance ?? ""] ?? "other", ...array });
329
+ if (type.schema?.paths) addPaths(type.schema.paths, `${name2}.`);
330
+ }
331
+ };
332
+ addPaths(model.schema.paths, "");
333
+ const name = model.collection.collectionName;
334
+ tables.push({ name, ...model.modelName === name ? {} : { key: model.modelName }, columns });
335
+ }
336
+ return { tables };
337
+ }
338
+ export {
339
+ createMongoIndexes,
340
+ isDuplicateKey,
341
+ mongoData,
342
+ mongoStore,
343
+ mongooseSchema
344
+ };
@@ -0,0 +1,65 @@
1
+ import type { Dpdp } from "./dpdp.js";
2
+ import { type AccessLogOptions, type GuardOptions } from "./guard.js";
3
+ /**
4
+ * The part of NestJS's `ExecutionContext` these guards use, so dpdp-kit doesn't depend on
5
+ * `@nestjs/common`. For HTTP routes, `switchToHttp().getRequest()` is the Express or Fastify request.
6
+ */
7
+ export interface ExecutionContextLike {
8
+ switchToHttp(): {
9
+ getRequest<T = any>(): T;
10
+ };
11
+ }
12
+ /** What NestJS calls on a guard. `@UseGuards()` accepts any object with this method. */
13
+ export interface CanActivateLike {
14
+ canActivate(context: ExecutionContextLike): Promise<boolean>;
15
+ }
16
+ interface RequestOption<Req> {
17
+ /**
18
+ * Where to find the request. Default: `context.switchToHttp().getRequest()`, for HTTP routes. For
19
+ * GraphQL, pass e.g. `(ctx) => GqlExecutionContext.create(ctx).getContext().req`.
20
+ */
21
+ request?: (context: ExecutionContextLike) => Req | undefined;
22
+ }
23
+ export interface NestGuardOptions<Req> extends GuardOptions<Req>, RequestOption<Req> {
24
+ /**
25
+ * Throw your own exception when consent is missing, for example
26
+ * `(purpose) => new ForbiddenException(CONSENT_REQUIRED_BODY(purpose))`. Default: the guard
27
+ * returns `false`, and NestJS answers 403 Forbidden.
28
+ */
29
+ onDenied?: (purpose: string, request: Req) => Error;
30
+ }
31
+ /**
32
+ * A NestJS guard that lets the request through only if the person may be processed for `purpose`.
33
+ *
34
+ * ```ts
35
+ * import { ForbiddenException, UseGuards } from "@nestjs/common";
36
+ * import { CONSENT_REQUIRED_BODY } from "dpdp-kit";
37
+ *
38
+ * @UseGuards(consentGuard(dpdp, "marketing_sms", {
39
+ * subject: (req) => req.user?.id,
40
+ * onDenied: (purpose) => new ForbiddenException(CONSENT_REQUIRED_BODY(purpose)),
41
+ * }))
42
+ * @Post("promo")
43
+ * sendPromo() { … }
44
+ * ```
45
+ */
46
+ export declare function consentGuard<P extends string, Req = any>(dpdp: Dpdp<P>, purpose: P, options: NestGuardOptions<Req>): CanActivateLike;
47
+ /**
48
+ * A NestJS guard that records each request in the access log (Rule 6(1)(c)) and lets it through.
49
+ * If logging fails, or the fields aren't held for the purpose and the instance was created with
50
+ * `access: { outOfPurpose: "throw" }`, the error reaches NestJS's exception filters and the
51
+ * handler doesn't run.
52
+ *
53
+ * ```ts
54
+ * @UseGuards(accessLogGuard(dpdp, {
55
+ * purpose: "account",
56
+ * fields: ["users"],
57
+ * actor: (req) => req.user?.staffId,
58
+ * subject: (req) => req.params.id,
59
+ * }))
60
+ * @Get("admin/users/:id")
61
+ * getUser() { … }
62
+ * ```
63
+ */
64
+ export declare function accessLogGuard<P extends string, Req = any>(dpdp: Dpdp<P>, options: AccessLogOptions<Req, P> & RequestOption<Req>): CanActivateLike;
65
+ export {};
package/dist/nestjs.js ADDED
@@ -0,0 +1,41 @@
1
+ import {
2
+ checkConsent,
3
+ recordAccess
4
+ } from "./chunk-5TVA2TKG.js";
5
+ import {
6
+ DpdpError
7
+ } from "./chunk-67Q5GFD6.js";
8
+
9
+ // src/nestjs.ts
10
+ function requestOf(context, options, guard) {
11
+ const request = options.request ? options.request(context) : context.switchToHttp().getRequest();
12
+ if (request === void 0 || request === null) {
13
+ throw new DpdpError(
14
+ "invalid-input",
15
+ `${guard} found no request. It reads HTTP requests by default; for GraphQL or other contexts, pass request: (context) => \u2026.`
16
+ );
17
+ }
18
+ return request;
19
+ }
20
+ function consentGuard(dpdp, purpose, options) {
21
+ return {
22
+ async canActivate(context) {
23
+ const request = requestOf(context, options, "consentGuard");
24
+ if (await checkConsent(dpdp, purpose, options, request)) return true;
25
+ if (options.onDenied) throw options.onDenied(purpose, request);
26
+ return false;
27
+ }
28
+ };
29
+ }
30
+ function accessLogGuard(dpdp, options) {
31
+ return {
32
+ async canActivate(context) {
33
+ await recordAccess(dpdp, options, requestOf(context, options, "accessLogGuard"));
34
+ return true;
35
+ }
36
+ };
37
+ }
38
+ export {
39
+ accessLogGuard,
40
+ consentGuard
41
+ };
@@ -0,0 +1,45 @@
1
+ import type { AccessLogStore } from "./access.js";
2
+ import type { BreachStore } from "./breach.js";
3
+ import type { DataAccess } from "./data-access.js";
4
+ import type { Schema } from "./schema-check.js";
5
+ import type { DpdpStore } from "./store.js";
6
+ export { ACCESS_LOG_DDL, BREACH_DDL, CONSENT_EVENTS_DDL, DPDP_DDL, RECORDS_DDL } from "./ddl.js";
7
+ /**
8
+ * Runs one parameterised SQL statement (`$1`, `$2`… placeholders) and resolves with its rows.
9
+ *
10
+ * ```ts
11
+ * const query: SqlQuery = async (text, params) => (await pool.query(text, [...params])).rows; // node-postgres
12
+ * ```
13
+ */
14
+ export type SqlQuery = (text: string, params: readonly unknown[]) => Promise<Record<string, unknown>[]>;
15
+ /** Quote a table or column name for Postgres. */
16
+ export declare const ident: (name: string) => string;
17
+ /** Unique violations look different per client: pg and PGlite set code 23505, Prisma wraps it in `meta`. */
18
+ export declare function isUniqueViolation(err: unknown): boolean;
19
+ /**
20
+ * Store on Postgres with plain SQL: consent events, rights requests, erasure tasks, the access log and
21
+ * breaches. Needs the dpdp-kit tables (`DPDP_DDL` from `dpdp-kit/drizzle`, or `PRISMA_MODELS` from
22
+ * `dpdp-kit/prisma`).
23
+ *
24
+ * ```ts
25
+ * import pg from "pg";
26
+ * const pool = new pg.Pool();
27
+ * const store = postgresStore(async (text, params) => (await pool.query(text, [...params])).rows);
28
+ * ```
29
+ */
30
+ export declare function postgresStore(query: SqlQuery): DpdpStore & AccessLogStore & BreachStore;
31
+ /**
32
+ * The type to cast a parameter to for a column. Length limits are dropped, because a cast to
33
+ * `varchar(3)` cuts the value short and would match the wrong rows; serials are plain integers.
34
+ */
35
+ export declare function castType(sqlType: string): string;
36
+ /**
37
+ * Data access for your own Postgres tables with plain SQL, for access summaries and erasure. Pass a
38
+ * `schema` (from `prismaSchema()` or `drizzleSchema()`) when the data map uses names from code
39
+ * (a `User` model, a `userId` property) rather than the database's (`users`, `user_id`); it also
40
+ * gives each column's type, so parameters are cast to it. Erasure writes each field's `erase`
41
+ * replacement, or NULL; `dpdp-kit audit --schema` checks that each column can take it.
42
+ */
43
+ export declare function postgresData(query: SqlQuery, options?: {
44
+ schema?: Schema;
45
+ }): DataAccess;
@@ -0,0 +1,27 @@
1
+ import {
2
+ castType,
3
+ ident,
4
+ isUniqueViolation,
5
+ postgresData,
6
+ postgresStore
7
+ } from "./chunk-KLMR7S7I.js";
8
+ import {
9
+ ACCESS_LOG_DDL,
10
+ BREACH_DDL,
11
+ CONSENT_EVENTS_DDL,
12
+ DPDP_DDL,
13
+ RECORDS_DDL
14
+ } from "./chunk-2ELTZSW3.js";
15
+ import "./chunk-67Q5GFD6.js";
16
+ export {
17
+ ACCESS_LOG_DDL,
18
+ BREACH_DDL,
19
+ CONSENT_EVENTS_DDL,
20
+ DPDP_DDL,
21
+ RECORDS_DDL,
22
+ castType,
23
+ ident,
24
+ isUniqueViolation,
25
+ postgresData,
26
+ postgresStore
27
+ };
@@ -0,0 +1,43 @@
1
+ import type { AccessLogStore } from "./access.js";
2
+ import type { BreachStore } from "./breach.js";
3
+ import type { DataAccess } from "./data-access.js";
4
+ import { type SqlQuery } from "./postgres.js";
5
+ import type { Schema } from "./schema-check.js";
6
+ import type { DpdpStore } from "./store.js";
7
+ export { castType, DPDP_DDL, isUniqueViolation, type SqlQuery } from "./postgres.js";
8
+ /** The one method dpdp-kit needs from a PrismaClient (or a transaction client). */
9
+ export interface PrismaLike {
10
+ $queryRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
11
+ }
12
+ /** Run SQL through a PrismaClient. */
13
+ export declare const prismaQuery: (prisma: PrismaLike) => SqlQuery;
14
+ /**
15
+ * Store on Postgres through Prisma: consent events, rights requests, erasure tasks, the access
16
+ * log and breaches. Add `PRISMA_MODELS` to your schema.prisma and run `prisma migrate dev`.
17
+ *
18
+ * ```ts
19
+ * const dpdp = createDpdp({ config, store: prismaStore(prisma), data: prismaData(prisma, { schema }) });
20
+ * ```
21
+ */
22
+ export declare function prismaStore(prisma: PrismaLike): DpdpStore & AccessLogStore & BreachStore;
23
+ /**
24
+ * Data access for your own tables through Prisma, for access summaries and erasure. Pass the
25
+ * schema (`prismaSchema(text)`) so the data map can use model and field names (`User`,
26
+ * `phoneNumber`) where the database has others (`users`, `phone_number`).
27
+ */
28
+ export declare function prismaData(prisma: PrismaLike, options?: {
29
+ schema?: Schema;
30
+ }): DataAccess;
31
+ /**
32
+ * Read a Prisma schema (the text of schema.prisma, or of several .prisma files joined) into the
33
+ * neutral shape `dpdp-kit audit --schema` and `prismaData()` use. Each model and view becomes a
34
+ * table named as in the database (`@@map`), with the model name as its `key`; each scalar field
35
+ * becomes a column (`@map`), with the field name as its `key`. Relation fields are skipped.
36
+ */
37
+ export declare function prismaSchema(text: string): Schema;
38
+ /**
39
+ * Prisma models for dpdp-kit's own tables. Paste them into schema.prisma (or save as
40
+ * `prisma/schema/dpdp.prisma` with a multi-file schema) and run `prisma migrate dev`. They match
41
+ * `DPDP_DDL` from `dpdp-kit/drizzle`, so either can create the tables.
42
+ */
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";