dpdp-kit 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +240 -17
  3. package/dist/access.d.ts +111 -0
  4. package/dist/audit.d.ts +3 -1
  5. package/dist/breach.d.ts +170 -0
  6. package/dist/chunk-2ELTZSW3.js +94 -0
  7. package/dist/chunk-5TVA2TKG.js +37 -0
  8. package/dist/chunk-HXVP446N.js +1051 -0
  9. package/dist/chunk-KLMR7S7I.js +438 -0
  10. package/dist/cli.js +53 -17
  11. package/dist/config.d.ts +69 -0
  12. package/dist/data-access.d.ts +6 -2
  13. package/dist/ddl.d.ts +10 -0
  14. package/dist/dpdp.d.ts +210 -0
  15. package/dist/drizzle.d.ts +403 -11
  16. package/dist/drizzle.js +209 -56
  17. package/dist/errors.d.ts +1 -1
  18. package/dist/express.d.ts +17 -1
  19. package/dist/express.js +10 -2
  20. package/dist/fastify.d.ts +41 -0
  21. package/dist/fastify.js +25 -0
  22. package/dist/guard.d.ts +19 -0
  23. package/dist/hono.d.ts +16 -1
  24. package/dist/hono.js +11 -2
  25. package/dist/index.d.ts +7 -4
  26. package/dist/index.js +420 -100
  27. package/dist/mongodb.d.ts +87 -0
  28. package/dist/mongodb.js +344 -0
  29. package/dist/nestjs.d.ts +65 -0
  30. package/dist/nestjs.js +41 -0
  31. package/dist/postgres.d.ts +45 -0
  32. package/dist/postgres.js +27 -0
  33. package/dist/prisma.d.ts +43 -0
  34. package/dist/prisma.js +281 -0
  35. package/dist/protect.d.ts +74 -0
  36. package/dist/protect.js +114 -0
  37. package/dist/retention.d.ts +1 -1
  38. package/dist/run-audit.d.ts +13 -1
  39. package/dist/safeguards.d.ts +23 -0
  40. package/dist/schedule.d.ts +37 -0
  41. package/dist/schedule.js +66 -0
  42. package/dist/schema-check.d.ts +25 -8
  43. package/dist/store.d.ts +11 -1
  44. package/package.json +58 -5
  45. package/dist/chunk-FGZAH2NF.js +0 -16
  46. package/dist/chunk-KVTUMHXO.js +0 -491
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, 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,42 +70,88 @@ 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
73
+ var accessLog = pgTable(
74
+ "dpdp_access_log",
75
+ {
76
+ id: text("id").primaryKey(),
77
+ at: ts("at").notNull(),
78
+ actor: text("actor").notNull(),
79
+ subjectId: text("subject_id").notNull(),
80
+ action: text("action").notNull(),
81
+ purpose: text("purpose").notNull(),
82
+ fields: jsonb("fields").$type(),
83
+ outOfPurpose: jsonb("out_of_purpose").$type(),
84
+ reason: text("reason"),
85
+ evidence: jsonb("evidence").$type()
86
+ },
87
+ (t) => [
88
+ index("dpdp_access_log_at_idx").on(t.at),
89
+ index("dpdp_access_log_subject_idx").on(t.subjectId, t.at),
90
+ index("dpdp_access_log_actor_idx").on(t.actor, t.at)
91
+ ]
92
+ );
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)]
88
103
  );
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
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)]
109
115
  );
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
- var DPDP_DDL = `${CONSENT_EVENTS_DDL}
113
- ${RECORDS_DDL}`;
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 });
127
+ function accessFromRow(row) {
128
+ return {
129
+ id: row.id,
130
+ at: row.at.toISOString(),
131
+ actor: row.actor,
132
+ subjectId: row.subjectId,
133
+ action: row.action,
134
+ purpose: row.purpose,
135
+ ...row.fields !== null ? { fields: row.fields } : {},
136
+ ...row.outOfPurpose !== null ? { outOfPurpose: row.outOfPurpose } : {},
137
+ ...row.reason !== null ? { reason: row.reason } : {},
138
+ ...row.evidence !== null ? { evidence: row.evidence } : {}
139
+ };
140
+ }
141
+ function accessToRow(e) {
142
+ return {
143
+ id: e.id,
144
+ at: new Date(e.at),
145
+ actor: e.actor,
146
+ subjectId: e.subjectId,
147
+ action: e.action,
148
+ purpose: e.purpose,
149
+ fields: e.fields ?? null,
150
+ outOfPurpose: e.outOfPurpose ?? null,
151
+ reason: e.reason ?? null,
152
+ evidence: e.evidence ?? null
153
+ };
154
+ }
114
155
  function fromRow(row) {
115
156
  return {
116
157
  subjectId: row.subjectId,
@@ -218,6 +259,95 @@ function runnable(when) {
218
259
  }
219
260
  function drizzleStore(db) {
220
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
+ },
329
+ async insertAccess(entries) {
330
+ if (entries.length > 0) await db.insert(accessLog).values(entries.map(accessToRow));
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
+ },
336
+ async listAccess(filter) {
337
+ const query = db.select().from(accessLog).where(accessWhere(filter)).orderBy(asc(accessLog.at), asc(accessLog.id));
338
+ const rows = filter.limit === void 0 ? await query : await query.limit(filter.limit);
339
+ return rows.map(accessFromRow);
340
+ },
341
+ async pruneAccess(before) {
342
+ const batch = 5e3;
343
+ let total = 0;
344
+ for (; ; ) {
345
+ const ids = db.select({ id: accessLog.id }).from(accessLog).where(lt(accessLog.at, new Date(before))).limit(batch);
346
+ const deleted = await db.delete(accessLog).where(sql`${accessLog.id} IN (${ids})`).returning({ one: sql`1` });
347
+ total += deleted.length;
348
+ if (deleted.length < batch) return total;
349
+ }
350
+ },
221
351
  async lastEvent(subjectId) {
222
352
  const rows = await db.select().from(consentEvents).where(eq(consentEvents.subjectId, subjectId)).orderBy(desc(consentEvents.seq)).limit(1);
223
353
  return rows[0] ? fromRow(rows[0]) : void 0;
@@ -300,13 +430,31 @@ function drizzleSchema(module) {
300
430
  if (!is(value, Table)) continue;
301
431
  const name = getTableName(value);
302
432
  if (tables.has(name)) continue;
303
- const columns = Object.entries(getTableColumns(value)).map(
304
- ([key, column]) => key === column.name ? { name: column.name } : { name: column.name, key }
305
- );
306
- tables.set(name, { name, columns });
433
+ const columns = Object.entries(getTableColumns(value)).map(([key, column]) => {
434
+ const type = ["string", "number", "boolean"].includes(column.dataType) ? column.dataType : "other";
435
+ return { name: column.name, ...key === column.name ? {} : { key }, notNull: column.notNull, type, sqlType: column.getSQLType() };
436
+ });
437
+ const references = foreignKeys(value);
438
+ tables.set(name, { name, columns, ...references.length ? { references } : {} });
307
439
  }
308
440
  return { tables: [...tables.values()] };
309
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
+ }
310
458
  function rowsOf(result) {
311
459
  if (Array.isArray(result)) return result;
312
460
  return result.rows ?? [];
@@ -330,10 +478,10 @@ function drizzleData(db, options = {}) {
330
478
  );
331
479
  return rowsOf(result);
332
480
  },
333
- async eraseFields(table, subjectColumn, subjectId, columns) {
481
+ async eraseFields(table, subjectColumn, subjectId, columns, values = {}) {
334
482
  if (columns.length === 0) return 0;
335
483
  const set = sql.join(
336
- columns.map((c) => sql`${col(table, c)} = NULL`),
484
+ columns.map((c) => Object.hasOwn(values, c) && values[c] !== null ? sql`${col(table, c)} = ${values[c]}` : sql`${col(table, c)} = NULL`),
337
485
  sql`, `
338
486
  );
339
487
  const result = await db.execute(
@@ -350,9 +498,14 @@ function drizzleData(db, options = {}) {
350
498
  };
351
499
  }
352
500
  export {
501
+ ACCESS_LOG_DDL,
502
+ BREACH_DDL,
353
503
  CONSENT_EVENTS_DDL,
354
504
  DPDP_DDL,
355
505
  RECORDS_DDL,
506
+ accessLog,
507
+ breachNotices,
508
+ breaches,
356
509
  consentEvents,
357
510
  drizzleData,
358
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";
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;
package/dist/express.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Dpdp } from "./dpdp.js";
2
- import { type GuardOptions } from "./guard.js";
2
+ import { type AccessLogOptions, type GuardOptions } from "./guard.js";
3
3
  /** The parts of Express's response this middleware uses. */
4
4
  interface ResponseLike {
5
5
  status(code: number): {
@@ -20,4 +20,20 @@ export interface ExpressGuardOptions<Req, Res> extends GuardOptions<Req> {
20
20
  * ```
21
21
  */
22
22
  export declare function requireConsent<P extends string, Req = any, Res extends ResponseLike = any>(dpdp: Dpdp<P>, purpose: P, options: ExpressGuardOptions<Req, Res>): (req: Req, res: Res, next: Next) => void;
23
+ /**
24
+ * Express middleware that records each request in the access log (Rule 6(1)(c)) before the
25
+ * handler runs. If logging fails, or the fields aren't held for the purpose and the instance was
26
+ * created with `access: { outOfPurpose: "throw" }`, the error goes to `next(err)` and the handler
27
+ * doesn't run.
28
+ *
29
+ * ```ts
30
+ * app.get("/admin/users/:id", logAccess(dpdp, {
31
+ * purpose: "account",
32
+ * fields: ["users"],
33
+ * actor: (req) => req.staff?.id,
34
+ * subject: (req) => req.params.id,
35
+ * }), handler);
36
+ * ```
37
+ */
38
+ export declare function logAccess<P extends string, Req = any>(dpdp: Dpdp<P>, options: AccessLogOptions<Req, P>): (req: Req, _res: unknown, next: Next) => void;
23
39
  export {};
package/dist/express.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import {
2
2
  CONSENT_REQUIRED_BODY,
3
- checkConsent
4
- } from "./chunk-FGZAH2NF.js";
3
+ checkConsent,
4
+ recordAccess
5
+ } from "./chunk-5TVA2TKG.js";
6
+ import "./chunk-67Q5GFD6.js";
5
7
 
6
8
  // src/express.ts
7
9
  function requireConsent(dpdp, purpose, options) {
@@ -16,6 +18,12 @@ function requireConsent(dpdp, purpose, options) {
16
18
  );
17
19
  };
18
20
  }
21
+ function logAccess(dpdp, options) {
22
+ return (req, _res, next) => {
23
+ recordAccess(dpdp, options, req).then(() => next(), (err) => next(err));
24
+ };
25
+ }
19
26
  export {
27
+ logAccess,
20
28
  requireConsent
21
29
  };
@@ -0,0 +1,41 @@
1
+ import type { Dpdp } from "./dpdp.js";
2
+ import { type AccessLogOptions, type GuardOptions } from "./guard.js";
3
+ /** The parts of Fastify's reply these hooks use. */
4
+ interface ReplyLike {
5
+ code(statusCode: number): {
6
+ send(payload: unknown): unknown;
7
+ };
8
+ /** Whether a reply has been sent (Fastify sets it). */
9
+ readonly sent?: boolean;
10
+ }
11
+ export interface FastifyGuardOptions<Req, Reply> extends GuardOptions<Req> {
12
+ /** Send your own reply when consent is missing. Default (and if it sends nothing): 403 with a JSON body. */
13
+ onDenied?: (request: Req, reply: Reply, purpose: string) => unknown;
14
+ }
15
+ /**
16
+ * Fastify `preHandler` hook that lets the request through only if the person may be processed for
17
+ * `purpose`.
18
+ *
19
+ * ```ts
20
+ * app.post("/promo", { preHandler: requireConsent(dpdp, "marketing_sms", { subject: (req) => req.user?.id }) }, handler);
21
+ * ```
22
+ */
23
+ export declare function requireConsent<P extends string, Req = any, Reply = any>(dpdp: Dpdp<P>, purpose: P, options: FastifyGuardOptions<Req, Reply>): (request: Req, reply: ReplyLike) => Promise<unknown>;
24
+ /**
25
+ * Fastify `preHandler` hook that records each request in the access log (Rule 6(1)(c)) before the
26
+ * handler runs. Errors (a failed write, or out-of-purpose fields with `access: { outOfPurpose:
27
+ * "throw" }`) go to Fastify's error handler and the handler doesn't run.
28
+ *
29
+ * ```ts
30
+ * app.get("/admin/users/:id", {
31
+ * preHandler: logAccess(dpdp, {
32
+ * purpose: "account",
33
+ * fields: ["users"],
34
+ * actor: (req) => req.staff?.id,
35
+ * subject: (req) => req.params.id,
36
+ * }),
37
+ * }, handler);
38
+ * ```
39
+ */
40
+ export declare function logAccess<P extends string, Req = any>(dpdp: Dpdp<P>, options: AccessLogOptions<Req, P>): (request: Req) => Promise<void>;
41
+ export {};
@@ -0,0 +1,25 @@
1
+ import {
2
+ CONSENT_REQUIRED_BODY,
3
+ checkConsent,
4
+ recordAccess
5
+ } from "./chunk-5TVA2TKG.js";
6
+ import "./chunk-67Q5GFD6.js";
7
+
8
+ // src/fastify.ts
9
+ function requireConsent(dpdp, purpose, options) {
10
+ return async (request, reply) => {
11
+ if (await checkConsent(dpdp, purpose, options, request)) return void 0;
12
+ if (options.onDenied) await options.onDenied(request, reply, purpose);
13
+ if (!reply.sent) reply.code(403).send(CONSENT_REQUIRED_BODY(purpose));
14
+ return reply;
15
+ };
16
+ }
17
+ function logAccess(dpdp, options) {
18
+ return async (request) => {
19
+ await recordAccess(dpdp, options, request);
20
+ };
21
+ }
22
+ export {
23
+ logAccess,
24
+ requireConsent
25
+ };
package/dist/guard.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { AccessAction } from "./access.js";
1
2
  import type { Dpdp } from "./dpdp.js";
2
3
  export interface GuardOptions<Ctx> {
3
4
  /** Read the signed-in person's id from the request. Return nothing when nobody is signed in. */
@@ -11,3 +12,21 @@ export declare const CONSENT_REQUIRED_BODY: (purpose: string) => {
11
12
  };
12
13
  /** Shared by the Express and Hono middleware. */
13
14
  export declare function checkConsent<P extends string, Ctx>(dpdp: Dpdp<P>, purpose: P, options: GuardOptions<Ctx>, ctx: Ctx): Promise<boolean>;
15
+ type Maybe<T> = T | null | undefined;
16
+ export interface AccessLogOptions<Ctx, P extends string> {
17
+ /** Why the route reads the data: one of your purposes. */
18
+ purpose: P;
19
+ /** Who is making the request: the signed-in staff user or service. Required. */
20
+ actor: (ctx: Ctx) => Maybe<string> | Promise<Maybe<string>>;
21
+ /** Whose data the route reads, e.g. the `:userId` route parameter. Nothing is logged if it returns nothing. */
22
+ subject: (ctx: Ctx) => Maybe<string | readonly string[]> | Promise<Maybe<string | readonly string[]>>;
23
+ /** What the route reads, as data map keys: `"users.phone"` or `"users"`. */
24
+ fields?: readonly string[];
25
+ /** Default `"read"`. */
26
+ action?: AccessAction;
27
+ /** Request details to keep with the entry, e.g. IP address and request id. */
28
+ evidence?: (ctx: Ctx) => Maybe<Record<string, string>>;
29
+ }
30
+ /** Shared by the Express and Hono access-log middleware. */
31
+ export declare function recordAccess<P extends string, Ctx>(dpdp: Dpdp<P>, options: AccessLogOptions<Ctx, P>, ctx: Ctx): Promise<void>;
32
+ export {};
package/dist/hono.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Dpdp } from "./dpdp.js";
2
- import { type GuardOptions } from "./guard.js";
2
+ import { type AccessLogOptions, type GuardOptions } from "./guard.js";
3
3
  /** The parts of Hono's context this middleware uses. */
4
4
  interface ContextLike {
5
5
  json(body: unknown, status?: number): Response;
@@ -17,4 +17,19 @@ export interface HonoGuardOptions<C> extends GuardOptions<C> {
17
17
  * ```
18
18
  */
19
19
  export declare function requireConsent<P extends string, C extends ContextLike = any>(dpdp: Dpdp<P>, purpose: P, options: HonoGuardOptions<C>): (c: C, next: () => Promise<void>) => Promise<Response | void>;
20
+ /**
21
+ * Hono middleware that records each request in the access log (Rule 6(1)(c)) before the handler
22
+ * runs. Errors (a failed write, or out-of-purpose fields with `access: { outOfPurpose: "throw" }`)
23
+ * are thrown to Hono's error handler and the handler doesn't run.
24
+ *
25
+ * ```ts
26
+ * app.get("/admin/users/:id", logAccess(dpdp, {
27
+ * purpose: "account",
28
+ * fields: ["users"],
29
+ * actor: (c) => c.get("staffId"),
30
+ * subject: (c) => c.req.param("id"),
31
+ * }), handler);
32
+ * ```
33
+ */
34
+ export declare function logAccess<P extends string, C = any>(dpdp: Dpdp<P>, options: AccessLogOptions<C, P>): (c: C, next: () => Promise<void>) => Promise<void>;
20
35
  export {};
package/dist/hono.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import {
2
2
  CONSENT_REQUIRED_BODY,
3
- checkConsent
4
- } from "./chunk-FGZAH2NF.js";
3
+ checkConsent,
4
+ recordAccess
5
+ } from "./chunk-5TVA2TKG.js";
6
+ import "./chunk-67Q5GFD6.js";
5
7
 
6
8
  // src/hono.ts
7
9
  function requireConsent(dpdp, purpose, options) {
@@ -11,6 +13,13 @@ function requireConsent(dpdp, purpose, options) {
11
13
  return c.json(CONSENT_REQUIRED_BODY(purpose), 403);
12
14
  };
13
15
  }
16
+ function logAccess(dpdp, options) {
17
+ return async (c, next) => {
18
+ await recordAccess(dpdp, options, c);
19
+ await next();
20
+ };
21
+ }
14
22
  export {
23
+ logAccess,
15
24
  requireConsent
16
25
  };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
- export { audit, hasErrors, type Issue, type IssueLevel } from "./audit.js";
2
- export { type Basis, type Category, type DpdpConfig, defineConfig, type FiduciaryDef, type LegalHold, type PersonalField, type ProcessorDef, type PurposeDef, type PurposeOf, type RightsConfig, purposeNames, type Retention, type TableDef, } from "./config.js";
3
- export { type ConsentMeta, createDpdp, type Dpdp, type DpdpOptions, hashEvent, type VerifyResult, } from "./dpdp.js";
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";
3
+ export { audit, hasErrors, isHighRisk, type Issue, type IssueLevel } from "./audit.js";
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";
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";
4
6
  export { type Duration, durationMs, isDuration } from "./duration.js";
5
7
  export { type ErasurePlan, type ErasureReason, type FieldPlan, type PlanInput, type ProcessorPlan, planErasure, type TablePlan, } from "./erasure.js";
6
8
  export { DpdpError, type DpdpErrorCode, SeqConflictError } from "./errors.js";
7
- export { CONSENT_REQUIRED_BODY, type GuardOptions } from "./guard.js";
9
+ export { type AccessLogOptions, CONSENT_REQUIRED_BODY, type GuardOptions } from "./guard.js";
8
10
  export { isNoticeLanguage, NOTICE_LANGUAGES, type NoticeLanguage } from "./languages.js";
9
11
  export { type Confidence, guessPersonal, type PersonalGuess, tokenize } from "./personal.js";
10
12
  export { checkSchema, type Schema, type SchemaColumn, type SchemaTable } from "./schema-check.js";
@@ -13,3 +15,4 @@ export { type DataAccess, memoryData } from "./data-access.js";
13
15
  export { type ErasureTask, REQUEST_TYPES, type RequestFilter, type RequestHistoryEntry, type RequestStatus, type RequestStore, type RequestType, type RightsRequest, type TaskFilter, type TaskKind, type TaskStatus, type TaskStore, } from "./records.js";
14
16
  export { type ProcessorHookInput, type ProcessorHooks, type RunReport, tasksFromPlan, } from "./retention.js";
15
17
  export { type AccessSummary, DEFAULT_RESPONSE_WITHIN } from "./rights.js";
18
+ export { formatSafeguards, type Safeguard, type SafeguardStatus, safeguardsReport } from "./safeguards.js";