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/nestjs.js ADDED
@@ -0,0 +1,41 @@
1
+ import {
2
+ checkConsent,
3
+ recordAccess
4
+ } from "./chunk-5TVA2TKG.js";
5
+ import {
6
+ DpdpError
7
+ } from "./chunk-67Q5GFD6.js";
8
+
9
+ // src/nestjs.ts
10
+ function requestOf(context, options, guard) {
11
+ const request = options.request ? options.request(context) : context.switchToHttp().getRequest();
12
+ if (request === void 0 || request === null) {
13
+ throw new DpdpError(
14
+ "invalid-input",
15
+ `${guard} found no request. It reads HTTP requests by default; for GraphQL or other contexts, pass request: (context) => \u2026.`
16
+ );
17
+ }
18
+ return request;
19
+ }
20
+ function consentGuard(dpdp, purpose, options) {
21
+ return {
22
+ async canActivate(context) {
23
+ const request = requestOf(context, options, "consentGuard");
24
+ if (await checkConsent(dpdp, purpose, options, request)) return true;
25
+ if (options.onDenied) throw options.onDenied(purpose, request);
26
+ return false;
27
+ }
28
+ };
29
+ }
30
+ function accessLogGuard(dpdp, options) {
31
+ return {
32
+ async canActivate(context) {
33
+ await recordAccess(dpdp, options, requestOf(context, options, "accessLogGuard"));
34
+ return true;
35
+ }
36
+ };
37
+ }
38
+ export {
39
+ accessLogGuard,
40
+ consentGuard
41
+ };
@@ -0,0 +1,74 @@
1
+ type KeyInput = string | Uint8Array;
2
+ /** A new random 256-bit key, as base64url text. Keep it in your secrets manager, not in code. */
3
+ export declare function generateKey(): string;
4
+ export interface EncryptorOptions {
5
+ /** Keys by id, each 32 bytes: base64 or base64url text (see `generateKey()`) or bytes. */
6
+ keys: Record<string, KeyInput>;
7
+ /** The id of the key that encrypts. The others only decrypt older values, so you can rotate keys. */
8
+ current: string;
9
+ }
10
+ export interface Encryptor {
11
+ /**
12
+ * Encrypt a value with AES-256-GCM. Each call uses a fresh random IV, so the same value encrypts
13
+ * differently every time; use `createTokenizer` to look values up. Pass `context` (for example
14
+ * `"users.phone:42"`) to bind the ciphertext to one place: decrypting it with another context
15
+ * fails, so a copied value can't be moved to another row.
16
+ */
17
+ encrypt(plaintext: string, context?: string): string;
18
+ /** Decrypt a value from `encrypt`. Throws `DpdpError("decrypt-failed")` if it was changed, or the key or context is wrong. */
19
+ decrypt(ciphertext: string, context?: string): string;
20
+ /** Whether a value looks like the output of `encrypt`. */
21
+ isEncrypted(value: string): boolean;
22
+ /** Whether a value was encrypted with a key other than `current`, and should be re-encrypted. */
23
+ needsRotation(ciphertext: string): boolean;
24
+ }
25
+ /**
26
+ * Field encryption for personal data at rest.
27
+ *
28
+ * ```ts
29
+ * const crypto = createEncryptor({ keys: { k1: process.env.DPDP_KEY_1! }, current: "k1" });
30
+ * const stored = crypto.encrypt(user.aadhaar, `users.aadhaar:${user.id}`);
31
+ * ```
32
+ */
33
+ export declare function createEncryptor(options: EncryptorOptions): Encryptor;
34
+ export interface TokenizerOptions {
35
+ /** A secret key, at least 32 bytes (see `generateKey()`). Use a different key from encryption. */
36
+ key: KeyInput;
37
+ /**
38
+ * Make equal values equal before tokenising, e.g. lower-case an email or strip spaces from a phone
39
+ * number. Default: trim surrounding whitespace.
40
+ */
41
+ normalize?: (value: string) => string;
42
+ }
43
+ export interface Tokenizer {
44
+ /**
45
+ * A stable token for a value (keyed HMAC-SHA256): the same value always gives the same token, and
46
+ * without the key the token reveals nothing about the value. Store it beside the encrypted value
47
+ * and look rows up by it, or use it in place of the value where you only need to match.
48
+ */
49
+ token(value: string): string;
50
+ }
51
+ /** Virtual tokens mapped to personal data, for lookups without storing the value in the clear. */
52
+ export declare function createTokenizer(options: TokenizerOptions): Tokenizer;
53
+ export interface MaskOptions {
54
+ /** Characters to leave visible at the start. Default 0. */
55
+ keepStart?: number;
56
+ /** Characters to leave visible at the end. Default 4. */
57
+ keepEnd?: number;
58
+ /** Replacement character. Default `"•"`. */
59
+ char?: string;
60
+ }
61
+ /** Hide all but a few characters of a value, for showing on screens and in logs. */
62
+ export declare function mask(value: string, options?: MaskOptions): string;
63
+ /** `"+91 98765 43210"` → `"+91 ••••••3210"`. Keeps an Indian country code if there is one. */
64
+ export declare function maskPhone(value: string): string;
65
+ /** `"asha.k@gmail.com"` → `"a•••••@gmail.com"`. The domain stays, so support staff can tell accounts apart. */
66
+ export declare function maskEmail(value: string): string;
67
+ /**
68
+ * `"1234 5678 9012"` → `"XXXX XXXX 9012"`: the masked Aadhaar format, which shows only the last four
69
+ * digits.
70
+ */
71
+ export declare function maskAadhaar(value: string): string;
72
+ /** `"ABCDE1234F"` → `"XXXXXX234F"`. */
73
+ export declare function maskPan(value: string): string;
74
+ export {};
@@ -0,0 +1,114 @@
1
+ import {
2
+ DpdpError
3
+ } from "./chunk-67Q5GFD6.js";
4
+
5
+ // src/protect.ts
6
+ import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "crypto";
7
+ var VERSION = "v1";
8
+ var KEY_BYTES = 32;
9
+ var IV_BYTES = 12;
10
+ function generateKey() {
11
+ return randomBytes(KEY_BYTES).toString("base64url");
12
+ }
13
+ function toKey(input, label, exact = true) {
14
+ const key = typeof input === "string" ? Buffer.from(input, "base64") : Buffer.from(input);
15
+ if (exact ? key.length !== KEY_BYTES : key.length < KEY_BYTES) {
16
+ throw new DpdpError(
17
+ "invalid-key",
18
+ `${label} must be ${exact ? "" : "at least "}${KEY_BYTES} bytes (base64 or base64url text, or bytes); got ${key.length}`
19
+ );
20
+ }
21
+ return key;
22
+ }
23
+ function createEncryptor(options) {
24
+ const keys = /* @__PURE__ */ new Map();
25
+ for (const [id, key] of Object.entries(options.keys)) {
26
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
27
+ throw new DpdpError("invalid-key", `Key id ${JSON.stringify(id)} may only use letters, digits, "_" and "-"`);
28
+ }
29
+ keys.set(id, toKey(key, `Key ${JSON.stringify(id)}`));
30
+ }
31
+ const current = keys.get(options.current);
32
+ if (!current) throw new DpdpError("invalid-key", `current key ${JSON.stringify(options.current)} isn't in keys`);
33
+ const parse = (value) => {
34
+ const parts = value.split(".");
35
+ if (parts.length !== 5 || parts[0] !== VERSION) return void 0;
36
+ const [, keyId, iv, tag, data] = parts;
37
+ return { keyId, iv: Buffer.from(iv, "base64url"), tag: Buffer.from(tag, "base64url"), data: Buffer.from(data, "base64url") };
38
+ };
39
+ return {
40
+ encrypt(plaintext, context) {
41
+ if (typeof plaintext !== "string") throw new DpdpError("invalid-input", "encrypt() takes a string");
42
+ const iv = randomBytes(IV_BYTES);
43
+ const cipher = createCipheriv("aes-256-gcm", current, iv);
44
+ if (context !== void 0) cipher.setAAD(Buffer.from(context, "utf8"));
45
+ const data = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
46
+ const tag = cipher.getAuthTag();
47
+ return [VERSION, options.current, iv.toString("base64url"), tag.toString("base64url"), data.toString("base64url")].join(".");
48
+ },
49
+ decrypt(ciphertext, context) {
50
+ const parsed = typeof ciphertext === "string" ? parse(ciphertext) : void 0;
51
+ if (!parsed) throw new DpdpError("decrypt-failed", "Not a value from encrypt()");
52
+ const key = keys.get(parsed.keyId);
53
+ if (!key) throw new DpdpError("decrypt-failed", `Encrypted with key ${JSON.stringify(parsed.keyId)}, which isn't in keys`);
54
+ try {
55
+ const decipher = createDecipheriv("aes-256-gcm", key, parsed.iv);
56
+ if (context !== void 0) decipher.setAAD(Buffer.from(context, "utf8"));
57
+ decipher.setAuthTag(parsed.tag);
58
+ return Buffer.concat([decipher.update(parsed.data), decipher.final()]).toString("utf8");
59
+ } catch {
60
+ throw new DpdpError("decrypt-failed", "Couldn't decrypt: the value was changed, or the key or context is wrong");
61
+ }
62
+ },
63
+ isEncrypted: (value) => typeof value === "string" && parse(value) !== void 0,
64
+ needsRotation(ciphertext) {
65
+ const parsed = parse(ciphertext);
66
+ return parsed !== void 0 && parsed.keyId !== options.current;
67
+ }
68
+ };
69
+ }
70
+ function createTokenizer(options) {
71
+ const key = toKey(options.key, "Tokenizer key", false);
72
+ const normalize = options.normalize ?? ((v) => v.trim());
73
+ return {
74
+ token(value) {
75
+ if (typeof value !== "string") throw new DpdpError("invalid-input", "token() takes a string");
76
+ return `tk_${createHmac("sha256", key).update(normalize(value), "utf8").digest("base64url")}`;
77
+ }
78
+ };
79
+ }
80
+ function mask(value, options = {}) {
81
+ const { keepStart = 0, keepEnd = 4, char = "\u2022" } = options;
82
+ const chars = [...value];
83
+ if (chars.length <= keepStart + keepEnd) return char.repeat(chars.length);
84
+ return chars.slice(0, keepStart).join("") + char.repeat(chars.length - keepStart - keepEnd) + chars.slice(chars.length - keepEnd).join("");
85
+ }
86
+ function maskPhone(value) {
87
+ const digits = value.replace(/\D/g, "");
88
+ if (digits.length === 12 && digits.startsWith("91")) return `+91 ${mask(digits.slice(2))}`;
89
+ return mask(digits);
90
+ }
91
+ function maskEmail(value) {
92
+ const at = value.lastIndexOf("@");
93
+ if (at <= 0) return mask(value);
94
+ const local = value.slice(0, at);
95
+ return mask(local, { keepStart: local.length > 1 ? 1 : 0, keepEnd: 0 }) + value.slice(at);
96
+ }
97
+ function maskAadhaar(value) {
98
+ const digits = value.replace(/\D/g, "");
99
+ if (digits.length !== 12) return mask(digits, { char: "X" });
100
+ return `XXXX XXXX ${digits.slice(8)}`;
101
+ }
102
+ function maskPan(value) {
103
+ return mask(value.trim().toUpperCase(), { char: "X" });
104
+ }
105
+ export {
106
+ createEncryptor,
107
+ createTokenizer,
108
+ generateKey,
109
+ mask,
110
+ maskAadhaar,
111
+ maskEmail,
112
+ maskPan,
113
+ maskPhone
114
+ };
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Records kept alongside consent events: rights requests (Sections 11–14) and erasure tasks
3
+ * (Section 8(7), Rule 8(3)).
4
+ */
5
+ /** The rights a person can exercise under Sections 11–14 of the Act. */
6
+ export type RequestType = "access" | "correction" | "erasure" | "grievance" | "nomination";
7
+ export declare const REQUEST_TYPES: readonly RequestType[];
8
+ export type RequestStatus = "open" | "resolved" | "rejected";
9
+ export interface RequestHistoryEntry {
10
+ at: string;
11
+ status: RequestStatus;
12
+ note?: string;
13
+ }
14
+ /** A rights request or grievance, from the moment it's raised until it's answered. */
15
+ export interface RightsRequest {
16
+ id: string;
17
+ subjectId: string;
18
+ type: RequestType;
19
+ status: RequestStatus;
20
+ openedAt: string;
21
+ /** When the answer is due. */
22
+ dueAt: string;
23
+ closedAt?: string;
24
+ /** What the person asked for: the correction, the nominee, the grievance text… */
25
+ details?: Record<string, unknown>;
26
+ /** Every status change, oldest first, so the response can be shown later. */
27
+ history: RequestHistoryEntry[];
28
+ }
29
+ /**
30
+ * One step of erasing a person's data.
31
+ * - `erase-fields`: set the listed fields to null in that table's rows for the person.
32
+ * - `delete-rows`: delete the person's rows in that table.
33
+ * - `processor-stop`: tell a processor to stop using the data for the ended purposes (Section 6(6)).
34
+ * - `processor-erase`: tell a processor to erase the data (Section 8(7)(b)).
35
+ */
36
+ export type TaskKind = "erase-fields" | "delete-rows" | "processor-stop" | "processor-erase";
37
+ /**
38
+ * - `pending`: waiting for its due date.
39
+ * - `running`: claimed by a runner.
40
+ * - `done`: carried out.
41
+ * - `failed`: the last attempt threw; retried on the next run (up to 5 attempts).
42
+ * - `manual`: needs a person, e.g. a processor with no `erase` hook. Mark it done when handled.
43
+ */
44
+ export type TaskStatus = "pending" | "running" | "done" | "failed" | "manual";
45
+ export interface ErasureTask {
46
+ id: string;
47
+ subjectId: string;
48
+ /** Why it exists: `"withdrawal"`, `"account-deletion"` or `"erasure-request"`. */
49
+ reason: string;
50
+ kind: TaskKind;
51
+ /** Key in `config.data`, for table tasks. */
52
+ table?: string;
53
+ /** Field names (as in the data map), for `erase-fields`. */
54
+ fields?: string[];
55
+ /** Key in `config.processors`, for processor tasks. */
56
+ processor?: string;
57
+ /** Purposes that ended, for processor tasks. */
58
+ purposes?: string[];
59
+ createdAt: string;
60
+ /** Not run before this time. */
61
+ dueAt: string;
62
+ status: TaskStatus;
63
+ attempts: number;
64
+ claimedAt?: string;
65
+ doneAt?: string;
66
+ /** Rows changed, for table tasks. */
67
+ affected?: number;
68
+ /** Message from the last failure, for developers. */
69
+ lastError?: string;
70
+ /** Who or what completed a manual task. */
71
+ note?: string;
72
+ }
73
+ export interface RequestFilter {
74
+ subjectId?: string;
75
+ status?: RequestStatus;
76
+ }
77
+ export interface TaskFilter {
78
+ subjectId?: string;
79
+ status?: TaskStatus;
80
+ }
81
+ /** Storage for rights requests. */
82
+ export interface RequestStore {
83
+ insertRequest(request: RightsRequest): Promise<void>;
84
+ getRequest(id: string): Promise<RightsRequest | undefined>;
85
+ /** Replace a stored request. */
86
+ updateRequest(request: RightsRequest): Promise<void>;
87
+ /** Oldest first. */
88
+ listRequests(filter: RequestFilter): Promise<RightsRequest[]>;
89
+ }
90
+ /** Storage for erasure tasks. */
91
+ export interface TaskStore {
92
+ insertTasks(tasks: readonly ErasureTask[]): Promise<void>;
93
+ /**
94
+ * Tasks to run now: `pending` or `failed` (fewer than `maxAttempts`) with `dueAt <= now`, plus
95
+ * `running` tasks claimed before `staleBefore` (their runner died). Oldest due first.
96
+ */
97
+ dueTasks(input: {
98
+ now: string;
99
+ staleBefore: string;
100
+ maxAttempts: number;
101
+ limit: number;
102
+ }): Promise<ErasureTask[]>;
103
+ /**
104
+ * Atomically mark a due task as `running`. Returns false if another runner got it first, so the
105
+ * same task is never carried out twice at once.
106
+ */
107
+ claimTask(input: {
108
+ id: string;
109
+ now: string;
110
+ staleBefore: string;
111
+ maxAttempts: number;
112
+ }): Promise<boolean>;
113
+ /** Replace a stored task. */
114
+ updateTask(task: ErasureTask): Promise<void>;
115
+ getTask(id: string): Promise<ErasureTask | undefined>;
116
+ /** Oldest due first. */
117
+ listTasks(filter: TaskFilter): Promise<ErasureTask[]>;
118
+ }
119
+ /** Whether a task can be picked up by a runner right now. */
120
+ export declare function isRunnable(task: ErasureTask, { now, staleBefore, maxAttempts }: {
121
+ now: string;
122
+ staleBefore: string;
123
+ maxAttempts: number;
124
+ }): boolean;
@@ -0,0 +1,47 @@
1
+ import { type DpdpConfig } from "./config.js";
2
+ import type { DataAccess } from "./data-access.js";
3
+ import type { ErasurePlan } from "./erasure.js";
4
+ import type { ErasureTask, TaskStore } from "./records.js";
5
+ /** What a processor hook is told. */
6
+ export interface ProcessorHookInput {
7
+ subjectId: string;
8
+ /** Purposes that ended. */
9
+ purposes: string[];
10
+ /** `"withdrawal"`, `"account-deletion"` or `"erasure-request"`. */
11
+ reason: string;
12
+ }
13
+ /**
14
+ * How to reach a third party you shared data with. A hook should call their API (or open a ticket).
15
+ * Without a hook the task becomes `manual`, for a person to handle and mark done.
16
+ */
17
+ export interface ProcessorHooks {
18
+ /** Stop using the person's data for the ended purposes (Section 6(6)). */
19
+ stop?: (input: ProcessorHookInput) => Promise<void> | void;
20
+ /** Erase the person's data (Section 8(7)(b)). */
21
+ erase?: (input: ProcessorHookInput) => Promise<void> | void;
22
+ }
23
+ export interface RunReport {
24
+ done: ErasureTask[];
25
+ failed: ErasureTask[];
26
+ manual: ErasureTask[];
27
+ }
28
+ export declare const MAX_ATTEMPTS = 5;
29
+ /** A `running` task claimed longer ago than this is assumed abandoned and picked up again. */
30
+ export declare const STALE_AFTER_MS: number;
31
+ /**
32
+ * Turn an erasure plan into dated tasks. Nothing is erased before the person's data has been kept
33
+ * for `config.minimumRetention` (Rule 8(3)), and legal holds wait for their own period. Those
34
+ * periods count from now, the time the plan is scheduled, which is never earlier than the last
35
+ * processing, so data is kept at least as long as the law requires.
36
+ */
37
+ export declare function tasksFromPlan(config: DpdpConfig<string>, plan: ErasurePlan, now: string): ErasureTask[];
38
+ export interface RunInput {
39
+ config: DpdpConfig<string>;
40
+ store: TaskStore;
41
+ data: DataAccess | undefined;
42
+ processors: Record<string, ProcessorHooks>;
43
+ now: string;
44
+ limit: number;
45
+ }
46
+ /** Carry out every due task once. Safe to run from several processes at the same time. */
47
+ export declare function runDueTasks(input: RunInput): Promise<RunReport>;
@@ -0,0 +1,49 @@
1
+ import type { Category, DpdpConfig } from "./config.js";
2
+ import type { DataAccess } from "./data-access.js";
3
+ import { type Duration } from "./duration.js";
4
+ import type { RequestType } from "./records.js";
5
+ /** Default answer time: Rule 14(3) caps grievance responses at ninety days. */
6
+ export declare const DEFAULT_RESPONSE_WITHIN: Duration;
7
+ export declare function responseWithin(config: DpdpConfig<string>, type: RequestType): Duration;
8
+ export declare function dueAt(config: DpdpConfig<string>, type: RequestType, openedAt: string): string;
9
+ /**
10
+ * What a person gets back from an access request (Section 11(1)): (a) the personal data you
11
+ * process and why, and (b) who else it was shared with.
12
+ */
13
+ export interface AccessSummary {
14
+ subjectId: string;
15
+ generatedAt: string;
16
+ data: Array<{
17
+ /** Key in `config.data`. */
18
+ key: string;
19
+ table: string;
20
+ fields: Array<{
21
+ field: string;
22
+ category: Category;
23
+ purposes: string[];
24
+ }>;
25
+ /** The person's rows, personal fields only. */
26
+ rows: Record<string, unknown>[];
27
+ }>;
28
+ /** Consent purposes currently granted. */
29
+ consents: string[];
30
+ /** Legitimate-use purposes that apply without consent (Section 7). */
31
+ legitimateUses: string[];
32
+ /**
33
+ * Processors that receive data for a purpose that applies to this person (Section 11(1)(b)).
34
+ * Section 11(2) exempts sharing with authorities for preventing or investigating offences;
35
+ * leave those out of `config.processors`.
36
+ */
37
+ sharedWith: Array<{
38
+ name: string;
39
+ description?: string;
40
+ purposes: string[];
41
+ }>;
42
+ }
43
+ export declare function buildAccessSummary(input: {
44
+ config: DpdpConfig<string>;
45
+ data: DataAccess;
46
+ subjectId: string;
47
+ consents: string[];
48
+ now: string;
49
+ }): Promise<AccessSummary>;
@@ -6,7 +6,21 @@ export declare function findConfig(cwd: string, explicit?: string): string | und
6
6
  /** Load a config file (TypeScript or JavaScript). Accepts a default export or `export const config`. */
