dpdp-kit 0.2.0 → 0.4.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 +90 -0
- package/README.md +240 -17
- package/dist/access.d.ts +111 -0
- package/dist/audit.d.ts +3 -1
- package/dist/breach.d.ts +170 -0
- package/dist/chunk-2ELTZSW3.js +94 -0
- package/dist/chunk-5TVA2TKG.js +37 -0
- package/dist/chunk-HXVP446N.js +1051 -0
- package/dist/chunk-KLMR7S7I.js +438 -0
- package/dist/cli.js +53 -17
- package/dist/config.d.ts +69 -0
- package/dist/data-access.d.ts +6 -2
- package/dist/ddl.d.ts +10 -0
- package/dist/dpdp.d.ts +210 -0
- package/dist/drizzle.d.ts +403 -11
- package/dist/drizzle.js +209 -56
- package/dist/errors.d.ts +1 -1
- package/dist/express.d.ts +17 -1
- package/dist/express.js +10 -2
- package/dist/fastify.d.ts +41 -0
- package/dist/fastify.js +25 -0
- package/dist/guard.d.ts +19 -0
- package/dist/hono.d.ts +16 -1
- package/dist/hono.js +11 -2
- package/dist/index.d.ts +7 -4
- package/dist/index.js +420 -100
- package/dist/mongodb.d.ts +87 -0
- package/dist/mongodb.js +344 -0
- package/dist/nestjs.d.ts +65 -0
- package/dist/nestjs.js +41 -0
- package/dist/postgres.d.ts +45 -0
- package/dist/postgres.js +27 -0
- package/dist/prisma.d.ts +43 -0
- package/dist/prisma.js +281 -0
- package/dist/protect.d.ts +74 -0
- package/dist/protect.js +114 -0
- package/dist/retention.d.ts +1 -1
- package/dist/run-audit.d.ts +13 -1
- package/dist/safeguards.d.ts +23 -0
- package/dist/schedule.d.ts +37 -0
- package/dist/schedule.js +66 -0
- package/dist/schema-check.d.ts +25 -8
- package/dist/store.d.ts +11 -1
- package/package.json +58 -5
- package/dist/chunk-FGZAH2NF.js +0 -16
- package/dist/chunk-KVTUMHXO.js +0 -491
package/dist/prisma.js
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import {
|
|
2
|
+
castType,
|
|
3
|
+
isUniqueViolation,
|
|
4
|
+
postgresData,
|
|
5
|
+
postgresStore
|
|
6
|
+
} from "./chunk-KLMR7S7I.js";
|
|
7
|
+
import {
|
|
8
|
+
DPDP_DDL
|
|
9
|
+
} from "./chunk-2ELTZSW3.js";
|
|
10
|
+
import "./chunk-67Q5GFD6.js";
|
|
11
|
+
|
|
12
|
+
// src/prisma.ts
|
|
13
|
+
var prismaQuery = (prisma) => async (text, params) => await prisma.$queryRawUnsafe(text, ...params);
|
|
14
|
+
function prismaStore(prisma) {
|
|
15
|
+
return postgresStore(prismaQuery(prisma));
|
|
16
|
+
}
|
|
17
|
+
function prismaData(prisma, options = {}) {
|
|
18
|
+
return postgresData(prismaQuery(prisma), options);
|
|
19
|
+
}
|
|
20
|
+
var SCALAR = {
|
|
21
|
+
String: { type: "string", sqlType: "text" },
|
|
22
|
+
Boolean: { type: "boolean", sqlType: "boolean" },
|
|
23
|
+
Int: { type: "number", sqlType: "integer" },
|
|
24
|
+
BigInt: { type: "number", sqlType: "bigint" },
|
|
25
|
+
Float: { type: "number", sqlType: "double precision" },
|
|
26
|
+
Decimal: { type: "number", sqlType: "numeric" },
|
|
27
|
+
DateTime: { type: "other", sqlType: "timestamp(3)" },
|
|
28
|
+
Json: { type: "other", sqlType: "jsonb" },
|
|
29
|
+
Bytes: { type: "other", sqlType: "bytea" }
|
|
30
|
+
};
|
|
31
|
+
var NATIVE = {
|
|
32
|
+
Text: "text",
|
|
33
|
+
VarChar: "varchar",
|
|
34
|
+
Char: "char",
|
|
35
|
+
Uuid: "uuid",
|
|
36
|
+
Citext: "citext",
|
|
37
|
+
Inet: "inet",
|
|
38
|
+
Xml: "xml",
|
|
39
|
+
Bit: "bit",
|
|
40
|
+
VarBit: "varbit",
|
|
41
|
+
SmallInt: "smallint",
|
|
42
|
+
Integer: "integer",
|
|
43
|
+
Oid: "oid",
|
|
44
|
+
BigInt: "bigint",
|
|
45
|
+
Real: "real",
|
|
46
|
+
DoublePrecision: "double precision",
|
|
47
|
+
Decimal: "numeric",
|
|
48
|
+
Money: "money",
|
|
49
|
+
Timestamp: "timestamp",
|
|
50
|
+
Timestamptz: "timestamptz",
|
|
51
|
+
Date: "date",
|
|
52
|
+
Time: "time",
|
|
53
|
+
Timetz: "timetz",
|
|
54
|
+
Boolean: "boolean",
|
|
55
|
+
Json: "json",
|
|
56
|
+
JsonB: "jsonb",
|
|
57
|
+
ByteA: "bytea"
|
|
58
|
+
};
|
|
59
|
+
var quote = (name) => `"${name.replace(/"/g, '""')}"`;
|
|
60
|
+
function stripComment(line) {
|
|
61
|
+
let inString = false;
|
|
62
|
+
for (let i = 0; i < line.length; i++) {
|
|
63
|
+
const ch = line[i];
|
|
64
|
+
if (ch === "\\" && inString) i++;
|
|
65
|
+
else if (ch === '"') inString = !inString;
|
|
66
|
+
else if (!inString && ch === "/" && line[i + 1] === "/") return line.slice(0, i);
|
|
67
|
+
}
|
|
68
|
+
return line;
|
|
69
|
+
}
|
|
70
|
+
var mapName = (attrs, prefix) => {
|
|
71
|
+
const m = new RegExp(`(?:^|\\s)${prefix === "@" ? "@" : "@@"}map\\(\\s*(?:name\\s*:\\s*)?"((?:[^"\\\\]|\\\\.)*)"`).exec(attrs);
|
|
72
|
+
return m ? m[1].replace(/\\(.)/g, "$1") : void 0;
|
|
73
|
+
};
|
|
74
|
+
function blocks(text) {
|
|
75
|
+
const out = [];
|
|
76
|
+
let current;
|
|
77
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
78
|
+
const line = stripComment(raw).trim();
|
|
79
|
+
if (!line) continue;
|
|
80
|
+
if (!current) {
|
|
81
|
+
const m = /^(model|view|enum|type)\s+(\w+)\s*\{\s*$/.exec(line);
|
|
82
|
+
if (m) current = { kind: m[1], name: m[2], lines: [] };
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (line === "}") {
|
|
86
|
+
out.push(current);
|
|
87
|
+
current = void 0;
|
|
88
|
+
} else current.lines.push(line);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
function prismaSchema(text) {
|
|
93
|
+
const all = blocks(text);
|
|
94
|
+
const enums = new Map(all.filter((b) => b.kind === "enum").map((b) => [b.name, mapName(b.lines.join(" "), "@@") ?? b.name]));
|
|
95
|
+
const composites = new Set(all.filter((b) => b.kind === "type").map((b) => b.name));
|
|
96
|
+
const models = new Set(all.filter((b) => b.kind === "model" || b.kind === "view").map((b) => b.name));
|
|
97
|
+
const tables = [];
|
|
98
|
+
const tableOf = /* @__PURE__ */ new Map();
|
|
99
|
+
const relations = [];
|
|
100
|
+
for (const block of all) {
|
|
101
|
+
if (block.kind !== "model" && block.kind !== "view") continue;
|
|
102
|
+
const columns = [];
|
|
103
|
+
let tableName = block.name;
|
|
104
|
+
for (const line of block.lines) {
|
|
105
|
+
if (line.startsWith("@@")) {
|
|
106
|
+
tableName = mapName(line, "@@") ?? tableName;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const m = /^(\w+)\s+(Unsupported\(\s*"(?:[^"\\]|\\.)*"\s*\)|[\w.]+)(\[\])?(\?)?(.*)$/.exec(line);
|
|
110
|
+
if (!m) continue;
|
|
111
|
+
const [, field, typeName, list, optional, attrs = ""] = m;
|
|
112
|
+
if (models.has(typeName) || composites.has(typeName)) {
|
|
113
|
+
const relation = /@relation\(([^)]*(?:\[[^\]]*\][^)]*)*)\)/.exec(attrs)?.[1] ?? "";
|
|
114
|
+
const fields = /fields\s*:\s*\[([^\]]*)\]/.exec(relation)?.[1];
|
|
115
|
+
if (fields && models.has(typeName)) {
|
|
116
|
+
const action = /onDelete\s*:\s*(\w+)/.exec(relation)?.[1];
|
|
117
|
+
relations.push({
|
|
118
|
+
model: block.name,
|
|
119
|
+
fields: fields.split(",").map((f) => f.trim()).filter(Boolean),
|
|
120
|
+
target: typeName,
|
|
121
|
+
// Prisma's defaults: SetNull for an optional relation, Restrict for a required one.
|
|
122
|
+
onDelete: PRISMA_ACTIONS[action ?? (optional ? "SetNull" : "Restrict")] ?? "no action"
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const name = mapName(attrs, "@") ?? field;
|
|
128
|
+
const native = /@db\.(\w+)(\(([^)]*)\))?/.exec(attrs);
|
|
129
|
+
let sqlType;
|
|
130
|
+
let type = "other";
|
|
131
|
+
const unsupported = /^Unsupported\(\s*"((?:[^"\\]|\\.)*)"/.exec(typeName);
|
|
132
|
+
if (unsupported) sqlType = unsupported[1];
|
|
133
|
+
else if (enums.has(typeName)) sqlType = quote(enums.get(typeName));
|
|
134
|
+
else if (SCALAR[typeName]) {
|
|
135
|
+
type = SCALAR[typeName].type;
|
|
136
|
+
sqlType = SCALAR[typeName].sqlType;
|
|
137
|
+
}
|
|
138
|
+
if (native && NATIVE[native[1]]) sqlType = `${NATIVE[native[1]]}${native[2] ?? ""}`;
|
|
139
|
+
if (sqlType && list) sqlType += "[]";
|
|
140
|
+
columns.push({
|
|
141
|
+
name,
|
|
142
|
+
...name === field ? {} : { key: field },
|
|
143
|
+
notNull: !optional && !list,
|
|
144
|
+
type: list ? "other" : type,
|
|
145
|
+
...sqlType ? { sqlType } : {}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
tableOf.set(block.name, tableName);
|
|
149
|
+
tables.push({ name: tableName, ...tableName === block.name ? {} : { key: block.name }, columns });
|
|
150
|
+
}
|
|
151
|
+
for (const r of relations) {
|
|
152
|
+
const table = tables.find((t) => (t.key ?? t.name) === r.model);
|
|
153
|
+
if (!table) continue;
|
|
154
|
+
const columnName = (field) => table.columns.find((c) => (c.key ?? c.name) === field)?.name ?? field;
|
|
155
|
+
const reference = { columns: r.fields.map(columnName), table: tableOf.get(r.target) ?? r.target, ...r.onDelete ? { onDelete: r.onDelete } : {} };
|
|
156
|
+
Object.assign(table, { references: [...table.references ?? [], reference] });
|
|
157
|
+
}
|
|
158
|
+
return { tables };
|
|
159
|
+
}
|
|
160
|
+
var PRISMA_ACTIONS = {
|
|
161
|
+
Cascade: "cascade",
|
|
162
|
+
SetNull: "set null",
|
|
163
|
+
SetDefault: "set default",
|
|
164
|
+
Restrict: "restrict",
|
|
165
|
+
NoAction: "no action"
|
|
166
|
+
};
|
|
167
|
+
var PRISMA_MODELS = `/// dpdp-kit: consent events, a hash chain per person (Section 6).
|
|
168
|
+
model DpdpConsentEvent {
|
|
169
|
+
subjectId String @map("subject_id")
|
|
170
|
+
seq Int
|
|
171
|
+
action String
|
|
172
|
+
purposes Json
|
|
173
|
+
noticeVersion String? @map("notice_version")
|
|
174
|
+
language String?
|
|
175
|
+
channel String?
|
|
176
|
+
evidence Json?
|
|
177
|
+
at DateTime @db.Timestamptz(6)
|
|
178
|
+
prevHash String? @map("prev_hash")
|
|
179
|
+
hash String
|
|
180
|
+
|
|
181
|
+
@@id([subjectId, seq])
|
|
182
|
+
@@map("dpdp_consent_events")
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/// dpdp-kit: rights requests and grievances (Sections 11 to 14).
|
|
186
|
+
model DpdpRequest {
|
|
187
|
+
id String @id
|
|
188
|
+
subjectId String @map("subject_id")
|
|
189
|
+
type String
|
|
190
|
+
status String
|
|
191
|
+
openedAt DateTime @map("opened_at") @db.Timestamptz(6)
|
|
192
|
+
dueAt DateTime @map("due_at") @db.Timestamptz(6)
|
|
193
|
+
closedAt DateTime? @map("closed_at") @db.Timestamptz(6)
|
|
194
|
+
details Json?
|
|
195
|
+
history Json
|
|
196
|
+
|
|
197
|
+
@@index([subjectId], map: "dpdp_requests_subject_idx")
|
|
198
|
+
@@index([status, dueAt], map: "dpdp_requests_status_due_idx")
|
|
199
|
+
@@map("dpdp_requests")
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/// dpdp-kit: erasure and processor tasks (Section 8(7), Rule 8).
|
|
203
|
+
model DpdpErasureTask {
|
|
204
|
+
id String @id
|
|
205
|
+
subjectId String @map("subject_id")
|
|
206
|
+
reason String
|
|
207
|
+
kind String
|
|
208
|
+
tableKey String? @map("table_key")
|
|
209
|
+
fields Json?
|
|
210
|
+
processor String?
|
|
211
|
+
purposes Json?
|
|
212
|
+
createdAt DateTime @map("created_at") @db.Timestamptz(6)
|
|
213
|
+
dueAt DateTime @map("due_at") @db.Timestamptz(6)
|
|
214
|
+
status String
|
|
215
|
+
attempts Int
|
|
216
|
+
claimedAt DateTime? @map("claimed_at") @db.Timestamptz(6)
|
|
217
|
+
doneAt DateTime? @map("done_at") @db.Timestamptz(6)
|
|
218
|
+
affected Int?
|
|
219
|
+
lastError String? @map("last_error")
|
|
220
|
+
note String?
|
|
221
|
+
|
|
222
|
+
@@index([subjectId], map: "dpdp_erasure_tasks_subject_idx")
|
|
223
|
+
@@index([status, dueAt], map: "dpdp_erasure_tasks_status_due_idx")
|
|
224
|
+
@@map("dpdp_erasure_tasks")
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/// dpdp-kit: who accessed whose data, and why (Rule 6(1)(c), (e)).
|
|
228
|
+
model DpdpAccessLog {
|
|
229
|
+
id String @id
|
|
230
|
+
at DateTime @db.Timestamptz(6)
|
|
231
|
+
actor String
|
|
232
|
+
subjectId String @map("subject_id")
|
|
233
|
+
action String
|
|
234
|
+
purpose String
|
|
235
|
+
fields Json?
|
|
236
|
+
outOfPurpose Json? @map("out_of_purpose")
|
|
237
|
+
reason String?
|
|
238
|
+
evidence Json?
|
|
239
|
+
|
|
240
|
+
@@index([at], map: "dpdp_access_log_at_idx")
|
|
241
|
+
@@index([subjectId, at], map: "dpdp_access_log_subject_idx")
|
|
242
|
+
@@index([actor, at], map: "dpdp_access_log_actor_idx")
|
|
243
|
+
@@map("dpdp_access_log")
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/// dpdp-kit: personal data breaches (Section 8(6), Rule 7).
|
|
247
|
+
model DpdpBreach {
|
|
248
|
+
id String @id
|
|
249
|
+
status String
|
|
250
|
+
awareAt DateTime @map("aware_at") @db.Timestamptz(6)
|
|
251
|
+
reportDueAt DateTime @map("report_due_at") @db.Timestamptz(6)
|
|
252
|
+
data Json
|
|
253
|
+
|
|
254
|
+
@@index([status, awareAt], map: "dpdp_breaches_status_idx")
|
|
255
|
+
@@map("dpdp_breaches")
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/// dpdp-kit: each person affected by a breach, and whether they've been told (Rule 7(1)).
|
|
259
|
+
model DpdpBreachNotice {
|
|
260
|
+
breachId String @map("breach_id")
|
|
261
|
+
subjectId String @map("subject_id")
|
|
262
|
+
status String
|
|
263
|
+
addedAt DateTime @map("added_at") @db.Timestamptz(6)
|
|
264
|
+
sentAt DateTime? @map("sent_at") @db.Timestamptz(6)
|
|
265
|
+
channel String?
|
|
266
|
+
|
|
267
|
+
@@id([breachId, subjectId])
|
|
268
|
+
@@index([breachId, status, addedAt], map: "dpdp_breach_notices_status_idx")
|
|
269
|
+
@@map("dpdp_breach_notices")
|
|
270
|
+
}
|
|
271
|
+
`;
|
|
272
|
+
export {
|
|
273
|
+
DPDP_DDL,
|
|
274
|
+
PRISMA_MODELS,
|
|
275
|
+
castType,
|
|
276
|
+
isUniqueViolation,
|
|
277
|
+
prismaData,
|
|
278
|
+
prismaQuery,
|
|
279
|
+
prismaSchema,
|
|
280
|
+
prismaStore
|
|
281
|
+
};
|
|
@@ -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 {};
|
package/dist/protect.js
ADDED
|
@@ -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
|
+
};
|
package/dist/retention.d.ts
CHANGED
package/dist/run-audit.d.ts
CHANGED
|
@@ -15,7 +15,19 @@ export declare function formatGithubAnnotations(issues: readonly Issue[], files:
|
|
|
15
15
|
config: string;
|
|
16
16
|
schema?: string | undefined;
|
|
17
17
|
}, root: string): string;
|
|
18
|
-
/** Load a
|
|
18
|
+
/** Load a schema module and read its tables: Mongoose models it exports, or else Drizzle tables. */
|
|
19
19
|
export declare function loadDrizzleSchema(file: string): Promise<Schema>;
|
|
20
|
+
/**
|
|
21
|
+
* Read a Prisma schema: a schema.prisma file, or a folder of .prisma files (a multi-file schema,
|
|
22
|
+
* e.g. prisma/schema).
|
|
23
|
+
*/
|
|
24
|
+
export declare function loadPrismaSchema(path: string): Promise<Schema>;
|
|
25
|
+
/** A Prisma schema (.prisma file or a folder of them), or else a Drizzle schema module. */
|
|
26
|
+
export declare function loadSchema(path: string): Promise<Schema>;
|
|
20
27
|
/** Run `dpdp-kit audit`. Returns the exit code: 1 when there are errors (or `--strict` and warnings). */
|
|
21
28
|
export declare function runAudit(argv: readonly string[], cwd: string, log: (line: string) => void): Promise<number>;
|
|
29
|
+
/**
|
|
30
|
+
* Run `dpdp-kit safeguards`: a Rule 6(1) report from the config. Returns 0, or with `--strict` 1
|
|
31
|
+
* when a safeguard is missing or partly recorded.
|
|
32
|
+
*/
|
|
33
|
+
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;
|
package/dist/schedule.js
ADDED
|
@@ -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
|
+
};
|
package/dist/schema-check.d.ts
CHANGED
|
@@ -1,22 +1,39 @@
|
|
|
1
1
|
import type { Issue } from "./audit.js";
|
|
2
|
-
import type
|
|
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";
|
|
11
|
+
/**
|
|
12
|
+
* The column's SQL type (`integer`, `uuid`, `varchar(255)`…), when known. SQL data access casts
|
|
13
|
+
* parameters to it. From `mongooseSchema()`, `array` marks an array, so erasure reaches every element.
|
|
14
|
+
*/
|
|
15
|
+
sqlType?: string;
|
|
16
|
+
}
|
|
17
|
+
/** A foreign key: these columns point at rows of another table. */
|
|
18
|
+
export interface SchemaReference {
|
|
19
|
+
/** The referencing columns, as named in the database. */
|
|
20
|
+
columns: readonly string[];
|
|
21
|
+
/** The referenced table's database name. */
|
|
22
|
+
table: string;
|
|
23
|
+
/** What the database does to these rows when the referenced row is deleted. Default "no action". */
|
|
24
|
+
onDelete?: "cascade" | "set null" | "set default" | "restrict" | "no action";
|
|
7
25
|
}
|
|
8
26
|
export interface SchemaTable {
|
|
27
|
+
/** The table's name in the database. */
|
|
9
28
|
name: string;
|
|
29
|
+
/** The name in code, if different: a Prisma model name (`User` for `@@map("users")`). The data map may use either. */
|
|
30
|
+
key?: string;
|
|
10
31
|
columns: readonly SchemaColumn[];
|
|
32
|
+
/** Foreign keys from this table. Used to check that legal holds survive account deletion. */
|
|
33
|
+
references?: readonly SchemaReference[];
|
|
11
34
|
}
|
|
12
|
-
/** Your database schema in a neutral shape. `drizzleSchema()`
|
|
35
|
+
/** Your database schema in a neutral shape. `drizzleSchema()`, `prismaSchema()` and `mongooseSchema()` build one. */
|
|
13
36
|
export interface Schema {
|
|
14
37
|
tables: readonly SchemaTable[];
|
|
15
38
|
}
|
|
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
39
|
export declare function checkSchema(config: DpdpConfig<string>, schema: Schema): Issue[];
|