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/dist/ddl.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** The same table as plain SQL, if you don't use drizzle-kit for migrations. */
2
+ export declare const CONSENT_EVENTS_DDL = "CREATE TABLE IF NOT EXISTS dpdp_consent_events (\n subject_id text NOT NULL,\n seq integer NOT NULL,\n action text NOT NULL CHECK (action IN ('grant', 'withdraw')),\n purposes jsonb NOT NULL,\n notice_version text,\n language text,\n channel text,\n evidence jsonb,\n at timestamptz NOT NULL,\n prev_hash text,\n hash text NOT NULL,\n PRIMARY KEY (subject_id, seq)\n);";
3
+ /** Rights requests and erasure tasks as plain SQL, if you don't use drizzle-kit for migrations. */
4
+ export declare const RECORDS_DDL = "CREATE TABLE IF NOT EXISTS dpdp_requests (\n id text PRIMARY KEY,\n subject_id text NOT NULL,\n type text NOT NULL,\n status text NOT NULL,\n opened_at timestamptz NOT NULL,\n due_at timestamptz NOT NULL,\n closed_at timestamptz,\n details jsonb,\n history jsonb NOT NULL\n);\nCREATE INDEX IF NOT EXISTS dpdp_requests_subject_idx ON dpdp_requests (subject_id);\nCREATE INDEX IF NOT EXISTS dpdp_requests_status_due_idx ON dpdp_requests (status, due_at);\nCREATE TABLE IF NOT EXISTS dpdp_erasure_tasks (\n id text PRIMARY KEY,\n subject_id text NOT NULL,\n reason text NOT NULL,\n kind text NOT NULL,\n table_key text,\n fields jsonb,\n processor text,\n purposes jsonb,\n created_at timestamptz NOT NULL,\n due_at timestamptz NOT NULL,\n status text NOT NULL,\n attempts integer NOT NULL,\n claimed_at timestamptz,\n done_at timestamptz,\n affected integer,\n last_error text,\n note text\n);\nCREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_subject_idx ON dpdp_erasure_tasks (subject_id);\nCREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_status_due_idx ON dpdp_erasure_tasks (status, due_at);";
5
+ /** The access log as plain SQL, if you don't use drizzle-kit for migrations. */
6
+ export declare const ACCESS_LOG_DDL = "CREATE TABLE IF NOT EXISTS dpdp_access_log (\n id text PRIMARY KEY,\n at timestamptz NOT NULL,\n actor text NOT NULL,\n subject_id text NOT NULL,\n action text NOT NULL,\n purpose text NOT NULL,\n fields jsonb,\n out_of_purpose jsonb,\n reason text,\n evidence jsonb\n);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_at_idx ON dpdp_access_log (at);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_subject_idx ON dpdp_access_log (subject_id, at);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_actor_idx ON dpdp_access_log (actor, at);";
7
+ /** The breach tables as plain SQL, if you don't use drizzle-kit for migrations. */
8
+ export declare const BREACH_DDL = "CREATE TABLE IF NOT EXISTS dpdp_breaches (\n id text PRIMARY KEY,\n status text NOT NULL,\n aware_at timestamptz NOT NULL,\n report_due_at timestamptz NOT NULL,\n data jsonb NOT NULL\n);\nCREATE INDEX IF NOT EXISTS dpdp_breaches_status_idx ON dpdp_breaches (status, aware_at);\nCREATE TABLE IF NOT EXISTS dpdp_breach_notices (\n breach_id text NOT NULL,\n subject_id text NOT NULL,\n status text NOT NULL,\n added_at timestamptz NOT NULL,\n sent_at timestamptz,\n channel text,\n PRIMARY KEY (breach_id, subject_id)\n);\nCREATE INDEX IF NOT EXISTS dpdp_breach_notices_status_idx ON dpdp_breach_notices (breach_id, status, added_at);";
9
+ /** Every dpdp-kit table as plain SQL. */
10
+ export declare const DPDP_DDL = "CREATE TABLE IF NOT EXISTS dpdp_consent_events (\n subject_id text NOT NULL,\n seq integer NOT NULL,\n action text NOT NULL CHECK (action IN ('grant', 'withdraw')),\n purposes jsonb NOT NULL,\n notice_version text,\n language text,\n channel text,\n evidence jsonb,\n at timestamptz NOT NULL,\n prev_hash text,\n hash text NOT NULL,\n PRIMARY KEY (subject_id, seq)\n);\nCREATE TABLE IF NOT EXISTS dpdp_requests (\n id text PRIMARY KEY,\n subject_id text NOT NULL,\n type text NOT NULL,\n status text NOT NULL,\n opened_at timestamptz NOT NULL,\n due_at timestamptz NOT NULL,\n closed_at timestamptz,\n details jsonb,\n history jsonb NOT NULL\n);\nCREATE INDEX IF NOT EXISTS dpdp_requests_subject_idx ON dpdp_requests (subject_id);\nCREATE INDEX IF NOT EXISTS dpdp_requests_status_due_idx ON dpdp_requests (status, due_at);\nCREATE TABLE IF NOT EXISTS dpdp_erasure_tasks (\n id text PRIMARY KEY,\n subject_id text NOT NULL,\n reason text NOT NULL,\n kind text NOT NULL,\n table_key text,\n fields jsonb,\n processor text,\n purposes jsonb,\n created_at timestamptz NOT NULL,\n due_at timestamptz NOT NULL,\n status text NOT NULL,\n attempts integer NOT NULL,\n claimed_at timestamptz,\n done_at timestamptz,\n affected integer,\n last_error text,\n note text\n);\nCREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_subject_idx ON dpdp_erasure_tasks (subject_id);\nCREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_status_due_idx ON dpdp_erasure_tasks (status, due_at);\nCREATE TABLE IF NOT EXISTS dpdp_access_log (\n id text PRIMARY KEY,\n at timestamptz NOT NULL,\n actor text NOT NULL,\n subject_id text NOT NULL,\n action text NOT NULL,\n purpose text NOT NULL,\n fields jsonb,\n out_of_purpose jsonb,\n reason text,\n evidence jsonb\n);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_at_idx ON dpdp_access_log (at);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_subject_idx ON dpdp_access_log (subject_id, at);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_actor_idx ON dpdp_access_log (actor, at);\nCREATE TABLE IF NOT EXISTS dpdp_breaches (\n id text PRIMARY KEY,\n status text NOT NULL,\n aware_at timestamptz NOT NULL,\n report_due_at timestamptz NOT NULL,\n data jsonb NOT NULL\n);\nCREATE INDEX IF NOT EXISTS dpdp_breaches_status_idx ON dpdp_breaches (status, aware_at);\nCREATE TABLE IF NOT EXISTS dpdp_breach_notices (\n breach_id text NOT NULL,\n subject_id text NOT NULL,\n status text NOT NULL,\n added_at timestamptz NOT NULL,\n sent_at timestamptz,\n channel text,\n PRIMARY KEY (breach_id, subject_id)\n);\nCREATE INDEX IF NOT EXISTS dpdp_breach_notices_status_idx ON dpdp_breach_notices (breach_id, status, added_at);";
package/dist/dpdp.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type AccessAction, type AccessEntry, type AccessFilter, type AccessReview } from "./access.js";
2
+ import { type Breach, type BreachInput, type BreachNotice, type BoardReport, type BoardReportInput, type BreachStatus, type PersonNotice } from "./breach.js";
2
3
  import type { DpdpConfig } from "./config.js";
