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/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0
4
+
5
+ **Security safeguards and access logs (Rule 6 of the DPDP Rules)**, plus Fastify and NestJS guards, events, `NOT NULL` erasure and daily upkeep.
6
+
7
+ ### Added
8
+
9
+ - **Access log** (Rule 6(1)(c), (e)): `dpdp.access.log()`, `list()`, `review()` and `prune()`. Records who accessed whose personal data, for which purpose and which fields; flags fields read for a purpose they aren't held for (or refuses them with `access: { outOfPurpose: "throw" }`). `review()` reports out-of-purpose reads, consent purposes used without consent at the time, and bulk access (`ignoreActors` exempts batch jobs). `prune()` keeps at least a year.
10
+ - **`dpdp-kit/protect`** (Rule 6(1)(a)): `createEncryptor` (AES-256-GCM, tamper detection, row-binding context, key rotation), `createTokenizer` (keyed HMAC tokens for lookups), `mask`, `maskPhone`, `maskEmail`, `maskAadhaar`, `maskPan`, `generateKey`.
11
+ - **Rule 6 in the config and audit**: `protect` on fields, `contract` on processors, a `security` block (`accessControl`, `backups`, `measures`, `accessLogRetention`). New audit warnings: `unprotected-high-risk-field`, `processor-contract-missing`, `security-measure-missing`; new errors: `access-log-retention-too-short`, `invalid-erase`.
12
+ - **`npx dpdp-kit safeguards`**: Rule 6(1)(a)–(g), what's recorded and what's missing; `--strict` fails on gaps.
13
+ - **Guards**: `dpdp-kit/fastify` (`requireConsent`, `logAccess` as `preHandler` hooks) and `dpdp-kit/nestjs` (`consentGuard`, `accessLogGuard`), plus `logAccess` for Express and Hono.
14
+ - **Events**: `dpdp.on()` for `consent.granted`, `consent.withdrawn`, `erasure.scheduled`, `retention.ran`, `rights.opened`, `rights.closed`, `access.logged`, `daily.ran`.
15
+ - **`erase` on fields**: `"null"` (default), `"redact"` or `{ value }` (fixed or a function), so `NOT NULL` and `UNIQUE` columns can be erased.
16
+ - **Daily upkeep**: `dpdp.daily()` (erasure, access-log pruning and review, overdue requests) and `startDaily()` in `dpdp-kit/schedule`. Each step runs even if another fails (failures are in `report.errors`), and `startDaily` starts each review where the last successful one ended, so a failed night isn't skipped.
17
+ - **`audit --schema` checks erase settings against the columns**: `erase-not-null` when a `NOT NULL` column would be erased to `NULL`, `erase-type-mismatch` when the replacement doesn't fit the column. Without it, such a mistake shows up only when the task runs, often a year later.
18
+ - NestJS guards take a `request` option for GraphQL and other non-HTTP contexts; the Fastify guard falls back to 403 if `onDenied` sends nothing; event listeners each get their own copy of the payload; concurrent consent writes for one person back off with jitter.
19
+
20
+ ### Upgrading from 0.2.x
21
+
22
+ 1. **New table.** Add `accessLog` to your Drizzle schema (`export { accessLog } from "dpdp-kit/drizzle"`) and generate a migration, or run `ACCESS_LOG_DDL`.
23
+ 2. **New audit warnings.** If you run `dpdp-kit audit --strict`, add a `security` block and a `contract` for each processor first, and mark high-risk fields with `protect` (or the build will fail on the new warnings).
24
+ 3. **Custom `DataAccess`.** `eraseFields` now gets an optional fifth argument with each column's replacement value. Implementations that ignore it keep writing `NULL`, as before.
25
+ 4. **Custom stores.** The access log needs `AccessLogStore` (`insertAccess`, `listAccess`, `pruneAccess`). Without it, `dpdp.access` throws `store-unsupported` and `daily()` skips it.
26
+
27
+ ## 0.2.0
28
+
29
+ Rights requests (Sections 11–14, Rule 14), the retention runner (Section 8(7), Rule 8(3), legal holds), processor hooks, `drizzleData`, and the GitHub Action with pull request annotations.
30
+
31
+ ## 0.1.2
32
+
33
+ Schema drift check: `audit --schema`, `checkSchema`, `drizzleSchema`, `notPersonal`.
34
+
35
+ ## 0.1.0
36
+
37
+ Typed config, `audit` and the CLI, hash-chained consent records, erasure plans, the Drizzle store, Express and Hono guards.
package/README.md CHANGED
@@ -4,9 +4,14 @@
4
4
 
