dpdp-kit 0.4.1 → 0.5.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 (47) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +12 -9
  3. package/dist/access.d.ts +3 -2
  4. package/dist/audit.d.ts +7 -2
  5. package/dist/{chunk-5TVA2TKG.js → chunk-3DOVLBUB.js} +12 -2
  6. package/dist/chunk-EMNABUCL.js +34 -0
  7. package/dist/{chunk-HXVP446N.js → chunk-FEGA6SOM.js} +817 -149
  8. package/dist/chunk-HGN6TO6R.js +294 -0
  9. package/dist/{chunk-KLMR7S7I.js → chunk-LVT4OKBC.js} +65 -0
  10. package/dist/chunk-M2PDT6DD.js +88 -0
  11. package/dist/chunk-NBVJQDDP.js +16 -0
  12. package/dist/{chunk-2ELTZSW3.js → chunk-VWGKAQCM.js} +18 -3
  13. package/dist/cli.js +48 -5
  14. package/dist/config.d.ts +67 -0
  15. package/dist/data-access.d.ts +8 -0
  16. package/dist/ddl.d.ts +13 -2
  17. package/dist/dpdp.d.ts +155 -9
  18. package/dist/drizzle.d.ts +108 -6
  19. package/dist/drizzle.js +85 -4
  20. package/dist/erasure.d.ts +1 -1
  21. package/dist/errors.d.ts +1 -1
  22. package/dist/evidence.d.ts +91 -0
  23. package/dist/express.d.ts +30 -0
  24. package/dist/express.js +70 -3
  25. package/dist/fastify.js +3 -3
  26. package/dist/guard.d.ts +23 -2
  27. package/dist/hono.d.ts +21 -0
  28. package/dist/hono.js +11 -3
  29. package/dist/http.d.ts +78 -0
  30. package/dist/index.d.ts +7 -3
  31. package/dist/index.js +375 -125
  32. package/dist/mongodb.d.ts +3 -1
  33. package/dist/mongodb.js +99 -1
  34. package/dist/nestjs.js +1 -1
  35. package/dist/next.d.ts +25 -0
  36. package/dist/next.js +14 -0
  37. package/dist/notice.d.ts +139 -0
  38. package/dist/postgres.d.ts +5 -3
  39. package/dist/postgres.js +8 -2
  40. package/dist/prisma.d.ts +4 -2
  41. package/dist/prisma.js +16 -2
  42. package/dist/records.d.ts +24 -1
  43. package/dist/rights.d.ts +35 -2
  44. package/dist/run-audit.d.ts +8 -0
  45. package/dist/stats.d.ts +41 -0
  46. package/dist/store.d.ts +15 -2
  47. package/package.json +5 -1
package/dist/drizzle.js CHANGED
@@ -3,8 +3,22 @@ import {
3
3
  BREACH_DDL,
4
4
  CONSENT_EVENTS_DDL,
5
5
  DPDP_DDL,
6
+ MIGRATE_0_5_DDL,
7
+ PRIVACY_NOTICES_DDL,
6
8
  RECORDS_DDL
7
- } from "./chunk-2ELTZSW3.js";
9
+ } from "./chunk-VWGKAQCM.js";
10
+ import {
11
+ columnValue
12
+ } from "./chunk-EMNABUCL.js";
13
+ import {
14
+ ACTIONS_SQL,
15
+ NOW_SQL,
16
+ PERIOD_SQL,
17
+ TASKS_SQL,
18
+ TOTALS_SQL,
19
+ statsFromRows,
20
+ taskCountsFromRows
21
+ } from "./chunk-M2PDT6DD.js";
8
22
  import {
9
23
  SeqConflictError
10
24
  } from "./chunk-67Q5GFD6.js";
