dpdp-kit 0.3.0 → 0.4.1

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/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { type AccessAction, type AccessEntry, type AccessFilter, type AccessFinding, type AccessFindingKind, type AccessLogStore, type AccessReview, DEFAULT_ACCESS_LOG_RETENTION, isAccessLogStore, } from "./access.js";
2
+ export { BOARD_REPORT_WITHIN_HOURS, type BoardReport, type BoardReportInput, type Breach, type BreachInput, type BreachNotice, type BreachStatus, type BreachStore, breachStatus, isBreachStore, type NoticeCounts, type PersonNotice, personNotice, } from "./breach.js";
2
3
  export { audit, hasErrors, isHighRisk, type Issue, type IssueLevel } from "./audit.js";
3
4
  export { type Basis, type Category, type DpdpConfig, defineConfig, type ErasedValue, erasedValue, type EraseWith, type FiduciaryDef, type LegalHold, type PersonalField, type ProcessorDef, type PurposeDef, type Protection, type PurposeOf, REDACTED, type RightsConfig, type SecurityConfig, purposeNames, type Retention, type TableDef, } from "./config.js";
4
5
  export { type AccessInput, type AccessOptions, type ConsentMeta, createDpdp, type DailyReport, type DpdpEventName, type DpdpEvents, type DpdpListener, type Dpdp, type DpdpOptions, hashEvent, type VerifyResult, } from "./dpdp.js";
package/dist/index.js CHANGED
@@ -24,7 +24,7 @@ import {
24
24
  reviewAccess,
25
25
  safeguardsReport,
26
26
  tokenize
27
- } from "./chunk-YOEAZX65.js";
27
+ } from "./chunk-HXVP446N.js";
28
28
  import {
29
29
  CONSENT_REQUIRED_BODY
30
30
  } from "./chunk-5TVA2TKG.js";
@@ -33,6 +33,72 @@ import {
33
33
  SeqConflictError
34
34
  } from "./chunk-67Q5GFD6.js";
35
35
 
36
+ // src/breach.ts
37
+ var BOARD_REPORT_WITHIN_HOURS = 72;
38
+ function isBreachStore(store) {
39
+ const s = store;
40
+ return typeof s.insertBreach === "function" && typeof s.addNotices === "function" && typeof s.countNotices === "function";
41
+ }
42
+ var REPORT_PARTS = [
43
+ ["details", "(i) updated and detailed information"],
44
+ ["facts", "(ii) the facts, circumstances and reasons"],
45
+ ["mitigation", "(iii) measures to mitigate the risk"],
46
+ ["findings", "(iv) findings about who caused it"],
47
+ ["remedial", "(v) measures to prevent recurrence"]
48
+ ];
49
+ function breachStatus(breach, counts, now) {
50
+ const missing = REPORT_PARTS.filter(([k]) => !breach.report[k]).map(([k]) => k);
51
+ const sent = breach.reportSentAt !== void 0;
52
+ const hoursLeft = Math.round((Date.parse(breach.reportDueAt) - Date.parse(now)) / 36e5 * 10) / 10;
53
+ const pending = counts.total - counts.sent;
54
+ const todo = [];
55
+ if (breach.status === "open") {
56
+ if (!breach.boardNotifiedAt) todo.push("Tell the Board without delay: nature, extent, timing, location and likely impact (Rule 7(2)(a)).");
57
+ if (pending > 0) todo.push(`Tell ${pending} affected ${pending === 1 ? "person" : "people"} without delay (Rule 7(1)).`);
58
+ if (counts.total === 0) todo.push("Record who is affected, so each person can be told (Rule 7(1)).");
59
+ if (!sent) {
60
+ todo.push(
61
+ hoursLeft >= 0 ? `Send the Board the detailed report within ${hoursLeft} hours (Rule 7(2)(b)).${missing.length ? ` Still missing: ${REPORT_PARTS.filter(([k]) => missing.includes(k)).map(([, label]) => label).join("; ")}.` : ""}` : `The detailed report to the Board was due ${-hoursLeft} hours ago (Rule 7(2)(b)). Send it now, or record the Board's written extension.`
62
+ );
63
+ }
64
+ }
65
+ return {
66
+ id: breach.id,
67
+ status: breach.status,
68
+ awareAt: breach.awareAt,
69
+ boardNotified: breach.boardNotifiedAt !== void 0,
70
+ report: { dueAt: breach.reportDueAt, sent, overdue: !sent && hoursLeft < 0, hoursLeft, missing },
71
+ people: { total: counts.total, sent: counts.sent, pending },
72
+ todo
73
+ };
74
+ }
75
+ function personNotice(config, breach) {
76
+ const when = breach.occurredAt ? ` It happened on ${breach.occurredAt.slice(0, 10)}` : "";
77
+ const description = `${breach.description.trim()}${breach.extent ? ` ${breach.extent.trim()}` : ""}${when ? `${when}.` : ""}`;
78
+ const contact = config.fiduciary.dpo ? `If you have questions, contact ${config.fiduciary.dpo}, on behalf of ${config.fiduciary.name}.` : "";
79
+ const missing = [];
80
+ if (!breach.consequences) missing.push("consequences");
81
+ if (!breach.measures) missing.push("measures");
82
+ if (!breach.safetySteps) missing.push("safetySteps");
83
+ if (!contact) missing.push("contact");
84
+ const parts = {
85
+ description,
86
+ consequences: breach.consequences?.trim() ?? "",
87
+ measures: breach.measures?.trim() ?? "",
88
+ safetySteps: breach.safetySteps?.trim() ?? "",
89
+ contact
90
+ };
91
+ const text = [
92
+ `We're writing to tell you about a personal data breach at ${config.fiduciary.name}.`,
93
+ `What happened: ${parts.description}`,
94
+ parts.consequences && `What this may mean for you: ${parts.consequences}`,
95
+ parts.measures && `What we're doing: ${parts.measures}`,
96
+ parts.safetySteps && `What you can do: ${parts.safetySteps}`,
97
+ parts.contact
98
+ ].filter(Boolean).join("\n\n");
99
+ return { ...parts, text, missing };
100
+ }
101
+
36
102
  // src/dpdp.ts
