deltaveil 0.0.0-stage → 0.1.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,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ Initial release prepared for Node.js 20+. Adds deep object differences, whole-array replacement, two-sided masking, privacy reports, reusable configuration, and ESM TypeScript declarations.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeltaVeil contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,216 @@
1
- # Temporary Holding Version
1
+ # DeltaVeil
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Track every change. Reveal no secrets.**
4
+
5
+ [GitHub repository](https://github.com/ARISTOTLE777/deltaVeil) · [Issue tracker](https://github.com/ARISTOTLE777/deltaVeil/issues)
6
+
7
+ DeltaVeil computes deep differences between JSON-like values and masks recognized sensitive data before returning an audit record. It runs synchronously on Node.js 20+ as a native ECMAScript module with zero dependencies. Use it when a profile edit, configuration update, or database write needs a readable history of what changed.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install deltaveil
13
+ ```
14
+
15
+ ## Quick start
16
+
17
+ ```js
18
+ import { diffAndMask } from 'deltaveil';
19
+
20
+ const before = { name: 'Rahul', balance: 5000, password: 'fixture-a' };
21
+ const after = { name: 'Rahul', balance: 8000, password: 'fixture-b' };
22
+ const result = diffAndMask(before, after);
23
+ ```
24
+
25
+ ```json
26
+ {
27
+ "changes": {
28
+ "balance": { "from": 5000, "to": 8000 },
29
+ "password": { "from": "***MASKED***", "to": "***MASKED***" }
30
+ },
31
+ "privacyReport": {
32
+ "maskedFields": ["password"],
33
+ "detectedTypes": ["password"],
34
+ "totalChanges": 2
35
+ }
36
+ }
37
+ ```
38
+
39
+ ### Nested records
40
+
41
+ ```js
42
+ import { diffAndMask } from 'deltaveil';
43
+
44
+ const before = { account: { profile: { contact: 'first@example.com', region: 'IN' } } };
45
+ const after = { account: { profile: { contact: null, region: 'IN', active: true } } };
46
+ const result = diffAndMask(before, after);
47
+ ```
48
+
49
+ ```json
50
+ {
51
+ "changes": {
52
+ "account": {
53
+ "profile": {
54
+ "active": { "added": true },
55
+ "contact": { "from": "***MASKED***", "to": "***MASKED***" }
56
+ }
57
+ }
58
+ },
59
+ "privacyReport": {
60
+ "maskedFields": ["account.profile.contact"],
61
+ "detectedTypes": ["email"],
62
+ "totalChanges": 2
63
+ }
64
+ }
65
+ ```
66
+
67
+ ### Arrays
68
+
69
+ An array replacement counts once. Both snapshots preserve order and sanitize every emitted element, including unchanged credentials. The comparison uses the original values, so two changed passwords produce a change even when the sanitized snapshots look identical.
70
+
71
+ ```js
72
+ import { diffAndMask } from 'deltaveil';
73
+
74
+ const result = diffAndMask(
75
+ { users: [{ id: 1, password: 'fixture-a' }] },
76
+ { users: [{ id: 1, password: 'fixture-b' }] }
77
+ );
78
+ ```
79
+
80
+ ```json
81
+ {
82
+ "changes": {
83
+ "users": {
84
+ "from": [{ "id": 1, "password": "***MASKED***" }],
85
+ "to": [{ "id": 1, "password": "***MASKED***" }]
86
+ }
87
+ },
88
+ "privacyReport": {
89
+ "maskedFields": ["users[0].password"],
90
+ "detectedTypes": ["password"],
91
+ "totalChanges": 1
92
+ }
93
+ }
94
+ ```
95
+
96
+ ## Comparison and reporting
97
+
98
+ | Situation | Entry in `changes` | Contribution to `totalChanges` |
99
+ | --- | --- | --- |
100
+ | Equal values | Omitted, or `{}` at the root | 0 |
101
+ | Modified scalar, changed array, or change of type | `{ from, to }` | 1 |
102
+ | Both sides are ordinary records | Changed properties only | Sum of changed descendants |
103
+ | Property added or removed | `{ added }` or `{ removed }` containing a sanitized snapshot | Number of leaves, treating each array, empty record, or fully masked parent as one |
104
+ | Changed sensitive parent | Mask marker on every present side | 1 |
105
+
106
+ Values compare with `Object.is` at the leaves. `NaN` equals itself, while `0` and `-0` differ. An own property with value `undefined` differs from an absent property. Sparse arrays preserve holes and distinguish them from present `undefined` values. Native JSON serialization omits undefined object properties and loses distinctions including holes, nonfinite numbers, and signed zero. Choose a storage encoding appropriate for your audit data.
107
+
108
+ The optional `privacyReport` provides sorted, unique `maskedFields` paths and `detectedTypes` labels, plus the count above. Omitted unchanged branches contribute no paths. A completely masked parent contributes its own path only. Disabling the report keeps masking active.
109
+
110
+ Paths start at the first property (`user.password`) or array index (`[0].contact`). A masked root scalar uses `$`. Unusual property names use JSON-quoted brackets, as in `["a.b"].password`, `["0"]`, and `["$"]`. Array indices use unquoted decimal numbers. Paths and diff keys expose the schema. Use stable, nonsensitive field names. A key that itself matches an enabled whole-value detector causes a generic error before output is built.
111
+
112
+ ## Masking rules
113
+
114
+ Built-in sensitive names include `password`, `passwordHash`, `secret`, `clientSecret`, `token`, `accessToken`, `refreshToken`, `apiKey`, `api_key`, `authorization`, `privateKey`, `cvv`, `aadhaar`, and `ssn`. These map to stable category labels such as `password`, `secret`, `token`, and `apiKey`.
115
+
116
+ Normalized matching folds case, spaces, underscores, and hyphens. It also recognizes built-in names at camel-case and separator-delimited suffixes such as `userPassword` and `user_password`. In exact mode the full spelling and case must match. Add ambiguous domain-specific keys such as `pin` and `pan` explicitly. A custom bare name matches a complete field at any depth. Names composed entirely of separators match their literal spelling. The reserved path `$` masks the entire root value. Use `["$"]` to select a literal root property named `$`. Custom paths anchor at the root, support quoted names and numeric indices, and use the selected matching mode on each field. For example, `billing.taxId` scopes a rule to one parent, while `["billing.taxId"]` selects a literal root key. Custom matches receive the label `custom`.
117
+
118
+ Value detection inspects **both sides**. If either direct value is recognized, both are masked. Array snapshots apply this rule to corresponding indices and object properties. When a key rule matches, it takes precedence over value categories and masks the whole field, including any children.
119
+
120
+ ```js
121
+ import { detectSensitiveValue } from 'deltaveil';
122
+
123
+ const category = detectSensitiveValue('contact@example.com'); // 'email'
124
+ const phone = detectSensitiveValue('+12025550123', { detectPhones: true }); // 'phone'
125
+ ```
126
+
127
+ The classifier returns `'email'`, `'token'`, `'phone'`, or `null`. It inspects individual strings and returns `null` for other types.
128
+
129
+ | Category | Recognized whole-string shapes |
130
+ | --- | --- |
131
+ | Email | Common ASCII dot-atom addresses with a dotted domain and alphabetic suffix |
132
+ | Token | Three base64url-like JWT segments starting with `eyJ`, or `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_` followed by 36–255 alphanumeric characters |
133
+ | Phone (opt-in) | A plus sign followed by 8–15 digits, starting with a nonzero digit |
134
+
135
+ A positional rule such as `users[0].id` protects that position. For lists that reorder, use a field rule that applies at every index. These heuristics can mask an ordinary identifier and miss a secret. Free text, embedded matches, internationalized email, local phone formats, opaque credentials, and provider formats outside the listed patterns need application-specific handling. Token recognition checks format only. A privacy report records decisions made by these rules. It cannot establish anonymization or regulatory compliance.
136
+
137
+ ## Configuration and factory
138
+
139
+ | Option | Default | Accepted values and behavior |
140
+ | --- | --- | --- |
141
+ | `maskString` | `'***MASKED***'` | Any string. Use a public constant. |
142
+ | `sensitiveKeys` | `[]` | Dense array of nonempty field names or paths. Extends built-ins. |
143
+ | `detectEmails` | `true` | Boolean |
144
+ | `detectPhones` | `false` | Boolean |
145
+ | `detectTokens` | `true` | Boolean |
146
+ | `arrayStrategy` | `'replace'` | Whole-array replacement is the supported strategy. |
147
+ | `circular` | `'throw'` | `'throw'` or `'truncate'` |
148
+ | `maxDepth` | `64` | Integer from 1 to 256. Root depth is zero. |
149
+ | `includePrivacyReport` | `true` | Boolean |
150
+ | `keyMatchMode` | `'normalized'` | `'normalized'` or `'exact'` |
151
+
152
+ ```js
153
+ import { createDeltaMask } from 'deltaveil';
154
+
155
+ const audit = createDeltaMask({ sensitiveKeys: ['billing.taxId'], maskString: '[hidden]' });
156
+ const result = audit({}, { billing: { taxId: 'sample-id' } }, { includePrivacyReport: false });
157
+ // result.changes.billing.added.taxId === '[hidden]'
158
+ ```
159
+
160
+ A factory captures a detached copy of its configuration. Overrides apply to one call. An override of `sensitiveKeys` replaces the factory's custom list for that call. Built-ins always apply. Unknown options, malformed paths, invalid types, and unsupported modes throw.
161
+
162
+ ### TypeScript
163
+
164
+ Declarations ship with the ESM entry point. A NodeNext ESM project can type its audit report directly.
165
+
166
+ ```ts
167
+ import { diffAndMask, type DeltaVeilOptions, type PrivacyReport } from 'deltaveil';
168
+
169
+ const options = { sensitiveKeys: ['taxId'] } satisfies DeltaVeilOptions;
170
+ const report: PrivacyReport = diffAndMask({}, { taxId: 'sample-id' }, options).privacyReport;
171
+ const changed: number = report.totalChanges;
172
+ ```
173
+
174
+ ## Backend audit logging
175
+
176
+ ```js
177
+ import { createDeltaMask } from 'deltaveil';
178
+
179
+ const audit = createDeltaMask({ sensitiveKeys: ['recoveryCode'] });
180
+ export async function saveUserAudit(tx, before, after) {
181
+ const delta = audit(before, after);
182
+ return tx.auditLog.create({ data: { event: 'user.updated', delta } });
183
+ }
184
+ ```
185
+
186
+ Call this inside the same database transaction as the user update using the snapshots for that update. The audit row contains an event and the sanitized diff. If the row needs a subject identifier, use a separately approved identifier. Copying a record field directly into audit metadata bypasses masking. Select an audit-appropriate set of columns, and convert database-native dates or decimal objects explicitly. The executable [simulated integration](examples/express-audit.js) uses an internal numeric subject ID and an in-memory repository so it can run without Express, Prisma, or a database.
187
+
188
+ ## Input safety, cycles, and errors
189
+
190
+ Pass strings, numbers, booleans, null, undefined, ordinary local arrays, and plain records with `Object.prototype` or a null prototype. Only own, enumerable, string-keyed data properties are accepted. Arrays can have index properties and their standard length. Accessors, proxies, symbol keys, extra array properties, dates, typed arrays, maps, sets, regular expressions, functions, bigints, and class instances are unsupported. Convert a Date explicitly with `getTime()` or `toISOString()` before comparison.
191
+
192
+ Validation includes unchanged and masked branches. `TypeError` covers unsupported inputs or invalid option types. `RangeError` covers unsupported modes and traversal limits. Input values are excluded from diagnostics. Catch errors at the audit boundary and apply your application's transaction policy. Keep raw records out of error logs.
193
+
194
+ An active recursion stack distinguishes cycles from shared children. The default throws a `TypeError` containing `Circular reference detected`. Truncation treats each back-edge as a terminal marker and renders it as `"[Circular]"` unless masked. Distinct cycle targets can produce the same truncated shape. A real marker is distinct from a literal string during comparison, although the rendered strings can look identical. A shared child is visited at each path so different field policies can apply.
195
+
196
+ Both complete inputs are validated before comparison. Unchanged subtrees need no deep clone. Changed arrays require full sanitized snapshots on both sides, which can dominate runtime and memory. Sorting a record's keys adds sorting cost. Shared references are counted per occurrence. Each side is limited to one million visited values, counting the root, each container, and each array slot (including holes). The configured depth limit applies separately. Limit incoming data sizes, array lengths, and property-name lengths to suit your service. The runtime library performs no network, filesystem, environment, or telemetry access.
197
+
198
+ ## Development
199
+
200
+ Run the following commands from a source checkout with Node.js 20+.
201
+
202
+ ```sh
203
+ npm test
204
+ npm run lint
205
+ npm run check
206
+ npm pack --dry-run
207
+ node examples/basic.js
208
+ node examples/nested.js
209
+ node examples/express-audit.js
210
+ ```
211
+
212
+ The suite uses `node:test` and strict assertions. Lint runs Node's syntax checker across runtime, example, test, and tooling JavaScript. For contributions, include synthetic regression fixtures for behavior changes, check the declarations and examples, and run the checks above. Send security findings privately as described in [SECURITY.md](SECURITY.md).
213
+
214
+ ## License
215
+
216
+ [MIT](LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,11 @@
1
+ # Security
2
+
3
+ ## Report a vulnerability
4
+
5
+ Use the private advisory form to report a vulnerability. Include the DeltaVeil and Node.js versions, a minimal example using synthetic records, the expected result, and the observed impact. Keep credentials and production records out of the report. [Report privately on GitHub](https://github.com/ARISTOTLE777/deltaVeil/security/advisories/new)
6
+
7
+ If the form is unavailable, open a public issue asking the maintainer to enable private reporting. Share technical details only after a private channel is available. [DeltaVeil issue tracker](https://github.com/ARISTOTLE777/deltaVeil/issues)
8
+
9
+ ## Handling audit data
10
+
11
+ DeltaVeil accepts ordinary in-process data on a trusted Node.js runtime. The library reads own data properties, rejects proxies and accessors, and performs no logging or I/O. Results include unclassified values and field names. Use schema-specific sensitive keys and log only permitted fields. Use a fixed public mask string. See the README for detector, traversal, serialization, and audit storage limits.
@@ -0,0 +1,5 @@
1
+ import { diffAndMask } from 'deltaveil';
2
+
3
+ const before = { name: 'Rahul', balance: 5000, password: 'fixture-a' };
4
+ const after = { name: 'Rahul', balance: 8000, password: 'fixture-b' };
5
+ console.log(JSON.stringify(diffAndMask(before, after), null, 2));
@@ -0,0 +1,25 @@
1
+ import { createDeltaMask } from 'deltaveil';
2
+
3
+ const audit = createDeltaMask({ sensitiveKeys: ['recoveryCode'] });
4
+
5
+ // Stand-ins for a transaction's user and auditLog repositories.
6
+ const auditRows = [];
7
+ const tx = {
8
+ user: {
9
+ async findUniqueOrThrow() { return { id: 7, role: 'viewer', recoveryCode: null }; },
10
+ async update({ where, data }) { return { id: where.id, ...data }; }
11
+ },
12
+ auditLog: {
13
+ async create({ data }) { auditRows.push(data); }
14
+ }
15
+ };
16
+
17
+ async function changeRole(tx, id, patch) {
18
+ if (!Number.isSafeInteger(id)) throw new TypeError('Expected an internal numeric subject ID');
19
+ const before = await tx.user.findUniqueOrThrow({ where: { id } });
20
+ const after = await tx.user.update({ where: { id }, data: patch });
21
+ await tx.auditLog.create({ data: { event: 'user.updated', subjectId: id, delta: audit(before, after) } });
22
+ }
23
+
24
+ await changeRole(tx, 7, { role: 'editor', recoveryCode: 'sample-code' });
25
+ console.log(JSON.stringify(auditRows, null, 2));
@@ -0,0 +1,6 @@
1
+ import { createDeltaMask } from 'deltaveil';
2
+
3
+ const audit = createDeltaMask({ sensitiveKeys: ['billing.taxId'] });
4
+ const before = { users: [{ contact: 'old@example.com' }], billing: { taxId: null } };
5
+ const after = { users: [{ contact: 'new@example.com' }], billing: { taxId: 'sample-id' } };
6
+ console.log(JSON.stringify(audit(before, after), null, 2));
package/index.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ /** Plain data accepted by DeltaVeil. Runtime also checks property descriptors and depth. */
2
+ export type JsonLike = string | number | boolean | null | undefined | readonly JsonLike[] | {
3
+ readonly [key: string]: JsonLike;
4
+ };
5
+
6
+ export interface DeltaVeilOptions {
7
+ maskString?: string;
8
+ sensitiveKeys?: readonly string[];
9
+ detectEmails?: boolean;
10
+ detectPhones?: boolean;
11
+ detectTokens?: boolean;
12
+ arrayStrategy?: 'replace';
13
+ circular?: 'throw' | 'truncate';
14
+ maxDepth?: number;
15
+ includePrivacyReport?: boolean;
16
+ keyMatchMode?: 'exact' | 'normalized';
17
+ }
18
+
19
+ export interface PrivacyReport {
20
+ maskedFields: string[];
21
+ detectedTypes: string[];
22
+ totalChanges: number;
23
+ }
24
+
25
+ export type Change = { from: JsonLike; to: JsonLike } | { added: JsonLike } |
26
+ { removed: JsonLike } | { [key: string]: Change };
27
+
28
+ export interface DeltaVeilResult {
29
+ changes: Change;
30
+ privacyReport?: PrivacyReport;
31
+ }
32
+
33
+ type WithReport = DeltaVeilResult & { privacyReport: PrivacyReport };
34
+ type WithoutReport = { changes: Change; privacyReport?: never };
35
+
36
+ /** @example diffAndMask({ ok: false }, { ok: true }).privacyReport.totalChanges */
37
+ export function diffAndMask(before: JsonLike, after: JsonLike,
38
+ options?: DeltaVeilOptions & { includePrivacyReport?: true }): WithReport;
39
+ export function diffAndMask(before: JsonLike, after: JsonLike,
40
+ options: DeltaVeilOptions & { includePrivacyReport: false }): WithoutReport;
41
+ export function diffAndMask(before: JsonLike, after: JsonLike, options?: DeltaVeilOptions): DeltaVeilResult;
42
+
43
+ export interface DeltaMask<DefaultResult extends DeltaVeilResult = DeltaVeilResult> {
44
+ (before: JsonLike, after: JsonLike, options?: DeltaVeilOptions & { includePrivacyReport?: never }): DefaultResult;
45
+ (before: JsonLike, after: JsonLike, options: DeltaVeilOptions & { includePrivacyReport: true }): WithReport;
46
+ (before: JsonLike, after: JsonLike, options: DeltaVeilOptions & { includePrivacyReport: false }): WithoutReport;
47
+ (before: JsonLike, after: JsonLike, options?: DeltaVeilOptions): DeltaVeilResult;
48
+ }
49
+
50
+ /** @example const audit = createDeltaMask({ sensitiveKeys: ['billing.taxId'] }); */
51
+ export function createDeltaMask(options?: DeltaVeilOptions & { includePrivacyReport?: true }): DeltaMask<WithReport>;
52
+ export function createDeltaMask(options: DeltaVeilOptions & { includePrivacyReport: false }): DeltaMask<WithoutReport>;
53
+ export function createDeltaMask(options?: DeltaVeilOptions): DeltaMask;
54
+
55
+ /** @example detectSensitiveValue('person@example.com') // 'email' */
56
+ export function detectSensitiveValue(value: unknown, options?: DeltaVeilOptions): 'email' | 'phone' | 'token' | null;
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "deltaveil",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Compute deep differences between JSON-like values with sensitive-data masking and structured privacy reports.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./index.d.ts",
12
+ "default": "./src/index.js"
13
+ }
14
+ }
15
+ },
16
+ "files": [
17
+ "src/**/*.js",
18
+ "examples/*.js",
19
+ "index.d.ts",
20
+ "README.md",
21
+ "CHANGELOG.md",
22
+ "SECURITY.md",
23
+ "LICENSE"
24
+ ],
25
+ "engines": {
26
+ "node": ">=20"
27
+ },
28
+ "scripts": {
29
+ "test": "node --test",
30
+ "lint": "node scripts/check-syntax.js",
31
+ "check": "npm run lint && npm test",
32
+ "prepack": "npm run check"
33
+ },
34
+ "keywords": [
35
+ "json",
36
+ "diff",
37
+ "mask",
38
+ "redaction",
39
+ "privacy",
40
+ "audit",
41
+ "logging",
42
+ "javascript",
43
+ "security"
44
+ ],
45
+ "author": "Labhansh Agarwal",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/ARISTOTLE777/deltaVeil.git"
49
+ },
50
+ "homepage": "https://github.com/ARISTOTLE777/deltaVeil#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/ARISTOTLE777/deltaVeil/issues"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "license": "MIT"
58
+ }
@@ -0,0 +1,12 @@
1
+ export const defaults = Object.freeze({
2
+ maskString: '***MASKED***',
3
+ sensitiveKeys: Object.freeze([]),
4
+ detectEmails: true,
5
+ detectPhones: false,
6
+ detectTokens: true,
7
+ arrayStrategy: 'replace',
8
+ circular: 'throw',
9
+ maxDepth: 64,
10
+ includePrivacyReport: true,
11
+ keyMatchMode: 'normalized'
12
+ });
@@ -0,0 +1,45 @@
1
+ import { defaults } from './defaults.js';
2
+ import { dataKeys, isRecord, isDataArray } from '../utils/object.js';
3
+ import { parsePath } from '../utils/path.js';
4
+
5
+ function sensitiveKeys(value) {
6
+ if (!isDataArray(value) || dataKeys(value, true).length !== value.length) {
7
+ throw new TypeError('sensitiveKeys must be a dense array of strings');
8
+ }
9
+ const paths = [];
10
+ for (let i = 0; i < value.length; i++) {
11
+ const item = value[i];
12
+ if (typeof item !== 'string' || !item.length) throw new TypeError('Invalid sensitiveKeys entry');
13
+ // Bare names (including hyphenated names) apply anywhere.
14
+ if (item === '$') paths.push({ path: [] });
15
+ else paths.push(/[.\[\]]/.test(item) ? { path: parsePath(item) } : { name: item });
16
+ }
17
+ return paths;
18
+ }
19
+
20
+ /** Overrides replace individual options, including the complete custom key list. */
21
+ export function configure(options, base = defaults) {
22
+ if (options === undefined) return base;
23
+ if (!isRecord(options)) throw new TypeError('Options must be a plain object');
24
+ const result = { ...base };
25
+ for (const key of dataKeys(options)) {
26
+ if (!Object.hasOwn(defaults, key)) throw new TypeError('Unknown DeltaVeil option');
27
+ const value = options[key];
28
+ if (key === 'sensitiveKeys') result[key] = sensitiveKeys(value);
29
+ else if (key === 'maxDepth') {
30
+ if (!Number.isInteger(value) || value < 1 || value > 256) {
31
+ throw new RangeError('maxDepth must be an integer from 1 to 256');
32
+ }
33
+ result[key] = value;
34
+ } else {
35
+ if (typeof value !== typeof defaults[key]) throw new TypeError('Invalid type for ' + key);
36
+ if ((key === 'arrayStrategy' && value !== 'replace') ||
37
+ (key === 'circular' && !['throw', 'truncate'].includes(value)) ||
38
+ (key === 'keyMatchMode' && !['exact', 'normalized'].includes(value))) {
39
+ throw new RangeError('Unsupported ' + key);
40
+ }
41
+ result[key] = value;
42
+ }
43
+ }
44
+ return result;
45
+ }
@@ -0,0 +1,41 @@
1
+ import { equal, container } from './equality.js';
2
+ import { labels, sanitizePair, missing, getOwn } from '../privacy/masker.js';
3
+ import { PrivacyReportBuilder } from '../privacy/privacyReport.js';
4
+ import { prepare } from '../utils/circular.js';
5
+ import { put, sortedUnion } from '../utils/object.js';
6
+
7
+ const unchanged = Symbol('unchanged');
8
+
9
+ function compare(left, right, path, context) {
10
+ if (Object.is(left, right)) return unchanged;
11
+ const bothRecords = container(left) && container(right) && !Array.isArray(left) && !Array.isArray(right);
12
+ if (bothRecords && !labels(left, right, path, context.options).length) {
13
+ const changes = {};
14
+ let changed = false;
15
+ for (const key of sortedUnion(left, right)) {
16
+ const child = compare(getOwn(left, key), getOwn(right, key), [...path, key], context);
17
+ if (child !== unchanged) {
18
+ put(changes, key, child);
19
+ changed = true;
20
+ }
21
+ }
22
+ return changed ? changes : unchanged;
23
+ }
24
+ if (equal(left, right)) return unchanged;
25
+ const { from, to, weight } = sanitizePair(left, right, path, context);
26
+ const oneSided = left === missing || right === missing;
27
+ if (context.report) context.report.totalChanges += oneSided ? weight : 1;
28
+ if (left === missing) return { added: to };
29
+ if (right === missing) return { removed: from };
30
+ return { from, to };
31
+ }
32
+
33
+ export function diff(before, after, options) {
34
+ const left = prepare(before, options);
35
+ const right = Object.is(before, after) ? left : prepare(after, options);
36
+ const report = options.includePrivacyReport ? new PrivacyReportBuilder() : null;
37
+ const changes = compare(left, right, [], { options, report });
38
+ const result = { changes: changes === unchanged ? {} : changes };
39
+ if (report) result.privacyReport = report.finish();
40
+ return result;
41
+ }
@@ -0,0 +1,13 @@
1
+ /** Inputs have already passed descriptor, depth, and cycle validation. */
2
+ export function equal(left, right) {
3
+ if (Object.is(left, right)) return true;
4
+ if (!container(left) || !container(right) || Array.isArray(left) !== Array.isArray(right)) return false;
5
+ if (Array.isArray(left) && left.length !== right.length) return false;
6
+ const keys = Object.keys(left);
7
+ if (keys.length !== Object.keys(right).length) return false;
8
+ return keys.every(key => Object.hasOwn(right, key) && equal(left[key], right[key]));
9
+ }
10
+
11
+ export function container(value) {
12
+ return value !== null && typeof value === 'object';
13
+ }
package/src/index.js ADDED
@@ -0,0 +1,41 @@
1
+ import { configure } from './config/validateOptions.js';
2
+ import { diff } from './core/differ.js';
3
+ import { valueType } from './privacy/detector.js';
4
+
5
+ /** @typedef {import('../index.js').DeltaVeilOptions} DeltaVeilOptions */
6
+ /** @typedef {import('../index.js').JsonLike} JsonLike */
7
+ /** @typedef {import('../index.js').DeltaVeilResult} DeltaVeilResult */
8
+
9
+ /**
10
+ * Compare validated JSON-like values and return detached, sanitized changes.
11
+ * @param {JsonLike} before
12
+ * @param {JsonLike} after
13
+ * @param {DeltaVeilOptions} [options]
14
+ * @returns {DeltaVeilResult}
15
+ * @example diffAndMask({ count: 1 }, { count: 2 }).privacyReport.totalChanges // 1
16
+ */
17
+ export function diffAndMask(before, after, options) {
18
+ return diff(before, after, configure(options));
19
+ }
20
+
21
+ /**
22
+ * Capture reusable configuration. Per-call options override individual defaults.
23
+ * @param {DeltaVeilOptions} [defaultOptions]
24
+ * @returns {import('../index.js').DeltaMask}
25
+ * @example const audit = createDeltaMask({ sensitiveKeys: ['taxId'] });
26
+ */
27
+ export function createDeltaMask(defaultOptions) {
28
+ const base = configure(defaultOptions);
29
+ return (before, after, overrides) => diff(before, after, configure(overrides, base));
30
+ }
31
+
32
+ /**
33
+ * Classify a single scalar by value. Objects and other non-strings return null.
34
+ * @param {unknown} value
35
+ * @param {DeltaVeilOptions} [options]
36
+ * @returns {'email'|'phone'|'token'|null}
37
+ * @example detectSensitiveValue('person@example.com') // 'email'
38
+ */
39
+ export function detectSensitiveValue(value, options) {
40
+ return valueType(value, configure(options));
41
+ }
@@ -0,0 +1,71 @@
1
+ const groups = {
2
+ password: ['password', 'passwordHash'],
3
+ secret: ['secret', 'clientSecret'],
4
+ token: ['token', 'accessToken', 'refreshToken', 'authorization'],
5
+ apiKey: ['apiKey', 'api_key'],
6
+ privateKey: ['privateKey'],
7
+ cvv: ['cvv'],
8
+ aadhaar: ['aadhaar'],
9
+ ssn: ['ssn']
10
+ };
11
+ const exact = new Map(Object.entries(groups).flatMap(([label, keys]) => keys.map(key => [key, label])));
12
+ const fold = key => key.replace(/[_\s-]+/g, '').toLowerCase();
13
+ const normalized = new Map([...exact].map(([key, label]) => [fold(key), label]));
14
+ const longestName = Math.max(...Array.from(normalized.keys(), key => key.length));
15
+
16
+ function normalizedLabel(key) {
17
+ const words = key.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
18
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2').toLowerCase().split(/[\s_-]+/);
19
+ let suffix = '';
20
+ for (let i = words.length - 1; i >= 0; i--) {
21
+ suffix = words[i] + suffix;
22
+ if (suffix.length > longestName) break;
23
+ const label = normalized.get(suffix);
24
+ if (label) return label;
25
+ }
26
+ return null;
27
+ }
28
+
29
+ function sameSegment(left, right, mode) {
30
+ if (left === right) return true;
31
+ if (mode !== 'normalized' || typeof left !== 'string' || typeof right !== 'string') return false;
32
+ const folded = fold(left);
33
+ return folded.length > 0 && folded === fold(right);
34
+ }
35
+
36
+ export function keyType(path, options) {
37
+ const key = path.at(-1);
38
+ if (typeof key === 'string') {
39
+ const label = exact.get(key) ?? (options.keyMatchMode === 'normalized' && normalizedLabel(key));
40
+ if (label) return label;
41
+ }
42
+ for (const custom of options.sensitiveKeys) {
43
+ if (Object.hasOwn(custom, 'name')) {
44
+ if (sameSegment(custom.name, key, options.keyMatchMode)) return 'custom';
45
+ } else if (custom.path.length === path.length &&
46
+ custom.path.every((segment, i) => sameSegment(segment, path[i], options.keyMatchMode))) return 'custom';
47
+ }
48
+ return null;
49
+ }
50
+
51
+ function isEmail(value) {
52
+ if (value.length > 254) return false;
53
+ const parts = value.split('@');
54
+ if (parts.length !== 2) return false;
55
+ const [local, domain] = parts;
56
+ if (!/^[A-Za-z0-9.!#$%&'*+/=?^_\x60{|}~-]{1,64}$/.test(local) ||
57
+ local.startsWith('.') || local.endsWith('.') || local.includes('..')) return false;
58
+ const labels = domain.split('.');
59
+ return labels.length > 1 && /^[a-z]{2,63}$/i.test(labels.at(-1)) &&
60
+ labels.every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label));
61
+ }
62
+
63
+ /** Whole-string classifiers. Returns a category only, never the matched text. */
64
+ export function valueType(value, options) {
65
+ if (typeof value !== 'string') return null;
66
+ if (options.detectEmails && isEmail(value)) return 'email';
67
+ if (options.detectTokens && (/^gh[pousr]_[A-Za-z0-9]{36,255}$/.test(value) ||
68
+ /^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value))) return 'token';
69
+ if (options.detectPhones && /^\+[1-9][0-9]{7,14}$/.test(value)) return 'phone';
70
+ return null;
71
+ }
@@ -0,0 +1,57 @@
1
+ import { container } from '../core/equality.js';
2
+ import { keyType, valueType } from './detector.js';
3
+ import { cycle } from '../utils/circular.js';
4
+ import { put, sortedUnion } from '../utils/object.js';
5
+
6
+ export const missing = Symbol('absent property');
7
+ export const getOwn = (value, key) => Object.hasOwn(value, key) ? value[key] : missing;
8
+
9
+ /** A key classification takes precedence over value labels. */
10
+ export function labels(left, right, path, options) {
11
+ const key = keyType(path, options);
12
+ if (key) return [key];
13
+ return [valueType(left, options), valueType(right, options)].filter(Boolean);
14
+ }
15
+
16
+ function shell(value) {
17
+ if (Array.isArray(value)) return new Array(value.length);
18
+ if (container(value)) return {};
19
+ return value === cycle ? '[Circular]' : value;
20
+ }
21
+
22
+ /** Build detached, redacted snapshots together so classification can protect both sides.
23
+ * Weight counts leaves for whole-record additions/removals; arrays and masked parents are atomic.
24
+ */
25
+ export function sanitizePair(left, right, path, context) {
26
+ const types = labels(left, right, path, context.options);
27
+ if (types.length) {
28
+ context.report?.record(path, types);
29
+ return { from: context.options.maskString, to: context.options.maskString, weight: 1 };
30
+ }
31
+ const from = shell(left);
32
+ const to = shell(right);
33
+ const hasLeft = container(left);
34
+ const hasRight = container(right);
35
+ if (!hasLeft && !hasRight) return { from, to, weight: 1 };
36
+
37
+ // An object property named "0" and array index 0 have different paths.
38
+ if (hasLeft && hasRight && Array.isArray(left) !== Array.isArray(right)) {
39
+ return {
40
+ from: sanitizePair(left, missing, path, context).from,
41
+ to: sanitizePair(missing, right, path, context).to,
42
+ weight: 1
43
+ };
44
+ }
45
+ const array = Array.isArray(left) || Array.isArray(right);
46
+ const keys = sortedUnion(hasLeft ? left : {}, hasRight ? right : {});
47
+ let weight = 0;
48
+ for (const key of keys) {
49
+ const oldValue = hasLeft ? getOwn(left, key) : missing;
50
+ const newValue = hasRight ? getOwn(right, key) : missing;
51
+ const child = sanitizePair(oldValue, newValue, [...path, array ? Number(key) : key], context);
52
+ if (oldValue !== missing) put(from, key, child.from);
53
+ if (newValue !== missing) put(to, key, child.to);
54
+ weight += child.weight;
55
+ }
56
+ return { from, to, weight: array ? 1 : Math.max(1, weight) };
57
+ }
@@ -0,0 +1,20 @@
1
+ import { formatPath } from '../utils/path.js';
2
+
3
+ export class PrivacyReportBuilder {
4
+ fields = new Set();
5
+ types = new Set();
6
+ totalChanges = 0;
7
+
8
+ record(path, types) {
9
+ this.fields.add(formatPath(path));
10
+ for (const type of types) this.types.add(type);
11
+ }
12
+
13
+ finish() {
14
+ return {
15
+ maskedFields: [...this.fields].sort(),
16
+ detectedTypes: [...this.types].sort(),
17
+ totalChanges: this.totalChanges
18
+ };
19
+ }
20
+ }
@@ -0,0 +1,46 @@
1
+ import { dataKeys, isDataArray, isRecord, put } from './object.js';
2
+ import { valueType } from '../privacy/detector.js';
3
+
4
+ // Internal identity keeps a back-edge distinct from a caller's literal "[Circular]".
5
+ export const cycle = Symbol('truncated cycle');
6
+ const visitLimit = 1_000_000;
7
+
8
+ /** Validate both complete graphs, including hidden-by-masking and identical subtrees.
9
+ * Reuse input branches unless a truncated back-edge requires a different representation.
10
+ */
11
+ export function prepare(root, options) {
12
+ const ancestors = new WeakSet();
13
+ let visits = 0;
14
+ function visit(value, depth) {
15
+ if (++visits > visitLimit) throw new RangeError('Input traversal limit exceeded');
16
+ if (depth > options.maxDepth) throw new RangeError('Maximum depth exceeded');
17
+ if (value === null || ['string', 'boolean', 'number', 'undefined'].includes(typeof value)) return value;
18
+ const array = isDataArray(value);
19
+ if (!array && !isRecord(value)) throw new TypeError('Unsupported value. Expected plain JSON-like data');
20
+ if (ancestors.has(value)) {
21
+ if (options.circular === 'truncate') return cycle;
22
+ throw new TypeError('Circular reference detected');
23
+ }
24
+ ancestors.add(value);
25
+ const remaining = visitLimit - visits;
26
+ if (array && value.length > remaining) throw new RangeError('Input traversal limit exceeded');
27
+ const keys = dataKeys(value, array, remaining);
28
+ // Snapshots preserve array length. Charge holes as well as materialized elements.
29
+ if (array) visits += value.length - keys.length;
30
+ let result = value;
31
+ for (const key of keys) {
32
+ if (!array && valueType(key, options)) throw new TypeError('Sensitive property name is unsupported');
33
+ const child = visit(value[key], depth + 1);
34
+ if (!Object.is(child, value[key])) {
35
+ if (result === value) {
36
+ result = array ? new Array(value.length) : {};
37
+ for (const name of keys) put(result, name, value[name]);
38
+ }
39
+ put(result, key, child);
40
+ }
41
+ }
42
+ ancestors.delete(value);
43
+ return result;
44
+ }
45
+ return visit(root, 0);
46
+ }
@@ -0,0 +1,54 @@
1
+ import { types } from 'node:util';
2
+
3
+ // A built-in retains its internal slots after a caller changes its prototype.
4
+ // Native brand checks avoid invoking Symbol.toStringTag or other user properties.
5
+ const nativeBrands = [
6
+ Array.isArray, types.isDate, types.isMap, types.isSet, types.isRegExp,
7
+ types.isArrayBufferView, types.isAnyArrayBuffer, types.isBoxedPrimitive,
8
+ types.isWeakMap, types.isWeakSet, types.isPromise, types.isArgumentsObject,
9
+ types.isMapIterator, types.isSetIterator, types.isGeneratorObject,
10
+ types.isModuleNamespaceObject, types.isExternal, Error.isError ?? types.isNativeError
11
+ ];
12
+
13
+ /** Accept local plain records and null-prototype dictionaries. Never probe a proxy. */
14
+ export function isRecord(value) {
15
+ if (value === null || typeof value !== 'object' || types.isProxy(value)) return false;
16
+ const prototype = Object.getPrototypeOf(value);
17
+ return (prototype === null || prototype === Object.prototype) &&
18
+ !nativeBrands.some(check => check(value));
19
+ }
20
+
21
+ export function isDataArray(value) {
22
+ return !types.isProxy(value) && Array.isArray(value) &&
23
+ Object.getPrototypeOf(value) === Array.prototype;
24
+ }
25
+
26
+ /** Define a data property, including for names inherited from Object.prototype. */
27
+ export function put(target, key, value) {
28
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
29
+ }
30
+
31
+ /** Validate before any direct reads. Arrays may be sparse but cannot have extra fields. */
32
+ export function dataKeys(value, array = false, remaining = Infinity) {
33
+ const ownKeys = Reflect.ownKeys(value);
34
+ if (ownKeys.length - Number(array) > remaining) throw new RangeError('Input traversal limit exceeded');
35
+ const keys = [];
36
+ for (const key of ownKeys) {
37
+ if (array && key === 'length') continue;
38
+ if (typeof key !== 'string' ||
39
+ (array && (String(Number(key) >>> 0) !== key || Number(key) >= 0xffffffff))) {
40
+ throw new TypeError('Unsupported property key on input or options');
41
+ }
42
+ // Reject hidden properties before asking V8 for a potentially lazy value.
43
+ if (!Object.prototype.propertyIsEnumerable.call(value, key) ||
44
+ !Object.hasOwn(Object.getOwnPropertyDescriptor(value, key), 'value')) {
45
+ throw new TypeError('Only enumerable data properties are supported');
46
+ }
47
+ keys.push(key);
48
+ }
49
+ return keys;
50
+ }
51
+
52
+ export function sortedUnion(left, right) {
53
+ return [...new Set([...Object.keys(left), ...Object.keys(right)])].sort();
54
+ }
@@ -0,0 +1,34 @@
1
+ const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2
+
3
+ /** Numeric segments are array indices. String segments always denote object keys. */
4
+ export function formatPath(segments) {
5
+ let result = '';
6
+ for (const segment of segments) {
7
+ if (typeof segment === 'number') result += '[' + segment + ']';
8
+ else if (identifier.test(segment) && segment !== '$') result += (result ? '.' : '') + segment;
9
+ else result += '[' + JSON.stringify(segment) + ']';
10
+ }
11
+ return result || '$';
12
+ }
13
+
14
+ /** Accept the same unambiguous syntax used by the report. */
15
+ export function parsePath(input) {
16
+ const parts = [];
17
+ const token = /(?:([A-Za-z_$][A-Za-z0-9_$]*)|\[(0|[1-9][0-9]*)\]|\[("(?:[^"\\\x00-\x1f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*")\])/y;
18
+ let offset = 0;
19
+ while (offset < input.length) {
20
+ const dot = input[offset] === '.';
21
+ token.lastIndex = offset + Number(dot);
22
+ const match = token.exec(input);
23
+ if (!match || (dot !== (offset > 0 && match[1] !== undefined))) break;
24
+ if (match[1] !== undefined) parts.push(match[1]);
25
+ else if (match[2] !== undefined) {
26
+ const index = Number(match[2]);
27
+ if (index >= 0xffffffff) break;
28
+ parts.push(index);
29
+ } else parts.push(JSON.parse(match[3]));
30
+ offset = token.lastIndex;
31
+ }
32
+ if (!parts.length || offset !== input.length) throw new TypeError('Invalid sensitiveKeys path');
33
+ return parts;
34
+ }