@@ -12,14 +26,14 @@ import {
12
26
  // src/drizzle.ts
13
27
  import { and, asc, count, desc, eq, getTableColumns, getTableName, gte, inArray, is, lt, lte, max, min, or, sql, Table } from "drizzle-orm";
14
28
  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";
29
+ import { check, getTableConfig as pgTableConfig, index, integer, jsonb, PgTable, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
16
30
  import { SQLiteTable, getTableConfig as sqliteTableConfig } from "drizzle-orm/sqlite-core";
17
31
  var consentEvents = pgTable(
18
32
  "dpdp_consent_events",
19
33
  {
20
34
  subjectId: text("subject_id").notNull(),
21
35
  seq: integer("seq").notNull(),
22
- action: text("action", { enum: ["grant", "withdraw"] }).notNull(),
36
+ action: text("action", { enum: ["grant", "withdraw", "object", "lift-objection"] }).notNull(),
23
37
  purposes: jsonb("purposes").$type().notNull(),
24
38
  noticeVersion: text("notice_version"),
25
39
  language: text("language"),
@@ -29,7 +43,11 @@ var consentEvents = pgTable(
29
43
  prevHash: text("prev_hash"),
30
44
  hash: text("hash").notNull()
31
45
  },
32
- (t) => [primaryKey({ columns: [t.subjectId, t.seq] })]
46
+ (t) => [
47
+ primaryKey({ columns: [t.subjectId, t.seq] }),
48
+ // The same constraint DPDP_DDL creates, so drizzle-kit and the plain SQL agree.
49
+ check("dpdp_consent_events_action_check", sql`${t.action} IN ('grant', 'withdraw', 'object', 'lift-objection')`)
50
+ ]
33
51
  );
34
52
  var ts = (name) => timestamp(name, { withTimezone: true, mode: "date" });
35
53
  var rightsRequests = pgTable(
@@ -101,6 +119,17 @@ var breaches = pgTable(
101
119
  },
102
120
  (t) => [index("dpdp_breaches_status_idx").on(t.status, t.awareAt)]
103
121
  );
122
+ var privacyNotices = pgTable(
123
+ "dpdp_privacy_notices",
124
+ {
125
+ version: text("version").notNull(),
126
+ language: text("language").$type().notNull(),
127
+ kind: text("kind").$type().notNull(),
128
+ content: jsonb("content").$type().notNull(),
129
+ firstShownAt: ts("first_shown_at").notNull()
130
+ },
131
+ (t) => [primaryKey({ columns: [t.version, t.language, t.kind] })]
132
+ );
104
133
  var breachNotices = pgTable(
105
134
  "dpdp_breach_notices",
106
135
  {
@@ -258,7 +287,32 @@ function runnable(when) {
258
287
  );
259
288
  }
260
289
  function drizzleStore(db) {
290
+ const savedNotice = (r) => ({ notice: r.content, firstShownAt: new Date(r.firstShownAt).toISOString() });
261
291
  return {
292
+ async consentStats(from, to) {
293
+ const [totals, actions, period, now] = await Promise.all([
294
+ raw(db, TOTALS_SQL, [from, to]),
295
+ raw(db, ACTIONS_SQL, [from, to]),
296
+ raw(db, PERIOD_SQL, [from, to]),
297
+ raw(db, NOW_SQL, [])
298
+ ]);
299
+ return statsFromRows(from, to, totals[0], actions, period, now);
300
+ },
301
+ async taskCounts(now) {
302
+ return taskCountsFromRows(await raw(db, TASKS_SQL, [now]));
303
+ },
304
+ async savePrivacyNotice(notice, at) {
305
+ const rows = await db.insert(privacyNotices).values({ version: notice.version, language: notice.language, kind: notice.kind, content: notice, firstShownAt: new Date(at) }).onConflictDoNothing().returning({ one: sql`1` });
306
+ return rows.length > 0;
307
+ },
308
+ async getPrivacyNotice(version, language, kind) {
309
+ const [row] = await db.select({ content: privacyNotices.content, firstShownAt: privacyNotices.firstShownAt }).from(privacyNotices).where(and(eq(privacyNotices.version, version), eq(privacyNotices.language, language), eq(privacyNotices.kind, kind))).limit(1);
310
+ return row ? savedNotice(row) : void 0;
311
+ },
312
+ async listPrivacyNotices() {
313
+ const rows = await db.select({ content: privacyNotices.content, firstShownAt: privacyNotices.firstShownAt }).from(privacyNotices).orderBy(asc(privacyNotices.firstShownAt), asc(privacyNotices.version), asc(privacyNotices.language), asc(privacyNotices.kind));
314
+ return rows.map(savedNotice);
315
+ },
262
316
  async insertBreach(breach) {
263
317
  await db.insert(breaches).values(breachRow(breach));
264
318
  },
@@ -461,8 +515,10 @@ function rowsOf(result) {
461
515
  }
462
516
  function drizzleData(db, options = {}) {
463
517
  const columnsByTable = /* @__PURE__ */ new Map();
518
+ const arrayColumns = /* @__PURE__ */ new Set();
464
519
  for (const table of options.schema ? drizzleSchema(options.schema).tables : []) {
465
520
  columnsByTable.set(table.name, new Map(table.columns.map((c) => [c.key ?? c.name, c.name])));
521
+ for (const c of table.columns) if (/\[\]$/.test(c.sqlType ?? "")) arrayColumns.add(`${table.name}\0${c.key ?? c.name}`);
466
522
  }
467
523
  const col = (table, name) => sql.identifier(columnsByTable.get(table)?.get(name) ?? name);
468
524
  const where = (table, subjectColumn, subjectId) => sql`${col(table, subjectColumn)} = ${subjectId}`;
@@ -489,6 +545,22 @@ function drizzleData(db, options = {}) {
489
545
  );
490
546
  return rowsOf(result).length;
491
547
  },
548
+ async updateFields(table, subjectColumn, subjectId, values, only = {}) {
549
+ const entries = Object.entries(values);
550
+ if (entries.length === 0) return 0;
551
+ const set = sql.join(
552
+ entries.map(([c, v]) => {
553
+ if (v === null || v === void 0) return sql`${col(table, c)} = NULL`;
554
+ return sql`${col(table, c)} = ${Array.isArray(v) && arrayColumns.has(`${table}\0${c}`) ? sql.param(v) : columnValue(v)}`;
555
+ }),
556
+ sql`, `
557
+ );
558
+ const narrow = Object.entries(only).map(([c, v]) => sql` AND ${col(table, c)} = ${v}`);
559
+ const result = await db.execute(
560
+ sql`UPDATE ${sql.identifier(table)} SET ${set} WHERE ${where(table, subjectColumn, subjectId)}${sql.join(narrow, sql``)} RETURNING 1`
561
+ );
562
+ return rowsOf(result).length;
563
+ },
492
564
  async deleteRows(table, subjectColumn, subjectId) {
493
565
  const result = await db.execute(
494
566
  sql`DELETE FROM ${sql.identifier(table)} WHERE ${where(table, subjectColumn, subjectId)} RETURNING 1`
@@ -497,11 +569,19 @@ function drizzleData(db, options = {}) {
497
569
  }
498
570
  };
499
571
  }
572
+ async function raw(db, text2, params) {
573
+ const parts = text2.split(/\$(\d+)/);
574
+ const chunks = [];
575
+ for (let i = 0; i < parts.length; i++) chunks.push(i % 2 === 0 ? sql.raw(parts[i]) : sql`${params[Number(parts[i]) - 1]}`);
576
+ return rowsOf(await db.execute(sql.join(chunks, sql``)));
577
+ }
500
578
  export {
501
579
  ACCESS_LOG_DDL,
502
580
  BREACH_DDL,
503
581
  CONSENT_EVENTS_DDL,
504
582
  DPDP_DDL,
583
+ MIGRATE_0_5_DDL,
584
+ PRIVACY_NOTICES_DDL,
505
585
  RECORDS_DDL,
506
586
  accessLog,
507
587
  breachNotices,
@@ -511,5 +591,6 @@ export {
511
591
  drizzleSchema,
512
592
  drizzleStore,
513
593
  erasureTasks,
594
+ privacyNotices,
514
595
  rightsRequests
515
596
  };
package/dist/erasure.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { DpdpConfig, LegalHold } from "./config.js";
2
2
  import { type Duration } from "./duration.js";
3
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
+ export type ErasureReason = "withdrawal" | "objection" | "account-deletion" | "erasure-request";
5
5
  export interface FieldPlan {
6
6
  field: string;
7
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" | "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";
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" | "not-objectable" | "notice-not-configured" | "notice-language-unavailable" | "notice-translation-incomplete" | "notice-description-missing" | "notice-version-conflict" | "not-correctable" | "request-not-verified" | "wrong-request-type" | "nominee-not-found" | "data-access-unsupported" | "no-matching-rows";
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;
@@ -0,0 +1,91 @@
1
+ import type { AccessFinding, AccessFindingKind } from "./access.js";
2
+ import { type Issue } from "./audit.js";
3
+ import type { BreachStatus } from "./breach.js";
4
+ import type { DpdpConfig, FiduciaryDef, LegalHold, Retention } from "./config.js";
5
+ import type { NoticeKind } from "./notice.js";
6
+ import type { NoticeLanguage } from "./languages.js";
7
+ import type { RequestStatus, RequestType, RightsRequest } from "./records.js";
8
+ import { type RightsInfo } from "./rights.js";
9
+ import { type Safeguard } from "./safeguards.js";
10
+ import type { ConsentStats, TaskCounts } from "./stats.js";
11
+ /** A part of the report the store couldn't provide, and why. */
12
+ export interface Unavailable {
13
+ unavailable: string;
14
+ }
15
+ export declare const isUnavailable: (v: unknown) => v is Unavailable;
16
+ export interface RequestStats {
17
+ /** Requests opened in the period, by type. */
18
+ opened: Partial<Record<RequestType, number>>;
19
+ /** Requests answered (resolved or rejected) in the period. */
20
+ closed: number;
21
+ /** Of those, answered after their due date. */
22
+ closedLate: number;
23
+ /** All requests by status, now. */
24
+ byStatus: Partial<Record<RequestStatus, number>>;
25
+ /** Open requests past their due date, now. */
26
+ overdue: number;
27
+ }
28
+ export interface EvidenceReport {
29
+ generatedAt: string;
30
+ /** For the records; absent in a report built from the config alone. */
31
+ period?: {
32
+ from: string;
33
+ to: string;
34
+ };
35
+ fiduciary: FiduciaryDef;
36
+ purposes: Array<{
37
+ purpose: string;
38
+ basis: string;
39
+ legitimateUse?: string;
40
+ description?: string;
41
+ retain: string;
42
+ }>;
43
+ data: Array<{
44
+ key: string;
45
+ table: string;
46
+ fields: Array<{
47
+ field: string;
48
+ category: string;
49
+ purposes: string[];
50
+ protect?: string;
51
+ }>;
52
+ legalHold?: LegalHold;
53
+ }>;
54
+ processors: Array<{
55
+ name: string;
56
+ purposes: string[];
57
+ contract?: string;
58
+ countries?: string[];
59
+ foreignState?: boolean;
60
+ }>;
61
+ minimumRetention?: string;
62
+ audit: Issue[];
63
+ safeguards: Safeguard[];
64
+ rights: RightsInfo;
65
+ notices?: Array<{
66
+ version: string;
67
+ language: NoticeLanguage;
68
+ kind: NoticeKind;
69
+ firstShownAt: string;
70
+ purposes: number;
71
+ }> | Unavailable;
72
+ consent?: ConsentStats | Unavailable;
73
+ requests?: RequestStats | Unavailable;
74
+ erasure?: TaskCounts | Unavailable;
75
+ access?: {
76
+ scanned: number;
77
+ findings: Partial<Record<AccessFindingKind, number>>;
78
+ examples: AccessFinding[];
79
+ } | Unavailable;
80
+ breaches?: BreachStatus[] | Unavailable;
81
+ /** What needs attention, in plain words. Empty when nothing does. */
82
+ gaps: string[];
83
+ }
84
+ export declare function describeRetention(retain: Retention): string;
85
+ /** The parts of the report that come from the config alone: no database needed. */
86
+ export declare function staticEvidence(config: DpdpConfig<string>, generatedAt?: string): EvidenceReport;
87
+ export declare function requestStats(requests: readonly RightsRequest[], from: string, to: string, now: string): RequestStats;
88
+ /** What needs attention, from everything else in the report. */
89
+ export declare function gapsOf(r: EvidenceReport): string[];
90
+ /** The report as Markdown, ready to save, print or convert to PDF. */
91
+ export declare function formatEvidence(r: EvidenceReport): string;
package/dist/express.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Dpdp } from "./dpdp.js";
2
+ import { type ApiOptions } from "./http.js";
2
3
  import { type AccessLogOptions, type GuardOptions } from "./guard.js";
3
4
  /** The parts of Express's response this middleware uses. */
4
5
  interface ResponseLike {
@@ -36,4 +37,33 @@ export declare function requireConsent<P extends string, Req = any, Res extends
36
37
  * ```
37
38
  */
38
39
  export declare function logAccess<P extends string, Req = any>(dpdp: Dpdp<P>, options: AccessLogOptions<Req, P>): (req: Req, _res: unknown, next: Next) => void;
40
+ /** The parts of Express's request the API uses. */
41
+ interface ApiRequestLike {
42
+ method: string;
43
+ path: string;
44
+ query: Record<string, unknown>;
45
+ body?: unknown;
46
+ ip?: string;
47
+ headers: Record<string, string | string[] | undefined>;
48
+ on(event: "data", listener: (chunk: Buffer) => void): unknown;
49
+ on(event: "end" | "error", listener: (err?: unknown) => void): unknown;
50
+ }
51
+ interface ApiResponseLike {
52
+ status(code: number): {
53
+ json(body: unknown): unknown;
54
+ };
55
+ setHeader(name: string, value: string): unknown;
56
+ }
57
+ /**
58
+ * The dpdp-kit HTTP API as Express middleware: consents, objections, the notice, the person's data,
59
+ * rights requests and nominees, and optional `/admin` routes for your privacy team. The person is
60
+ * whoever `subject` says is signed in; nothing in the request can choose someone else.
61
+ *
62
+ * ```ts
63
+ * app.use("/privacy", dpdpRouter(dpdp, { subject: (req) => req.user?.id, admin: (req) => req.staff?.id }));
64
+ * ```
65
+ *
66
+ * Works with or without `express.json()` before it. Unknown paths go on to your next handler.
67
+ */
68
+ export declare function dpdpRouter<P extends string, Req extends ApiRequestLike = any, Res extends ApiResponseLike = any>(dpdp: Dpdp<P>, options: ApiOptions<Req>): (req: Req, res: Res, next: Next) => void;
39
69
  export {};
package/dist/express.js CHANGED
@@ -1,8 +1,15 @@
1
1
  import {
2
- CONSENT_REQUIRED_BODY,
2
+ DEFAULT_BODY_LIMIT,
3
+ bodyOrResponse,
4
+ handle,
5
+ isApiRoute
6
+ } from "./chunk-HGN6TO6R.js";
7
+ import "./chunk-NBVJQDDP.js";
8
+ import {
3
9
  checkConsent,
10
+ consentDeniedBody,
4
11
  recordAccess
5
- } from "./chunk-5TVA2TKG.js";
12
+ } from "./chunk-3DOVLBUB.js";
6
13
  import "./chunk-67Q5GFD6.js";
7
14
 
8
15
  // src/express.ts
@@ -12,7 +19,7 @@ function requireConsent(dpdp, purpose, options) {
12
19
  (ok) => {
13
20
  if (ok) return next();
14
21
  if (options.onDenied) return options.onDenied(req, res, purpose);
15
- res.status(403).json(CONSENT_REQUIRED_BODY(purpose));
22
+ res.status(403).json(consentDeniedBody(dpdp, purpose));
16
23
  },
17
24
  (err) => next(err)
18
25
  );
@@ -23,7 +30,67 @@ function logAccess(dpdp, options) {
23
30
  recordAccess(dpdp, options, req).then(() => next(), (err) => next(err));
24
31
  };
25
32
  }
33
+ var header = (req, name) => {
34
+ const v = req.headers[name];
35
+ return Array.isArray(v) ? v[0] : v;
36
+ };
37
+ function readBody(req, limit) {
38
+ return new Promise((resolve, reject) => {
39
+ const chunks = [];
40
+ let size = 0;
41
+ req.on("data", (chunk) => {
42
+ size += chunk.length;
43
+ if (size <= limit) chunks.push(chunk);
44
+ });
45
+ req.on("end", () => resolve(size > limit ? null : Buffer.concat(chunks).toString("utf8")));
46
+ req.on("error", reject);
47
+ });
48
+ }
49
+ function dpdpRouter(dpdp, options) {
50
+ const limit = options.bodyLimit ?? DEFAULT_BODY_LIMIT;
51
+ const admin = options.admin !== void 0;
52
+ return (req, res, next) => {
53
+ if (!isApiRoute(req.method, req.path, { admin })) return next();
54
+ (async () => {
55
+ let body = req.body;
56
+ if (body === void 0 && req.method !== "GET" && req.method !== "HEAD") {
57
+ if (Number(header(req, "content-length") ?? 0) > limit) return { status: 413, body: { error: "payload-too-large" } };
58
+ const raw = await readBody(req, limit);
59
+ if (raw === null) return { status: 413, body: { error: "payload-too-large" } };
60
+ const parsed = bodyOrResponse(raw, limit);
61
+ if ("response" in parsed) return parsed.response;
62
+ body = parsed.body;
63
+ }
64
+ const [subjectId, actor] = await Promise.all([options.subject(req), options.admin?.(req)]);
65
+ const query = Object.fromEntries(Object.entries(req.query ?? {}).map(([k, v]) => [k, Array.isArray(v) ? String(v[0]) : v === void 0 ? void 0 : String(v)]));
66
+ const contentType = header(req, "content-type");
67
+ const userAgent = header(req, "user-agent");
68
+ return handle(
69
+ dpdp,
70
+ {
71
+ method: req.method,
72
+ path: req.path,
73
+ query,
74
+ body,
75
+ ...contentType ? { contentType } : {},
76
+ ...subjectId ? { subjectId } : {},
77
+ ...actor ? { actor } : {},
78
+ ...req.ip ? { ip: req.ip } : {},
79
+ ...userAgent ? { userAgent } : {}
80
+ },
81
+ { ...options, admin }
82
+ );
83
+ })().then(
84
+ (r) => {
85
+ res.setHeader("cache-control", "no-store");
86
+ res.status(r.status).json(r.body);
87
+ },
88
+ (err) => next(err)
89
+ );
90
+ };
91
+ }
26
92
  export {
93
+ dpdpRouter,
27
94
  logAccess,
28
95
  requireConsent
29
96
  };
package/dist/fastify.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
- CONSENT_REQUIRED_BODY,
3
2
  checkConsent,
3
+ consentDeniedBody,
4
4
  recordAccess
5
- } from "./chunk-5TVA2TKG.js";
5
+ } from "./chunk-3DOVLBUB.js";
6
6
  import "./chunk-67Q5GFD6.js";
7
7
 
8
8
  // src/fastify.ts
@@ -10,7 +10,7 @@ function requireConsent(dpdp, purpose, options) {
10
10
  return async (request, reply) => {
11
11
  if (await checkConsent(dpdp, purpose, options, request)) return void 0;
12
12
  if (options.onDenied) await options.onDenied(request, reply, purpose);
13
- if (!reply.sent) reply.code(403).send(CONSENT_REQUIRED_BODY(purpose));
13
+ if (!reply.sent) reply.code(403).send(consentDeniedBody(dpdp, purpose));
14
14
  return reply;
15
15
  };
16
16
  }
package/dist/guard.d.ts CHANGED
@@ -4,8 +4,29 @@ export interface GuardOptions<Ctx> {
4
4
  /** Read the signed-in person's id from the request. Return nothing when nobody is signed in. */
5
5
  subject: (ctx: Ctx) => string | null | undefined | Promise<string | null | undefined>;
6
6
  }
7
- /** Body sent when consent is missing. Safe to show to end users. */
8
- export declare const CONSENT_REQUIRED_BODY: (purpose: string) => {
7
+ /**
8
+ * Body sent when consent is missing, or (with `reason: "objected"`) when the person objected to a
9
+ * Section 7(a) use. Safe to show to end users.
10
+ */
11
+ export declare const CONSENT_REQUIRED_BODY: (purpose: string, reason?: "objected") => {
12
+ error: "consent_required";
13
+ purpose: string;
14
+ reason: "objected";
15
+ message: string;
16
+ } | {
17
+ reason?: never;
18
+ error: "consent_required";
19
+ purpose: string;
20
+ message: string;
21
+ };
22
+ /** The body for a refused request: says "objected" for a Section 7(a) purpose, since consent isn't what's missing. */
23
+ export declare function consentDeniedBody<P extends string>(dpdp: Dpdp<P>, purpose: P): {
24
+ error: "consent_required";
25
+ purpose: string;
26
+ reason: "objected";
27
+ message: string;
28
+ } | {
29
+ reason?: never;
9
30
  error: "consent_required";
10
31
  purpose: string;
11
32
  message: string;
package/dist/hono.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Dpdp } from "./dpdp.js";
2
+ import { type ApiOptions } from "./http.js";
2
3
  import { type AccessLogOptions, type GuardOptions } from "./guard.js";
3
4
  /** The parts of Hono's context this middleware uses. */
4
5
  interface ContextLike {
@@ -32,4 +33,24 @@ export declare function requireConsent<P extends string, C extends ContextLike =
32
33
  * ```
33
34
  */
34
35
  export declare function logAccess<P extends string, C = any>(dpdp: Dpdp<P>, options: AccessLogOptions<C, P>): (c: C, next: () => Promise<void>) => Promise<void>;
36
+ /** The parts of Hono's context the API uses. */
37
+ interface ApiContextLike {
38
+ req: {
39
+ raw: Request;
40
+ text(): Promise<string>;
41
+ };
42
+ }
43
+ /**
44
+ * The dpdp-kit HTTP API as a Hono handler. Mount it under `base`:
45
+ *
46
+ * ```ts
47
+ * app.all("/privacy/*", dpdpRoutes(dpdp, { base: "/privacy", subject: (c) => c.get("userId") }));
48
+ * ```
49
+ *
50
+ * `ip` gives the client address the way your runtime knows it, e.g. from `hono/conninfo`.
51
+ */
52
+ export declare function dpdpRoutes<P extends string, C extends ApiContextLike = any>(dpdp: Dpdp<P>, options: ApiOptions<C> & {
53
+ base: string;
54
+ ip?: (c: C) => string | undefined;
55
+ }): (c: C) => Promise<Response>;
35
56
  export {};
package/dist/hono.js CHANGED
@@ -1,8 +1,12 @@
1
1
  import {
2
- CONSENT_REQUIRED_BODY,
2
+ handleWeb
3
+ } from "./chunk-HGN6TO6R.js";
4
+ import "./chunk-NBVJQDDP.js";
5
+ import {
3
6
  checkConsent,
7
+ consentDeniedBody,
4
8
  recordAccess
5
- } from "./chunk-5TVA2TKG.js";
9
+ } from "./chunk-3DOVLBUB.js";
6
10
  import "./chunk-67Q5GFD6.js";
7
11
 
8
12
  // src/hono.ts
@@ -10,7 +14,7 @@ function requireConsent(dpdp, purpose, options) {
10
14
  return async (c, next) => {
11
15
  if (await checkConsent(dpdp, purpose, options, c)) return next();
12
16
  if (options.onDenied) return options.onDenied(c, purpose);
13
- return c.json(CONSENT_REQUIRED_BODY(purpose), 403);
17
+ return c.json(consentDeniedBody(dpdp, purpose), 403);
14
18
  };
15
19
  }
16
20
  function logAccess(dpdp, options) {
@@ -19,7 +23,11 @@ function logAccess(dpdp, options) {
19
23
  await next();
20
24
  };
21
25
  }
26
+ function dpdpRoutes(dpdp, options) {
27
+ return (c) => handleWeb(dpdp, c.req.raw, c, { ...options, readBody: () => c.req.text() });
28
+ }
22
29
  export {
30
+ dpdpRoutes,
23
31
  logAccess,
24
32
  requireConsent
25
33
  };
package/dist/http.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ import type { Dpdp } from "./dpdp.js";
2
+ /** One request, as the adapters hand it over. */
3
+ export interface HttpRequest {
4
+ method: string;
5
+ /** The path below where the API is mounted, e.g. `"/consents"`. */
6
+ path: string;
7
+ query?: Readonly<Record<string, string | undefined>>;
8
+ /** The parsed JSON body, if any. */
9
+ body?: unknown;
10
+ /** The `Content-Type` header. POST requests must be `application/json`. */
11
+ contentType?: string;
12
+ /** The signed-in person, from your own authentication. Never from the request itself. */
13
+ subjectId?: string;
14
+ /** The signed-in staff member, for `/admin` routes, from your own authentication. */
15
+ actor?: string;
16
+ ip?: string;
17
+ userAgent?: string;
18
+ }
19
+ export interface HttpResponse {
20
+ status: number;
21
+ body: unknown;
22
+ }
23
+ export interface HttpOptions {
24
+ /** Whether `/admin` routes exist. The adapters set this when you pass `admin`. */
25
+ admin?: boolean;
26
+ /**
27
+ * Called before each change a person makes (consents, objections, requests, nominees). Return
28
+ * false to refuse it with 429, e.g. to stop a script flooding someone's consent record.
29
+ */
30
+ limitWrites?: (subjectId: string) => boolean | Promise<boolean>;
31
+ /** Recorded as the consent event's `channel`. Default `"web"`. */
32
+ channel?: string;
33
+ /** Unexpected errors (not `DpdpError`). Default `console.error`. They answer 500 `{ error: "internal" }`. */
34
+ onError?: (err: unknown) => void;
35
+ }
36
+ /**
37
+ * Answer one request. Person routes need `subjectId`; `/admin` routes need `actor` and
38
+ * `options.admin`. Errors answer `{ error: code }` with no message, so nothing internal leaks.
39
+ */
40
+ export declare function handle<P extends string>(dpdp: Dpdp<P>, req: HttpRequest, options?: HttpOptions): Promise<HttpResponse>;
41
+ /**
42
+ * Whether the API answers this method and path (below where it's mounted). The adapters pass
43
+ * anything else on to your own handlers, before reading the body or checking who's signed in.
44
+ */
45
+ export declare function isApiRoute(method: string, path: string, options?: {
46
+ admin?: boolean;
47
+ }): boolean;
48
+ /** Read a body of at most `limit` bytes as JSON. An empty body is `undefined`. */
49
+ export declare function parseJsonBody(raw: string, limit: number): unknown;
50
+ /** The default body limit: 16 KiB, plenty for consents and requests. */
51
+ export declare const DEFAULT_BODY_LIMIT: number;
52
+ /** `parseJsonBody` as a response when it fails. */
53
+ export declare function bodyOrResponse(raw: string, limit: number): {
54
+ body: unknown;
55
+ } | {
56
+ response: HttpResponse;
57
+ };
58
+ /** Options shared by the framework adapters. `Req` is the framework's request or context. */
59
+ export interface ApiOptions<Req> extends Omit<HttpOptions, "admin"> {
60
+ /** The signed-in person's id, from your authentication. `undefined` answers 401. */
61
+ subject: (req: Req) => string | undefined | Promise<string | undefined>;
62
+ /**
63
+ * The signed-in staff member's id, for `/admin` routes, or `undefined` for anyone else (403).
64
+ * Without this option the `/admin` routes don't exist.
65
+ */
66
+ admin?: (req: Req) => string | undefined | Promise<string | undefined>;
67
+ /** Largest body accepted, in bytes. Default 16 KiB. */
68
+ bodyLimit?: number;
69
+ }
70
+ /**
71
+ * The API over Web `Request` and `Response`, for Hono, Next.js route handlers and other
72
+ * fetch-style servers. `base` is the path the API is mounted at, e.g. `"/api/privacy"`.
73
+ */
74
+ export declare function handleWeb<P extends string, Req>(dpdp: Dpdp<P>, request: Request, ctx: Req, options: ApiOptions<Req> & {
75
+ base?: string;
76
+ ip?: (req: Req) => string | undefined;
77
+ readBody?: () => Promise<string>;
78
+ }): Promise<Response>;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  export { type AccessAction, type AccessEntry, type AccessFilter, type AccessFinding, type AccessFindingKind, type AccessLogStore, type AccessReview, DEFAULT_ACCESS_LOG_RETENTION, isAccessLogStore, } from "./access.js";
2
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
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";
4
+ export { type Basis, type Category, type DpdpConfig, defineConfig, type ErasedValue, erasedValue, type EraseWith, type FiduciaryDef, type LegalHold, LEGITIMATE_USES, type LegitimateUse, type PersonalField, type ProcessorDef, type TransfersConfig, type PurposeDef, type Protection, type PurposeOf, REDACTED, type RightsConfig, type SecurityConfig, purposeNames, type Retention, type TableDef, } from "./config.js";
5
+ export { buildNotice, ENGLISH_WORDING, isNoticeStore, NOTICE_KINDS, type NoticeConfig, type NoticeItem, type NoticeKind, type NoticeLinks, type NoticeStore, type NoticeTranslation, type NoticeWording, type PrivacyNotice, type SavedNotice, } from "./notice.js";
6
+ export { describeRetention, type EvidenceReport, formatEvidence, isUnavailable, type RequestStats, staticEvidence, type Unavailable, } from "./evidence.js";
7
+ export { type ConsentStats, isStatsStore, type StatsStore, type TaskCounts } from "./stats.js";
8
+ export { type ApiOptions, handle, isApiRoute, type HttpOptions, type HttpRequest, type HttpResponse } from "./http.js";
5
9
  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";
6
10
  export { type Duration, durationMs, isDuration } from "./duration.js";
7
11
  export { type ErasurePlan, type ErasureReason, type FieldPlan, type PlanInput, type ProcessorPlan, planErasure, type TablePlan, } from "./erasure.js";
@@ -12,7 +16,7 @@ export { type Confidence, guessPersonal, type PersonalGuess, tokenize } from "./
12
16
  export { checkSchema, type Schema, type SchemaColumn, type SchemaTable } from "./schema-check.js";
13
17
  export { type ConsentAction, type ConsentEvent, type ConsentStore, type DpdpStore, isDpdpStore, memoryStore, } from "./store.js";
14
18
  export { type DataAccess, memoryData } from "./data-access.js";
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";
19
+ export { type ErasureTask, REQUEST_TYPES, type RequestFilter, type RequestHistoryEntry, isVerified, type Nominee, type RequestStatus, type RequestStore, type RequestType, type RightsRequest, type TaskFilter, type TaskKind, type TaskStatus, type TaskStore, } from "./records.js";
16
20
  export { type ProcessorHookInput, type ProcessorHooks, type RunReport, tasksFromPlan, } from "./retention.js";
17
- export { type AccessSummary, DEFAULT_RESPONSE_WITHIN } from "./rights.js";
21
+ export { type AccessSummary, type Acknowledgement, DEFAULT_RESPONSE_WITHIN, type RightsInfo } from "./rights.js";
18
22
  export { formatSafeguards, type Safeguard, type SafeguardStatus, safeguardsReport } from "./safeguards.js";