37
103
  import { randomUUID as randomUUID2 } from "crypto";
38
104
 
@@ -401,6 +467,43 @@ ${lines.join("\n")}`, issues);
401
467
  });
402
468
  }
403
469
  }
470
+ function breachStore() {
471
+ if (!isBreachStore(store)) {
472
+ throw new DpdpError(
473
+ "store-unsupported",
474
+ "Breach records need a store that keeps them: memoryStore(), drizzleStore(db), or your own BreachStore"
475
+ );
476
+ }
477
+ return store;
478
+ }
479
+ function checkIso(value, name) {
480
+ if (value !== void 0 && (typeof value !== "string" || Number.isNaN(Date.parse(value)))) {
481
+ throw new DpdpError("invalid-input", `${name} must be an ISO 8601 date and time, e.g. "2027-06-01T10:00:00Z"`);
482
+ }
483
+ }
484
+ async function requireBreach(id, open = false) {
485
+ const breach = await breachStore().getBreach(id);
486
+ if (!breach) throw new DpdpError("breach-not-found", `No breach with id ${JSON.stringify(id)}`);
487
+ if (open && breach.status !== "open") throw new DpdpError("breach-closed", `Breach ${id} is closed`);
488
+ return breach;
489
+ }
490
+ async function changeBreach(id, change, event, note) {
491
+ for (let attempt = 1; ; attempt++) {
492
+ const breach = await requireBreach(id, true);
493
+ const next = { ...change(breach), history: [...breach.history, { at: nowIso(), event, ...note !== void 0 ? { note } : {} }] };
494
+ if (await breachStore().updateBreach(next) !== false) return next;
495
+ if (attempt >= maxRetries) throw new DpdpError("write-conflict", `Gave up after ${maxRetries} conflicting updates to breach ${id}`);
496
+ await new Promise((r) => setTimeout(r, Math.random() * 5 * attempt));
497
+ }
498
+ }
499
+ function breachFields(keys) {
500
+ const { fields, unknown } = resolveFields(config, keys ?? []);
501
+ if (unknown.length > 0) {
502
+ throw new DpdpError("unknown-field", `Not in the data map: ${unknown.map((k) => JSON.stringify(k)).join(", ")}`);
503
+ }
504
+ return fields;
505
+ }
506
+ const BREACH_TEXT = ["occurredAt", "description", "extent", "location", "likelyImpact", "consequences", "measures", "safetySteps"];
404
507
  function accessStore() {
405
508
  if (!isAccessLogStore(store)) {
406
509
  throw new DpdpError(
@@ -463,6 +566,15 @@ ${lines.join("\n")}`, issues);
463
566
  } else {
464
567
  report.skipped.push("retention", "rights");
465
568
  }
