@platform-sec/sensitive-string-testing 0.2.0 → 0.2.1

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.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @platform-sec/sensitive-string-testing
3
+ *
4
+ * Test utilities for code that handles `SensitiveString` values.
5
+ *
6
+ * - `createTestSecret` builds unique, conspicuous canary values.
7
+ * - `expectNotLeaked` and `expectRedacted` assert the core security property.
8
+ * - `sensitiveMatchers` adds matchers to Vitest or Jest.
9
+ * - `sensitiveSerializer` keeps snapshots readable without recording a value.
10
+ * - `mockRevealContext` and `createMockAuditLog` record what was accessed.
11
+ *
12
+ * The package depends on no test framework. The matchers are a plain object
13
+ * passed to `expect.extend`, and anything that needs a spy takes a factory such
14
+ * as `vi.fn` or `jest.fn` as an argument.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import {
19
+ * createTestSecret,
20
+ * expectNotLeaked,
21
+ * sensitiveMatchers,
22
+ * } from '@platform-sec/sensitive-string-testing';
23
+ *
24
+ * expect.extend(sensitiveMatchers);
25
+ *
26
+ * it('does not leak the key into the response', async () => {
27
+ * const apiKey = createTestSecret('credential', 'api_key');
28
+ *
29
+ * const response = await handler(apiKey);
30
+ *
31
+ * expect(apiKey).toHaveSensitivityClass('credential');
32
+ * expectNotLeaked(apiKey, response);
33
+ * });
34
+ * ```
35
+ *
36
+ * @packageDocumentation
37
+ */
38
+ export { createTestSecret, createExpiredSecret, createExpiringSecret, } from './create-test-secret.js';
39
+ export type { TestSecretOptions } from './create-test-secret.js';
40
+ export { expectNotLeaked, expectRedacted, LeakageDetectedError } from './assertions.js';
41
+ export type { RedactionOptions } from './assertions.js';
42
+ export { sensitiveMatchers, setupSensitiveMatchers } from './matchers.js';
43
+ export type { SensitiveMatchers, MatcherResult } from './matchers.js';
44
+ export { sensitiveSerializer, createSensitiveSerializer } from './serializer.js';
45
+ export type { SensitiveSerializerOptions, SnapshotSerializerPlugin } from './serializer.js';
46
+ export { mockRevealContext, createMockAuditLog } from './mocks.js';
47
+ export type { AuditCall, AuditEntry, AuditRevealFn, MockAuditLog, MockFunctionFactory, MockRevealContext, MockRevealContextOptions, } from './mocks.js';
48
+ export { collectFragments, findRawValue, findRawValueIn, joinFragments } from './leak-scan.js';
49
+ export type { Fragment, LeakLocation } from './leak-scan.js';
50
+ export { UnreadableSecretError, TESTING_CONTEXT_NAMES, LEAK_CHECK_CONTEXT, REDACTION_CHECK_CONTEXT, MATCHER_CONTEXT, CONTAINS_CHECK_CONTEXT, } from './canary.js';
51
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAGH,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAGjE,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACxF,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAGxD,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAC1E,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAGtE,OAAO,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AACjF,YAAY,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAG5F,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACnE,YAAY,EACV,SAAS,EACT,UAAU,EACV,aAAa,EACb,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,wBAAwB,GACzB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/F,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG7D,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,uBAAuB,EACvB,eAAe,EACf,sBAAsB,GACvB,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ /**
3
+ * @platform-sec/sensitive-string-testing
4
+ *
5
+ * Test utilities for code that handles `SensitiveString` values.
6
+ *
7
+ * - `createTestSecret` builds unique, conspicuous canary values.
8
+ * - `expectNotLeaked` and `expectRedacted` assert the core security property.
9
+ * - `sensitiveMatchers` adds matchers to Vitest or Jest.
10
+ * - `sensitiveSerializer` keeps snapshots readable without recording a value.
11
+ * - `mockRevealContext` and `createMockAuditLog` record what was accessed.
12
+ *
13
+ * The package depends on no test framework. The matchers are a plain object
14
+ * passed to `expect.extend`, and anything that needs a spy takes a factory such
15
+ * as `vi.fn` or `jest.fn` as an argument.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import {
20
+ * createTestSecret,
21
+ * expectNotLeaked,
22
+ * sensitiveMatchers,
23
+ * } from '@platform-sec/sensitive-string-testing';
24
+ *
25
+ * expect.extend(sensitiveMatchers);
26
+ *
27
+ * it('does not leak the key into the response', async () => {
28
+ * const apiKey = createTestSecret('credential', 'api_key');
29
+ *
30
+ * const response = await handler(apiKey);
31
+ *
32
+ * expect(apiKey).toHaveSensitivityClass('credential');
33
+ * expectNotLeaked(apiKey, response);
34
+ * });
35
+ * ```
36
+ *
37
+ * @packageDocumentation
38
+ */
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.CONTAINS_CHECK_CONTEXT = exports.MATCHER_CONTEXT = exports.REDACTION_CHECK_CONTEXT = exports.LEAK_CHECK_CONTEXT = exports.TESTING_CONTEXT_NAMES = exports.UnreadableSecretError = exports.joinFragments = exports.findRawValueIn = exports.findRawValue = exports.collectFragments = exports.createMockAuditLog = exports.mockRevealContext = exports.createSensitiveSerializer = exports.sensitiveSerializer = exports.setupSensitiveMatchers = exports.sensitiveMatchers = exports.LeakageDetectedError = exports.expectRedacted = exports.expectNotLeaked = exports.createExpiringSecret = exports.createExpiredSecret = exports.createTestSecret = void 0;
41
+ // Test secret creation
42
+ var create_test_secret_js_1 = require("./create-test-secret.js");
43
+ Object.defineProperty(exports, "createTestSecret", { enumerable: true, get: function () { return create_test_secret_js_1.createTestSecret; } });
44
+ Object.defineProperty(exports, "createExpiredSecret", { enumerable: true, get: function () { return create_test_secret_js_1.createExpiredSecret; } });
45
+ Object.defineProperty(exports, "createExpiringSecret", { enumerable: true, get: function () { return create_test_secret_js_1.createExpiringSecret; } });
46
+ // Assertions
47
+ var assertions_js_1 = require("./assertions.js");
48
+ Object.defineProperty(exports, "expectNotLeaked", { enumerable: true, get: function () { return assertions_js_1.expectNotLeaked; } });
49
+ Object.defineProperty(exports, "expectRedacted", { enumerable: true, get: function () { return assertions_js_1.expectRedacted; } });
50
+ Object.defineProperty(exports, "LeakageDetectedError", { enumerable: true, get: function () { return assertions_js_1.LeakageDetectedError; } });
51
+ // Matchers
52
+ var matchers_js_1 = require("./matchers.js");
53
+ Object.defineProperty(exports, "sensitiveMatchers", { enumerable: true, get: function () { return matchers_js_1.sensitiveMatchers; } });
54
+ Object.defineProperty(exports, "setupSensitiveMatchers", { enumerable: true, get: function () { return matchers_js_1.setupSensitiveMatchers; } });
55
+ // Snapshot serializer
56
+ var serializer_js_1 = require("./serializer.js");
57
+ Object.defineProperty(exports, "sensitiveSerializer", { enumerable: true, get: function () { return serializer_js_1.sensitiveSerializer; } });
58
+ Object.defineProperty(exports, "createSensitiveSerializer", { enumerable: true, get: function () { return serializer_js_1.createSensitiveSerializer; } });
59
+ // Mocks
60
+ var mocks_js_1 = require("./mocks.js");
61
+ Object.defineProperty(exports, "mockRevealContext", { enumerable: true, get: function () { return mocks_js_1.mockRevealContext; } });
62
+ Object.defineProperty(exports, "createMockAuditLog", { enumerable: true, get: function () { return mocks_js_1.createMockAuditLog; } });
63
+ // Leak scanning, for a check this package does not already provide
64
+ var leak_scan_js_1 = require("./leak-scan.js");
65
+ Object.defineProperty(exports, "collectFragments", { enumerable: true, get: function () { return leak_scan_js_1.collectFragments; } });
66
+ Object.defineProperty(exports, "findRawValue", { enumerable: true, get: function () { return leak_scan_js_1.findRawValue; } });
67
+ Object.defineProperty(exports, "findRawValueIn", { enumerable: true, get: function () { return leak_scan_js_1.findRawValueIn; } });
68
+ Object.defineProperty(exports, "joinFragments", { enumerable: true, get: function () { return leak_scan_js_1.joinFragments; } });
69
+ // Reveal context names, so a strict policy can allow them
70
+ var canary_js_1 = require("./canary.js");
71
+ Object.defineProperty(exports, "UnreadableSecretError", { enumerable: true, get: function () { return canary_js_1.UnreadableSecretError; } });
72
+ Object.defineProperty(exports, "TESTING_CONTEXT_NAMES", { enumerable: true, get: function () { return canary_js_1.TESTING_CONTEXT_NAMES; } });
73
+ Object.defineProperty(exports, "LEAK_CHECK_CONTEXT", { enumerable: true, get: function () { return canary_js_1.LEAK_CHECK_CONTEXT; } });
74
+ Object.defineProperty(exports, "REDACTION_CHECK_CONTEXT", { enumerable: true, get: function () { return canary_js_1.REDACTION_CHECK_CONTEXT; } });
75
+ Object.defineProperty(exports, "MATCHER_CONTEXT", { enumerable: true, get: function () { return canary_js_1.MATCHER_CONTEXT; } });
76
+ Object.defineProperty(exports, "CONTAINS_CHECK_CONTEXT", { enumerable: true, get: function () { return canary_js_1.CONTAINS_CHECK_CONTEXT; } });
77
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;;;AAEH,uBAAuB;AACvB,iEAIiC;AAH/B,yHAAA,gBAAgB,OAAA;AAChB,4HAAA,mBAAmB,OAAA;AACnB,6HAAA,oBAAoB,OAAA;AAItB,aAAa;AACb,iDAAwF;AAA/E,gHAAA,eAAe,OAAA;AAAE,+GAAA,cAAc,OAAA;AAAE,qHAAA,oBAAoB,OAAA;AAG9D,WAAW;AACX,6CAA0E;AAAjE,gHAAA,iBAAiB,OAAA;AAAE,qHAAA,sBAAsB,OAAA;AAGlD,sBAAsB;AACtB,iDAAiF;AAAxE,oHAAA,mBAAmB,OAAA;AAAE,0HAAA,yBAAyB,OAAA;AAGvD,QAAQ;AACR,uCAAmE;AAA1D,6GAAA,iBAAiB,OAAA;AAAE,8GAAA,kBAAkB,OAAA;AAW9C,mEAAmE;AACnE,+CAA+F;AAAtF,gHAAA,gBAAgB,OAAA;AAAE,4GAAA,YAAY,OAAA;AAAE,8GAAA,cAAc,OAAA;AAAE,6GAAA,aAAa,OAAA;AAGtE,0DAA0D;AAC1D,yCAOqB;AANnB,kHAAA,qBAAqB,OAAA;AACrB,kHAAA,qBAAqB,OAAA;AACrB,+GAAA,kBAAkB,OAAA;AAClB,oHAAA,uBAAuB,OAAA;AACvB,4GAAA,eAAe,OAAA;AACf,mHAAA,sBAAsB,OAAA"}
@@ -0,0 +1,94 @@
1
+ import { SensitiveString } from '@platform-sec/sensitive-string-core';
2
+ import type { SensitivityClass } from '@platform-sec/sensitive-string-core';
3
+ /**
4
+ * `instanceof SensitiveString` narrows to `SensitiveString<any>`, because the
5
+ * class is generic in its sensitivity class and the check says nothing about
6
+ * which one. The predicate names the union instead, so nothing downstream of
7
+ * the narrowing is typed `any`.
8
+ */
9
+ export declare function isSensitiveString(value: unknown): value is SensitiveString<SensitivityClass>;
10
+ /**
11
+ * One piece of text found while walking a value, and where it came from.
12
+ */
13
+ export interface Fragment {
14
+ /** Where the text was found, such as `.body.headers['x-api-key']`. */
15
+ readonly path: string;
16
+ /** The text itself. */
17
+ readonly text: string;
18
+ /**
19
+ * True when the text is the redacted rendering of a `SensitiveString` that
20
+ * was still wrapped where it was found, rather than text the target held
21
+ * directly.
22
+ *
23
+ * A leak search still checks these. A wrapper is the correct state for a
24
+ * sensitive value to be in, and the raw value is unreachable through it, so
25
+ * under any policy `registerPolicy` accepts the rendering cannot contain the
26
+ * value and the wrapper is never reported. A rendering that does contain the
27
+ * whole value comes from a policy registered with `skipRedactValidation` or
28
+ * from a subclass that overrode `toString`, and that is a leak, not a false
29
+ * positive: passing it over is the one failure a leak assertion must not have.
30
+ */
31
+ readonly wrapped: boolean;
32
+ }
33
+ /** Where a raw value was found, and enough context to locate it. */
34
+ export interface LeakLocation {
35
+ /** Path within the target, such as `.headers['authorization']`. */
36
+ readonly path: string;
37
+ /**
38
+ * The surrounding text, with every occurrence of the raw value replaced by
39
+ * `[LEAKED VALUE]`.
40
+ *
41
+ * The value is withheld on purpose: an assertion message ends up in CI logs,
42
+ * and a leak check that prints the secret to prove the secret leaked has only
43
+ * moved the leak.
44
+ */
45
+ readonly context: string;
46
+ }
47
+ /**
48
+ * Walk a value and collect every piece of text it holds.
49
+ *
50
+ * This deliberately does not use `JSON.stringify`. `JSON.stringify` calls
51
+ * `toJSON`, and `toJSON` is exactly the method an object uses to decide what it
52
+ * shows: a response class whose `toJSON` omits a field hides a raw value that
53
+ * is still sitting on the object, and every `SensitiveString` renders as its
54
+ * redacted form whether or not the object also holds a leaked plain copy. This
55
+ * walk reads own properties instead, so what it reports is what the object
56
+ * actually holds.
57
+ *
58
+ * Covered: strings, other primitives, arrays and the properties attached to
59
+ * them, `Map`, `Set`, typed arrays and `Buffer` (decoded as UTF-8), `RegExp`
60
+ * sources, own property keys, and own properties whether enumerable or not.
61
+ * That last one is how an `Error`'s `message` and `stack` are reached, and the
62
+ * array properties are how a `String.prototype.match` result's `input`, which
63
+ * holds the whole subject string, is reached. Accessors are invoked, so a value
64
+ * behind a getter is found; a getter that throws is skipped.
65
+ *
66
+ * Not covered: closure variables, `WeakMap` and `WeakSet` contents, unsettled
67
+ * promises, and function bodies. A value reachable only from one of those is
68
+ * beyond what a synchronous walk can see.
69
+ *
70
+ * The traversal is depth first and pre-order, so the first match a search finds
71
+ * is the one nearest the front of the structure as it reads.
72
+ */
73
+ export declare function collectFragments(root: unknown): Fragment[];
74
+ /**
75
+ * Find the first place a raw value appears in a target.
76
+ *
77
+ * An empty raw value is never reported: it is a substring of every string, and
78
+ * it carries no information to leak.
79
+ */
80
+ export declare function findRawValue(target: unknown, raw: string): LeakLocation | undefined;
81
+ /**
82
+ * Find a raw value in fragments that have already been collected, for a caller
83
+ * that also needs the joined text and should not walk the target twice.
84
+ */
85
+ export declare function findRawValueIn(fragments: readonly Fragment[], raw: string): LeakLocation | undefined;
86
+ /**
87
+ * Render the collected text of a value as one string, for a check that needs to
88
+ * search the whole target rather than a single leaf.
89
+ *
90
+ * Fragments are joined with a newline, which no fragment contains a boundary
91
+ * across, so a match in the result is a match within one fragment.
92
+ */
93
+ export declare function joinFragments(fragments: readonly Fragment[]): string;
94
+ //# sourceMappingURL=leak-scan.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leak-scan.d.ts","sourceRoot":"","sources":["../src/leak-scan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AACtE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAE5E;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,eAAe,CAAC,gBAAgB,CAAC,CAE5F;AA0BD;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,sEAAsE;IACtE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,uBAAuB;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;;;;;;;;;OAYG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AAED,oEAAoE;AACpE,MAAM,WAAW,YAAY;IAC3B,mEAAmE;IACnE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;;;;OAOG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,OAAO,GAAG,QAAQ,EAAE,CAuB1D;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAEnF;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,SAAS,EAAE,SAAS,QAAQ,EAAE,EAC9B,GAAG,EAAE,MAAM,GACV,YAAY,GAAG,SAAS,CAa1B;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,SAAS,EAAE,SAAS,QAAQ,EAAE,GAAG,MAAM,CAEpE"}
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isSensitiveString = isSensitiveString;
4
+ exports.collectFragments = collectFragments;
5
+ exports.findRawValue = findRawValue;
6
+ exports.findRawValueIn = findRawValueIn;
7
+ exports.joinFragments = joinFragments;
8
+ const sensitive_string_core_1 = require("@platform-sec/sensitive-string-core");
9
+ /**
10
+ * `instanceof SensitiveString` narrows to `SensitiveString<any>`, because the
11
+ * class is generic in its sensitivity class and the check says nothing about
12
+ * which one. The predicate names the union instead, so nothing downstream of
13
+ * the narrowing is typed `any`.
14
+ */
15
+ function isSensitiveString(value) {
16
+ return value instanceof sensitive_string_core_1.SensitiveString;
17
+ }
18
+ /**
19
+ * Most values the walk will look at before it gives up.
20
+ *
21
+ * This is a guard against a hostile target, not a limit a real one reaches. A
22
+ * `Proxy` can fabricate a fresh object for every key forever, and a leak check
23
+ * that hangs the suite is worse than one that stops. Nothing built by ordinary
24
+ * code comes close to this count.
25
+ *
26
+ * There is deliberately no depth limit. A depth limit stops the walk in the
27
+ * middle of a structure it could otherwise finish, and a leak below the cut is
28
+ * then reported as no leak at all, which is the one answer a leak check must
29
+ * never give by accident. The walk uses an explicit stack instead of recursion,
30
+ * so depth costs heap rather than call frames and no limit is needed.
31
+ */
32
+ const MAX_NODES = 200_000;
33
+ /** Characters of surrounding text kept on each side of a reported match. */
34
+ const CONTEXT_RADIUS = 60;
35
+ /** What a reported match stands in for, so a failure never reprints a secret. */
36
+ const LEAK_PLACEHOLDER = '[LEAKED VALUE]';
37
+ const utf8 = new TextDecoder('utf-8', { fatal: false });
38
+ /**
39
+ * Walk a value and collect every piece of text it holds.
40
+ *
41
+ * This deliberately does not use `JSON.stringify`. `JSON.stringify` calls
42
+ * `toJSON`, and `toJSON` is exactly the method an object uses to decide what it
43
+ * shows: a response class whose `toJSON` omits a field hides a raw value that
44
+ * is still sitting on the object, and every `SensitiveString` renders as its
45
+ * redacted form whether or not the object also holds a leaked plain copy. This
46
+ * walk reads own properties instead, so what it reports is what the object
47
+ * actually holds.
48
+ *
49
+ * Covered: strings, other primitives, arrays and the properties attached to
50
+ * them, `Map`, `Set`, typed arrays and `Buffer` (decoded as UTF-8), `RegExp`
51
+ * sources, own property keys, and own properties whether enumerable or not.
52
+ * That last one is how an `Error`'s `message` and `stack` are reached, and the
53
+ * array properties are how a `String.prototype.match` result's `input`, which
54
+ * holds the whole subject string, is reached. Accessors are invoked, so a value
55
+ * behind a getter is found; a getter that throws is skipped.
56
+ *
57
+ * Not covered: closure variables, `WeakMap` and `WeakSet` contents, unsettled
58
+ * promises, and function bodies. A value reachable only from one of those is
59
+ * beyond what a synchronous walk can see.
60
+ *
61
+ * The traversal is depth first and pre-order, so the first match a search finds
62
+ * is the one nearest the front of the structure as it reads.
63
+ */
64
+ function collectFragments(root) {
65
+ const fragments = [];
66
+ const seen = new WeakSet();
67
+ const stack = [{ kind: 'value', value: root, path: '' }];
68
+ let budget = MAX_NODES;
69
+ while (stack.length > 0 && budget > 0) {
70
+ budget -= 1;
71
+ const item = stack.pop();
72
+ if (item === undefined) {
73
+ break;
74
+ }
75
+ if (item.kind === 'text') {
76
+ push(fragments, item.path, item.text, item.wrapped);
77
+ continue;
78
+ }
79
+ expand(item.value, item.path, fragments, seen, stack);
80
+ }
81
+ return fragments;
82
+ }
83
+ /**
84
+ * Find the first place a raw value appears in a target.
85
+ *
86
+ * An empty raw value is never reported: it is a substring of every string, and
87
+ * it carries no information to leak.
88
+ */
89
+ function findRawValue(target, raw) {
90
+ return findRawValueIn(collectFragments(target), raw);
91
+ }
92
+ /**
93
+ * Find a raw value in fragments that have already been collected, for a caller
94
+ * that also needs the joined text and should not walk the target twice.
95
+ */
96
+ function findRawValueIn(fragments, raw) {
97
+ if (raw.length === 0) {
98
+ return undefined;
99
+ }
100
+ for (const fragment of fragments) {
101
+ const index = fragment.text.indexOf(raw);
102
+ if (index !== -1) {
103
+ return { path: fragment.path, context: describeContext(fragment.text, raw, index) };
104
+ }
105
+ }
106
+ return undefined;
107
+ }
108
+ /**
109
+ * Render the collected text of a value as one string, for a check that needs to
110
+ * search the whole target rather than a single leaf.
111
+ *
112
+ * Fragments are joined with a newline, which no fragment contains a boundary
113
+ * across, so a match in the result is a match within one fragment.
114
+ */
115
+ function joinFragments(fragments) {
116
+ return fragments.map((fragment) => fragment.text).join('\n');
117
+ }
118
+ /**
119
+ * The text around a match, with the matched value replaced.
120
+ */
121
+ function describeContext(text, raw, index) {
122
+ const start = Math.max(0, index - CONTEXT_RADIUS);
123
+ const end = Math.min(text.length, index + raw.length + CONTEXT_RADIUS);
124
+ // split/join replaces every occurrence without building a RegExp from the
125
+ // raw value, which would need escaping and would put the value in a pattern.
126
+ const window = text.slice(start, end).split(raw).join(LEAK_PLACEHOLDER);
127
+ return `${start > 0 ? '...' : ''}${window}${end < text.length ? '...' : ''}`;
128
+ }
129
+ function push(fragments, path, text, wrapped = false) {
130
+ if (text.length > 0) {
131
+ fragments.push({ path, text, wrapped });
132
+ }
133
+ }
134
+ function valueItem(value, path) {
135
+ return { kind: 'value', value, path };
136
+ }
137
+ /**
138
+ * Queue children so the stack pops them in source order.
139
+ *
140
+ * Reversing here is what keeps the traversal depth first and pre-order, which
141
+ * is the order the reported path assumes.
142
+ */
143
+ function queue(stack, children) {
144
+ for (let index = children.length - 1; index >= 0; index -= 1) {
145
+ const child = children[index];
146
+ if (child !== undefined) {
147
+ stack.push(child);
148
+ }
149
+ }
150
+ }
151
+ /** Record what a value contributes directly, and queue what it contains. */
152
+ function expand(value, path, fragments, seen, stack) {
153
+ if (value === null || value === undefined) {
154
+ return;
155
+ }
156
+ switch (typeof value) {
157
+ case 'string':
158
+ push(fragments, path, value);
159
+ return;
160
+ case 'number':
161
+ case 'boolean':
162
+ case 'bigint':
163
+ push(fragments, path, String(value));
164
+ return;
165
+ case 'symbol':
166
+ push(fragments, path, value.description ?? '');
167
+ return;
168
+ case 'function':
169
+ // The name only. A function body can hold a literal secret, but reading
170
+ // every function source in a response object costs more than it finds.
171
+ push(fragments, `${path}.name`, value.name);
172
+ return;
173
+ default:
174
+ break;
175
+ }
176
+ expandObject(value, path, fragments, seen, stack);
177
+ }
178
+ function expandObject(obj, path, fragments, seen, stack) {
179
+ if (isSensitiveString(obj)) {
180
+ // The raw value is unreachable from here, which is the point: a value that
181
+ // is still wrapped has nothing for a leak search to find. What is recorded
182
+ // is the rendering the class policy produces, so a redaction check can look
183
+ // for it and so a policy that renders the value itself is still caught.
184
+ push(fragments, path, safeRedaction(obj), true);
185
+ return;
186
+ }
187
+ if (seen.has(obj)) {
188
+ return;
189
+ }
190
+ seen.add(obj);
191
+ const children = [];
192
+ if (Array.isArray(obj)) {
193
+ obj.forEach((item, index) => {
194
+ children.push(valueItem(item, `${path}[${index}]`));
195
+ });
196
+ // Arrays carry properties beyond their elements often enough to matter: a
197
+ // `String.prototype.match` result is an array whose `input` holds the whole
198
+ // subject string, which is the value the match came from.
199
+ collectOwnProperties(obj, path, children, isElementKey);
200
+ queue(stack, children);
201
+ return;
202
+ }
203
+ if (obj instanceof Map) {
204
+ let index = 0;
205
+ for (const [key, value] of obj) {
206
+ children.push(valueItem(key, `${path}<map key ${index}>`));
207
+ children.push(valueItem(value, `${path}<map value ${index}>`));
208
+ index += 1;
209
+ }
210
+ queue(stack, children);
211
+ return;
212
+ }
213
+ if (obj instanceof Set) {
214
+ let index = 0;
215
+ for (const value of obj) {
216
+ children.push(valueItem(value, `${path}<set ${index}>`));
217
+ index += 1;
218
+ }
219
+ queue(stack, children);
220
+ return;
221
+ }
222
+ if (obj instanceof RegExp) {
223
+ push(fragments, `${path}.source`, obj.source);
224
+ return;
225
+ }
226
+ if (ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer) {
227
+ push(fragments, path, decodeBytes(obj));
228
+ return;
229
+ }
230
+ collectOwnProperties(obj, path, children);
231
+ queue(stack, children);
232
+ }
233
+ /**
234
+ * Queue own properties, enumerable or not.
235
+ *
236
+ * Non-enumerable properties are included because hiding a value behind
237
+ * `enumerable: false` is precisely how a copy escapes `JSON.stringify`, and
238
+ * because an `Error`'s `message` and `stack` are non-enumerable own properties.
239
+ */
240
+ function collectOwnProperties(obj, path, out, skip) {
241
+ for (const key of Reflect.ownKeys(obj)) {
242
+ if (skip?.(key)) {
243
+ continue;
244
+ }
245
+ const keyPath = `${path}${accessorFor(key)}`;
246
+ if (typeof key === 'string') {
247
+ // A raw value used as an object key, such as a cache keyed by token.
248
+ out.push({ kind: 'text', path: `${keyPath} (key)`, text: key, wrapped: false });
249
+ }
250
+ const descriptor = Object.getOwnPropertyDescriptor(obj, key);
251
+ if (descriptor === undefined) {
252
+ continue;
253
+ }
254
+ if ('value' in descriptor) {
255
+ out.push(valueItem(descriptor.value, keyPath));
256
+ continue;
257
+ }
258
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- read to test for presence, then invoked as getter.call(obj) below
259
+ const getter = descriptor.get;
260
+ if (getter === undefined) {
261
+ continue;
262
+ }
263
+ // A value reachable only through a getter is still a value the object
264
+ // holds. A getter that throws tells us nothing, so it is skipped.
265
+ try {
266
+ out.push(valueItem(getter.call(obj), keyPath));
267
+ }
268
+ catch {
269
+ // Intentionally ignored.
270
+ }
271
+ }
272
+ }
273
+ /** Keys an array walk has already covered as elements, plus its length. */
274
+ function isElementKey(key) {
275
+ return typeof key === 'string' && (key === 'length' || ARRAY_INDEX.test(key));
276
+ }
277
+ const ARRAY_INDEX = /^(?:0|[1-9]\d*)$/;
278
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
279
+ function accessorFor(key) {
280
+ if (typeof key === 'symbol') {
281
+ return `[Symbol(${key.description ?? ''})]`;
282
+ }
283
+ return IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
284
+ }
285
+ /**
286
+ * The redacted rendering of a wrapped value, or a marker when the class policy
287
+ * refuses to produce one. A policy that throws must not turn a leak check into
288
+ * an error about the policy.
289
+ */
290
+ function safeRedaction(value) {
291
+ try {
292
+ return value.toString();
293
+ }
294
+ catch {
295
+ return `[SensitiveString<${value.klass}> redaction threw]`;
296
+ }
297
+ }
298
+ function decodeBytes(source) {
299
+ try {
300
+ const bytes = source instanceof ArrayBuffer
301
+ ? new Uint8Array(source)
302
+ : new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
303
+ return utf8.decode(bytes);
304
+ }
305
+ catch {
306
+ return '';
307
+ }
308
+ }
309
+ //# sourceMappingURL=leak-scan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leak-scan.js","sourceRoot":"","sources":["../src/leak-scan.ts"],"names":[],"mappings":";;AASA,8CAEC;AA2FD,4CAuBC;AAQD,oCAEC;AAMD,wCAgBC;AASD,sCAEC;AAxKD,+EAAsE;AAGtE;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,OAAO,KAAK,YAAY,uCAAe,CAAC;AAC1C,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,SAAS,GAAG,OAAO,CAAC;AAE1B,4EAA4E;AAC5E,MAAM,cAAc,GA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AAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
@@ -0,0 +1,93 @@
1
+ import { SensitiveString } from '@platform-sec/sensitive-string-core';
2
+ import type { SensitivityClass } from '@platform-sec/sensitive-string-core';
3
+ /**
4
+ * What a matcher returns. Structurally the result type Vitest and Jest both
5
+ * expect, declared here so this package depends on neither.
6
+ */
7
+ export interface MatcherResult {
8
+ pass: boolean;
9
+ message: () => string;
10
+ }
11
+ /**
12
+ * The matchers this package adds, as an interface a consumer can use to
13
+ * augment their test framework's assertion types.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * // vitest.d.ts, when not importing the ready-made augmentation
18
+ * import type { SensitiveMatchers } from '@platform-sec/sensitive-string-testing';
19
+ *
20
+ * declare module 'vitest' {
21
+ * interface Assertion<T = unknown> extends SensitiveMatchers<T> {}
22
+ * interface AsymmetricMatchersContaining extends SensitiveMatchers<unknown> {}
23
+ * }
24
+ * ```
25
+ */
26
+ export interface SensitiveMatchers<R = unknown> {
27
+ /** The value is a `SensitiveString`. */
28
+ toBeSensitiveString(): R;
29
+ /** The value is a `SensitiveString` of this sensitivity class. */
30
+ toHaveSensitivityClass(expected: SensitivityClass): R;
31
+ /** The value is a `SensitiveString` with this label. */
32
+ toHaveLabel(expected: string | undefined): R;
33
+ /** Revealing the value yields exactly this string. */
34
+ toRevealAs(expected: string): R;
35
+ /** The value has a deadline and that deadline has passed. */
36
+ toBeExpired(): R;
37
+ /** The received output contains the raw value of the given secret. */
38
+ toContainSensitive(expected: SensitiveString<SensitivityClass>): R;
39
+ }
40
+ /**
41
+ * Custom matchers for Vitest and Jest.
42
+ *
43
+ * Register them once, in a setup file:
44
+ *
45
+ * ```ts
46
+ * import { expect } from 'vitest';
47
+ * import { sensitiveMatchers } from '@platform-sec/sensitive-string-testing';
48
+ *
49
+ * expect.extend(sensitiveMatchers);
50
+ * ```
51
+ *
52
+ * Both frameworks also expose a registered matcher asymmetrically, so
53
+ * `expect.toBeSensitiveString()` works inside `toEqual` and
54
+ * `expect.objectContaining` without any further registration.
55
+ *
56
+ * Every matcher is read only: none of them changes the value under assertion,
57
+ * and none of them puts a raw value into a failure message. `toRevealAs` is the
58
+ * one that could, and it reports the redacted rendering and the length instead,
59
+ * because an assertion message ends up in a CI log.
60
+ *
61
+ * `toRevealAs` reveals through the instance, so an expired value or a policy
62
+ * denial fails the assertion rather than passing on a remembered copy. The leak
63
+ * matcher `toContainSensitive` reads the canary registry instead, since what it
64
+ * needs is a string to search output for, not permission to use the value.
65
+ */
66
+ export declare const sensitiveMatchers: {
67
+ toBeSensitiveString(received: unknown): MatcherResult;
68
+ toHaveSensitivityClass(received: unknown, expected: SensitivityClass): MatcherResult;
69
+ toHaveLabel(received: unknown, expected: string | undefined): MatcherResult;
70
+ toRevealAs(received: unknown, expected: string): MatcherResult;
71
+ toBeExpired(received: unknown): MatcherResult;
72
+ toContainSensitive(received: unknown, expected: SensitiveString<SensitivityClass>): MatcherResult;
73
+ };
74
+ /**
75
+ * Register the matchers with a test framework's `expect`.
76
+ *
77
+ * Taking `expect` as an argument rather than importing it keeps this package
78
+ * free of a dependency on either framework, which is what lets the same build
79
+ * serve Vitest and Jest.
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * // vitest.setup.ts
84
+ * import { expect } from 'vitest';
85
+ * import { setupSensitiveMatchers } from '@platform-sec/sensitive-string-testing';
86
+ *
87
+ * setupSensitiveMatchers(expect);
88
+ * ```
89
+ */
90
+ export declare function setupSensitiveMatchers(expect: {
91
+ extend(matchers: typeof sensitiveMatchers): unknown;
92
+ }): void;
93
+ //# sourceMappingURL=matchers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matchers.d.ts","sourceRoot":"","sources":["../src/matchers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AACtE,OAAO,KAAK,EAAE,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