@platform-sec/sensitive-string-zod 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.
- package/LICENSE +21 -0
- package/README.md +312 -2
- package/package.json +47 -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,313 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @platform-sec/sensitive-string-zod
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Zod integration for SensitiveString - parse and validate input directly into sensitive types at boundary layers.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @platform-sec/sensitive-string-zod zod
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Requirements
|
|
12
|
+
|
|
13
|
+
- Node.js 22.12+
|
|
14
|
+
- Zod 4.0+
|
|
15
|
+
- @platform-sec/sensitive-string-core (peer dependency)
|
|
16
|
+
|
|
17
|
+
Zod 3 is not supported. A v3 schema and a v4 schema cannot be composed in either direction, and the
|
|
18
|
+
failure is a raw `TypeError` at schema construction rather than a type error, so a peer range
|
|
19
|
+
admitting both majors would be a promise this package could not keep.
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { z } from 'zod';
|
|
25
|
+
import { zCredential, zSensitiveWithValidation } from '@platform-sec/sensitive-string-zod';
|
|
26
|
+
|
|
27
|
+
// Define schema with sensitive fields
|
|
28
|
+
const WebhookSchema = z.object({
|
|
29
|
+
token: zCredential('session_token'),
|
|
30
|
+
email: zSensitiveWithValidation('sensitive', z.email(), 'email'),
|
|
31
|
+
note: z.string().optional(),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// Parse request body
|
|
35
|
+
const webhook = WebhookSchema.parse(req.body);
|
|
36
|
+
|
|
37
|
+
// Type inference works correctly
|
|
38
|
+
// webhook.token is SensitiveString<'credential'>
|
|
39
|
+
// webhook.email is SensitiveString<'sensitive'>
|
|
40
|
+
|
|
41
|
+
// Safe to serialize
|
|
42
|
+
res.json(webhook); // Sensitive fields automatically redacted
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Available Schemas
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
// Generic sensitive string with specified class + label
|
|
49
|
+
zSensitiveString('sensitive', 'email') // → SensitiveString<'sensitive'>
|
|
50
|
+
zSensitiveString('credential', 'token') // → SensitiveString<'credential'>
|
|
51
|
+
|
|
52
|
+
// Convenience shortcuts
|
|
53
|
+
zSensitive('email') // → SensitiveString<'sensitive'>
|
|
54
|
+
zCredential('session_token') // → SensitiveString<'credential'>
|
|
55
|
+
|
|
56
|
+
// With custom validation
|
|
57
|
+
zSensitiveWithValidation('credential', z.string().min(32), 'api_key')
|
|
58
|
+
|
|
59
|
+
// Optional (returns null for missing)
|
|
60
|
+
zSensitiveOptional('sensitive', 'phone')
|
|
61
|
+
|
|
62
|
+
// Parse from serialized format
|
|
63
|
+
zSensitiveDeserialize('credential')
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Collections
|
|
67
|
+
|
|
68
|
+
Arrays and records wrap each element on its own, so the collection combinators still apply and a
|
|
69
|
+
failing element reports its own index or key.
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
zSensitiveArray('email') // → SensitiveString<'sensitive'>[]
|
|
73
|
+
zCredentialArray('api_key').min(1).max(10) // ZodArray, so .min() and friends work
|
|
74
|
+
zSensitiveStringArray('credential', 'token') // explicit class
|
|
75
|
+
|
|
76
|
+
zSensitiveRecord('note') // → Record<string, SensitiveString<'sensitive'>>
|
|
77
|
+
zCredentialRecord('secret') // → Record<string, SensitiveString<'credential'>>
|
|
78
|
+
zSensitiveStringRecord('credential', 'secret')
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Record keys stay in the clear. A key is a field name, not the secret, and redacting it would leave
|
|
82
|
+
the record impossible to look anything up in.
|
|
83
|
+
|
|
84
|
+
Nothing stops you writing `z.array(zCredential('api_key'))` by hand; the helpers are the same thing
|
|
85
|
+
with the label named once.
|
|
86
|
+
|
|
87
|
+
### Refinements over the raw value
|
|
88
|
+
|
|
89
|
+
`refineSensitive` runs a predicate against the raw string after wrapping. That read goes through
|
|
90
|
+
`reveal()`, so the ambient `RevealContext` authorizes it and its `auditReveal` hook records it with
|
|
91
|
+
`operation: 'reveal'`.
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
const PasswordSchema = zCredential('password')
|
|
95
|
+
.refineSensitive((raw) => raw.length >= 12, { message: 'Password must be at least 12 characters' })
|
|
96
|
+
.refineSensitive((raw) => /[0-9]/.test(raw), { message: 'Password must contain a digit' });
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
The refinement manufactures no authority of its own. If a policy refuses a reveal without a context,
|
|
100
|
+
it refuses this one too; pass `params.context` to give the check a context of its own.
|
|
101
|
+
|
|
102
|
+
An async predicate is supported under `parseAsync`. Reached from a synchronous `parse()`, Zod throws
|
|
103
|
+
`$ZodAsyncError` rather than treating the pending promise as a pass.
|
|
104
|
+
|
|
105
|
+
The method is attached to the schemas this package builds. Standard Zod combinators return plain Zod
|
|
106
|
+
schemas and drop it, so refine before calling `.optional()` or `.array()`, or use the standalone
|
|
107
|
+
function:
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
import { refineSensitive } from '@platform-sec/sensitive-string-zod';
|
|
111
|
+
|
|
112
|
+
refineSensitive(someSchema, (raw) => raw.startsWith('sk_'), { message: 'must start with sk_' });
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Normalizing before wrapping
|
|
116
|
+
|
|
117
|
+
Trimming a `SensitiveString` means revealing it. Normalizing during the parse keeps the whole
|
|
118
|
+
sequence on the raw string, with no reveal at all. Order is normalize, then validate, then wrap.
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
zSensitivePreprocess({ trim: true, lowercase: true }, 'email', z.email());
|
|
122
|
+
zCredentialPreprocess({ stripWhitespace: true }, 'api_key'); // a key pasted with line breaks
|
|
123
|
+
zSensitivePreprocess([(v) => v.trim(), (v) => v.replace(/-/gu, '')], 'account_number');
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Options are applied in the order `normalize`, `collapseWhitespace`, `stripWhitespace`, `trim`,
|
|
127
|
+
`lowercase` or `uppercase`. A function or a list of functions works in place of the options object.
|
|
128
|
+
Non-string input passes through untouched, so it still reports Zod's usual `invalid_type`.
|
|
129
|
+
|
|
130
|
+
### Defaults
|
|
131
|
+
|
|
132
|
+
The default is produced as a raw string and wrapped by the schema, so a generated fallback is
|
|
133
|
+
classified the same way a parsed one is. A function default is called once per parse that needs it.
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
const Config = z.object({
|
|
137
|
+
apiKey: zSensitiveDefault('credential', 'api_key', () => process.env.API_KEY ?? ''),
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
`undefined` triggers the default. `null` and `''` do not: they are values a client sent, and
|
|
142
|
+
treating them as absent would substitute a secret for input that should have been rejected.
|
|
143
|
+
|
|
144
|
+
The fallback is held in a closure rather than in a `z.string().default(...)`, and that placement is
|
|
145
|
+
load-bearing. `z.toJSONSchema(schema, { io: 'input' })` reads a schema definition's `default` and
|
|
146
|
+
emits it verbatim, calling a function default to do so, which is exactly what an OpenAPI
|
|
147
|
+
request-body generator does. Under a `.default()`, the example above would put the live
|
|
148
|
+
`process.env.API_KEY` into the published document.
|
|
149
|
+
|
|
150
|
+
The same reasoning applies to what you attach yourself. `z.toJSONSchema` emits `.meta({ examples })`
|
|
151
|
+
and `.meta({ description })` verbatim, and `z.literal(secret)` emits `const: "<secret>"`. Those are
|
|
152
|
+
yours to keep clean; `toJSONSchema`'s `override` callback is the documented escape hatch. On the
|
|
153
|
+
output side, a schema built by this package produces a `SensitiveString` and `toJSONSchema` refuses
|
|
154
|
+
with `Transforms cannot be represented in JSON Schema`, which is the right answer.
|
|
155
|
+
|
|
156
|
+
### Sensitivity decided by a sibling field
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
const Setting = zConditionalSensitive({
|
|
160
|
+
discriminator: 'type',
|
|
161
|
+
valueField: 'value',
|
|
162
|
+
conditions: {
|
|
163
|
+
secret: { klass: 'credential', label: 'secret_data' },
|
|
164
|
+
private: { klass: 'sensitive', label: 'private_data' },
|
|
165
|
+
public: null,
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
Setting.parse({ type: 'secret', value: 'sk-live-x' }); // value is SensitiveString
|
|
170
|
+
Setting.parse({ type: 'public', value: 'motd' }); // value is a string
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The result is a `z.discriminatedUnion`, so an unknown discriminator is rejected before the value is
|
|
174
|
+
looked at. For payloads with more than these two fields, write the branches by hand; `zSensitive`
|
|
175
|
+
and `zCredential` work as object fields there with nothing extra.
|
|
176
|
+
|
|
177
|
+
## Errors That Do Not Echo the Input
|
|
178
|
+
|
|
179
|
+
Most of Zod's issues are already safe. A failed `min`, `email`, or `regex` check reports the rule,
|
|
180
|
+
not the string that failed it, and Zod 4 closed two leaks v3 had: the enum and literal codes both
|
|
181
|
+
became `invalid_value`, which carries the *allowed* set rather than what arrived. What is left,
|
|
182
|
+
measured against 4.5.4 with a canary:
|
|
183
|
+
|
|
184
|
+
| Issue code | What it carries |
|
|
185
|
+
|---|---|
|
|
186
|
+
| `unrecognized_keys` | unknown key names, in `keys` and in the message |
|
|
187
|
+
| `custom` | whatever a `superRefine` caller attached to `params` |
|
|
188
|
+
| `invalid_element` | the offending map key, in `key` |
|
|
189
|
+
| any | the value itself, in `input`, when the parse options set `reportInput: true` |
|
|
190
|
+
|
|
191
|
+
`invalid_union`, `invalid_key`, and `invalid_element` nest issue lists, so any of the above can
|
|
192
|
+
arrive one or more levels down.
|
|
193
|
+
|
|
194
|
+
The guarantee is about the input, not about values you put in your own schema. `invalid_value`
|
|
195
|
+
echoes what `z.literal()` and `z.enum()` were given, and `invalid_format` echoes the argument to
|
|
196
|
+
`startsWith`, `endsWith`, and `includes`. Nothing here can tell a secret apart from a legitimate
|
|
197
|
+
allowed value, so do not build a schema out of one. This is the same hazard as `z.literal(secret)`
|
|
198
|
+
under `z.toJSONSchema`, above.
|
|
199
|
+
|
|
200
|
+
That splits the fix in two. An error map can only rewrite the message. The `keys`, `params`, `key`,
|
|
201
|
+
and `input` fields survive it untouched and reach anything that serializes the error, which is where
|
|
202
|
+
structured logging picks them up.
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
import { sensitiveSafeParse } from '@platform-sec/sensitive-string-zod';
|
|
206
|
+
|
|
207
|
+
const result = sensitiveSafeParse(LoginSchema, req.body);
|
|
208
|
+
if (!result.success) {
|
|
209
|
+
res.status(400).json({ issues: result.error.issues }); // nothing echoed, message or field
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
`sensitiveParse` and `sensitiveSafeParseAsync` are the throwing and async counterparts. For an error
|
|
214
|
+
you already hold, `redactZodError` and `redactZodIssues` return redacted copies without touching the
|
|
215
|
+
originals. All three parse helpers take Zod 4's parse options, exported as `SensitiveParseOptions`;
|
|
216
|
+
they set `error` when you have not, and force `reportInput` off, since that option puts the raw value
|
|
217
|
+
back on every issue.
|
|
218
|
+
|
|
219
|
+
To cover schemas that never pass through these helpers, install the error map once at startup. It is
|
|
220
|
+
not installed on import: a library that reaches into a process's global Zod configuration behind the
|
|
221
|
+
application's back is worse than one that asks for a line of setup.
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
import { installSensitiveErrorMap } from '@platform-sec/sensitive-string-zod';
|
|
225
|
+
|
|
226
|
+
installSensitiveErrorMap();
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
That still leaves the structured fields, so keep using `sensitiveSafeParse` at the boundary.
|
|
230
|
+
|
|
231
|
+
### Do not key a container by a secret
|
|
232
|
+
|
|
233
|
+
One channel is deliberately left uncovered: `issue.path`. A `z.object`, `z.record`, or `z.map` keyed
|
|
234
|
+
by a sensitive value puts that value in the path of every issue below it, and `z.treeifyError`
|
|
235
|
+
reproduces it as an object key.
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
z.map(z.literal('k'), z.string()).safeParse(new Map([[secret, 'v']]));
|
|
239
|
+
// -> path: ['<the secret>']
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Redacting `path` is not the fix: it is the only thing that makes a multi-issue error actionable, and
|
|
243
|
+
collapsing it would turn a form validation response into a list of unattributed complaints. Put the
|
|
244
|
+
secret in the value position instead, which is what `zSensitiveRecord` does. The failure is silent,
|
|
245
|
+
so it is worth checking for by hand.
|
|
246
|
+
|
|
247
|
+
## Examples
|
|
248
|
+
|
|
249
|
+
### User Registration
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
const RegistrationSchema = z.object({
|
|
253
|
+
email: zSensitivePreprocess({ trim: true, lowercase: true }, 'email', z.email()),
|
|
254
|
+
password: zSensitiveWithValidation(
|
|
255
|
+
'credential',
|
|
256
|
+
z.string()
|
|
257
|
+
.min(8, 'Password must be at least 8 characters')
|
|
258
|
+
.regex(/[A-Z]/, 'Must contain uppercase')
|
|
259
|
+
.regex(/[0-9]/, 'Must contain number'),
|
|
260
|
+
'password'
|
|
261
|
+
).refineSensitive((raw) => !raw.toLowerCase().includes('password'), {
|
|
262
|
+
message: 'Password must not contain the word "password"',
|
|
263
|
+
}),
|
|
264
|
+
fullName: zSensitive('name'),
|
|
265
|
+
phone: zSensitiveOptional('sensitive', 'phone'),
|
|
266
|
+
backupCodes: zCredentialArray('backup_code').length(10),
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
const result = sensitiveSafeParse(RegistrationSchema, req.body);
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
### API Authentication
|
|
273
|
+
|
|
274
|
+
```typescript
|
|
275
|
+
const AuthHeaderSchema = z.object({
|
|
276
|
+
authorization: zCredential('auth_header'),
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
const headers = AuthHeaderSchema.parse(req.headers);
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Service-to-Service Communication
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
// Receiving service
|
|
286
|
+
const PayloadSchema = z.object({
|
|
287
|
+
userId: z.string(),
|
|
288
|
+
token: zSensitiveDeserialize('credential'),
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
const { token } = PayloadSchema.parse(req.body);
|
|
292
|
+
// token is SensitiveString<'credential'>, reconstructed from serialized form
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
A class mismatch, an unregistered class, and a malformed payload are all reported as Zod issues, so
|
|
296
|
+
`safeParse` reports them rather than throwing.
|
|
297
|
+
|
|
298
|
+
## Re-exports
|
|
299
|
+
|
|
300
|
+
For convenience, this package re-exports commonly used items from `@platform-sec/sensitive-string-core`:
|
|
301
|
+
|
|
302
|
+
- `SensitiveString`
|
|
303
|
+
- `SensitivityClass`
|
|
304
|
+
- `SerializedSensitiveString`
|
|
305
|
+
- `RevealContext`
|
|
306
|
+
- `withRevealContext`
|
|
307
|
+
- `getCurrentRevealContext`
|
|
308
|
+
- `safeLog`
|
|
309
|
+
- `redactInStructure`
|
|
310
|
+
|
|
311
|
+
## License
|
|
312
|
+
|
|
313
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@platform-sec/sensitive-string-zod",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Zod integration for SensitiveString - parse input directly into sensitive types",
|
|
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
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc",
|
|
19
|
+
"test": "vitest run --root ../.. packages/sensitive-zod/",
|
|
20
|
+
"test:watch": "vitest --root ../.. packages/sensitive-zod/"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"zod",
|
|
24
|
+
"validation",
|
|
25
|
+
"security",
|
|
26
|
+
"sensitive-data",
|
|
27
|
+
"typescript"
|
|
28
|
+
],
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/platform-sec/sensitive-string-js.git",
|
|
33
|
+
"directory": "packages/sensitive-zod"
|
|
34
|
+
},
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=22.12.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@platform-sec/sensitive-string-core": "^0.6.0",
|
|
40
|
+
"zod": "^4.0.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@platform-sec/sensitive-string-core": "workspace:*",
|
|
44
|
+
"@types/node": "^22.20.1",
|
|
45
|
+
"typescript": "^5.9.3",
|
|
46
|
+
"vitest": "^4.1.11",
|
|
47
|
+
"zod": "^4.5.4"
|
|
48
|
+
}
|
|
49
|
+
}
|