dpdp-kit 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/drizzle.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-67Q5GFD6.js";
4
4
 
5
5
  // src/drizzle.ts
6
- import { and, asc, desc, eq, getTableColumns, getTableName, is, lt, lte, or, sql, Table } from "drizzle-orm";
6
+ import { and, asc, desc, eq, getTableColumns, getTableName, gte, is, lt, lte, or, sql, Table } from "drizzle-orm";
7
7
  import { index, integer, jsonb, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
8
8
  var consentEvents = pgTable(
9
9
  "dpdp_consent_events",
@@ -109,8 +109,72 @@ CREATE TABLE IF NOT EXISTS dpdp_erasure_tasks (
109
109
  );
110
110
  CREATE INDEX IF NOT EXISTS dpdp_erasure_tasks_subject_idx ON dpdp_erasure_tasks (subject_id);
111
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);`;
112
147
  var DPDP_DDL = `${CONSENT_EVENTS_DDL}
113
- ${RECORDS_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
+ }
114
178
  function fromRow(row) {
115
179
  return {
116
180
  subjectId: row.subjectId,
@@ -218,6 +282,31 @@ function runnable(when) {
218
282
  }
219
283
  function drizzleStore(db) {
220
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
+ },
221
310
  async lastEvent(subjectId) {
222
311
  const rows = await db.select().from(consentEvents).where(eq(consentEvents.subjectId, subjectId)).orderBy(desc(consentEvents.seq)).limit(1);
223
312
  return rows[0] ? fromRow(rows[0]) : void 0;
@@ -300,9 +389,10 @@ function drizzleSchema(module) {
300
389
  if (!is(value, Table)) continue;
301
390
  const name = getTableName(value);
302
391
  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
- );
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
+ });
306
396
  tables.set(name, { name, columns });
307
397
  }
308
398
  return { tables: [...tables.values()] };
@@ -330,10 +420,10 @@ function drizzleData(db, options = {}) {
330
420
  );
331
421
  return rowsOf(result);
332
422
  },
333
- async eraseFields(table, subjectColumn, subjectId, columns) {
423
+ async eraseFields(table, subjectColumn, subjectId, columns, values = {}) {
334
424
  if (columns.length === 0) return 0;
335
425
  const set = sql.join(
336
- columns.map((c) => sql`${col(table, c)} = NULL`),
426
+ columns.map((c) => Object.hasOwn(values, c) && values[c] !== null ? sql`${col(table, c)} = ${values[c]}` : sql`${col(table, c)} = NULL`),
337
427
  sql`, `
338
428
  );
339
429
  const result = await db.execute(
@@ -350,9 +440,11 @@ function drizzleData(db, options = {}) {
350
440
  };
351
441
  }
352
442
  export {
443
+ ACCESS_LOG_DDL,
353
444
  CONSENT_EVENTS_DDL,
354
445
  DPDP_DDL,
355
446
  RECORDS_DDL,
447
+ accessLog,
356
448
  consentEvents,
357
449
  drizzleData,
358
450
  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";
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,11 @@
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 { 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";
@@ -13,3 +14,4 @@ export { type DataAccess, memoryData } from "./data-access.js";
13
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";
14
15
  export { type ProcessorHookInput, type ProcessorHooks, type RunReport, tasksFromPlan, } from "./retention.js";
15
16
  export { type AccessSummary, DEFAULT_RESPONSE_WITHIN } from "./rights.js";
17
+ export { formatSafeguards, type Safeguard, type SafeguardStatus, safeguardsReport } from "./safeguards.js";