dpdp-kit 0.1.2 → 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/dist/drizzle.js CHANGED
@@ -3,8 +3,8 @@ import {
3
3
  } from "./chunk-67Q5GFD6.js";
4
4
 
5
5
  // src/drizzle.ts
6
- import { asc, desc, eq, getTableColumns, getTableName, is, Table } from "drizzle-orm";
7
- import { integer, jsonb, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
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";
8
8
  var consentEvents = pgTable(
9
9
  "dpdp_consent_events",
10
10
  {
@@ -36,6 +36,145 @@ var CONSENT_EVENTS_DDL = `CREATE TABLE IF NOT EXISTS dpdp_consent_events (
36
36
  hash text NOT NULL,
37
37
  PRIMARY KEY (subject_id, seq)
38
38
  );`;
39
+ var ts = (name) => timestamp(name, { withTimezone: true, mode: "date" });
40
+ var rightsRequests = pgTable(
41
+ "dpdp_requests",
42
+ {
43
+ id: text("id").primaryKey(),
44
+ subjectId: text("subject_id").notNull(),
45
+ type: text("type").$type().notNull(),
46
+ status: text("status").$type().notNull(),
47
+ openedAt: ts("opened_at").notNull(),
48
+ dueAt: ts("due_at").notNull(),
49
+ closedAt: ts("closed_at"),
50
+ details: jsonb("details").$type(),
51
+ history: jsonb("history").$type().notNull()
52
+ },
53
+ (t) => [index("dpdp_requests_subject_idx").on(t.subjectId), index("dpdp_requests_status_due_idx").on(t.status, t.dueAt)]
54
+ );
55
+ var erasureTasks = pgTable(
56
+ "dpdp_erasure_tasks",
57
+ {
58
+ id: text("id").primaryKey(),
59
+ subjectId: text("subject_id").notNull(),
60
+ reason: text("reason").notNull(),
61
+ kind: text("kind").$type().notNull(),
62
+ tableKey: text("table_key"),
63
+ fields: jsonb("fields").$type(),
64
+ processor: text("processor"),
65
+ purposes: jsonb("purposes").$type(),
66
+ createdAt: ts("created_at").notNull(),
67
+ dueAt: ts("due_at").notNull(),
68
+ status: text("status").$type().notNull(),
69
+ attempts: integer("attempts").notNull(),
70
+ claimedAt: ts("claimed_at"),
71
+ doneAt: ts("done_at"),
72
+ affected: integer("affected"),
73
+ lastError: text("last_error"),
74
+ note: text("note")
75
+ },
76
+ (t) => [index("dpdp_erasure_tasks_subject_idx").on(t.subjectId), index("dpdp_erasure_tasks_status_due_idx").on(t.status, t.dueAt)]
77
+ );
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
+ var accessLog = pgTable(
113
+ "dpdp_access_log",
114
+ {
115
+ id: text("id").primaryKey(),
116
+ at: ts("at").notNull(),
117
+ actor: text("actor").notNull(),
118
+ subjectId: text("subject_id").notNull(),
119
+ action: text("action").notNull(),
120
+ purpose: text("purpose").notNull(),
121
+ fields: jsonb("fields").$type(),
122
+ outOfPurpose: jsonb("out_of_purpose").$type(),
123
+ reason: text("reason"),
124
+ evidence: jsonb("evidence").$type()
125
+ },
126
+ (t) => [
127
+ index("dpdp_access_log_at_idx").on(t.at),
128
+ index("dpdp_access_log_subject_idx").on(t.subjectId, t.at),
129
+ index("dpdp_access_log_actor_idx").on(t.actor, t.at)
130
+ ]
131
+ );
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
143
+ );
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}`;
150
+ function accessFromRow(row) {
151
+ return {
152
+ id: row.id,
153
+ at: row.at.toISOString(),
154
+ actor: row.actor,
155
+ subjectId: row.subjectId,
156
+ action: row.action,
157
+ purpose: row.purpose,
158
+ ...row.fields !== null ? { fields: row.fields } : {},
159
+ ...row.outOfPurpose !== null ? { outOfPurpose: row.outOfPurpose } : {},
160
+ ...row.reason !== null ? { reason: row.reason } : {},
161
+ ...row.evidence !== null ? { evidence: row.evidence } : {}
162
+ };
163
+ }
164
+ function accessToRow(e) {
165
+ return {
166
+ id: e.id,
167
+ at: new Date(e.at),
168
+ actor: e.actor,
169
+ subjectId: e.subjectId,
170
+ action: e.action,
171
+ purpose: e.purpose,
172
+ fields: e.fields ?? null,
173
+ outOfPurpose: e.outOfPurpose ?? null,
174
+ reason: e.reason ?? null,
175
+ evidence: e.evidence ?? null
176
+ };
177
+ }
39
178
  function fromRow(row) {
40
179
  return {
41
180
  subjectId: row.subjectId,
@@ -58,8 +197,116 @@ function isUniqueViolation(err) {
58
197
  }
59
198
  return false;
60
199
  }
200
+ var iso = (d) => d ? d.toISOString() : void 0;
201
+ var date = (value) => value === void 0 ? null : new Date(value);
202
+ function requestFromRow(row) {
203
+ return {
204
+ id: row.id,
205
+ subjectId: row.subjectId,
206
+ type: row.type,
207
+ status: row.status,
208
+ openedAt: row.openedAt.toISOString(),
209
+ dueAt: row.dueAt.toISOString(),
210
+ ...row.closedAt ? { closedAt: row.closedAt.toISOString() } : {},
211
+ ...row.details !== null ? { details: row.details } : {},
212
+ history: row.history
213
+ };
214
+ }
215
+ function requestToRow(r) {
216
+ return {
217
+ id: r.id,
218
+ subjectId: r.subjectId,
219
+ type: r.type,
220
+ status: r.status,
221
+ openedAt: new Date(r.openedAt),
222
+ dueAt: new Date(r.dueAt),
223
+ closedAt: date(r.closedAt),
224
+ details: r.details ?? null,
225
+ history: r.history
226
+ };
227
+ }
228
+ function taskFromRow(row) {
229
+ const optional = {
230
+ table: row.tableKey ?? void 0,
231
+ fields: row.fields ?? void 0,
232
+ processor: row.processor ?? void 0,
233
+ purposes: row.purposes ?? void 0,
234
+ claimedAt: iso(row.claimedAt),
235
+ doneAt: iso(row.doneAt),
236
+ affected: row.affected ?? void 0,
237
+ lastError: row.lastError ?? void 0,
238
+ note: row.note ?? void 0
239
+ };
240
+ return {
241
+ id: row.id,
242
+ subjectId: row.subjectId,
243
+ reason: row.reason,
244
+ kind: row.kind,
245
+ createdAt: row.createdAt.toISOString(),
246
+ dueAt: row.dueAt.toISOString(),
247
+ status: row.status,
248
+ attempts: row.attempts,
249
+ ...Object.fromEntries(Object.entries(optional).filter(([, v]) => v !== void 0))
250
+ };
251
+ }
252
+ function taskToRow(t) {
253
+ return {
254
+ id: t.id,
255
+ subjectId: t.subjectId,
256
+ reason: t.reason,
257
+ kind: t.kind,
258
+ tableKey: t.table ?? null,
259
+ fields: t.fields ?? null,
260
+ processor: t.processor ?? null,
261
+ purposes: t.purposes ?? null,
262
+ createdAt: new Date(t.createdAt),
263
+ dueAt: new Date(t.dueAt),
264
+ status: t.status,
265
+ attempts: t.attempts,
266
+ claimedAt: date(t.claimedAt),
267
+ doneAt: date(t.doneAt),
268
+ affected: t.affected ?? null,
269
+ lastError: t.lastError ?? null,
270
+ note: t.note ?? null
271
+ };
272
+ }
273
+ function runnable(when) {
274
+ return and(
275
+ lte(erasureTasks.dueAt, new Date(when.now)),
276
+ or(
277
+ eq(erasureTasks.status, "pending"),
278
+ and(eq(erasureTasks.status, "failed"), lt(erasureTasks.attempts, when.maxAttempts)),
279
+ and(eq(erasureTasks.status, "running"), lt(erasureTasks.claimedAt, new Date(when.staleBefore)))
280
+ )
281
+ );
282
+ }
61
283
  function drizzleStore(db) {
62
284
  return {
285
+ async insertAccess(entries) {
286
+ if (entries.length > 0) await db.insert(accessLog).values(entries.map(accessToRow));
287
+ },
288
+ 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));
297
+ const rows = filter.limit === void 0 ? await query : await query.limit(filter.limit);
298
+ return rows.map(accessFromRow);
299
+ },
300
+ async pruneAccess(before) {
301
+ const batch = 5e3;
302
+ let total = 0;
303
+ for (; ; ) {
304
+ const ids = db.select({ id: accessLog.id }).from(accessLog).where(lt(accessLog.at, new Date(before))).limit(batch);
305
+ const deleted = await db.delete(accessLog).where(sql`${accessLog.id} IN (${ids})`).returning({ one: sql`1` });
306
+ total += deleted.length;
307
+ if (deleted.length < batch) return total;
308
+ }
309
+ },
63
310
  async lastEvent(subjectId) {
64
311
  const rows = await db.select().from(consentEvents).where(eq(consentEvents.subjectId, subjectId)).orderBy(desc(consentEvents.seq)).limit(1);
65
312
  return rows[0] ? fromRow(rows[0]) : void 0;
@@ -87,6 +334,52 @@ function drizzleStore(db) {
87
334
  async events(subjectId) {
88
335
  const rows = await db.select().from(consentEvents).where(eq(consentEvents.subjectId, subjectId)).orderBy(asc(consentEvents.seq));
89
336
  return rows.map(fromRow);
337
+ },
338
+ async insertRequest(request) {
339
+ await db.insert(rightsRequests).values(requestToRow(request));
340
+ },
341
+ async getRequest(id) {
342
+ const rows = await db.select().from(rightsRequests).where(eq(rightsRequests.id, id)).limit(1);
343
+ return rows[0] ? requestFromRow(rows[0]) : void 0;
344
+ },
345
+ async updateRequest(request) {
346
+ const { id, ...rest } = requestToRow(request);
347
+ await db.update(rightsRequests).set(rest).where(eq(rightsRequests.id, id));
348
+ },
349
+ async listRequests(filter) {
350
+ const where = and(
351
+ filter.subjectId ? eq(rightsRequests.subjectId, filter.subjectId) : void 0,
352
+ filter.status ? eq(rightsRequests.status, filter.status) : void 0
353
+ );
354
+ const rows = await db.select().from(rightsRequests).where(where).orderBy(asc(rightsRequests.openedAt));
355
+ return rows.map(requestFromRow);
356
+ },
357
+ async insertTasks(tasks) {
358
+ if (tasks.length > 0) await db.insert(erasureTasks).values(tasks.map(taskToRow));
359
+ },
360
+ async dueTasks({ limit, ...when }) {
361
+ const rows = await db.select().from(erasureTasks).where(runnable(when)).orderBy(asc(erasureTasks.dueAt)).limit(limit);
362
+ return rows.map(taskFromRow);
363
+ },
364
+ async claimTask({ id, ...when }) {
365
+ const claimed = await db.update(erasureTasks).set({ status: "running", claimedAt: new Date(when.now) }).where(and(eq(erasureTasks.id, id), runnable(when))).returning({ id: erasureTasks.id });
366
+ return claimed.length === 1;
367
+ },
368
+ async updateTask(task) {
369
+ const { id, ...rest } = taskToRow(task);
370
+ await db.update(erasureTasks).set(rest).where(eq(erasureTasks.id, id));
371
+ },
372
+ async getTask(id) {
373
+ const rows = await db.select().from(erasureTasks).where(eq(erasureTasks.id, id)).limit(1);
374
+ return rows[0] ? taskFromRow(rows[0]) : void 0;
375
+ },
376
+ async listTasks(filter) {
377
+ const where = and(
378
+ filter.subjectId ? eq(erasureTasks.subjectId, filter.subjectId) : void 0,
379
+ filter.status ? eq(erasureTasks.status, filter.status) : void 0
380
+ );
381
+ const rows = await db.select().from(erasureTasks).where(where).orderBy(asc(erasureTasks.dueAt));
382
+ return rows.map(taskFromRow);
90
383
  }
91
384
  };
92
385
  }
@@ -96,16 +389,66 @@ function drizzleSchema(module) {
96
389
  if (!is(value, Table)) continue;
97
390
  const name = getTableName(value);
98
391
  if (tables.has(name)) continue;
99
- const columns = Object.entries(getTableColumns(value)).map(
100
- ([key, column]) => key === column.name ? { name: column.name } : { name: column.name, key }
101
- );
392
+ const columns = Object.entries(getTableColumns(value)).map(([key, column]) => {
393
+ const type = ["string", "number", "boolean"].includes(column.dataType) ? column.dataType : "other";
394
+ return { name: column.name, ...key === column.name ? {} : { key }, notNull: column.notNull, type };
395
+ });
102
396
  tables.set(name, { name, columns });
103
397
  }
104
398
  return { tables: [...tables.values()] };
105
399
  }
400
+ function rowsOf(result) {
401
+ if (Array.isArray(result)) return result;
402
+ return result.rows ?? [];
403
+ }
404
+ function drizzleData(db, options = {}) {
405
+ const columnsByTable = /* @__PURE__ */ new Map();
406
+ for (const table of options.schema ? drizzleSchema(options.schema).tables : []) {
407
+ columnsByTable.set(table.name, new Map(table.columns.map((c) => [c.key ?? c.name, c.name])));
408
+ }
409
+ const col = (table, name) => sql.identifier(columnsByTable.get(table)?.get(name) ?? name);
410
+ const where = (table, subjectColumn, subjectId) => sql`${col(table, subjectColumn)} = ${subjectId}`;
411
+ return {
412
+ async read(table, subjectColumn, subjectId, columns) {
413
+ if (columns.length === 0) return [];
414
+ const select = sql.join(
415
+ columns.map((c) => sql`${col(table, c)} AS ${sql.identifier(c)}`),
416
+ sql`, `
417
+ );
418
+ const result = await db.execute(
419
+ sql`SELECT ${select} FROM ${sql.identifier(table)} WHERE ${where(table, subjectColumn, subjectId)}`
420
+ );
421
+ return rowsOf(result);
422
+ },
423
+ async eraseFields(table, subjectColumn, subjectId, columns, values = {}) {
424
+ if (columns.length === 0) return 0;
425
+ const set = sql.join(
426
+ columns.map((c) => Object.hasOwn(values, c) && values[c] !== null ? sql`${col(table, c)} = ${values[c]}` : sql`${col(table, c)} = NULL`),
427
+ sql`, `
428
+ );
429
+ const result = await db.execute(
430
+ sql`UPDATE ${sql.identifier(table)} SET ${set} WHERE ${where(table, subjectColumn, subjectId)} RETURNING 1`
431
+ );
432
+ return rowsOf(result).length;
433
+ },
434
+ async deleteRows(table, subjectColumn, subjectId) {
435
+ const result = await db.execute(
436
+ sql`DELETE FROM ${sql.identifier(table)} WHERE ${where(table, subjectColumn, subjectId)} RETURNING 1`
437
+ );
438
+ return rowsOf(result).length;
439
+ }
440
+ };
441
+ }
106
442
  export {
443
+ ACCESS_LOG_DDL,
107
444
  CONSENT_EVENTS_DDL,
445
+ DPDP_DDL,
446
+ RECORDS_DDL,
447
+ accessLog,
108
448
  consentEvents,
449
+ drizzleData,
109
450
  drizzleSchema,
110
- drizzleStore
451
+ drizzleStore,
452
+ erasureTasks,
453
+ rightsRequests
111
454
  };
package/dist/erasure.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { DpdpConfig, LegalHold } from "./config.js";
2
2
  import { type Duration } from "./duration.js";
3
- export type ErasureReason = "withdrawal" | "account-deletion";
3
+ /** Why erasure is happening. An `"erasure-request"` (Section 12(3)) is handled like an account deletion, minus any purposes still needed. */
4
+ export type ErasureReason = "withdrawal" | "account-deletion" | "erasure-request";
4
5
  export interface FieldPlan {
5
6
  field: string;
6
7
  /**
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";
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";
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,11 +1,17 @@
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, 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 { audit, hasErrors, isHighRisk, type Issue, type IssueLevel } from "./audit.js";
3
+ 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
+ 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
5
  export { type Duration, durationMs, isDuration } from "./duration.js";
5
6
  export { type ErasurePlan, type ErasureReason, type FieldPlan, type PlanInput, type ProcessorPlan, planErasure, type TablePlan, } from "./erasure.js";
6
7
  export { DpdpError, type DpdpErrorCode, SeqConflictError } from "./errors.js";
7
- export { CONSENT_REQUIRED_BODY, type GuardOptions } from "./guard.js";
8
+ export { type AccessLogOptions, CONSENT_REQUIRED_BODY, type GuardOptions } from "./guard.js";
8
9
  export { isNoticeLanguage, NOTICE_LANGUAGES, type NoticeLanguage } from "./languages.js";
9
10
  export { type Confidence, guessPersonal, type PersonalGuess, tokenize } from "./personal.js";
10
11
  export { checkSchema, type Schema, type SchemaColumn, type SchemaTable } from "./schema-check.js";
11
- export { type ConsentAction, type ConsentEvent, type ConsentStore, memoryStore } from "./store.js";
12
+ export { type ConsentAction, type ConsentEvent, type ConsentStore, type DpdpStore, isDpdpStore, memoryStore, } from "./store.js";
13
+ export { type DataAccess, memoryData } from "./data-access.js";
14
+ 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";
15
+ export { type ProcessorHookInput, type ProcessorHooks, type RunReport, tasksFromPlan, } from "./retention.js";
16
+ export { type AccessSummary, DEFAULT_RESPONSE_WITHIN } from "./rights.js";
17
+ export { formatSafeguards, type Safeguard, type SafeguardStatus, safeguardsReport } from "./safeguards.js";