5
5
  **The Node.js-native toolkit for India's Digital Personal Data Protection Act, 2023.** Build it into your Node.js backend.
6
6
 
7
+ **Website and docs: [yogesh2902.github.io/dpdp-kit](https://yogesh2902.github.io/dpdp-kit/)**
8
+
9
+ ![dpdp-kit catching an unmapped aadhaar_number column in CI, then passing once it's mapped](docs/media/demo.gif)
10
+
7
11
  - **Declare why you hold each piece of personal data**, in one typed config file. A misspelt purpose is a type error.
8
12
  - **Keep consent records that show tampering.** Each person's grants and withdrawals form a hash chain, with the notice version and language they saw.
9
13
  - **Know what to erase.** When consent is withdrawn or an account is deleted, get a plan: which fields go, which stay (and why), which tables are under a legal hold, which third parties to tell.
14
+ - **Show who touched what.** An access log records who read whose data and why, flags reads outside a field's purpose, and keeps a year of entries, as Rule 6 requires. Encryption, tokens and masking for Aadhaar, PAN and other identifiers come in `dpdp-kit/protect`.
10
15
  - **Check it in CI.** `dpdp-kit audit` fails the build when the data map is inconsistent, and the GitHub Action puts each problem on the pull request.
11
16
  - **Catch drift.** `dpdp-kit audit --schema` reads your Drizzle schema and fails the build when someone adds a `phone`, `email` or `aadhaar_number` column without saying what it's for, or when the data map points at columns that no longer exist. Compliance that can't quietly fall out of date.
12
17
 
@@ -17,7 +22,7 @@ dpdp-kit is a TypeScript library that runs **inside your Node.js process**, not
17
22
  - **No separate server.** There's nothing to deploy, no sidecar to keep running, and no REST API between your code and your consent records.
18
23
  - **No hosted service.** No account, no API key, and no network calls. Personal data never leaves your infrastructure.
19
24
  - **Your own database.** Consent records go into your own Postgres, through the Drizzle setup you already have, in the same database as the rest of your data.
20
- - **Fits your Node stack.** Typed config, middleware for Express and Hono, a CLI for CI, and works with ESM, `require()` and TypeScript.
25
+ - **Fits your Node stack.** Typed config, guards for Express, Hono, Fastify and NestJS, a CLI for CI, and works with ESM, `require()` and TypeScript.
21
26
 
22
27
  > **Not legal advice.** dpdp-kit helps you put compliance into practice; it does not make an app compliant on its own. Section and rule references point you to the text so you can check them. Have your own lawyer review your purposes, notices and retention periods.
23
28
 
@@ -228,7 +233,17 @@ const report = await dpdp.retention.run(); // { done, failed, manual }
228
233
  - **Failures are retried**, up to 5 times. `lastError` keeps the database's message for developers, for example when a column is `NOT NULL`.
229
234
  - **A processor with no hook** gives a `manual` task. Handle it yourself (email their support), then `retention.markDone(taskId, "ticket 4411")`.
230
235
  - **Consent records are never erased.** Section 6(10) makes you prove consent, and Rule 8(3) requires keeping records of processing.
231
- - **Erasure sets columns to `NULL`**, so erasable columns must be nullable. Data access currently covers Postgres.
236
+ - **Erasure sets columns to `NULL` by default.** For a `NOT NULL` column, say what to write instead with the field's `erase` setting (below). Data access currently covers Postgres.
237
+
238
+ ```ts
239
+ fields: {
240
+ nickname: { category: "identity", purposes: ["newsletter"], erase: "redact" }, // "[erased]"
241
+ points: { category: "behavioural", purposes: ["newsletter"], erase: { value: 0 } },
242
+ email: { category: "contact", purposes: ["newsletter"], erase: { value: ({ subjectId }) => `erased-${subjectId}@invalid` } }, // NOT NULL UNIQUE
243
+ },
244
+ ```
245
+
246
+ The replacement must not identify the person: use their internal id, never a hash of their data. `dpdp-kit audit --schema` checks each setting against your columns (a `NOT NULL` column erased to `NULL`, or text into a number column), so a mistake fails CI now instead of the erasure a year from now.
232
247
 
233
248
  ## 5. Rights requests
234
249
 
@@ -264,7 +279,70 @@ Corrections and nominations are recorded with the request (`details`); your app
264
279
  rights: { responseWithin: { grievance: "30d", access: "30d" } },
265
280
  ```
266
281
 
267
- ## 6. Guard routes
282
+ ## 6. Security safeguards and access logs
283
+
284
+ Rule 6(1) of the DPDP Rules sets the minimum security safeguards, and a breach of Section 8(5) carries the Act's highest penalty, up to ₹250 crore. The parts that live in code are built in.
285
+
286
+ **Access log (Rule 6(1)(c) and (e)).** Record who accessed whose data, why, and which fields:
287
+
288
+ ```ts
289
+ await dpdp.access.log({
290
+ actor: "support:priya", // who
291
+ subjectId: userId, // whose data
292
+ purpose: "account", // why: one of your purposes
293
+ fields: ["users.phone", "orders"], // what: "table.field", or a whole table
294
+ reason: "ticket 4411",
295
+ });
296
+
297
+ await dpdp.access.list({ subjectId: userId }); // investigate one person, an actor, or a period
298
+ await dpdp.access.review(); // daily: find unauthorised access
299
+ await dpdp.access.prune(); // keeps at least a year, as Rule 6(1)(e) requires
300
+ ```
301
+
302
+ A field read for a purpose it isn't held for is recorded as `outOfPurpose` (or refused, with `createDpdp({ ..., access: { outOfPurpose: "throw" } })`). `review()` reports reads outside their purpose, consent purposes used when the person hadn't consented at that moment, and one actor reaching more than 100 people within an hour (both adjustable). Or log whole routes:
303
+
304
+ ```ts
305
+ import { logAccess } from "dpdp-kit/express"; // or "dpdp-kit/hono"
306
+ app.get("/admin/users/:id", logAccess(dpdp, {
307
+ purpose: "account",
308
+ fields: ["users"],
309
+ actor: (req) => req.staff?.id,
310
+ subject: (req) => req.params.id,
311
+ }), handler);
312
+ ```
313
+
314
+ **Encryption, masking and virtual tokens (Rule 6(1)(a)).** `dpdp-kit/protect` has AES-256-GCM field encryption with key rotation, keyed tokens for lookups, and masking:
315
+
316
+ ```ts
317
+ import { createEncryptor, createTokenizer, maskAadhaar } from "dpdp-kit/protect";
318
+
319
+ const enc = createEncryptor({ keys: { k1: process.env.DPDP_KEY_1! }, current: "k1" });
320
+ const stored = enc.encrypt(aadhaar, `users.aadhaar:${user.id}`); // bound to this row
321
+ enc.decrypt(stored, `users.aadhaar:${user.id}`);
322
+
323
+ const tokens = createTokenizer({ key: process.env.DPDP_TOKEN_KEY! });
324
+ tokens.token(email); // same email → same token, so you can look rows up without storing the email in the clear
325
+
326
+ maskAadhaar("1234 5678 9012"); // "XXXX XXXX 9012"
327
+ ```
328
+
329
+ Generate keys with `generateKey()` and keep them in your secrets manager. To rotate, add a new key, make it `current`, and re-encrypt values where `needsRotation(value)` is true.
330
+
331
+ **The rest, as evidence in the config.** Say how each field is protected, where each processor contract has its security clause (Rule 6(1)(f)), and the safeguards that live outside code:
332
+
333
+ ```ts
334
+ data: { users: { /* … */ fields: { aadhaar: { category: "identity", purposes: ["kyc"], protect: "encrypted" } } } },
335
+ processors: { msg91: { purposes: ["marketing_sms"], contract: "DPA signed 2026-03-01, clause 7" } },
336
+ security: {
337
+ accessControl: "SSO with least-privilege roles", // Rule 6(1)(b)
338
+ backups: "Encrypted daily backups, restore tested monthly", // Rule 6(1)(d)
339
+ measures: "Annual security training, quarterly access reviews", // Rule 6(1)(g)
340
+ },
341
+ ```
342
+
343
+ The audit warns about high-risk identifiers (Aadhaar, PAN, passport, bank account, card numbers, health and biometric data) without `protect`, processors without `contract`, and missing `security` entries. `npx dpdp-kit safeguards` prints the whole of Rule 6(1), (a) to (g), with what's recorded and what's missing (`--strict` fails on gaps).
344
+
345
+ ## 7. Guard routes
268
346
 
269
347
  ```ts
270
348
  // Express
@@ -276,7 +354,46 @@ import { requireConsent } from "dpdp-kit/hono";
276
354
  app.post("/promo", requireConsent(dpdp, "marketing_sms", { subject: (c) => c.get("userId") }), handler);
277
355
  ```
278
356
 
279
- Without consent, the middleware responds `403 { error: "consent_required", purpose, message }`. The message is plain enough to show to people. Pass `onDenied` to send your own response.
357
+ ```ts
358
+ // Fastify
359
+ import { requireConsent } from "dpdp-kit/fastify";
360
+ app.post("/promo", { preHandler: requireConsent(dpdp, "marketing_sms", { subject: (req) => req.user?.id }) }, handler);
361
+
362
+ // NestJS
363
+ import { consentGuard } from "dpdp-kit/nestjs";
364
+ @UseGuards(consentGuard(dpdp, "marketing_sms", { subject: (req) => req.user?.id }))
365
+ @Post("promo")
366
+ sendPromo() {}
367
+ ```
368
+
369
+ Without consent, the middleware responds `403 { error: "consent_required", purpose, message }`. The message is plain enough to show to people. Pass `onDenied` to send your own response; in NestJS, return the exception to throw, e.g. `(purpose) => new ForbiddenException(CONSENT_REQUIRED_BODY(purpose))`. Access logging works the same way in every framework: `logAccess` for Express, Hono and Fastify, `accessLogGuard` for NestJS.
370
+
371
+ ## 8. Events
372
+
373
+ Listen for changes to feed your own audit trail, alerts or analytics:
374
+
375
+ ```ts
376
+ const off = dpdp.on("consent.withdrawn", ({ event }) => analytics.forget(event.subjectId, event.purposes));
377
+ dpdp.on("access.logged", ({ entries }) => {
378
+ if (entries.some((e) => e.outOfPurpose)) slack.alert("Out-of-purpose read", entries);
379
+ });
380
+ ```
381
+
382
+ Events: `consent.granted`, `consent.withdrawn`, `erasure.scheduled`, `retention.ran`, `rights.opened`, `rights.closed`, `access.logged`. Listeners run after the change is saved and after the call returns, and a listener that throws can't break it: errors go to `onListenerError` (default `console.error`). For work that must happen exactly once, like telling a vendor to erase, use processor hooks and the retention runner instead.
383
+
384
+ ## 9. Daily upkeep
385
+
386
+ One call does the jobs that must happen on time: carry out due erasure, prune access logs older than a year, review the last day of access, and list overdue rights requests.
387
+
388
+ ```ts
389
+ const report = await dpdp.daily(); // { retention, accessPruned, review, overdueRequests, skipped }
390
+
391
+ // schedule it in-process, with no dependencies:
392
+ import { startDaily } from "dpdp-kit/schedule";
393
+ startDaily(dpdp, { at: "03:00", onReport: (r) => r.retention?.failed.length && alert(r) });
394
+ ```
395
+
396
+ Or call `dpdp.daily()` from node-cron, a BullMQ repeatable job (to run it once across servers), or your platform's cron. It's safe to run from several servers at once.
280
397
 
281
398
  ## Storage
282
399
 
@@ -286,18 +403,20 @@ Add the tables to your schema so drizzle-kit creates them:
286
403
 
287
404
  ```ts
288
405
  // schema.ts
289
- export { consentEvents, erasureTasks, rightsRequests } from "dpdp-kit/drizzle";
406
+ export { accessLog, consentEvents, erasureTasks, rightsRequests } from "dpdp-kit/drizzle";
290
407
  ```
291
408
 
292
409
  If you don't use drizzle-kit, run `DPDP_DDL` (exported from `dpdp-kit/drizzle`). This works with any Drizzle Postgres driver: node-postgres, postgres.js, Neon, PGlite.
293
410
 
294
411
  > **Upgrading from 0.1.x?** Add `rightsRequests` and `erasureTasks` to your schema and generate a migration, or run `RECORDS_DDL`. `withdraw()` now schedules erasure tasks, so it needs the `dpdp_erasure_tasks` table.
412
+ >
413
+ > **Upgrading from 0.2.x?** Add `accessLog` to your schema and generate a migration, or run `ACCESS_LOG_DDL`, before using `dpdp.access`. The audit now warns about the Rule 6 safeguards; if you run it with `--strict`, add a `security` block and processor `contract`s first.
295
414
 
296
415
  `drizzleData(db, { schema })` reaches your own tables. Pass your schema module when the data map uses Drizzle property names (`userId`) rather than column names (`user_id`).
297
416
 
298
417
  ### Anything else
299
418
 
300
- Implement `DpdpStore`: consent events (`lastEvent`, `insert`, `events`), requests and tasks (see `RequestStore` and `TaskStore`). `insert` must throw `SeqConflictError` on a duplicate `(subjectId, seq)`, and `claimTask` must be atomic. A store with only the three consent methods still works for consent; rights and retention then throw `store-unsupported`. Implement `DataAccess` (`read`, `eraseFields`, `deleteRows`) for another database. `memoryStore()` and `memoryData()` are included for tests.
419
+ Implement `DpdpStore`: consent events (`lastEvent`, `insert`, `events`), requests and tasks (see `RequestStore` and `TaskStore`), and `AccessLogStore` for the access log. `insert` must throw `SeqConflictError` on a duplicate `(subjectId, seq)`, and `claimTask` must be atomic. A store with only the three consent methods still works for consent; rights and retention then throw `store-unsupported`. Implement `DataAccess` (`read`, `eraseFields`, `deleteRows`) for another database. `memoryStore()` and `memoryData()` are included for tests.
301
420
 
302
421
  ## How the consent record works
303
422
 
@@ -315,8 +434,11 @@ Section 6(10) puts the burden on you: if consent is questioned in a proceeding,
315
434
  | **v0.1** | Config and types, `audit` + CLI, consent records, erasure plans, Drizzle store, Express/Hono guards |
316
435
  | **v0.1.2** | Schema drift check: `audit --schema`, `checkSchema`, `drizzleSchema`, `notPersonal` |
317
436
  | **v0.2.0** | Rights requests (Sections 11–14, Rule 14), retention runner that carries out erasure (Section 8(7), Rule 8(3), legal holds), processor hooks, `drizzleData`, GitHub Action with pull request annotations |
318
- | later | Recording objections to a Section 7(a) use, React notice that meets Rule 3 + privacy centre, MySQL and SQLite data access |
319
- | v0.3 | Breach records with deadlines (Section 8(6), Rule 7: people and the Board without delay, detailed report to the Board within 72 hours), children and guardian consent (Section 9, Rule 10), inactivity erasure with 48 hours' warning for large e-commerce, gaming and social media platforms (Rule 8(1)–(2), Third Schedule), Consent Manager interop (Sections 6(7)–6(9), Rule 4), Prisma store |
437
+ | **v0.3.0** | Security safeguards (Rule 6): access log with review and one-year retention, `dpdp-kit/protect` (encryption, virtual tokens, masking), `protect` / `contract` / `security` in the config, `dpdp-kit safeguards`; Fastify and NestJS guards; `logAccess` for every framework; events (`dpdp.on`); `erase` replacements for `NOT NULL` columns; `dpdp.daily()` and `startDaily` |
438
+ | next (0.4) | **Prisma and MongoDB** stores and data access (with a Prisma schema drift check); **breach records** with the deadlines of Section 8(6) and Rule 7 |
439
+ | then (0.5) | Notices that meet Rule 3 from the config, recording objections to a Section 7(a) use, an HTTP API with Express, Hono and Next.js adapters, completing rights requests, cross-border transfer records (Section 16) |
440
+ | after (0.6) | MySQL and SQLite data access, React and React Native consent screens, example apps |
441
+ | later | Children and guardian consent (Section 9, Rule 10), inactivity erasure (Rule 8(1)–(2), Third Schedule), erasure beyond SQL (files, caches, search indexes), Consent Manager interop (Sections 6(7)–6(9), Rule 4) |
320
442
 
321
443
  ## When the Rules apply
322
444
 
@@ -0,0 +1,106 @@
1
+ import type { DpdpConfig } from "./config.js";
2
+ import { type Duration } from "./duration.js";
3
+ import { type ConsentEvent } from "./store.js";
4
+ /** What was done with the data. Free text is allowed; these are the common ones. */
5
+ export type AccessAction = "read" | "export" | "update" | "delete" | "search" | (string & {});
6
+ /**
7
+ * One access to one person's personal data. Rule 6(1)(c) of the DPDP Rules requires "visibility on
8
+ * the accessing of such personal data, through appropriate logs, monitoring and review", and Rule
9
+ * 6(1)(e) requires keeping those logs for a year.
10
+ */
11
+ export interface AccessEntry {
12
+ id: string;
13
+ /** ISO 8601 timestamp. */
14
+ at: string;
15
+ /** Who accessed the data: a staff user's id, a service or job name. */
16
+ actor: string;
17
+ /** Whose data it was. */
18
+ subjectId: string;
19
+ action: AccessAction;
20
+ /** Why: one of the config's purposes. */
21
+ purpose: string;
22
+ /** What was accessed, as data map keys: `"users.phone"`. */
23
+ fields?: string[];
24
+ /** The fields from `fields` that aren't held for `purpose`. */
25
+ outOfPurpose?: string[];
26
+ /** Free text, e.g. a support ticket number. */
27
+ reason?: string;
28
+ /** Details of the request, e.g. IP address, user agent, request id. */
29
+ evidence?: Record<string, string>;
30
+ }
31
+ export interface AccessFilter {
32
+ subjectId?: string;
33
+ actor?: string;
34
+ purpose?: string;
35
+ /** ISO 8601, inclusive. */
36
+ from?: string;
37
+ /** ISO 8601, exclusive. */
38
+ to?: string;
39
+ limit?: number;
40
+ }
41
+ /** Storage for the access log. Both built-in stores implement it. */
42
+ export interface AccessLogStore {
43
+ insertAccess(entries: readonly AccessEntry[]): Promise<void>;
44
+ /** Entries matching the filter, oldest first. */
45
+ listAccess(filter: AccessFilter): Promise<AccessEntry[]>;
46
+ /** Delete entries older than `before` (ISO 8601). Returns how many were deleted. */
47
+ pruneAccess(before: string): Promise<number>;
48
+ }
49
+ export declare function isAccessLogStore(store: object): store is AccessLogStore;
50
+ /**
51
+ * An id that sorts in the order entries were written: the time, then a per-process counter for
52
+ * entries in the same millisecond, then random bits so ids from different servers never collide.
53
+ */
54
+ export declare function accessId(at: string): string;
55
+ /** Default and minimum time to keep the access log (Rule 6(1)(e)). */
56
+ export declare const DEFAULT_ACCESS_LOG_RETENTION = "1y";
57
+ /**
58
+ * Expand field keys against the data map: `"users.phone"` stays as it is; `"users.*"` and
59
+ * `"users"` become every personal field of that table. Returns the keys it doesn't know too.
60
+ */
61
+ export declare function resolveFields(config: DpdpConfig<string>, keys: readonly string[]): {
62
+ fields: string[];
63
+ unknown: string[];
64
+ };
65
+ /** The fields that aren't held for `purpose` according to the data map. */
66
+ export declare function fieldsOutsidePurpose(config: DpdpConfig<string>, fields: readonly string[], purpose: string): string[];
67
+ export type AccessFindingKind = "out-of-purpose" | "no-consent" | "bulk-access";
68
+ export interface AccessFinding {
69
+ kind: AccessFindingKind;
70
+ actor: string;
71
+ /** Plain-language explanation, for whoever reviews the log. */
72
+ message: string;
73
+ /** Ids of the log entries involved. */
74
+ entries: string[];
75
+ subjectId?: string;
76
+ purpose?: string;
77
+ /** For `bulk-access`: distinct people accessed within one window. */
78
+ subjects?: number;
79
+ }
80
+ export interface AccessReview {
81
+ from: string;
82
+ to: string;
83
+ /** Entries looked at. */
84
+ scanned: number;
85
+ findings: AccessFinding[];
86
+ }
87
+ export interface ReviewInput {
88
+ config: DpdpConfig<string>;
89
+ entries: readonly AccessEntry[];
90
+ from: string;
91
+ to: string;
92
+ /** Consent events for a person, oldest first. */
93
+ history: (subjectId: string) => Promise<readonly ConsentEvent[]>;
94
+ /** Window for bulk-access detection, e.g. `"1h"`. */
95
+ window: Duration;
96
+ /** More distinct people than this within one window is reported as bulk access. */
97
+ maxSubjects: number;
98
+ /** Actors exempt from bulk-access findings (batch jobs). */
99
+ ignoreActors?: readonly string[];
100
+ }
101
+ /**
102
+ * Look through access log entries for signs of unauthorised access (Rule 6(1)(c)): fields read for
103
+ * a purpose they aren't held for, consent purposes used without consent at the time, and one actor
104
+ * reaching an unusual number of people in a short time.
105
+ */
106
+ export declare function reviewAccess(input: ReviewInput): Promise<AccessReview>;
package/dist/audit.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { DpdpConfig } from "./config.js";
2
2
  export type IssueLevel = "error" | "warning";
3
3
  export interface Issue {
4
4
  level: IssueLevel;
5
- code: "no-purposes" | "invalid-basis" | "invalid-retention" | "invalid-duration" | "unknown-purpose" | "field-without-purpose" | "table-without-fields" | "missing-subject-column" | "unused-purpose" | "minimum-retention-missing" | "minimum-retention-too-short" | "grievance-missing" | "fiduciary-missing" | "invalid-not-personal" | "unknown-table" | "unknown-column" | "unmapped-personal-column" | "stale-not-personal" | "grievance-response-too-long" | "invalid-request-type";
5
+ code: "no-purposes" | "invalid-basis" | "invalid-retention" | "invalid-duration" | "unknown-purpose" | "field-without-purpose" | "table-without-fields" | "missing-subject-column" | "unused-purpose" | "minimum-retention-missing" | "minimum-retention-too-short" | "grievance-missing" | "fiduciary-missing" | "invalid-not-personal" | "unknown-table" | "unknown-column" | "unmapped-personal-column" | "stale-not-personal" | "grievance-response-too-long" | "invalid-request-type" | "unprotected-high-risk-field" | "processor-contract-missing" | "security-measure-missing" | "access-log-retention-too-short" | "invalid-erase" | "erase-not-null" | "erase-type-mismatch";
6
6
  /** Where in the config (`data.users.fields.phone`), or in the schema (`schema.users.phone`). */
7
7
  path: string;
8
8
  message: string;
@@ -12,4 +12,6 @@ export interface Issue {
12
12
  * reviewer should look at. This checks the config's own consistency, not legal compliance.
13
13
  */
14
14
  export declare function audit(config: DpdpConfig<string>): Issue[];
15
+ /** Whether a field holds high-risk data, judging by its declared category and its name. */
16
+ export declare function isHighRisk(field: string, category: string): boolean;
15
17
  export declare function hasErrors(issues: readonly Issue[]): boolean;
@@ -0,0 +1,37 @@
1
+ import {
2
+ DpdpError
3
+ } from "./chunk-67Q5GFD6.js";
4
+
5
+ // src/guard.ts
6
+ var CONSENT_REQUIRED_BODY = (purpose) => ({
7
+ error: "consent_required",
8
+ purpose,
9
+ message: "You haven't agreed to this yet. You can turn it on in your privacy settings."
10
+ });
11
+ async function checkConsent(dpdp, purpose, options, ctx) {
12
+ const subjectId = await options.subject(ctx);
13
+ if (!subjectId) return false;
14
+ return dpdp.consent.has(subjectId, purpose);
15
+ }
16
+ async function recordAccess(dpdp, options, ctx) {
17
+ const subject = await options.subject(ctx);
18
+ const subjectIds = typeof subject === "string" ? [subject] : subject ? [...subject] : [];
19
+ if (subjectIds.length === 0) return;
20
+ const actor = await options.actor(ctx);
21
+ if (!actor) throw new DpdpError("invalid-actor", "logAccess: actor() returned nothing; every access to personal data needs a known actor");
22
+ const evidence = options.evidence?.(ctx) ?? void 0;
23
+ await dpdp.access.log({
24
+ actor,
25
+ subjectIds,
26
+ purpose: options.purpose,
27
+ ...options.fields ? { fields: options.fields } : {},
28
+ ...options.action ? { action: options.action } : {},
29
+ ...evidence ? { evidence } : {}
30
+ });
31
+ }
32
+
33
+ export {
34
+ CONSENT_REQUIRED_BODY,
35
+ checkConsent,
36
+ recordAccess
37
+ };