3
4
  import type { DataAccess } from "./data-access.js";
4
5
  import { type Duration } from "./duration.js";
@@ -80,6 +81,15 @@ export interface DpdpEvents {
80
81
  "daily.ran": {
81
82
  report: DailyReport;
82
83
  };
84
+ "breach.opened": {
85
+ breach: Breach;
86
+ };
87
+ "breach.reported": {
88
+ breach: Breach;
89
+ };
90
+ "breach.closed": {
91
+ breach: Breach;
92
+ };
83
93
  }
84
94
  /** What `daily()` did. A part the store can't do (a custom store without the access log) is listed in `skipped`. */
85
95
  export interface DailyReport {
@@ -93,10 +103,12 @@ export interface DailyReport {
93
103
  review?: AccessReview;
94
104
  /** Open rights requests past their due date. */
95
105
  overdueRequests?: RightsRequest[];
96
- skipped: Array<"retention" | "access" | "rights">;
106
+ /** Open breaches with their Rule 7 deadlines and what's left to do. */
107
+ breaches?: BreachStatus[];
108
+ skipped: Array<"retention" | "access" | "rights" | "breaches">;
97
109
  /** Steps that failed. The other steps still ran. */
98
110
  errors: Array<{
99
- step: "retention" | "rights" | "access-prune" | "access-review";
111
+ step: "retention" | "rights" | "access-prune" | "access-review" | "breaches";
100
112
  message: string;
101
113
  error: unknown;
102
114
  }>;
@@ -235,6 +247,58 @@ export interface Dpdp<P extends string> {
235
247
  before: string;
236
248
  }>;
237
249
  };
250
+ /**
251
+ * Personal data breaches (Section 8(6), Rule 7): record one, find and tell the people affected,
252
+ * and track the Board's deadlines. Needs a store that keeps breaches: `memoryStore()`,
253
+ * `drizzleStore(db)`, or your own `BreachStore`.
254
+ */
255
+ readonly breach: {
256
+ /** Record a breach. The 72-hour clock for the Board's detailed report starts at `awareAt` (default now). */
257
+ open(input: BreachInput): Promise<Breach>;
258
+ /** Fill in or correct details, e.g. consequences and safety steps once they're known. */
259
+ update(id: string, input: Partial<Omit<BreachInput, "awareAt">>): Promise<Breach>;
260
+ get(id: string): Promise<Breach | undefined>;
261
+ /** Breaches, newest first. */
262
+ list(filter?: {
263
+ status?: Breach["status"];
264
+ }): Promise<Breach[]>;
265
+ /** Deadlines and what's left to do. */
266
+ status(id: string): Promise<BreachStatus>;
267
+ /** Record people affected. People already recorded are left as they are. Returns how many were new. */
268
+ addAffected(id: string, subjectIds: readonly string[]): Promise<number>;
269
+ /**
270
+ * Record as affected everyone in the access log matching the filter, e.g. everyone a compromised
271
+ * account read: `{ actor: "support:ravi", from: "2027-06-01T00:00:00Z" }`. Returns how many were new.
272
+ */
273
+ addAffectedFromAccessLog(id: string, filter: Omit<AccessFilter, "limit">): Promise<number>;
274
+ /** The notice to send each affected person, Rule 7(1)(a)–(e). `missing` lists parts still to fill in. */
275
+ notice(id: string): Promise<PersonNotice>;
276
+ /** People not yet told, oldest first. */
277
+ pending(id: string, limit?: number): Promise<BreachNotice[]>;
278
+ /** Record that these people were told. Returns how many changed. */
279
+ markNotified(id: string, subjectIds: readonly string[], input?: {
280
+ channel?: string;
281
+ at?: string;
282
+ }): Promise<number>;
283
+ /** Record that you told the Board, without delay (Rule 7(2)(a)). */
284
+ boardNotified(id: string, input?: {
285
+ at?: string;
286
+ }): Promise<Breach>;
287
+ /** Save parts (i)–(v) of the detailed report. */
288
+ updateReport(id: string, parts: BoardReportInput): Promise<Breach>;
289
+ /** The detailed report, Rule 7(2)(b)(i)–(vi). Part (vi) comes from the notice records. */
290
+ boardReport(id: string): Promise<BoardReport>;
291
+ /** Record that you sent the detailed report to the Board. */
292
+ reportSent(id: string, input?: {
293
+ at?: string;
294
+ }): Promise<Breach>;
295
+ /** Record a longer period the Board allowed on your written request (Rule 7(2)(b)). */
296
+ extend(id: string, input: {
297
+ until: string;
298
+ reference: string;
299
+ }): Promise<Breach>;
300
+ close(id: string, note?: string): Promise<Breach>;
301
+ };
238
302
  readonly rights: {
239
303
  /** Record a request (Sections 11–14). It's due after `config.rights.responseWithin` (default 90 days). */
240
304
  open(subjectId: string, type: RequestType, details?: Record<string, unknown>): Promise<RightsRequest>;
package/dist/drizzle.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { type PgDatabase } from "drizzle-orm/pg-core";
2
2
  import type { AccessLogStore } from "./access.js";
3
+ import type { Breach, BreachStore } from "./breach.js";
3
4
  import type { DataAccess } from "./data-access.js";
4
5
  import type { RequestStatus, RequestType, TaskKind, TaskStatus } from "./records.js";
5
6
  import type { Schema } from "./schema-check.js";
6
7
  import type { DpdpStore } from "./store.js";
8
+ export { ACCESS_LOG_DDL, BREACH_DDL, CONSENT_EVENTS_DDL, DPDP_DDL, RECORDS_DDL } from "./ddl.js";
7
9
  /**
8
10
  * The consent events table. Export it from your Drizzle schema so drizzle-kit creates it:
9
11
  *
@@ -209,8 +211,6 @@ export declare const consentEvents: import("drizzle-orm/pg-core").PgTableWithCol
209
211
  };
210
212
  dialect: 'pg';
211
213
  }>;
212
- /** The same table as plain SQL, if you don't use drizzle-kit for migrations. */
213
- export declare const CONSENT_EVENTS_DDL = "CREATE TABLE IF NOT EXISTS dpdp_consent_events (\n subject_id text NOT NULL,\n seq integer NOT NULL,\n action text NOT NULL CHECK (action IN ('grant', 'withdraw')),\n purposes jsonb NOT NULL,\n notice_version text,\n language text,\n channel text,\n evidence jsonb,\n at timestamptz NOT NULL,\n prev_hash text,\n hash text NOT NULL,\n PRIMARY KEY (subject_id, seq)\n);";
214
214
  /** Rights requests (Sections 11–14). Export it from your Drizzle schema with `consentEvents`. */
215
215
  export declare const rightsRequests: import("drizzle-orm/pg-core").PgTableWithColumns<{
216
216
  name: "dpdp_requests";
@@ -685,8 +685,6 @@ export declare const erasureTasks: import("drizzle-orm/pg-core").PgTableWithColu
685
685
  };
686
686
  dialect: 'pg';
687
687
  }>;
688
- /** Rights requests and erasure tasks as plain SQL, if you don't use drizzle-kit for migrations. */
689
- export declare const RECORDS_DDL = "CREATE TABLE IF NOT EXISTS dpdp_requests (\n id text PRIMARY KEY,\n subject_id text NOT NULL,\n type text NOT NULL,\n status text NOT NULL,\n opened_at timestamptz NOT NULL,\n due_at timestamptz NOT NULL,\n closed_at timestamptz,\n details jsonb,\n history jsonb NOT NULL\n);\nCREATE INDEX IF NOT EXISTS dpdp_requests_subject_idx ON dpdp_requests (subject_id);\nCREATE INDEX IF NOT EXISTS dpdp_requests_status_due_idx ON dpdp_requests (status, due_at);\nCREATE TABLE IF NOT EXISTS dpdp_erasure_tasks (\n id text PRIMARY KEY,\n subject_id text NOT NULL,\n reason text NOT NULL,\n kind text NOT NULL,\n table_key text,\n fields jsonb,\n processor text,\n purposes jsonb,\n created_at timestamptz NOT NULL,\n due_at timestamptz NOT NULL,\n status text NOT NULL,\n attempts integer NOT NULL,\n claimed_at timestamptz,\n done_at timestamptz,\n affected integer,\n last_error text,\n note text\n);\nCREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_subject_idx ON dpdp_erasure_tasks (subject_id);\nCREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_status_due_idx ON dpdp_erasure_tasks (status, due_at);";
690
688
  /**
691
689
  * The access log (Rule 6(1)(c) and (e)): who accessed whose personal data, when, for which purpose.
692
690
  * Export it from your Drizzle schema with `consentEvents`.
@@ -874,17 +872,222 @@ export declare const accessLog: import("drizzle-orm/pg-core").PgTableWithColumns
874
872
  };
875
873
  dialect: 'pg';
876
874
  }>;
877
- /** The access log as plain SQL, if you don't use drizzle-kit for migrations. */
878
- export declare const ACCESS_LOG_DDL = "CREATE TABLE IF NOT EXISTS dpdp_access_log (\n id text PRIMARY KEY,\n at timestamptz NOT NULL,\n actor text NOT NULL,\n subject_id text NOT NULL,\n action text NOT NULL,\n purpose text NOT NULL,\n fields jsonb,\n out_of_purpose jsonb,\n reason text,\n evidence jsonb\n);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_at_idx ON dpdp_access_log (at);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_subject_idx ON dpdp_access_log (subject_id, at);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_actor_idx ON dpdp_access_log (actor, at);";
879
- /** Every dpdp-kit table as plain SQL. */
880
- export declare const DPDP_DDL = "CREATE TABLE IF NOT EXISTS dpdp_consent_events (\n subject_id text NOT NULL,\n seq integer NOT NULL,\n action text NOT NULL CHECK (action IN ('grant', 'withdraw')),\n purposes jsonb NOT NULL,\n notice_version text,\n language text,\n channel text,\n evidence jsonb,\n at timestamptz NOT NULL,\n prev_hash text,\n hash text NOT NULL,\n PRIMARY KEY (subject_id, seq)\n);\nCREATE TABLE IF NOT EXISTS dpdp_requests (\n id text PRIMARY KEY,\n subject_id text NOT NULL,\n type text NOT NULL,\n status text NOT NULL,\n opened_at timestamptz NOT NULL,\n due_at timestamptz NOT NULL,\n closed_at timestamptz,\n details jsonb,\n history jsonb NOT NULL\n);\nCREATE INDEX IF NOT EXISTS dpdp_requests_subject_idx ON dpdp_requests (subject_id);\nCREATE INDEX IF NOT EXISTS dpdp_requests_status_due_idx ON dpdp_requests (status, due_at);\nCREATE TABLE IF NOT EXISTS dpdp_erasure_tasks (\n id text PRIMARY KEY,\n subject_id text NOT NULL,\n reason text NOT NULL,\n kind text NOT NULL,\n table_key text,\n fields jsonb,\n processor text,\n purposes jsonb,\n created_at timestamptz NOT NULL,\n due_at timestamptz NOT NULL,\n status text NOT NULL,\n attempts integer NOT NULL,\n claimed_at timestamptz,\n done_at timestamptz,\n affected integer,\n last_error text,\n note text\n);\nCREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_subject_idx ON dpdp_erasure_tasks (subject_id);\nCREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_status_due_idx ON dpdp_erasure_tasks (status, due_at);\nCREATE TABLE IF NOT EXISTS dpdp_access_log (\n id text PRIMARY KEY,\n at timestamptz NOT NULL,\n actor text NOT NULL,\n subject_id text NOT NULL,\n action text NOT NULL,\n purpose text NOT NULL,\n fields jsonb,\n out_of_purpose jsonb,\n reason text,\n evidence jsonb\n);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_at_idx ON dpdp_access_log (at);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_subject_idx ON dpdp_access_log (subject_id, at);\nCREATE INDEX IF NOT EXISTS dpdp_access_log_actor_idx ON dpdp_access_log (actor, at);";
875
+ /** Personal data breaches (Section 8(6), Rule 7). Export it from your Drizzle schema with `consentEvents`. */
876
+ export declare const breaches: import("drizzle-orm/pg-core").PgTableWithColumns<{
877
+ name: "dpdp_breaches";
878
+ schema: undefined;
879
+ columns: {
880
+ id: import("drizzle-orm/pg-core").PgColumn<{
881
+ name: "id";
882
+ tableName: "dpdp_breaches";
883
+ dataType: "string";
884
+ columnType: "PgText";
885
+ data: string;
886
+ driverParam: string;
887
+ notNull: true;
888
+ hasDefault: false;
889
+ isPrimaryKey: true;
890
+ isAutoincrement: false;
891
+ hasRuntimeDefault: false;
892
+ enumValues: [string, ...string[]];
893
+ baseColumn: never;
894
+ identity: undefined;
895
+ generated: undefined;
896
+ }, {}, {}>;
897
+ status: import("drizzle-orm/pg-core").PgColumn<{
898
+ name: "status";
899
+ tableName: "dpdp_breaches";
900
+ dataType: "string";
901
+ columnType: "PgText";
902
+ data: "closed" | "open";
903
+ driverParam: string;
904
+ notNull: true;
905
+ hasDefault: false;
906
+ isPrimaryKey: false;
907
+ isAutoincrement: false;
908
+ hasRuntimeDefault: false;
909
+ enumValues: [string, ...string[]];
910
+ baseColumn: never;
911
+ identity: undefined;
912
+ generated: undefined;
913
+ }, {}, {
914
+ $type: "closed" | "open";
915
+ }>;
916
+ awareAt: import("drizzle-orm/pg-core").PgColumn<{
917
+ name: string;
918
+ tableName: "dpdp_breaches";
919
+ dataType: "date";
920
+ columnType: "PgTimestamp";
921
+ data: Date;
922
+ driverParam: string;
923
+ notNull: true;
924
+ hasDefault: false;
925
+ isPrimaryKey: false;
926
+ isAutoincrement: false;
927
+ hasRuntimeDefault: false;
928
+ enumValues: undefined;
929
+ baseColumn: never;
930
+ identity: undefined;
931
+ generated: undefined;
932
+ }, {}, {}>;
933
+ reportDueAt: import("drizzle-orm/pg-core").PgColumn<{
934
+ name: string;
935
+ tableName: "dpdp_breaches";
936
+ dataType: "date";
937
+ columnType: "PgTimestamp";
938
+ data: Date;
939
+ driverParam: string;
940
+ notNull: true;
941
+ hasDefault: false;
942
+ isPrimaryKey: false;
943
+ isAutoincrement: false;
944
+ hasRuntimeDefault: false;
945
+ enumValues: undefined;
946
+ baseColumn: never;
947
+ identity: undefined;
948
+ generated: undefined;
949
+ }, {}, {}>;
950
+ data: import("drizzle-orm/pg-core").PgColumn<{
951
+ name: "data";
952
+ tableName: "dpdp_breaches";
953
+ dataType: "json";
954
+ columnType: "PgJsonb";
955
+ data: Breach;
956
+ driverParam: unknown;
957
+ notNull: true;
958
+ hasDefault: false;
959
+ isPrimaryKey: false;
960
+ isAutoincrement: false;
961
+ hasRuntimeDefault: false;
962
+ enumValues: undefined;
963
+ baseColumn: never;
964
+ identity: undefined;
965
+ generated: undefined;
966
+ }, {}, {
967
+ $type: Breach;
968
+ }>;
969
+ };
970
+ dialect: 'pg';
971
+ }>;
972
+ /** The people affected by each breach, and whether they've been told (Rule 7(1)). */
973
+ export declare const breachNotices: import("drizzle-orm/pg-core").PgTableWithColumns<{
974
+ name: "dpdp_breach_notices";
975
+ schema: undefined;
976
+ columns: {
977
+ breachId: import("drizzle-orm/pg-core").PgColumn<{
978
+ name: "breach_id";
979
+ tableName: "dpdp_breach_notices";
980
+ dataType: "string";
981
+ columnType: "PgText";
982
+ data: string;
983
+ driverParam: string;
984
+ notNull: true;
985
+ hasDefault: false;
986
+ isPrimaryKey: false;
987
+ isAutoincrement: false;
988
+ hasRuntimeDefault: false;
989
+ enumValues: [string, ...string[]];
990
+ baseColumn: never;
991
+ identity: undefined;
992
+ generated: undefined;
993
+ }, {}, {}>;
994
+ subjectId: import("drizzle-orm/pg-core").PgColumn<{
995
+ name: "subject_id";
996
+ tableName: "dpdp_breach_notices";
997
+ dataType: "string";
998
+ columnType: "PgText";
999
+ data: string;
1000
+ driverParam: string;
1001
+ notNull: true;
1002
+ hasDefault: false;
1003
+ isPrimaryKey: false;
1004
+ isAutoincrement: false;
1005
+ hasRuntimeDefault: false;
1006
+ enumValues: [string, ...string[]];
1007
+ baseColumn: never;
1008
+ identity: undefined;
1009
+ generated: undefined;
1010
+ }, {}, {}>;
1011
+ status: import("drizzle-orm/pg-core").PgColumn<{
1012
+ name: "status";
1013
+ tableName: "dpdp_breach_notices";
1014
+ dataType: "string";
1015
+ columnType: "PgText";
1016
+ data: "pending" | "sent";
1017
+ driverParam: string;
1018
+ notNull: true;
1019
+ hasDefault: false;
1020
+ isPrimaryKey: false;
1021
+ isAutoincrement: false;
1022
+ hasRuntimeDefault: false;
1023
+ enumValues: [string, ...string[]];
1024
+ baseColumn: never;
1025
+ identity: undefined;
1026
+ generated: undefined;
1027
+ }, {}, {
1028
+ $type: "pending" | "sent";
1029
+ }>;
1030
+ addedAt: import("drizzle-orm/pg-core").PgColumn<{
1031
+ name: string;
1032
+ tableName: "dpdp_breach_notices";
1033
+ dataType: "date";
1034
+ columnType: "PgTimestamp";
1035
+ data: Date;
1036
+ driverParam: string;
1037
+ notNull: true;
1038
+ hasDefault: false;
1039
+ isPrimaryKey: false;
1040
+ isAutoincrement: false;
1041
+ hasRuntimeDefault: false;
1042
+ enumValues: undefined;
1043
+ baseColumn: never;
1044
+ identity: undefined;
1045
+ generated: undefined;
1046
+ }, {}, {}>;
1047
+ sentAt: import("drizzle-orm/pg-core").PgColumn<{
1048
+ name: string;
1049
+ tableName: "dpdp_breach_notices";
1050
+ dataType: "date";
1051
+ columnType: "PgTimestamp";
1052
+ data: Date;
1053
+ driverParam: string;
1054
+ notNull: false;
1055
+ hasDefault: false;
1056
+ isPrimaryKey: false;
1057
+ isAutoincrement: false;
1058
+ hasRuntimeDefault: false;
1059
+ enumValues: undefined;
1060
+ baseColumn: never;
1061
+ identity: undefined;
1062
+ generated: undefined;
1063
+ }, {}, {}>;
1064
+ channel: import("drizzle-orm/pg-core").PgColumn<{
1065
+ name: "channel";
1066
+ tableName: "dpdp_breach_notices";
1067
+ dataType: "string";
1068
+ columnType: "PgText";
1069
+ data: string;
1070
+ driverParam: string;
1071
+ notNull: false;
1072
+ hasDefault: false;
1073
+ isPrimaryKey: false;
1074
+ isAutoincrement: false;
1075
+ hasRuntimeDefault: false;
1076
+ enumValues: [string, ...string[]];
1077
+ baseColumn: never;
1078
+ identity: undefined;
1079
+ generated: undefined;
1080
+ }, {}, {}>;
1081
+ };
1082
+ dialect: 'pg';
1083
+ }>;
881
1084
  type AnyPgDatabase = PgDatabase<any, any, any>;
882
1085
  /**
883
1086
  * Store on Postgres through Drizzle: consent events, rights requests and erasure tasks. Works with
884
1087
  * node-postgres, postgres.js, Neon, PGlite and other Drizzle Postgres drivers. Needs the tables
885
- * `consentEvents`, `rightsRequests`, `erasureTasks` and `accessLog` (or `DPDP_DDL`).
1088
+ * `consentEvents`, `rightsRequests`, `erasureTasks`, `accessLog`, `breaches` and `breachNotices` (or `DPDP_DDL`).
886
1089
  */
887
- export declare function drizzleStore(db: AnyPgDatabase): DpdpStore & AccessLogStore;
1090
+ export declare function drizzleStore(db: AnyPgDatabase): DpdpStore & AccessLogStore & BreachStore;
888
1091
  /**
889
1092
  * Read a Drizzle schema module (Postgres, MySQL or SQLite) for `checkSchema()`. Pass the module
890
1093
  * itself, so every exported table is found:
@@ -904,4 +1107,3 @@ export declare function drizzleSchema(module: Record<string, unknown>): Schema;
904
1107
  export declare function drizzleData(db: AnyPgDatabase, options?: {
905
1108
  schema?: Record<string, unknown>;
906
1109
  }): DataAccess;
907
- export {};
package/dist/drizzle.js CHANGED
@@ -1,10 +1,19 @@
1
+ import {
2
+ ACCESS_LOG_DDL,
3
+ BREACH_DDL,
4
+ CONSENT_EVENTS_DDL,
5
+ DPDP_DDL,
6
+ RECORDS_DDL
7
+ } from "./chunk-2ELTZSW3.js";
1
8
  import {
2
9
  SeqConflictError
3
10
  } from "./chunk-67Q5GFD6.js";
4
11
 
5
12
  // src/drizzle.ts
6
- import { and, asc, desc, eq, getTableColumns, getTableName, gte, is, lt, lte, or, sql, Table } from "drizzle-orm";
7
- import { index, integer, jsonb, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
13
+ import { and, asc, count, desc, eq, getTableColumns, getTableName, gte, inArray, is, lt, lte, max, min, or, sql, Table } from "drizzle-orm";
14
+ import { getTableConfig as mysqlTableConfig, MySqlTable } from "drizzle-orm/mysql-core";
15
+ import { getTableConfig as pgTableConfig, index, integer, jsonb, PgTable, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
16
+ import { SQLiteTable, getTableConfig as sqliteTableConfig } from "drizzle-orm/sqlite-core";
8
17
  var consentEvents = pgTable(
9
18
  "dpdp_consent_events",
10
19
  {
@@ -22,20 +31,6 @@ var consentEvents = pgTable(
22
31
  },
23
32
  (t) => [primaryKey({ columns: [t.subjectId, t.seq] })]
24
33
  );
25
- var CONSENT_EVENTS_DDL = `CREATE TABLE IF NOT EXISTS dpdp_consent_events (
26
- subject_id text NOT NULL,
27
- seq integer NOT NULL,
28
- action text NOT NULL CHECK (action IN ('grant', 'withdraw')),
29
- purposes jsonb NOT NULL,
30
- notice_version text,
31
- language text,
32
- channel text,
33
- evidence jsonb,
34
- at timestamptz NOT NULL,
35
- prev_hash text,
36
- hash text NOT NULL,
37
- PRIMARY KEY (subject_id, seq)
38
- );`;
39
34
  var ts = (name) => timestamp(name, { withTimezone: true, mode: "date" });
40
35
  var rightsRequests = pgTable(
41
36
  "dpdp_requests",
@@ -75,40 +70,6 @@ var erasureTasks = pgTable(
75
70
  },
76
71
  (t) => [index("dpdp_erasure_tasks_subject_idx").on(t.subjectId), index("dpdp_erasure_tasks_status_due_idx").on(t.status, t.dueAt)]
77
72
  );
78
- var RECORDS_DDL = `CREATE TABLE IF NOT EXISTS dpdp_requests (
79
- id text PRIMARY KEY,
80
- subject_id text NOT NULL,
81
- type text NOT NULL,
82
- status text NOT NULL,
83
- opened_at timestamptz NOT NULL,
84
- due_at timestamptz NOT NULL,
85
- closed_at timestamptz,
86
- details jsonb,
87
- history jsonb NOT NULL
88
- );
89
- CREATE INDEX IF NOT EXISTS dpdp_requests_subject_idx ON dpdp_requests (subject_id);
90
- CREATE INDEX IF NOT EXISTS dpdp_requests_status_due_idx ON dpdp_requests (status, due_at);
91
- CREATE TABLE IF NOT EXISTS dpdp_erasure_tasks (
92
- id text PRIMARY KEY,
93
- subject_id text NOT NULL,
94
- reason text NOT NULL,
95
- kind text NOT NULL,
96
- table_key text,
97
- fields jsonb,
98
- processor text,
99
- purposes jsonb,
100
- created_at timestamptz NOT NULL,
101
- due_at timestamptz NOT NULL,
102
- status text NOT NULL,
103
- attempts integer NOT NULL,
104
- claimed_at timestamptz,
105
- done_at timestamptz,
106
- affected integer,
107
- last_error text,
108
- note text
109
- );
110
- CREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_subject_idx ON dpdp_erasure_tasks (subject_id);
111
- CREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_status_due_idx ON dpdp_erasure_tasks (status, due_at);`;
112
73
  var accessLog = pgTable(
113
74
  "dpdp_access_log",
114
75
  {
@@ -129,24 +90,40 @@ var accessLog = pgTable(
129
90
  index("dpdp_access_log_actor_idx").on(t.actor, t.at)
130
91
  ]
131
92
  );
132
- var ACCESS_LOG_DDL = `CREATE TABLE IF NOT EXISTS dpdp_access_log (
133
- id text PRIMARY KEY,
134
- at timestamptz NOT NULL,
135
- actor text NOT NULL,
136
- subject_id text NOT NULL,
137
- action text NOT NULL,
138
- purpose text NOT NULL,
139
- fields jsonb,
140
- out_of_purpose jsonb,
141
- reason text,
142
- evidence jsonb
93
+ var breaches = pgTable(
94
+ "dpdp_breaches",
95
+ {
96
+ id: text("id").primaryKey(),
97
+ status: text("status").$type().notNull(),
98
+ awareAt: ts("aware_at").notNull(),
99
+ reportDueAt: ts("report_due_at").notNull(),
100
+ data: jsonb("data").$type().notNull()
101
+ },
102
+ (t) => [index("dpdp_breaches_status_idx").on(t.status, t.awareAt)]
143
103
  );
144
- CREATE INDEX IF NOT EXISTS dpdp_access_log_at_idx ON dpdp_access_log (at);
145
- CREATE INDEX IF NOT EXISTS dpdp_access_log_subject_idx ON dpdp_access_log (subject_id, at);
146
- CREATE INDEX IF NOT EXISTS dpdp_access_log_actor_idx ON dpdp_access_log (actor, at);`;
147
- var DPDP_DDL = `${CONSENT_EVENTS_DDL}
148
- ${RECORDS_DDL}
149
- ${ACCESS_LOG_DDL}`;
104
+ var breachNotices = pgTable(
105
+ "dpdp_breach_notices",
106
+ {
107
+ breachId: text("breach_id").notNull(),
108
+ subjectId: text("subject_id").notNull(),
109
+ status: text("status").$type().notNull(),
110
+ addedAt: ts("added_at").notNull(),
111
+ sentAt: ts("sent_at"),
112
+ channel: text("channel")
113
+ },
114
+ (t) => [primaryKey({ columns: [t.breachId, t.subjectId] }), index("dpdp_breach_notices_status_idx").on(t.breachId, t.status, t.addedAt)]
115
+ );
116
+ function noticeFromRow(row) {
117
+ return {
118
+ breachId: row.breachId,
119
+ subjectId: row.subjectId,
120
+ status: row.status,
121
+ addedAt: row.addedAt.toISOString(),
122
+ ...row.sentAt ? { sentAt: row.sentAt.toISOString() } : {},
123
+ ...row.channel !== null ? { channel: row.channel } : {}
124
+ };
125
+ }
126
+ var breachRow = (b) => ({ id: b.id, status: b.status, awareAt: new Date(b.awareAt), reportDueAt: new Date(b.reportDueAt), data: b });
150
127
  function accessFromRow(row) {
151
128
  return {
152
129
  id: row.id,
@@ -282,18 +259,82 @@ function runnable(when) {
282
259
  }
283
260
  function drizzleStore(db) {
284
261
  return {
262
+ async insertBreach(breach) {
263
+ await db.insert(breaches).values(breachRow(breach));
264
+ },
265
+ async getBreach(id) {
266
+ const rows = await db.select({ data: breaches.data }).from(breaches).where(eq(breaches.id, id)).limit(1);
267
+ return rows[0]?.data;
268
+ },
269
+ async updateBreach(breach) {
270
+ const { id, ...rest } = breachRow(breach);
271
+ const unchanged = sql`jsonb_array_length(${breaches.data}->'history') = ${breach.history.length - 1}`;
272
+ const rows = await db.update(breaches).set(rest).where(and(eq(breaches.id, id), unchanged)).returning({ id: breaches.id });
273
+ return rows.length === 1;
274
+ },
275
+ async listBreaches(filter) {
276
+ const rows = await db.select({ data: breaches.data }).from(breaches).where(filter.status ? eq(breaches.status, filter.status) : void 0).orderBy(desc(breaches.awareAt));
277
+ return rows.map((r) => r.data);
278
+ },
279
+ async addNotices(list) {
280
+ if (list.length === 0) return 0;
281
+ let added = 0;
282
+ for (let i = 0; i < list.length; i += 1e3) {
283
+ const rows = list.slice(i, i + 1e3).map((n) => ({
284
+ breachId: n.breachId,
285
+ subjectId: n.subjectId,
286
+ status: n.status,
287
+ addedAt: new Date(n.addedAt),
288
+ sentAt: n.sentAt ? new Date(n.sentAt) : null,
289
+ channel: n.channel ?? null
290
+ }));
291
+ const inserted = await db.insert(breachNotices).values(rows).onConflictDoNothing().returning({ one: sql`1` });
292
+ added += inserted.length;
293
+ }
294
+ return added;
295
+ },
296
+ async markNotices(breachId, subjectIds, sentAt, channel) {
297
+ let changed = 0;
298
+ for (let i = 0; i < subjectIds.length; i += 1e3) {
299
+ const updated = await db.update(breachNotices).set({ status: "sent", sentAt: new Date(sentAt), channel: channel ?? null }).where(
300
+ and(
301
+ eq(breachNotices.breachId, breachId),
302
+ eq(breachNotices.status, "pending"),
303
+ inArray(breachNotices.subjectId, [...subjectIds.slice(i, i + 1e3)])
304
+ )
305
+ ).returning({ one: sql`1` });
306
+ changed += updated.length;
307
+ }
308
+ return changed;
309
+ },
310
+ async listNotices(breachId, filter) {
311
+ const query = db.select().from(breachNotices).where(and(eq(breachNotices.breachId, breachId), filter.status ? eq(breachNotices.status, filter.status) : void 0)).orderBy(asc(breachNotices.addedAt), asc(breachNotices.subjectId));
312
+ const rows = filter.limit === void 0 ? await query : await query.limit(filter.limit);
313
+ return rows.map(noticeFromRow);
314
+ },
315
+ async countNotices(breachId) {
316
+ const [row] = await db.select({
317
+ total: count(),
318
+ sent: sql`count(*) filter (where ${breachNotices.status} = 'sent')`.mapWith(Number),
319
+ first: min(breachNotices.sentAt),
320
+ last: max(breachNotices.sentAt)
321
+ }).from(breachNotices).where(eq(breachNotices.breachId, breachId));
322
+ return {
323
+ total: Number(row?.total ?? 0),
324
+ sent: Number(row?.sent ?? 0),
325
+ ...row?.first ? { firstSentAt: new Date(row.first).toISOString() } : {},
326
+ ...row?.last ? { lastSentAt: new Date(row.last).toISOString() } : {}
327
+ };
328
+ },
285
329
  async insertAccess(entries) {
286
330
  if (entries.length > 0) await db.insert(accessLog).values(entries.map(accessToRow));
287
331
  },
332
+ async accessSubjects(filter) {
333
+ const rows = await db.selectDistinct({ subjectId: accessLog.subjectId }).from(accessLog).where(accessWhere(filter));
334
+ return rows.map((r) => r.subjectId);
335
+ },
288
336
  async listAccess(filter) {
289
- const where = and(
290
- filter.subjectId ? eq(accessLog.subjectId, filter.subjectId) : void 0,
291
- filter.actor ? eq(accessLog.actor, filter.actor) : void 0,
292
- filter.purpose ? eq(accessLog.purpose, filter.purpose) : void 0,
293
- filter.from ? gte(accessLog.at, new Date(filter.from)) : void 0,
294
- filter.to ? lt(accessLog.at, new Date(filter.to)) : void 0
295
- );
296
- const query = db.select().from(accessLog).where(where).orderBy(asc(accessLog.at), asc(accessLog.id));
337
+ const query = db.select().from(accessLog).where(accessWhere(filter)).orderBy(asc(accessLog.at), asc(accessLog.id));
297
338
  const rows = filter.limit === void 0 ? await query : await query.limit(filter.limit);
298
339
  return rows.map(accessFromRow);
299
340
  },
@@ -391,12 +432,29 @@ function drizzleSchema(module) {
391
432
  if (tables.has(name)) continue;
392
433
  const columns = Object.entries(getTableColumns(value)).map(([key, column]) => {
393
434
  const type = ["string", "number", "boolean"].includes(column.dataType) ? column.dataType : "other";
394
- return { name: column.name, ...key === column.name ? {} : { key }, notNull: column.notNull, type };
435
+ return { name: column.name, ...key === column.name ? {} : { key }, notNull: column.notNull, type, sqlType: column.getSQLType() };
395
436
  });
396
- tables.set(name, { name, columns });
437
+ const references = foreignKeys(value);
438
+ tables.set(name, { name, columns, ...references.length ? { references } : {} });
397
439
  }
398
440
  return { tables: [...tables.values()] };
399
441
  }
442
+ function accessWhere(filter) {
443
+ return and(
444
+ filter.subjectId ? eq(accessLog.subjectId, filter.subjectId) : void 0,
445
+ filter.actor ? eq(accessLog.actor, filter.actor) : void 0,
446
+ filter.purpose ? eq(accessLog.purpose, filter.purpose) : void 0,
447
+ filter.from ? gte(accessLog.at, new Date(filter.from)) : void 0,
448
+ filter.to ? lt(accessLog.at, new Date(filter.to)) : void 0
449
+ );
450
+ }
451
+ function foreignKeys(table) {
452
+ const config = is(table, PgTable) ? pgTableConfig(table) : is(table, MySqlTable) ? mysqlTableConfig(table) : is(table, SQLiteTable) ? sqliteTableConfig(table) : void 0;
453
+ return (config?.foreignKeys ?? []).map((fk) => {
454
+ const ref = fk.reference();
455
+ return { columns: ref.columns.map((c) => c.name), table: getTableName(ref.foreignTable), ...fk.onDelete ? { onDelete: fk.onDelete } : {} };
456
+ });
457
+ }
400
458
  function rowsOf(result) {
401
459
  if (Array.isArray(result)) return result;
402
460
  return result.rows ?? [];
@@ -441,10 +499,13 @@ function drizzleData(db, options = {}) {
441
499
  }
442
500
  export {
443
501
  ACCESS_LOG_DDL,
502
+ BREACH_DDL,
444
503
  CONSENT_EVENTS_DDL,
445
504
  DPDP_DDL,
446
505
  RECORDS_DDL,
447
506
  accessLog,
507
+ breachNotices,
508
+ breaches,
448
509
  consentEvents,
449
510
  drizzleData,
450
511
  drizzleSchema,
package/dist/errors.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Issue } from "./audit.js";
2
- export type DpdpErrorCode = "invalid-config" | "invalid-subject" | "unknown-purpose" | "not-a-consent-purpose" | "no-purposes" | "invalid-language" | "write-conflict" | "store-unsupported" | "no-data-access" | "invalid-request-type" | "request-not-found" | "request-closed" | "task-not-found" | "task-not-manual" | "invalid-actor" | "unknown-field" | "out-of-purpose" | "invalid-key" | "invalid-input" | "decrypt-failed" | "invalid-erase";
2
+ export type DpdpErrorCode = "invalid-config" | "invalid-subject" | "unknown-purpose" | "not-a-consent-purpose" | "no-purposes" | "invalid-language" | "write-conflict" | "store-unsupported" | "no-data-access" | "invalid-request-type" | "request-not-found" | "request-closed" | "task-not-found" | "task-not-manual" | "invalid-actor" | "unknown-field" | "out-of-purpose" | "invalid-key" | "invalid-input" | "decrypt-failed" | "invalid-erase" | "breach-not-found" | "breach-closed";
3
3
  /** Thrown for mistakes in how the library is called. Messages are for developers, not end users. */
4
4
  export declare class DpdpError extends Error {
5
5
  readonly code: DpdpErrorCode;