@platform-sec/sensitive-string-testing 0.0.0-stage → 0.2.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.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +329 -2
  3. package/package.json +56 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 AppSec Science, LLC
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,330 @@
1
- # Temporary Holding Version
1
+ # @platform-sec/sensitive-string-testing
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
+ Test secrets, leak assertions, matchers, and audit mocks for
4
+ [`@platform-sec/sensitive-string-core`](../sensitive-core).
5
+
6
+ The core promise of `SensitiveString` is that a sensitive value does not reach
7
+ output it was never meant to reach. That promise has to be tested, and every
8
+ project that tests it ends up writing the same three things: a canary value, a
9
+ check that the canary is absent, and a fake audit context. This package is those
10
+ three things, written once.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pnpm add -D @platform-sec/sensitive-string-testing
16
+ ```
17
+
18
+ `@platform-sec/sensitive-string-core` is a peer dependency. No test framework is:
19
+ the matchers are a plain object you hand to `expect.extend`, and anything that
20
+ needs a spy takes `vi.fn` or `jest.fn` as an argument.
21
+
22
+ ## Requirements
23
+
24
+ - Node.js 22.12+
25
+ - Vitest or Jest, or any runner whose `expect` has `extend`
26
+
27
+ ## Test secrets
28
+
29
+ ```typescript
30
+ import { createTestSecret } from '@platform-sec/sensitive-string-testing';
31
+
32
+ const apiKey = createTestSecret('credential', 'api_key');
33
+ // __CANARY_1767225600000_1_3f9c1ab4e207__
34
+ ```
35
+
36
+ The value is unique per call and conspicuous on purpose: when it turns up in a
37
+ log capture or a snapshot diff, there is no question about what it is or which
38
+ test produced it. Uniqueness comes from a counter, the clock, and
39
+ `node:crypto`, so it survives both fake timers and a stubbed `Math.random`.
40
+
41
+ `createTestSecret` takes everything `SensitiveStringOptions` takes, so a test
42
+ that needs an expiring secret or an `onExpire` hook passes those straight
43
+ through:
44
+
45
+ ```typescript
46
+ const otp = createTestSecret('credential', 'otp', { ttl: 30_000 });
47
+ const email = createTestSecret('sensitive', 'email', { value: 'jane@example.com' });
48
+ ```
49
+
50
+ Two shapes are common enough to have their own factory:
51
+
52
+ ```typescript
53
+ import { createExpiredSecret, createExpiringSecret } from '@platform-sec/sensitive-string-testing';
54
+
55
+ createExpiredSecret('credential', 'otp'); // already past its deadline
56
+ createExpiringSecret('credential', 'session', 60_000); // expires in a minute
57
+ ```
58
+
59
+ `createExpiredSecret` needs no fake timers: `ttl: 0` puts the deadline at
60
+ construction.
61
+
62
+ ## Leak assertions
63
+
64
+ ```typescript
65
+ import { createTestSecret, expectNotLeaked } from '@platform-sec/sensitive-string-testing';
66
+
67
+ it('does not leak the key into the response', async () => {
68
+ const apiKey = createTestSecret('credential', 'api_key');
69
+
70
+ const response = await handler(apiKey);
71
+
72
+ expectNotLeaked(apiKey, response, logger.entries, await response.text());
73
+ });
74
+ ```
75
+
76
+ `expectNotLeaked` walks each target rather than serializing it. `JSON.stringify`
77
+ asks an object what it wants to show, and what an object wants to show is
78
+ exactly the wrong question for a leak check: a `toJSON` that omits a field hides
79
+ a raw copy that is still sitting on the object, and a `SensitiveString` renders
80
+ as its redacted form whether or not a plain copy sits next to it.
81
+
82
+ The walk reaches strings, other primitives, arrays and the properties attached
83
+ to them, `Map` and `Set` contents, typed arrays and `Buffer` contents, `RegExp`
84
+ sources, object keys, values behind getters, and own properties whether or not
85
+ they are enumerable, which is how an `Error`'s `message` and `stack` and a
86
+ `match()` result's `input` are covered. It does not reach closure variables,
87
+ `WeakMap` contents, unsettled promises, or function bodies.
88
+
89
+ There is no depth limit. The walk uses an explicit stack, so a leak thousands of
90
+ levels down is still found; a limit would report it as no leak at all. Getters
91
+ are invoked, which is worth knowing if a getter in your fixture has side
92
+ effects.
93
+
94
+ A value still wrapped in a `SensitiveString` is not a leak and is not reported
95
+ as one.
96
+
97
+ When a value does leak, the failure names the class, the label, and the path it
98
+ was found at, and quotes the surrounding text with the value replaced:
99
+
100
+ ```
101
+ LeakageDetectedError: Sensitive value leaked.
102
+ Label: api_key
103
+ Class: credential
104
+ Target: [0].headers["authorization"]
105
+ Context: Bearer [LEAKED VALUE]
106
+ The value itself is withheld so this message is safe to log.
107
+ ```
108
+
109
+ A leak assertion that proves a secret leaked by printing the secret has only
110
+ moved the leak, so it prints the location instead.
111
+
112
+ ### Redaction assertions
113
+
114
+ ```typescript
115
+ import { expectRedacted } from '@platform-sec/sensitive-string-testing';
116
+
117
+ expectRedacted(formatUserLog({ email }), email);
118
+ ```
119
+
120
+ `expectRedacted` checks two things: the raw value is absent, and the rendering
121
+ the class policy actually produces is present. It reads that rendering from the
122
+ instance rather than assuming `[REDACTED:class]`, so a custom policy passes
123
+ without the test having to know its format, and a policy that stops redacting
124
+ fails. Pass `customPattern` when the output transforms the rendering.
125
+
126
+ Both assertions search for the complete value, so a policy that discloses only
127
+ part of one reads as a successful redaction. Partial disclosure is what `mask()`
128
+ and its `minMasked` floor govern in core, and `registerPolicy` already rejects a
129
+ redaction that embeds the value.
130
+
131
+ ## Matchers
132
+
133
+ ```typescript
134
+ // vitest.setup.ts
135
+ import { expect } from 'vitest';
136
+ import { setupSensitiveMatchers } from '@platform-sec/sensitive-string-testing';
137
+
138
+ setupSensitiveMatchers(expect);
139
+ ```
140
+
141
+ ```typescript
142
+ expect(token).toBeSensitiveString();
143
+ expect(token).toHaveSensitivityClass('credential');
144
+ expect(token).toHaveLabel('api_token');
145
+ expect(token).toRevealAs('abc123');
146
+ expect(otp).toBeExpired();
147
+ expect(response).not.toContainSensitive(token);
148
+ ```
149
+
150
+ Both frameworks expose a registered matcher asymmetrically as well, so this
151
+ works with no further setup:
152
+
153
+ ```typescript
154
+ expect(response).toEqual({
155
+ token: expect.toBeSensitiveString(),
156
+ status: 'ok',
157
+ });
158
+ ```
159
+
160
+ `toRevealAs` goes through `reveal()`, so an expired value or a policy denial
161
+ fails the assertion instead of passing on a remembered copy. When it fails it
162
+ reports the redacted rendering and the length rather than the value.
163
+
164
+ ### Types
165
+
166
+ With Vitest, import the ready-made augmentation once:
167
+
168
+ ```typescript
169
+ import '@platform-sec/sensitive-string-testing/vitest';
170
+ ```
171
+
172
+ With Jest, or to write it yourself, extend from the exported interface:
173
+
174
+ ```typescript
175
+ import type { SensitiveMatchers } from '@platform-sec/sensitive-string-testing';
176
+
177
+ declare global {
178
+ namespace jest {
179
+ interface Matchers<R> extends SensitiveMatchers<R> {}
180
+ }
181
+ }
182
+ ```
183
+
184
+ ## Snapshot serializer
185
+
186
+ ```typescript
187
+ // vitest.setup.ts
188
+ import { expect } from 'vitest';
189
+ import { sensitiveSerializer } from '@platform-sec/sensitive-string-testing';
190
+
191
+ expect.addSnapshotSerializer(sensitiveSerializer);
192
+ ```
193
+
194
+ ```javascript
195
+ // jest.config.js
196
+ module.exports = {
197
+ snapshotSerializers: ['@platform-sec/sensitive-string-testing/serializer'],
198
+ };
199
+ ```
200
+
201
+ A snapshot then keeps the shape of the structure and says what each sensitive
202
+ field is, without recording what it holds:
203
+
204
+ ```
205
+ {
206
+ "id": 1,
207
+ "email": SensitiveString<sensitive:email>,
208
+ "apiKey": SensitiveString<credential:api_key>,
209
+ "phone": SensitiveString<sensitive>,
210
+ }
211
+ ```
212
+
213
+ Without a serializer the same snapshot records whatever the class policy's
214
+ `redact()` returns, which loses the label, differs between projects, and changes
215
+ when a policy does. The rendering here is built from the class and the label,
216
+ which are public metadata. It never calls `reveal()`, never reads the policy,
217
+ and has no format placeholder for the value, so a value cannot reach a snapshot
218
+ through it even under a policy registered with `skipRedactValidation`.
219
+
220
+ For a different rendering:
221
+
222
+ ```typescript
223
+ import { createSensitiveSerializer } from '@platform-sec/sensitive-string-testing';
224
+
225
+ createSensitiveSerializer({ showLength: true });
226
+ // SensitiveString<credential:api_key:len=32>
227
+
228
+ createSensitiveSerializer({ showExpiration: true });
229
+ // SensitiveString<credential:otp:EXPIRED>
230
+
231
+ createSensitiveSerializer({ format: '<{class}{label}>' });
232
+ // <credential:api_key>
233
+ ```
234
+
235
+ `showLength` and `showExpiration` are off by default. A snapshot is committed to
236
+ version control, so the length of a credential is more than the class and the
237
+ label say about it, and whether a value is expired depends on when the test ran,
238
+ which makes a stored snapshot that records it stable only while the deadline
239
+ stays on the same side of the clock.
240
+
241
+ A `format` supersedes both options: the placeholders written in it decide what
242
+ appears. They are `{class}`, `{label}`, `{length}` and `{expired}`, and each
243
+ carries its own separator so the optional ones collapse cleanly. There is none
244
+ for the value, and an unknown one is rejected when the serializer is built
245
+ rather than passed through into every snapshot in the suite.
246
+
247
+ ## Audit mocks
248
+
249
+ ```typescript
250
+ import { mockRevealContext } from '@platform-sec/sensitive-string-testing';
251
+
252
+ const ctx = mockRevealContext('payment-handler', { fn: vi.fn });
253
+
254
+ token.reveal(ctx);
255
+
256
+ expect(ctx.calls).toHaveLength(1);
257
+ expect(ctx.calls[0]?.details.operation).toBe('reveal');
258
+ expect(ctx.auditReveal).toHaveBeenCalledTimes(1);
259
+ ```
260
+
261
+ `calls` is recorded whether or not a spy factory is given. Passing `vi.fn` or
262
+ `jest.fn` additionally makes `auditReveal` a spy, so the framework's own call
263
+ assertions work on it. `reset()` clears both.
264
+
265
+ Each call also records `context`, the context that operation ran under, which is
266
+ where the tags an integration attaches to a reveal appear:
267
+
268
+ ```typescript
269
+ expect(ctx.calls[0]?.context.tags).toEqual({ model: 'User', path: 'passwordHash' });
270
+ ```
271
+
272
+ It is a copy of the descriptive fields rather than the context itself, one level
273
+ deep. A record pointing at the live mock context would close a cycle through
274
+ `calls`, which neither `JSON.stringify` nor a snapshot assertion could walk.
275
+
276
+ Both helpers degrade rather than throw when something forwards the hook with the
277
+ two arguments it used to take: the record carries the mock's own name and no
278
+ tags, which is what a two-argument caller means. They run inside the reveal gate,
279
+ where a `TypeError` would surface as a failing reveal rather than as a missing
280
+ tag.
281
+
282
+ For assertions about a whole call path rather than a single operation:
283
+
284
+ ```typescript
285
+ import { createMockAuditLog } from '@platform-sec/sensitive-string-testing';
286
+ import { withRevealContext } from '@platform-sec/sensitive-string-core';
287
+
288
+ const audit = createMockAuditLog();
289
+
290
+ await withRevealContext(audit.context, () => chargeCard(card));
291
+
292
+ expect(audit.getEntriesFor('card_number')).toHaveLength(1);
293
+ expect(audit.getEntriesByClass('credential')).toHaveLength(1);
294
+ ```
295
+
296
+ An entry records the class, the label, the context name, and the operation. It
297
+ deliberately holds no raw value and no reference to the instance, because an
298
+ audit log is the thing most likely to end up in a failing assertion's output.
299
+
300
+ `contextName` is read from the context core reports the operation under, so a
301
+ reveal made under a nested child is recorded under the child's name rather than
302
+ the log's own.
303
+
304
+ ## How these utilities read a value
305
+
306
+ A leak check needs the raw value to search for. Values this package created are
307
+ remembered when they are created, so a leak check does not have to reveal them:
308
+ that keeps the class policy's authorization hook and the caller's audit context
309
+ out of an assertion about output, and it lets a leak check run on a secret whose
310
+ deadline has already passed.
311
+
312
+ A value from anywhere else is revealed under an explicit named context, exported
313
+ as `TESTING_CONTEXT_NAMES`, so a strict `checkRevealAllowed` can allow those
314
+ four names in one place. If that reveal is refused, by a deadline or by a
315
+ policy, the check raises `UnreadableSecretError` saying it could not run, rather
316
+ than letting an `ExpiredSensitiveValueError` surface from inside an assertion
317
+ about output where it would read as a clean result. The registry is keyed by object identity and is not
318
+ reachable from outside this package: it adds no property to the instance and no
319
+ second way to the value. It does hold whatever is passed through the `value`
320
+ option, which is a reason to keep real secrets out of that option.
321
+
322
+ ## Not included yet
323
+
324
+ - `createSingleUseSecret`, which needs the reveal counters from roadmap item
325
+ 1.4. There is nothing to exhaust until those exist.
326
+ - Streaming leak monitors, deferred by the design document.
327
+
328
+ ## License
329
+
330
+ MIT
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@platform-sec/sensitive-string-testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Test secrets, leak assertions, matchers, and audit mocks for SensitiveString",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./vitest": {
14
+ "types": "./dist/vitest.d.ts",
15
+ "default": "./dist/vitest.js"
16
+ },
17
+ "./serializer": {
18
+ "types": "./dist/serializer.d.ts",
19
+ "default": "./dist/serializer.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "scripts": {
26
+ "build": "tsc",
27
+ "test": "vitest run --root ../.. packages/sensitive-testing/",
28
+ "test:watch": "vitest --root ../.. packages/sensitive-testing/"
29
+ },
30
+ "keywords": [
31
+ "testing",
32
+ "vitest",
33
+ "jest",
34
+ "matchers",
35
+ "snapshot",
36
+ "security",
37
+ "sensitive-data",
38
+ "typescript"
39
+ ],
40
+ "license": "MIT",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/platform-sec/sensitive-string-js.git",
44
+ "directory": "packages/sensitive-testing"
45
+ },
46
+ "engines": {
47
+ "node": ">=22.12.0"
48
+ },
49
+ "peerDependencies": {
50
+ "@platform-sec/sensitive-string-core": "^0.6.0"
51
+ },
52
+ "devDependencies": {
53
+ "@platform-sec/sensitive-string-core": "workspace:*",
54
+ "@types/node": "^22.20.1",
55
+ "typescript": "^5.9.3",
56
+ "vitest": "^4.1.11"
57
+ }
58
+ }