dpdp-kit 0.2.0 → 0.3.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 +37 -0
- package/README.md +130 -8
- package/dist/access.d.ts +106 -0
- package/dist/audit.d.ts +3 -1
- package/dist/chunk-5TVA2TKG.js +37 -0
- package/dist/chunk-YOEAZX65.js +937 -0
- package/dist/cli.js +30 -10
- package/dist/config.d.ts +69 -0
- package/dist/data-access.d.ts +6 -2
- package/dist/dpdp.d.ts +146 -0
- package/dist/drizzle.d.ts +195 -5
- package/dist/drizzle.js +99 -7
- package/dist/errors.d.ts +1 -1
- package/dist/express.d.ts +17 -1
- package/dist/express.js +10 -2
- package/dist/fastify.d.ts +41 -0
- package/dist/fastify.js +25 -0
- package/dist/guard.d.ts +19 -0
- package/dist/hono.d.ts +16 -1
- package/dist/hono.js +11 -2
- package/dist/index.d.ts +6 -4
- package/dist/index.js +189 -103
- package/dist/nestjs.d.ts +65 -0
- package/dist/nestjs.js +41 -0
- package/dist/protect.d.ts +74 -0
- package/dist/protect.js +114 -0
- package/dist/retention.d.ts +1 -1
- package/dist/run-audit.d.ts +5 -0
- package/dist/safeguards.d.ts +23 -0
- package/dist/schedule.d.ts +37 -0
- package/dist/schedule.js +66 -0
- package/dist/schema-check.d.ts +5 -7
- package/dist/store.d.ts +8 -1
- package/package.json +35 -4
- package/dist/chunk-FGZAH2NF.js +0 -16
- package/dist/chunk-KVTUMHXO.js +0 -491
package/dist/index.js
CHANGED
|
@@ -1,30 +1,37 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
} from "./chunk-67Q5GFD6.js";
|
|
5
|
-
import {
|
|
6
|
-
CONSENT_REQUIRED_BODY
|
|
7
|
-
} from "./chunk-FGZAH2NF.js";
|
|
8
|
-
import {
|
|
2
|
+
DEFAULT_ACCESS_LOG_RETENTION,
|
|
3
|
+
REDACTED,
|
|
9
4
|
REQUEST_TYPES,
|
|
5
|
+
accessId,
|
|
10
6
|
audit,
|
|
11
7
|
checkSchema,
|
|
8
|
+
defineConfig,
|
|
12
9
|
durationMs,
|
|
10
|
+
erasedValue,
|
|
11
|
+
fieldsOutsidePurpose,
|
|
12
|
+
formatSafeguards,
|
|
13
|
+
grantedPurposes,
|
|
13
14
|
guessPersonal,
|
|
14
15
|
hasErrors,
|
|
16
|
+
isAccessLogStore,
|
|
17
|
+
isDpdpStore,
|
|
15
18
|
isDuration,
|
|
16
|
-
|
|
19
|
+
isHighRisk,
|
|
17
20
|
maxDuration,
|
|
21
|
+
memoryStore,
|
|
22
|
+
purposeNames,
|
|
23
|
+
resolveFields,
|
|
24
|
+
reviewAccess,
|
|
25
|
+
safeguardsReport,
|
|
18
26
|
tokenize
|
|
19
|
-
} from "./chunk-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
27
|
+
} from "./chunk-YOEAZX65.js";
|
|
28
|
+
import {
|
|
29
|
+
CONSENT_REQUIRED_BODY
|
|
30
|
+
} from "./chunk-5TVA2TKG.js";
|
|
31
|
+
import {
|
|
32
|
+
DpdpError,
|
|
33
|
+
SeqConflictError
|
|
34
|
+
} from "./chunk-67Q5GFD6.js";
|
|
28
35
|
|
|
29
36
|
// src/dpdp.ts
|
|
30
37
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
@@ -196,7 +203,11 @@ async function carryOut(task, input) {
|
|
|
196
203
|
if (task.kind === "delete-rows") {
|
|
197
204
|
return { affected: await input.data.deleteRows(def.table, def.subject, task.subjectId) };
|
|
198
205
|
}
|
|
199
|
-
|
|
206
|
+
const fields = task.fields ?? [];
|
|
207
|
+
const values = Object.fromEntries(
|
|
208
|
+
fields.map((field) => [field, erasedValue(def.fields[field]?.erase, { subjectId: task.subjectId, table: task.table ?? "", field })])
|
|
209
|
+
);
|
|
210
|
+
return { affected: await input.data.eraseFields(def.table, def.subject, task.subjectId, fields, values) };
|
|
200
211
|
}
|
|
201
212
|
async function runDueTasks(input) {
|
|
202
213
|
const when = { now: input.now, staleBefore: addMs(input.now, -STALE_AFTER_MS), maxAttempts: MAX_ATTEMPTS };
|
|
@@ -264,72 +275,6 @@ async function buildAccessSummary(input) {
|
|
|
264
275
|
return { subjectId, generatedAt: now, data: tables, consents, legitimateUses, sharedWith };
|
|
265
276
|
}
|
|
266
277
|
|
|
267
|
-
// src/store.ts
|
|
268
|
-
function isDpdpStore(store) {
|
|
269
|
-
const s = store;
|
|
270
|
-
return typeof s.insertRequest === "function" && typeof s.insertTasks === "function";
|
|
271
|
-
}
|
|
272
|
-
function memoryStore() {
|
|
273
|
-
const all = /* @__PURE__ */ new Map();
|
|
274
|
-
const requests = /* @__PURE__ */ new Map();
|
|
275
|
-
const tasks = /* @__PURE__ */ new Map();
|
|
276
|
-
const byDue = (a, b) => a.dueAt < b.dueAt ? -1 : a.dueAt > b.dueAt ? 1 : 0;
|
|
277
|
-
return {
|
|
278
|
-
all,
|
|
279
|
-
requests,
|
|
280
|
-
tasks,
|
|
281
|
-
async insertRequest(request) {
|
|
282
|
-
requests.set(request.id, structuredClone(request));
|
|
283
|
-
},
|
|
284
|
-
async getRequest(id) {
|
|
285
|
-
const r = requests.get(id);
|
|
286
|
-
return r && structuredClone(r);
|
|
287
|
-
},
|
|
288
|
-
async updateRequest(request) {
|
|
289
|
-
requests.set(request.id, structuredClone(request));
|
|
290
|
-
},
|
|
291
|
-
async listRequests(filter) {
|
|
292
|
-
return [...requests.values()].filter((r) => (!filter.subjectId || r.subjectId === filter.subjectId) && (!filter.status || r.status === filter.status)).sort((a, b) => a.openedAt < b.openedAt ? -1 : 1).map((r) => structuredClone(r));
|
|
293
|
-
},
|
|
294
|
-
async insertTasks(list) {
|
|
295
|
-
for (const t of list) tasks.set(t.id, structuredClone(t));
|
|
296
|
-
},
|
|
297
|
-
async dueTasks({ limit, ...when }) {
|
|
298
|
-
return [...tasks.values()].filter((t) => isRunnable(t, when)).sort(byDue).slice(0, limit).map((t) => structuredClone(t));
|
|
299
|
-
},
|
|
300
|
-
async claimTask({ id, ...when }) {
|
|
301
|
-
const t = tasks.get(id);
|
|
302
|
-
if (!t || !isRunnable(t, when)) return false;
|
|
303
|
-
tasks.set(id, { ...t, status: "running", claimedAt: when.now });
|
|
304
|
-
return true;
|
|
305
|
-
},
|
|
306
|
-
async updateTask(task) {
|
|
307
|
-
tasks.set(task.id, structuredClone(task));
|
|
308
|
-
},
|
|
309
|
-
async getTask(id) {
|
|
310
|
-
const t = tasks.get(id);
|
|
311
|
-
return t && structuredClone(t);
|
|
312
|
-
},
|
|
313
|
-
async listTasks(filter) {
|
|
314
|
-
return [...tasks.values()].filter((t) => (!filter.subjectId || t.subjectId === filter.subjectId) && (!filter.status || t.status === filter.status)).sort(byDue).map((t) => structuredClone(t));
|
|
315
|
-
},
|
|
316
|
-
async lastEvent(subjectId) {
|
|
317
|
-
const list = all.get(subjectId);
|
|
318
|
-
return list?.[list.length - 1];
|
|
319
|
-
},
|
|
320
|
-
async insert(event) {
|
|
321
|
-
const list = all.get(event.subjectId) ?? [];
|
|
322
|
-
if (list.some((e) => e.seq === event.seq)) throw new SeqConflictError(event.subjectId, event.seq);
|
|
323
|
-
list.push(structuredClone(event));
|
|
324
|
-
list.sort((a, b) => a.seq - b.seq);
|
|
325
|
-
all.set(event.subjectId, list);
|
|
326
|
-
},
|
|
327
|
-
async events(subjectId) {
|
|
328
|
-
return structuredClone(all.get(subjectId) ?? []);
|
|
329
|
-
}
|
|
330
|
-
};
|
|
331
|
-
}
|
|
332
|
-
|
|
333
278
|
// src/dpdp.ts
|
|
334
279
|
function hashEvent(event) {
|
|
335
280
|
return sha256(
|
|
@@ -347,16 +292,6 @@ function hashEvent(event) {
|
|
|
347
292
|
})
|
|
348
293
|
);
|
|
349
294
|
}
|
|
350
|
-
function grantedFrom(events) {
|
|
351
|
-
const granted = /* @__PURE__ */ new Set();
|
|
352
|
-
for (const e of events) {
|
|
353
|
-
for (const p of e.purposes) {
|
|
354
|
-
if (e.action === "grant") granted.add(p);
|
|
355
|
-
else granted.delete(p);
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
return granted;
|
|
359
|
-
}
|
|
360
295
|
function createDpdp(options) {
|
|
361
296
|
const { config, store } = options;
|
|
362
297
|
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
@@ -413,7 +348,10 @@ ${lines.join("\n")}`, issues);
|
|
|
413
348
|
await store.insert(event);
|
|
414
349
|
return event;
|
|
415
350
|
} catch (err) {
|
|
416
|
-
if (err instanceof SeqConflictError && attempt < maxRetries)
|
|
351
|
+
if (err instanceof SeqConflictError && attempt < maxRetries) {
|
|
352
|
+
await new Promise((r) => setTimeout(r, Math.random() * 5 * attempt));
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
417
355
|
if (err instanceof SeqConflictError) {
|
|
418
356
|
throw new DpdpError("write-conflict", `Gave up after ${maxRetries} conflicting writes for one subject`);
|
|
419
357
|
}
|
|
@@ -423,7 +361,7 @@ ${lines.join("\n")}`, issues);
|
|
|
423
361
|
}
|
|
424
362
|
async function activeFor(subjectId) {
|
|
425
363
|
checkSubject(subjectId);
|
|
426
|
-
return [...
|
|
364
|
+
return [...grantedPurposes(await store.events(subjectId))];
|
|
427
365
|
}
|
|
428
366
|
const nowIso = () => now().toISOString();
|
|
429
367
|
const processorHooks = options.processors ?? {};
|
|
@@ -444,9 +382,34 @@ ${lines.join("\n")}`, issues);
|
|
|
444
382
|
}
|
|
445
383
|
async function schedule(plan) {
|
|
446
384
|
const tasks = tasksFromPlan(config, plan, nowIso());
|
|
447
|
-
if (tasks.length > 0)
|
|
385
|
+
if (tasks.length > 0) {
|
|
386
|
+
await fullStore("Scheduling erasure").insertTasks(tasks);
|
|
387
|
+
emit("erasure.scheduled", { plan, tasks });
|
|
388
|
+
}
|
|
448
389
|
return tasks;
|
|
449
390
|
}
|
|
391
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
392
|
+
const onListenerError = options.onListenerError ?? ((err, event) => console.error(`dpdp-kit: a "${event}" listener failed`, err));
|
|
393
|
+
function emit(event, payload) {
|
|
394
|
+
for (const listener of listeners.get(event) ?? []) {
|
|
395
|
+
setImmediate(() => {
|
|
396
|
+
try {
|
|
397
|
+
Promise.resolve(listener(structuredClone(payload))).catch((err) => onListenerError(err, event));
|
|
398
|
+
} catch (err) {
|
|
399
|
+
onListenerError(err, event);
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
function accessStore() {
|
|
405
|
+
if (!isAccessLogStore(store)) {
|
|
406
|
+
throw new DpdpError(
|
|
407
|
+
"store-unsupported",
|
|
408
|
+
"The access log needs a store that keeps it: memoryStore(), drizzleStore(db), or your own AccessLogStore"
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
return store;
|
|
412
|
+
}
|
|
450
413
|
async function requireRequest(id) {
|
|
451
414
|
const request = await fullStore("Rights requests").getRequest(id);
|
|
452
415
|
if (!request) throw new DpdpError("request-not-found", `No rights request with id ${JSON.stringify(id)}`);
|
|
@@ -465,6 +428,7 @@ ${lines.join("\n")}`, issues);
|
|
|
465
428
|
history: [...request.history, { at, status, ...note !== void 0 ? { note } : {} }]
|
|
466
429
|
};
|
|
467
430
|
await fullStore("Rights requests").updateRequest(closed);
|
|
431
|
+
emit("rights.closed", { request: closed });
|
|
468
432
|
return closed;
|
|
469
433
|
}
|
|
470
434
|
function accountPlan(subjectId, reason, keepFor) {
|
|
@@ -478,10 +442,54 @@ ${lines.join("\n")}`, issues);
|
|
|
478
442
|
remaining: [...keepFor]
|
|
479
443
|
});
|
|
480
444
|
}
|
|
481
|
-
|
|
445
|
+
const api = {
|
|
482
446
|
config,
|
|
447
|
+
async daily(input = {}) {
|
|
448
|
+
const report = { at: nowIso(), skipped: [], errors: [] };
|
|
449
|
+
const step = async (name, run) => {
|
|
450
|
+
try {
|
|
451
|
+
await run();
|
|
452
|
+
} catch (error) {
|
|
453
|
+
report.errors.push({ step: name, message: error instanceof Error ? error.message : String(error), error });
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
if (isDpdpStore(store)) {
|
|
457
|
+
await step("retention", async () => {
|
|
458
|
+
report.retention = await api.retention.run();
|
|
459
|
+
});
|
|
460
|
+
await step("rights", async () => {
|
|
461
|
+
report.overdueRequests = await api.rights.list({ overdue: true });
|
|
462
|
+
});
|
|
463
|
+
} else {
|
|
464
|
+
report.skipped.push("retention", "rights");
|
|
465
|
+
}
|
|
466
|
+
if (isAccessLogStore(store)) {
|
|
467
|
+
await step("access-prune", async () => {
|
|
468
|
+
report.accessPruned = (await api.access.prune()).deleted;
|
|
469
|
+
});
|
|
470
|
+
await step("access-review", async () => {
|
|
471
|
+
report.review = await api.access.review({ ...input.review });
|
|
472
|
+
});
|
|
473
|
+
} else {
|
|
474
|
+
report.skipped.push("access");
|
|
475
|
+
}
|
|
476
|
+
emit("daily.ran", { report });
|
|
477
|
+
return report;
|
|
478
|
+
},
|
|
479
|
+
on(event, listener) {
|
|
480
|
+
let set = listeners.get(event);
|
|
481
|
+
if (!set) listeners.set(event, set = /* @__PURE__ */ new Set());
|
|
482
|
+
set.add(listener);
|
|
483
|
+
return () => {
|
|
484
|
+
set.delete(listener);
|
|
485
|
+
};
|
|
486
|
+
},
|
|
483
487
|
consent: {
|
|
484
|
-
grant
|
|
488
|
+
async grant(subjectId, list, meta) {
|
|
489
|
+
const event = await append(subjectId, "grant", list, meta);
|
|
490
|
+
emit("consent.granted", { event });
|
|
491
|
+
return event;
|
|
492
|
+
},
|
|
485
493
|
async withdraw(subjectId, list, meta) {
|
|
486
494
|
const event = await append(subjectId, "withdraw", list, meta);
|
|
487
495
|
const stillGranted = await activeFor(subjectId);
|
|
@@ -492,6 +500,7 @@ ${lines.join("\n")}`, issues);
|
|
|
492
500
|
remaining: [...legitimate, ...stillGranted]
|
|
493
501
|
});
|
|
494
502
|
const tasks = isDpdpStore(store) ? await schedule(erasure) : [];
|
|
503
|
+
emit("consent.withdrawn", { event, erasure, tasks });
|
|
495
504
|
return { event, erasure, tasks };
|
|
496
505
|
},
|
|
497
506
|
async has(subjectId, purpose) {
|
|
@@ -499,7 +508,7 @@ ${lines.join("\n")}`, issues);
|
|
|
499
508
|
const def = purposes[purpose];
|
|
500
509
|
if (!def) throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(purpose)}`);
|
|
501
510
|
if (def.basis === "legitimate-use") return true;
|
|
502
|
-
return
|
|
511
|
+
return grantedPurposes(await store.events(subjectId)).has(purpose);
|
|
503
512
|
},
|
|
504
513
|
active: activeFor,
|
|
505
514
|
async history(subjectId) {
|
|
@@ -540,7 +549,7 @@ ${lines.join("\n")}`, issues);
|
|
|
540
549
|
},
|
|
541
550
|
retention: {
|
|
542
551
|
async run(input = {}) {
|
|
543
|
-
|
|
552
|
+
const report = await runDueTasks({
|
|
544
553
|
config,
|
|
545
554
|
store: fullStore("The retention runner"),
|
|
546
555
|
data: options.data,
|
|
@@ -548,6 +557,8 @@ ${lines.join("\n")}`, issues);
|
|
|
548
557
|
now: nowIso(),
|
|
549
558
|
limit: input.limit ?? 500
|
|
550
559
|
});
|
|
560
|
+
emit("retention.ran", { report });
|
|
561
|
+
return report;
|
|
551
562
|
},
|
|
552
563
|
async tasks(filter = {}) {
|
|
553
564
|
return fullStore("Erasure tasks").listTasks(filter);
|
|
@@ -564,6 +575,72 @@ ${lines.join("\n")}`, issues);
|
|
|
564
575
|
return done;
|
|
565
576
|
}
|
|
566
577
|
},
|
|
578
|
+
access: {
|
|
579
|
+
async log(input) {
|
|
580
|
+
const log = accessStore();
|
|
581
|
+
if (typeof input.actor !== "string" || input.actor.length === 0) {
|
|
582
|
+
throw new DpdpError("invalid-actor", "actor must be a non-empty string: who is accessing the data");
|
|
583
|
+
}
|
|
584
|
+
const subjects = input.subjectIds ?? (input.subjectId !== void 0 ? [input.subjectId] : []);
|
|
585
|
+
if (subjects.length === 0) throw new DpdpError("invalid-subject", "Pass subjectId or subjectIds");
|
|
586
|
+
for (const id of subjects) checkSubject(id);
|
|
587
|
+
if (!purposes[input.purpose]) {
|
|
588
|
+
throw new DpdpError("unknown-purpose", `Unknown purpose ${JSON.stringify(input.purpose)}`);
|
|
589
|
+
}
|
|
590
|
+
const { fields, unknown } = resolveFields(config, input.fields ?? []);
|
|
591
|
+
if (unknown.length > 0) {
|
|
592
|
+
throw new DpdpError(
|
|
593
|
+
"unknown-field",
|
|
594
|
+
`Not in the data map: ${unknown.map((k) => JSON.stringify(k)).join(", ")}. Use keys like "users.phone" or "users".`
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
const outside = fieldsOutsidePurpose(config, fields, input.purpose);
|
|
598
|
+
const at = nowIso();
|
|
599
|
+
const entries = [...new Set(subjects)].map((subjectId) => ({
|
|
600
|
+
id: accessId(at),
|
|
601
|
+
at,
|
|
602
|
+
actor: input.actor,
|
|
603
|
+
subjectId,
|
|
604
|
+
action: input.action ?? "read",
|
|
605
|
+
purpose: input.purpose,
|
|
606
|
+
...fields.length > 0 ? { fields } : {},
|
|
607
|
+
...outside.length > 0 ? { outOfPurpose: outside } : {},
|
|
608
|
+
...input.reason !== void 0 ? { reason: input.reason } : {},
|
|
609
|
+
...input.evidence !== void 0 ? { evidence: { ...input.evidence } } : {}
|
|
610
|
+
}));
|
|
611
|
+
await log.insertAccess(entries);
|
|
612
|
+
emit("access.logged", { entries });
|
|
613
|
+
if (outside.length > 0 && options.access?.outOfPurpose === "throw") {
|
|
614
|
+
throw new DpdpError(
|
|
615
|
+
"out-of-purpose",
|
|
616
|
+
`${outside.join(", ")} ${outside.length === 1 ? "isn't" : "aren't"} held for "${input.purpose}". The attempt was logged.`
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
return entries;
|
|
620
|
+
},
|
|
621
|
+
list: (filter = {}) => accessStore().listAccess(filter),
|
|
622
|
+
async review(input = {}) {
|
|
623
|
+
const to = input.to ?? nowIso();
|
|
624
|
+
const from = input.from ?? new Date(Date.parse(to) - durationMs("1d")).toISOString();
|
|
625
|
+
const entries = await accessStore().listAccess(input.to ? { from, to } : { from });
|
|
626
|
+
return reviewAccess({
|
|
627
|
+
config,
|
|
628
|
+
entries,
|
|
629
|
+
from,
|
|
630
|
+
to,
|
|
631
|
+
history: (subjectId) => store.events(subjectId),
|
|
632
|
+
window: input.window ?? "1h",
|
|
633
|
+
maxSubjects: input.maxSubjects ?? 100,
|
|
634
|
+
ignoreActors: input.ignoreActors ?? []
|
|
635
|
+
});
|
|
636
|
+
},
|
|
637
|
+
async prune() {
|
|
638
|
+
const keep = config.security?.accessLogRetention ?? DEFAULT_ACCESS_LOG_RETENTION;
|
|
639
|
+
const keepMs = Math.max(durationMs(keep), durationMs(DEFAULT_ACCESS_LOG_RETENTION));
|
|
640
|
+
const before = new Date(now().getTime() - keepMs).toISOString();
|
|
641
|
+
return { deleted: await accessStore().pruneAccess(before), before };
|
|
642
|
+
}
|
|
643
|
+
},
|
|
567
644
|
rights: {
|
|
568
645
|
async open(subjectId, type, details) {
|
|
569
646
|
checkSubject(subjectId);
|
|
@@ -582,6 +659,7 @@ ${lines.join("\n")}`, issues);
|
|
|
582
659
|
history: [{ at: openedAt, status: "open" }]
|
|
583
660
|
};
|
|
584
661
|
await fullStore("Rights requests").insertRequest(request);
|
|
662
|
+
emit("rights.opened", { request });
|
|
585
663
|
return request;
|
|
586
664
|
},
|
|
587
665
|
get: (id) => fullStore("Rights requests").getRequest(id),
|
|
@@ -621,6 +699,7 @@ ${lines.join("\n")}`, issues);
|
|
|
621
699
|
}
|
|
622
700
|
}
|
|
623
701
|
};
|
|
702
|
+
return api;
|
|
624
703
|
}
|
|
625
704
|
|
|
626
705
|
// src/data-access.ts
|
|
@@ -632,9 +711,9 @@ function memoryData(tables) {
|
|
|
632
711
|
async read(table, subjectColumn, subjectId, columns) {
|
|
633
712
|
return rowsOf(table).filter(mine(subjectColumn, subjectId)).map((row) => Object.fromEntries(columns.map((c) => [c, row[c] ?? null])));
|
|
634
713
|
},
|
|
635
|
-
async eraseFields(table, subjectColumn, subjectId, columns) {
|
|
714
|
+
async eraseFields(table, subjectColumn, subjectId, columns, values = {}) {
|
|
636
715
|
const rows = rowsOf(table).filter(mine(subjectColumn, subjectId));
|
|
637
|
-
for (const row of rows) for (const c of columns) row[c] = null;
|
|
716
|
+
for (const row of rows) for (const c of columns) row[c] = Object.hasOwn(values, c) ? values[c] : null;
|
|
638
717
|
return rows.length;
|
|
639
718
|
},
|
|
640
719
|
async deleteRows(table, subjectColumn, subjectId) {
|
|
@@ -646,9 +725,11 @@ function memoryData(tables) {
|
|
|
646
725
|
}
|
|
647
726
|
export {
|
|
648
727
|
CONSENT_REQUIRED_BODY,
|
|
728
|
+
DEFAULT_ACCESS_LOG_RETENTION,
|
|
649
729
|
DEFAULT_RESPONSE_WITHIN,
|
|
650
730
|
DpdpError,
|
|
651
731
|
NOTICE_LANGUAGES,
|
|
732
|
+
REDACTED,
|
|
652
733
|
REQUEST_TYPES,
|
|
653
734
|
SeqConflictError,
|
|
654
735
|
audit,
|
|
@@ -656,16 +737,21 @@ export {
|
|
|
656
737
|
createDpdp,
|
|
657
738
|
defineConfig,
|
|
658
739
|
durationMs,
|
|
740
|
+
erasedValue,
|
|
741
|
+
formatSafeguards,
|
|
659
742
|
guessPersonal,
|
|
660
743
|
hasErrors,
|
|
661
744
|
hashEvent,
|
|
745
|
+
isAccessLogStore,
|
|
662
746
|
isDpdpStore,
|
|
663
747
|
isDuration,
|
|
748
|
+
isHighRisk,
|
|
664
749
|
isNoticeLanguage,
|
|
665
750
|
memoryData,
|
|
666
751
|
memoryStore,
|
|
667
752
|
planErasure,
|
|
668
753
|
purposeNames,
|
|
754
|
+
safeguardsReport,
|
|
669
755
|
tasksFromPlan,
|
|
670
756
|
tokenize
|
|
671
757
|
};
|
package/dist/nestjs.d.ts
ADDED
|
@@ -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,74 @@
|
|
|
1
|
+
type KeyInput = string | Uint8Array;
|
|
2
|
+
/** A new random 256-bit key, as base64url text. Keep it in your secrets manager, not in code. */
|
|
3
|
+
export declare function generateKey(): string;
|
|
4
|
+
export interface EncryptorOptions {
|
|
5
|
+
/** Keys by id, each 32 bytes: base64 or base64url text (see `generateKey()`) or bytes. */
|
|
6
|
+
keys: Record<string, KeyInput>;
|
|
7
|
+
/** The id of the key that encrypts. The others only decrypt older values, so you can rotate keys. */
|
|
8
|
+
current: string;
|
|
9
|
+
}
|
|
10
|
+
export interface Encryptor {
|
|
11
|
+
/**
|
|
12
|
+
* Encrypt a value with AES-256-GCM. Each call uses a fresh random IV, so the same value encrypts
|
|
13
|
+
* differently every time; use `createTokenizer` to look values up. Pass `context` (for example
|
|
14
|
+
* `"users.phone:42"`) to bind the ciphertext to one place: decrypting it with another context
|
|
15
|
+
* fails, so a copied value can't be moved to another row.
|
|
16
|
+
*/
|
|
17
|
+
encrypt(plaintext: string, context?: string): string;
|
|
18
|
+
/** Decrypt a value from `encrypt`. Throws `DpdpError("decrypt-failed")` if it was changed, or the key or context is wrong. */
|
|
19
|
+
decrypt(ciphertext: string, context?: string): string;
|
|
20
|
+
/** Whether a value looks like the output of `encrypt`. */
|
|
21
|
+
isEncrypted(value: string): boolean;
|
|
22
|
+
/** Whether a value was encrypted with a key other than `current`, and should be re-encrypted. */
|
|
23
|
+
needsRotation(ciphertext: string): boolean;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Field encryption for personal data at rest.
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* const crypto = createEncryptor({ keys: { k1: process.env.DPDP_KEY_1! }, current: "k1" });
|
|
30
|
+
* const stored = crypto.encrypt(user.aadhaar, `users.aadhaar:${user.id}`);
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function createEncryptor(options: EncryptorOptions): Encryptor;
|
|
34
|
+
export interface TokenizerOptions {
|
|
35
|
+
/** A secret key, at least 32 bytes (see `generateKey()`). Use a different key from encryption. */
|
|
36
|
+
key: KeyInput;
|
|
37
|
+
/**
|
|
38
|
+
* Make equal values equal before tokenising, e.g. lower-case an email or strip spaces from a phone
|
|
39
|
+
* number. Default: trim surrounding whitespace.
|
|
40
|
+
*/
|
|
41
|
+
normalize?: (value: string) => string;
|
|
42
|
+
}
|
|
43
|
+
export interface Tokenizer {
|
|
44
|
+
/**
|
|
45
|
+
* A stable token for a value (keyed HMAC-SHA256): the same value always gives the same token, and
|
|
46
|
+
* without the key the token reveals nothing about the value. Store it beside the encrypted value
|
|
47
|
+
* and look rows up by it, or use it in place of the value where you only need to match.
|
|
48
|
+
*/
|
|
49
|
+
token(value: string): string;
|
|
50
|
+
}
|
|
51
|
+
/** Virtual tokens mapped to personal data, for lookups without storing the value in the clear. */
|
|
52
|
+
export declare function createTokenizer(options: TokenizerOptions): Tokenizer;
|
|
53
|
+
export interface MaskOptions {
|
|
54
|
+
/** Characters to leave visible at the start. Default 0. */
|
|
55
|
+
keepStart?: number;
|
|
56
|
+
/** Characters to leave visible at the end. Default 4. */
|
|
57
|
+
keepEnd?: number;
|
|
58
|
+
/** Replacement character. Default `"•"`. */
|
|
59
|
+
char?: string;
|
|
60
|
+
}
|
|
61
|
+
/** Hide all but a few characters of a value, for showing on screens and in logs. */
|
|
62
|
+
export declare function mask(value: string, options?: MaskOptions): string;
|
|
63
|
+
/** `"+91 98765 43210"` → `"+91 ••••••3210"`. Keeps an Indian country code if there is one. */
|
|
64
|
+
export declare function maskPhone(value: string): string;
|
|
65
|
+
/** `"asha.k@gmail.com"` → `"a•••••@gmail.com"`. The domain stays, so support staff can tell accounts apart. */
|
|
66
|
+
export declare function maskEmail(value: string): string;
|
|
67
|
+
/**
|
|
68
|
+
* `"1234 5678 9012"` → `"XXXX XXXX 9012"`: the masked Aadhaar format, which shows only the last four
|
|
69
|
+
* digits.
|
|
70
|
+
*/
|
|
71
|
+
export declare function maskAadhaar(value: string): string;
|
|
72
|
+
/** `"ABCDE1234F"` → `"XXXXXX234F"`. */
|
|
73
|
+
export declare function maskPan(value: string): string;
|
|
74
|
+
export {};
|