7
7
  export declare function loadConfig(file: string): Promise<DpdpConfig<string>>;
8
8
  export declare function formatIssues(issues: readonly Issue[]): string;
9
+ /**
10
+ * GitHub Actions workflow commands, so each problem shows as an annotation on the pull request.
11
+ * Schema issues point at the schema file and the rest at the config file, relative to the
12
+ * repository root (`GITHUB_WORKSPACE`).
13
+ */
14
+ export declare function formatGithubAnnotations(issues: readonly Issue[], files: {
15
+ config: string;
16
+ schema?: string | undefined;
17
+ }, root: string): string;
9
18
  /** Load a Drizzle schema file and read its tables. */
10
19
  export declare function loadDrizzleSchema(file: string): Promise<Schema>;
11
20
  /** Run `dpdp-kit audit`. Returns the exit code: 1 when there are errors (or `--strict` and warnings). */
12
21
  export declare function runAudit(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
22
+ /**
23
+ * Run `dpdp-kit safeguards`: a Rule 6(1) report from the config. Returns 0, or with `--strict` 1
24
+ * when a safeguard is missing or partly recorded.
25
+ */
26
+ export declare function runSafeguards(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
@@ -0,0 +1,23 @@
1
+ import type { DpdpConfig } from "./config.js";
2
+ /**
3
+ * - `declared`: the config records it (a measure described, fields protected, contracts noted).
4
+ * - `partly`: some of it is recorded.
5
+ * - `missing`: nothing is recorded.
6
+ * - `in-code`: dpdp-kit provides it when your app uses the API (`dpdp.access`).
7
+ */
8
+ export type SafeguardStatus = "declared" | "partly" | "missing" | "in-code";
9
+ export interface Safeguard {
10
+ /** The clause of Rule 6(1), e.g. `"(a)"`. */
11
+ clause: string;
12
+ title: string;
13
+ status: SafeguardStatus;
14
+ /** What the config says, or what to add. */
15
+ details: string[];
16
+ }
17
+ /**
18
+ * Rule 6(1) of the DPDP Rules lists the minimum reasonable security safeguards, (a) to (g). This
19
+ * reports, for each one, what your config records as evidence and what's missing. It can't see
20
+ * your infrastructure: a described measure is only as true as the description.
21
+ */
22
+ export declare function safeguardsReport(config: DpdpConfig<string>): Safeguard[];
23
+ export declare function formatSafeguards(report: readonly Safeguard[]): string;
@@ -0,0 +1,37 @@
1
+ import type { DailyReport, Dpdp } from "./dpdp.js";
2
+ export interface StartDailyOptions {
3
+ /** Local time of day to run, `"HH:MM"` in 24-hour time. Default `"03:00"`. */
4
+ at?: string;
5
+ /** Called with each run's report, e.g. to alert on failed tasks or review findings. */
6
+ onReport?: (report: DailyReport) => void | Promise<void>;
7
+ /**
8
+ * Called when a run, or a step of it, fails. Default: `console.error`. The next day's run still
9
+ * happens, and its access review starts where the last successful one ended (up to a week back).
10
+ */
11
+ onError?: (error: unknown) => void;
12
+ /** Clock, for tests. */
13
+ now?: () => Date;
14
+ }
15
+ export interface DailySchedule {
16
+ /** Run once now (skipped if a run is already going). Resolves with the report, or undefined if skipped or failed. */
17
+ runNow(): Promise<DailyReport | undefined>;
18
+ /** When the next run is due. */
19
+ nextRunAt(): Date;
20
+ /** Stop scheduling runs. */
21
+ stop(): void;
22
+ }
23
+ /** Milliseconds from `now` until the next local `hours:minutes`. */
24
+ export declare function msUntil(now: Date, hours: number, minutes: number): number;
25
+ /**
26
+ * Run `dpdp.daily()` every day at a set local time, in this process, with no dependencies. Runs
27
+ * never overlap, and the timer doesn't keep the process alive on its own. If several servers each
28
+ * call this, each runs the job; that's safe (erasure tasks are claimed atomically), but you'll get
29
+ * one report per server. To run it once across servers, use your platform's cron or a BullMQ
30
+ * repeatable job with `dpdp.daily()` instead.
31
+ *
32
+ * ```ts
33
+ * import { startDaily } from "dpdp-kit/schedule";
34
+ * startDaily(dpdp, { at: "03:00", onReport: (r) => r.retention?.failed.length && alert(r) });
35
+ * ```
36
+ */
37
+ export declare function startDaily<P extends string>(dpdp: Dpdp<P>, options?: StartDailyOptions): DailySchedule;
@@ -0,0 +1,66 @@
1
+ import {
2
+ DpdpError
3
+ } from "./chunk-67Q5GFD6.js";
4
+
5
+ // src/schedule.ts
6
+ function msUntil(now, hours, minutes) {
7
+ const next = new Date(now);
8
+ next.setHours(hours, minutes, 0, 0);
9
+ if (next.getTime() <= now.getTime()) next.setDate(next.getDate() + 1);
10
+ return next.getTime() - now.getTime();
11
+ }
12
+ function startDaily(dpdp, options = {}) {
13
+ const at = options.at ?? "03:00";
14
+ const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(at);
15
+ if (!match) throw new DpdpError("invalid-input", `at must be "HH:MM" in 24-hour time, e.g. "03:00"; got ${JSON.stringify(at)}`);
16
+ const [hours, minutes] = [Number(match[1]), Number(match[2])];
17
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
18
+ const onError = options.onError ?? ((err) => console.error("dpdp-kit: the daily run failed", err));
19
+ let timer;
20
+ let running;
21
+ let stopped = false;
22
+ let next = new Date(now().getTime() + msUntil(now(), hours, minutes));
23
+ let reviewedUntil;
24
+ const MAX_CATCH_UP_MS = 7 * 24 * 60 * 60 * 1e3;
25
+ async function run() {
26
+ if (running) return void 0;
27
+ running = (async () => {
28
+ try {
29
+ const catchUp = reviewedUntil && now().getTime() - Date.parse(reviewedUntil) <= MAX_CATCH_UP_MS ? reviewedUntil : void 0;
30
+ const report = await dpdp.daily(catchUp ? { review: { from: catchUp } } : {});
31
+ if (report.review) reviewedUntil = report.review.to;
32
+ for (const failure of report.errors ?? []) onError(failure.error);
33
+ await options.onReport?.(report);
34
+ return report;
35
+ } catch (err) {
36
+ onError(err);
37
+ return void 0;
38
+ } finally {
39
+ running = void 0;
40
+ }
41
+ })();
42
+ return running;
43
+ }
44
+ function arm() {
45
+ if (stopped) return;
46
+ const wait = msUntil(now(), hours, minutes);
47
+ next = new Date(now().getTime() + wait);
48
+ timer = setTimeout(() => {
49
+ void run().finally(arm);
50
+ }, wait);
51
+ timer.unref?.();
52
+ }
53
+ arm();
54
+ return {
55
+ runNow: run,
56
+ nextRunAt: () => next,
57
+ stop() {
58
+ stopped = true;
59
+ if (timer) clearTimeout(timer);
60
+ }
61
+ };
62
+ }
63
+ export {
64
+ msUntil,
65
+ startDaily
66
+ };
@@ -1,9 +1,13 @@
1
1
  import type { Issue } from "./audit.js";
2
- import type { DpdpConfig } from "./config.js";
2
+ import { type DpdpConfig } from "./config.js";
3
3
  /** A column as your ORM sees it: its database name, and the property name in code if different. */
4
4
  export interface SchemaColumn {
5
5
  name: string;
6
6
  key?: string;
7
+ /** The column rejects NULL. Used to check each field's `erase` setting. */
8
+ notNull?: boolean;
9
+ /** Kind of value the column holds, when known. Used to check each field's `erase` setting. */
10
+ type?: "string" | "number" | "boolean" | "other";
7
11
  }
8
12
  export interface SchemaTable {
9
13
  name: string;
@@ -13,10 +17,4 @@ export interface SchemaTable {
13
17
  export interface Schema {
14
18
  tables: readonly SchemaTable[];
15
19
  }
16
- /**
17
- * Compare the data map with the real schema, both ways:
18
- * - columns that look personal but aren't in the data map (strong guesses are errors, weak ones
19
- * warnings), so a new `phone` column can't ship without a purpose;
20
- * - data map entries whose table or column no longer exists, so the map can't go stale.
21
- */
22
20
  export declare function checkSchema(config: DpdpConfig<string>, schema: Schema): Issue[];
package/dist/store.d.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import type { AccessEntry, AccessLogStore } from "./access.js";
1
2
  import type { NoticeLanguage } from "./languages.js";
3
+ import { type ErasureTask, type RequestStore, type RightsRequest, type TaskStore } from "./records.js";
2
4
  export type ConsentAction = "grant" | "withdraw";
3
5
  /** One entry in a person's consent record. Entries are only ever added, never changed. */
4
6
  export interface ConsentEvent {
@@ -32,7 +34,19 @@ export interface ConsentStore {
32
34
  /** All events for a subject, oldest first. */
33
35
  events(subjectId: string): Promise<ConsentEvent[]>;
34
36
  }
35
- /** Keeps events in memory. For tests and trying the library out; everything is lost on restart. */
36
- export declare function memoryStore(): ConsentStore & {
37
+ /** A store that also keeps rights requests and erasure tasks. Both built-in stores are one. */
38
+ export type DpdpStore = ConsentStore & RequestStore & TaskStore;
39
+ /** Whether a store can keep rights requests and erasure tasks too (custom stores may not). */
40
+ export declare function isDpdpStore(store: ConsentStore): store is DpdpStore;
41
+ /** Keeps everything in memory. For tests and trying the library out; everything is lost on restart. */
42
+ export declare function memoryStore(): DpdpStore & AccessLogStore & {
37
43
  readonly all: Map<string, ConsentEvent[]>;
44
+ readonly requests: Map<string, RightsRequest>;
45
+ readonly tasks: Map<string, ErasureTask>;
46
+ readonly accessLog: AccessEntry[];
38
47
  };
48
+ /**
49
+ * Purposes whose latest event is a grant: the person's consent state. Pass `until` (ISO 8601) for
50
+ * the state at that moment, counting only events at or before it.
51
+ */
52
+ export declare function grantedPurposes(events: readonly ConsentEvent[], until?: string): Set<string>;