569
+ if (isBreachStore(store)) {
570
+ await step("breaches", async () => {
571
+ const open = await breachStore().listBreaches({ status: "open" });
572
+ const now2 = nowIso();
573
+ report.breaches = await Promise.all(open.map(async (b) => breachStatus(b, await breachStore().countNotices(b.id), now2)));
574
+ });
575
+ } else {
576
+ report.skipped.push("breaches");
577
+ }
466
578
  if (isAccessLogStore(store)) {
467
579
  await step("access-prune", async () => {
468
580
  report.accessPruned = (await api.access.prune()).deleted;
@@ -641,6 +753,124 @@ ${lines.join("\n")}`, issues);
641
753
  return { deleted: await accessStore().pruneAccess(before), before };
642
754
  }
643
755
  },
756
+ breach: {
757
+ async open(input) {
758
+ if (!input || typeof input.description !== "string" || input.description.trim() === "") {
759
+ throw new DpdpError("invalid-input", "Describe the breach: description is required (Rule 7(1)(a), 7(2)(a))");
760
+ }
761
+ checkIso(input.awareAt, "awareAt");
762
+ checkIso(input.occurredAt, "occurredAt");
763
+ const awareAt = input.awareAt ? new Date(input.awareAt).toISOString() : nowIso();
764
+ const text = Object.fromEntries(BREACH_TEXT.filter((k) => input[k] !== void 0).map((k) => [k, input[k]]));
765
+ const breach = {
766
+ id: randomUUID2(),
767
+ ...text,
768
+ description: input.description,
769
+ awareAt,
770
+ fields: breachFields(input.fields),
771
+ reportDueAt: new Date(Date.parse(awareAt) + BOARD_REPORT_WITHIN_HOURS * 36e5).toISOString(),
772
+ report: {},
773
+ status: "open",
774
+ history: [{ at: nowIso(), event: "opened" }]
775
+ };
776
+ await breachStore().insertBreach(breach);
777
+ emit("breach.opened", { breach });
778
+ return breach;
779
+ },
780
+ async update(id, input) {
781
+ checkIso(input.occurredAt, "occurredAt");
782
+ const text = Object.fromEntries(BREACH_TEXT.filter((k) => input[k] !== void 0).map((k) => [k, input[k]]));
783
+ const fields = input.fields ? { fields: breachFields(input.fields) } : {};
784
+ return changeBreach(id, (breach) => ({ ...breach, ...text, ...fields }), "updated");
785
+ },
786
+ get: (id) => breachStore().getBreach(id),
787
+ list: (filter = {}) => breachStore().listBreaches(filter),
788
+ async status(id) {
789
+ const breach = await requireBreach(id);
790
+ return breachStatus(breach, await breachStore().countNotices(id), nowIso());
791
+ },
792
+ async addAffected(id, subjectIds) {
793
+ await requireBreach(id, true);
794
+ for (const subjectId of subjectIds) checkSubject(subjectId);
795
+ const addedAt = nowIso();
796
+ return breachStore().addNotices([...new Set(subjectIds)].map((subjectId) => ({ breachId: id, subjectId, status: "pending", addedAt })));
797
+ },
798
+ async addAffectedFromAccessLog(id, filter) {
799
+ await requireBreach(id, true);
800
+ const { limit: _, ...where } = filter;
801
+ const access = accessStore();
802
+ const subjects = access.accessSubjects ? await access.accessSubjects(where) : [...new Set((await access.listAccess(where)).map((e) => e.subjectId))];
803
+ let added = 0;
804
+ for (let i = 0; i < subjects.length; i += 5e3) added += await api.breach.addAffected(id, subjects.slice(i, i + 5e3));
805
+ return added;
806
+ },
807
+ async notice(id) {
808
+ return personNotice(config, await requireBreach(id));
809
+ },
810
+ pending: async (id, limit) => {
811
+ await requireBreach(id);
812
+ return breachStore().listNotices(id, { status: "pending", ...limit !== void 0 ? { limit } : {} });
813
+ },
814
+ async markNotified(id, subjectIds, input = {}) {
815
+ await requireBreach(id, true);
816
+ checkIso(input.at, "at");
817
+ const at = input.at ? new Date(input.at).toISOString() : nowIso();
818
+ return breachStore().markNotices(id, [...new Set(subjectIds)], at, input.channel);
819
+ },
820
+ async boardNotified(id, input = {}) {
821
+ checkIso(input.at, "at");
822
+ const at = input.at ? new Date(input.at).toISOString() : nowIso();
823
+ return changeBreach(id, (breach) => ({ ...breach, boardNotifiedAt: at }), "board notified");
824
+ },
825
+ async updateReport(id, parts) {
826
+ const keys = ["details", "facts", "mitigation", "findings", "remedial"];
827
+ const given = Object.fromEntries(keys.filter((k) => parts[k] !== void 0).map((k) => [k, parts[k]]));
828
+ return changeBreach(id, (breach) => ({ ...breach, report: { ...breach.report, ...given } }), "report updated");
829
+ },
830
+ async boardReport(id) {
831
+ const breach = await requireBreach(id);
832
+ const counts = await breachStore().countNotices(id);
833
+ const status = breachStatus(breach, counts, nowIso());
834
+ return {
835
+ breachId: id,
836
+ awareAt: breach.awareAt,
837
+ dueAt: breach.reportDueAt,
838
+ details: breach.report.details ?? "",
839
+ facts: breach.report.facts ?? "",
840
+ mitigation: breach.report.mitigation ?? "",
841
+ findings: breach.report.findings ?? "",
842
+ remedial: breach.report.remedial ?? "",
843
+ intimations: {
844
+ total: counts.total,
845
+ sent: counts.sent,
846
+ pending: counts.total - counts.sent,
847
+ ...counts.firstSentAt ? { firstSentAt: counts.firstSentAt } : {},
848
+ ...counts.lastSentAt ? { lastSentAt: counts.lastSentAt } : {}
849
+ },
850
+ missing: status.report.missing
851
+ };
852
+ },
853
+ async reportSent(id, input = {}) {
854
+ checkIso(input.at, "at");
855
+ const at = input.at ? new Date(input.at).toISOString() : nowIso();
856
+ const saved = await changeBreach(id, (breach) => ({ ...breach, reportSentAt: at }), "report sent");
857
+ emit("breach.reported", { breach: saved });
858
+ return saved;
859
+ },
860
+ async extend(id, input) {
861
+ checkIso(input.until, "until");
862
+ if (!input.reference) throw new DpdpError("invalid-input", "Record the Board's written permission: reference is required");
863
+ const until = new Date(input.until).toISOString();
864
+ const extension = { until, reference: input.reference, recordedAt: nowIso() };
865
+ return changeBreach(id, (breach) => ({ ...breach, reportDueAt: until, extension }), "extended", input.reference);
866
+ },
867
+ async close(id, note) {
868
+ const closedAt = nowIso();
869
+ const saved = await changeBreach(id, (breach) => ({ ...breach, status: "closed", closedAt }), "closed", note);
870
+ emit("breach.closed", { breach: saved });
871
+ return saved;
872
+ }
873
+ },
644
874
  rights: {
645
875
  async open(subjectId, type, details) {
646
876
  checkSubject(subjectId);
@@ -724,6 +954,7 @@ function memoryData(tables) {
724
954
  };
725
955
  }
726
956
  export {
957
+ BOARD_REPORT_WITHIN_HOURS,
727
958
  CONSENT_REQUIRED_BODY,
728
959
  DEFAULT_ACCESS_LOG_RETENTION,
729
960
  DEFAULT_RESPONSE_WITHIN,
@@ -733,6 +964,7 @@ export {
733
964
  REQUEST_TYPES,
734
965
  SeqConflictError,
735
966
  audit,
967
+ breachStatus,
736
968
  checkSchema,
737
969
  createDpdp,
738
970
  defineConfig,
@@ -743,12 +975,14 @@ export {
743
975
  hasErrors,
744
976
  hashEvent,
745
977
  isAccessLogStore,
978
+ isBreachStore,
746
979
  isDpdpStore,
747
980
  isDuration,
748
981
  isHighRisk,
749
982
  isNoticeLanguage,
750
983
  memoryData,
751
984
  memoryStore,
985
+ personNotice,
752
986
  planErasure,
753
987
  purposeNames,
754
988
  safeguardsReport,
@@ -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 {};