dpdp-kit 0.3.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.
- package/CHANGELOG.md +53 -0
- package/README.md +115 -14
- package/dist/access.d.ts +5 -0
- package/dist/audit.d.ts +1 -1
- package/dist/breach.d.ts +170 -0
- package/dist/chunk-2ELTZSW3.js +94 -0
- package/dist/{chunk-YOEAZX65.js → chunk-HXVP446N.js} +118 -4
- package/dist/chunk-KLMR7S7I.js +438 -0
- package/dist/cli.js +24 -8
- package/dist/ddl.d.ts +10 -0
- package/dist/dpdp.d.ts +66 -2
- package/dist/drizzle.d.ts +213 -11
- package/dist/drizzle.js +138 -77
- package/dist/errors.d.ts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +235 -1
- package/dist/mongodb.d.ts +87 -0
- package/dist/mongodb.js +344 -0
- package/dist/postgres.d.ts +45 -0
- package/dist/postgres.js +27 -0
- package/dist/prisma.d.ts +43 -0
- package/dist/prisma.js +281 -0
- package/dist/run-audit.d.ts +8 -1
- package/dist/schema-check.d.ts +20 -1
- package/dist/store.d.ts +4 -1
- package/package.json +25 -3
package/dist/mongodb.js
ADDED
|
@@ -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,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;
|
package/dist/postgres.js
ADDED
|
@@ -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
|
+
};
|
package/dist/prisma.d.ts
ADDED
|
@@ -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";
|