@platform-sec/sensitive-string-zod 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,311 @@
1
+ "use strict";
2
+ /**
3
+ * Keeping the input out of validation errors.
4
+ *
5
+ * Most of Zod's built-in issues report the rule, not the string that failed it,
6
+ * and Zod 4 closed two leaks v3 had: `invalid_enum_value` and `invalid_literal`
7
+ * are both `invalid_value` now, which carries the *allowed* set rather than
8
+ * what arrived. What is left, measured against 4.5.4 with a canary:
9
+ *
10
+ * - `unrecognized_keys` puts unknown key names in `keys` and in the message.
11
+ * - `custom` carries whatever a `superRefine` caller attached to `params`.
12
+ * - `invalid_element` carries the offending map key in `key`.
13
+ * - every issue can carry `input`, the value itself. Zod drops it during
14
+ * finalization by default, but `{ reportInput: true }` in the parse options
15
+ * keeps it, and the raw issue an error function sees always has it.
16
+ * - `invalid_union`, `invalid_key`, and `invalid_element` nest issue lists, so
17
+ * any of the above can arrive one or more levels down.
18
+ *
19
+ * That splits the fix in two. An error map can only rewrite the message, so it
20
+ * handles what a caller sees in `error.message`. The `keys`, `params`, `key`,
21
+ * and `input` fields survive an error map untouched and reach anything that
22
+ * serializes the error, which is where structured logging picks them up. Use
23
+ * {@link sensitiveSafeParse} to get both, or {@link redactZodError} on an error
24
+ * you already hold.
25
+ *
26
+ * What is deliberately *not* covered is `issue.path`. A container keyed by a
27
+ * sensitive value puts that value in the path of every issue below it. Redacting
28
+ * it would collapse every field of a multi-issue error into one bucket and make
29
+ * `z.treeifyError` useless, so the answer is not to key a container by a secret:
30
+ * put it in the value position, which is what `zSensitiveRecord` does.
31
+ *
32
+ * One thing this module does not attempt at all: the guarantee is about the
33
+ * *input*, not about values a schema author embedded in their own schema.
34
+ * `invalid_value.values` echoes what `z.literal()` and `z.enum()` were given,
35
+ * and `invalid_format` echoes the argument to `startsWith`, `endsWith`, and
36
+ * `includes`. Those read as safe in the table above, and they are, with respect
37
+ * to the input. `z.literal(secret)` still puts the secret in every issue it
38
+ * produces, and there is nothing here that could tell it apart from a legitimate
39
+ * allowed value. Do not build a schema out of a secret.
40
+ *
41
+ * @packageDocumentation
42
+ */
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.sensitiveErrorMap = exports.REDACTED_ISSUE_VALUE = void 0;
45
+ exports.installSensitiveErrorMap = installSensitiveErrorMap;
46
+ exports.redactZodIssues = redactZodIssues;
47
+ exports.redactZodError = redactZodError;
48
+ exports.sensitiveSafeParse = sensitiveSafeParse;
49
+ exports.sensitiveSafeParseAsync = sensitiveSafeParseAsync;
50
+ exports.sensitiveParse = sensitiveParse;
51
+ const zod_1 = require("zod");
52
+ /**
53
+ * Stand-in written over any value stripped from an issue.
54
+ *
55
+ * Matches the core library's redaction marker so that one grep over a log
56
+ * finds every kind of redaction the library performs.
57
+ */
58
+ exports.REDACTED_ISSUE_VALUE = '[REDACTED]';
59
+ /**
60
+ * A Zod error map that never echoes the input into a message.
61
+ *
62
+ * Install it globally with {@link installSensitiveErrorMap}, or pass it per
63
+ * call as `schema.safeParse(data, { error: sensitiveErrorMap })`.
64
+ *
65
+ * This rewrites messages only. The issue objects still carry `keys`, `params`,
66
+ * and `key`; see {@link redactZodError}.
67
+ *
68
+ * Returning `undefined` is how a v4 error map declines: there is no second
69
+ * `ctx` argument carrying a default message, and returning nothing hands the
70
+ * issue back to Zod's own message resolution.
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * const schema = z.object({ a: z.string() }).strict();
75
+ * const result = schema.safeParse({ a: 'x', [secret]: 1 }, { error: sensitiveErrorMap });
76
+ * // "Unrecognized key(s) in object: 1 not allowed" - and nothing about the key
77
+ * ```
78
+ */
79
+ const sensitiveErrorMap = (issue) => {
80
+ // Invariant S3: `issue.input` is never read here. The raw issue handed to an
81
+ // error function carries the value in full, so interpolating any part of the
82
+ // issue into a message is how this function would become the leak it exists
83
+ // to prevent.
84
+ switch (issue.code) {
85
+ case 'unrecognized_keys':
86
+ return `Unrecognized key(s) in object: ${issue.keys.length} not allowed`;
87
+ default:
88
+ return undefined;
89
+ }
90
+ };
91
+ exports.sensitiveErrorMap = sensitiveErrorMap;
92
+ /**
93
+ * Install {@link sensitiveErrorMap} as Zod's global error map.
94
+ *
95
+ * Global on purpose: the leaking issue codes come from schemas this package
96
+ * knows nothing about, most often a strict object sitting beside a sensitive
97
+ * field. Scoping the map to sensitive schemas would miss exactly the cases it
98
+ * exists for.
99
+ *
100
+ * It is not installed on import. A library that reaches into a process's
101
+ * global Zod configuration behind the application's back is worse than one
102
+ * that asks for a line of setup.
103
+ *
104
+ * `z.config()` reads the configuration back, so a caller who needs to undo this
105
+ * can capture `z.config().customError` first and restore it afterwards.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * // Once, during startup.
110
+ * installSensitiveErrorMap();
111
+ * ```
112
+ */
113
+ function installSensitiveErrorMap() {
114
+ zod_1.z.config({ customError: exports.sensitiveErrorMap });
115
+ }
116
+ /**
117
+ * Merge the caller's parse options with the ones this module requires.
118
+ *
119
+ * Two rules, and both are fail-open if dropped.
120
+ *
121
+ * An explicit `error: undefined` counts as not supplying a map. Spreading it
122
+ * over the default would leave Zod resolving the global map instead, which
123
+ * defeats the one helper whose whole job is not leaking the input.
124
+ *
125
+ * `reportInput` is forced off. It is a v4 parse option that keeps the raw
126
+ * value on every finalized issue; `redactIssue` strips it afterwards either
127
+ * way, but a helper named for not leaking the input should not ask Zod to put
128
+ * it there in the first place.
129
+ */
130
+ function withSensitiveParseOptions(params) {
131
+ return { ...params, error: params?.error ?? exports.sensitiveErrorMap, reportInput: false };
132
+ }
133
+ /**
134
+ * Replace every occurrence of a value's string form in a message.
135
+ *
136
+ * The message is rewritten rather than discarded so that a caller who has not
137
+ * installed the error map still gets a usable explanation of the failure.
138
+ */
139
+ function scrubFromMessage(message, value) {
140
+ const rendered = typeof value === 'string' ? value : String(value);
141
+ if (rendered === '' || !message.includes(rendered)) {
142
+ return message;
143
+ }
144
+ return message.split(rendered).join(exports.REDACTED_ISSUE_VALUE);
145
+ }
146
+ /**
147
+ * Drop `input` from an issue.
148
+ *
149
+ * Zod strips it during finalization under the default parse options, but
150
+ * `z.core.$ZodIssueBase` declares `readonly input?: unknown`, so the field
151
+ * type-checks on a finalized issue and `{ reportInput: true }` really does
152
+ * populate it. This does not depend on which of those a caller got.
153
+ */
154
+ function withoutInput(issue) {
155
+ if (!('input' in issue)) {
156
+ return issue;
157
+ }
158
+ const copy = { ...issue };
159
+ delete copy['input'];
160
+ return copy;
161
+ }
162
+ /**
163
+ * Strip input-derived values out of one issue's own fields.
164
+ *
165
+ * `invalid_type` is left alone: its `expected` is a type name such as
166
+ * `'string'`, not the value. `too_small`, `too_big`, `invalid_format`,
167
+ * `not_multiple_of`, and `invalid_value` describe the rule and were measured
168
+ * clean.
169
+ */
170
+ function redactIssueFields(issue) {
171
+ switch (issue.code) {
172
+ case 'unrecognized_keys': {
173
+ let message = issue.message;
174
+ for (const key of issue.keys) {
175
+ message = scrubFromMessage(message, key);
176
+ }
177
+ return {
178
+ ...issue,
179
+ keys: issue.keys.map(() => exports.REDACTED_ISSUE_VALUE),
180
+ message,
181
+ };
182
+ }
183
+ case 'custom': {
184
+ // `params` is whatever a superRefine caller attached. It is dropped
185
+ // rather than inspected: this helper cannot tell a locale key from the
186
+ // value that failed the check.
187
+ const { params: _params, ...rest } = issue;
188
+ return rest;
189
+ }
190
+ case 'invalid_union':
191
+ // The multiple-match member declares `errors: []` and carries nothing to
192
+ // redact, and mapping over it would not type-check against that member.
193
+ return 'matches' in issue
194
+ ? issue
195
+ : { ...issue, errors: issue.errors.map((nested) => redactZodIssues(nested)) };
196
+ case 'invalid_key':
197
+ // A record or map key rejected by its own schema. The nested issues are
198
+ // about the key, so a refinement on it can put the key in `params`.
199
+ return { ...issue, issues: redactZodIssues(issue.issues) };
200
+ case 'invalid_element':
201
+ // Zod reports a map value under a non-primitive key here, and `key` is
202
+ // that key verbatim.
203
+ return {
204
+ ...issue,
205
+ key: exports.REDACTED_ISSUE_VALUE,
206
+ issues: redactZodIssues(issue.issues),
207
+ };
208
+ default:
209
+ return issue;
210
+ }
211
+ }
212
+ /**
213
+ * Copy a list of issues with every input value stripped out.
214
+ *
215
+ * The originals are not modified: a caller may still be holding the unredacted
216
+ * error, and silently mutating it would change what an already-written handler
217
+ * reports.
218
+ *
219
+ * @param issues - The issues to copy
220
+ * @returns Issues safe to log or serialize
221
+ */
222
+ function redactZodIssues(issues) {
223
+ return issues.map((issue) => withoutInput(redactIssueFields(issue)));
224
+ }
225
+ /**
226
+ * Copy a ZodError with every input value stripped out, including from the
227
+ * issues nested inside a union, key, or element issue.
228
+ *
229
+ * @param error - The error to copy
230
+ * @returns A new ZodError safe to log or serialize
231
+ *
232
+ * @example
233
+ * ```ts
234
+ * try {
235
+ * schema.parse(payload);
236
+ * } catch (err) {
237
+ * if (err instanceof z.ZodError) {
238
+ * logger.warn('validation failed', { issues: redactZodError(err).issues });
239
+ * }
240
+ * }
241
+ * ```
242
+ */
243
+ function redactZodError(error) {
244
+ // v4 exports `ZodError` as `core.$constructor<ZodError>`, with no type
245
+ // parameter, so `new z.ZodError<T>(...)` is a compile error. The result
246
+ // carries the same issues for the same input, so the parameter is restored
247
+ // here rather than dropped from the signature and pushed onto every caller.
248
+ return new zod_1.z.ZodError(redactZodIssues(error.issues));
249
+ }
250
+ /**
251
+ * `safeParse` with both halves of the fix applied: the error map rewrites the
252
+ * messages, and the returned issues are redacted.
253
+ *
254
+ * @typeParam Output - What the schema produces
255
+ * @typeParam Input - What the schema accepts
256
+ * @param schema - The schema to parse with
257
+ * @param data - The input
258
+ * @param params - Additional Zod parse options; a supplied `error` map wins
259
+ * @returns Zod's usual safe-parse result, with a redacted error on failure
260
+ *
261
+ * @example
262
+ * ```ts
263
+ * const result = sensitiveSafeParse(LoginSchema, req.body);
264
+ * if (!result.success) {
265
+ * res.status(400).json({ issues: result.error.issues }); // no input echoed
266
+ * }
267
+ * ```
268
+ */
269
+ function sensitiveSafeParse(schema, data, params) {
270
+ const result = schema.safeParse(data, withSensitiveParseOptions(params));
271
+ return result.success ? result : { success: false, error: redactZodError(result.error) };
272
+ }
273
+ /**
274
+ * The async counterpart of {@link sensitiveSafeParse}, for schemas carrying an
275
+ * async refinement.
276
+ *
277
+ * @typeParam Output - What the schema produces
278
+ * @typeParam Input - What the schema accepts
279
+ * @param schema - The schema to parse with
280
+ * @param data - The input
281
+ * @param params - Additional Zod parse options; a supplied `error` map wins
282
+ * @returns Zod's usual safe-parse result, with a redacted error on failure
283
+ */
284
+ async function sensitiveSafeParseAsync(schema, data, params) {
285
+ const result = await schema.safeParseAsync(data, withSensitiveParseOptions(params));
286
+ return result.success ? result : { success: false, error: redactZodError(result.error) };
287
+ }
288
+ /**
289
+ * `parse` that throws a redacted ZodError.
290
+ *
291
+ * Anything else raised during parsing, such as an error thrown from inside a
292
+ * `transform`, propagates untouched. This helper cannot know what such an
293
+ * error's message contains, and pretending to have sanitized it would be worse
294
+ * than passing it through.
295
+ *
296
+ * @typeParam Output - What the schema produces
297
+ * @typeParam Input - What the schema accepts
298
+ * @param schema - The schema to parse with
299
+ * @param data - The input
300
+ * @param params - Additional Zod parse options; a supplied `error` map wins
301
+ * @returns The parsed value
302
+ * @throws z.ZodError Redacted, if validation fails.
303
+ */
304
+ function sensitiveParse(schema, data, params) {
305
+ const result = sensitiveSafeParse(schema, data, params);
306
+ if (!result.success) {
307
+ throw result.error;
308
+ }
309
+ return result.data;
310
+ }
311
+ //# sourceMappingURL=error-map.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-map.js","sourceRoot":"","sources":["../src/error-map.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;;;AA4EH,4DAEC;AAwHD,0CAEC;AAoBD,wCAMC;AAqBD,gDAOC;AAaD,0DAOC;AAkBD,wCAUC;AA5SD,6BAAwB;AAExB;;;;;GAKG;AACU,QAAA,oBAAoB,G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O,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,cAAc,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AAC3F,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,SAAgB,cAAc,CAC5B,MAAgC,EAChC,IAAa,EACb,MAA8B;IAE9B,MAAM,MAAM,GAAG,kBAAkB,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACxD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,MAAM,CAAC,KAAK,CAAC;IACrB,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @platform-sec/sensitive-string-zod
3
+ *
4
+ * Zod integration for SensitiveString.
5
+ * Parse and validate input directly into sensitive types at boundary layers.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { z } from 'zod';
10
+ * import { zSensitive, zCredential } from '@platform-sec/sensitive-string-zod';
11
+ *
12
+ * const WebhookSchema = z.object({
13
+ * token: zCredential('session_token'),
14
+ * email: zSensitive('email'),
15
+ * note: z.string().max(1024).optional(),
16
+ * });
17
+ *
18
+ * // Type inference works correctly
19
+ * type Webhook = z.infer<typeof WebhookSchema>;
20
+ * // Webhook['token'] is SensitiveString<'credential'>
21
+ * // Webhook['email'] is SensitiveString<'sensitive'>
22
+ * ```
23
+ *
24
+ * @example Collections, normalization, and refinements
25
+ * ```ts
26
+ * const SignupSchema = z.object({
27
+ * email: zSensitivePreprocess({ trim: true, lowercase: true }, 'email', z.email()),
28
+ * password: zCredential('password').refineSensitive((raw) => raw.length >= 12, {
29
+ * message: 'Password must be at least 12 characters',
30
+ * }),
31
+ * backupCodes: zCredentialArray('backup_code').min(1),
32
+ * });
33
+ *
34
+ * // Errors that never echo the input, in the message or in the issue objects.
35
+ * const result = sensitiveSafeParse(SignupSchema, req.body);
36
+ * ```
37
+ *
38
+ * @packageDocumentation
39
+ */
40
+ export { zSensitiveString, zSensitive, zCredential, zSensitiveWithValidation, zSensitiveOptional, zSensitiveDeserialize, } from './base.js';
41
+ export { zSensitiveStringArray, zSensitiveArray, zCredentialArray, zSensitiveStringRecord, zSensitiveRecord, zCredentialRecord, } from './collections.js';
42
+ export type { SensitiveArraySchema, SensitiveRecordSchema } from './collections.js';
43
+ export { refineSensitive } from './refine.js';
44
+ export { zSensitiveStringPreprocess, zSensitivePreprocess, zCredentialPreprocess, } from './preprocessing.js';
45
+ export type { PreprocessOptions, PreprocessSpec } from './preprocessing.js';
46
+ export { zConditionalSensitive } from './conditional.js';
47
+ export type { ConditionalSensitivity, ConditionalConditions, ConditionalSensitiveConfig, ConditionalSensitiveInput, ConditionalSensitiveOutput, } from './conditional.js';
48
+ export { zSensitiveDefault } from './defaults.js';
49
+ export { sensitiveErrorMap, installSensitiveErrorMap, redactZodIssues, redactZodError, sensitiveParse, sensitiveSafeParse, sensitiveSafeParseAsync, REDACTED_ISSUE_VALUE, } from './error-map.js';
50
+ export type { SensitiveParseOptions } from './error-map.js';
51
+ export type { SensitiveSchema, SensitiveSchemaMethods, SensitiveCheck, RefineSensitiveParams, } from './types.js';
52
+ export { SensitiveString } from '@platform-sec/sensitive-string-core';
53
+ export type { SensitivityClass, SerializedSensitiveString, RevealContext, } from '@platform-sec/sensitive-string-core';
54
+ export { withRevealContext, getCurrentRevealContext, safeLog, redactInStructure, } from '@platform-sec/sensitive-string-core';
55
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAGH,OAAO,EACL,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,wBAAwB,EACxB,kBAAkB,EAClB,qBAAqB,GACtB,MAAM,WAAW,CAAC;AAGnB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAGpF,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAG5E,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,YAAY,EACV,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAGlD,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,eAAe,EACf,cAAc,EACd,cAAc,EACd,kBAAkB,EAClB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAG5D,YAAY,EACV,eAAe,EACf,sBAAsB,EACtB,cAAc,EACd,qBAAqB,GACtB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AACtE,YAAY,EACV,gBAAgB,EAChB,yBAAyB,EACzB,aAAa,GACd,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,iBAAiB,EACjB,uBAAuB,EACvB,OAAO,EACP,iBAAiB,GAClB,MAAM,qCAAqC,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ /**
3
+ * @platform-sec/sensitive-string-zod
4
+ *
5
+ * Zod integration for SensitiveString.
6
+ * Parse and validate input directly into sensitive types at boundary layers.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { z } from 'zod';
11
+ * import { zSensitive, zCredential } from '@platform-sec/sensitive-string-zod';
12
+ *
13
+ * const WebhookSchema = z.object({
14
+ * token: zCredential('session_token'),
15
+ * email: zSensitive('email'),
16
+ * note: z.string().max(1024).optional(),
17
+ * });
18
+ *
19
+ * // Type inference works correctly
20
+ * type Webhook = z.infer<typeof WebhookSchema>;
21
+ * // Webhook['token'] is SensitiveString<'credential'>
22
+ * // Webhook['email'] is SensitiveString<'sensitive'>
23
+ * ```
24
+ *
25
+ * @example Collections, normalization, and refinements
26
+ * ```ts
27
+ * const SignupSchema = z.object({
28
+ * email: zSensitivePreprocess({ trim: true, lowercase: true }, 'email', z.email()),
29
+ * password: zCredential('password').refineSensitive((raw) => raw.length >= 12, {
30
+ * message: 'Password must be at least 12 characters',
31
+ * }),
32
+ * backupCodes: zCredentialArray('backup_code').min(1),
33
+ * });
34
+ *
35
+ * // Errors that never echo the input, in the message or in the issue objects.
36
+ * const result = sensitiveSafeParse(SignupSchema, req.body);
37
+ * ```
38
+ *
39
+ * @packageDocumentation
40
+ */
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.redactInStructure = exports.safeLog = exports.getCurrentRevealContext = exports.withRevealContext = exports.SensitiveString = exports.REDACTED_ISSUE_VALUE = exports.sensitiveSafeParseAsync = exports.sensitiveSafeParse = exports.sensitiveParse = exports.redactZodError = exports.redactZodIssues = exports.installSensitiveErrorMap = exports.sensitiveErrorMap = exports.zSensitiveDefault = exports.zConditionalSensitive = exports.zCredentialPreprocess = exports.zSensitivePreprocess = exports.zSensitiveStringPreprocess = exports.refineSensitive = exports.zCredentialRecord = exports.zSensitiveRecord = exports.zSensitiveStringRecord = exports.zCredentialArray = exports.zSensitiveArray = exports.zSensitiveStringArray = exports.zSensitiveDeserialize = exports.zSensitiveOptional = exports.zSensitiveWithValidation = exports.zCredential = exports.zSensitive = exports.zSensitiveString = void 0;
43
+ // Base schema factories
44
+ var base_js_1 = require("./base.js");
45
+ Object.defineProperty(exports, "zSensitiveString", { enumerable: true, get: function () { return base_js_1.zSensitiveString; } });
46
+ Object.defineProperty(exports, "zSensitive", { enumerable: true, get: function () { return base_js_1.zSensitive; } });
47
+ Object.defineProperty(exports, "zCredential", { enumerable: true, get: function () { return base_js_1.zCredential; } });
48
+ Object.defineProperty(exports, "zSensitiveWithValidation", { enumerable: true, get: function () { return base_js_1.zSensitiveWithValidation; } });
49
+ Object.defineProperty(exports, "zSensitiveOptional", { enumerable: true, get: function () { return base_js_1.zSensitiveOptional; } });
50
+ Object.defineProperty(exports, "zSensitiveDeserialize", { enumerable: true, get: function () { return base_js_1.zSensitiveDeserialize; } });
51
+ // Collections
52
+ var collections_js_1 = require("./collections.js");
53
+ Object.defineProperty(exports, "zSensitiveStringArray", { enumerable: true, get: function () { return collections_js_1.zSensitiveStringArray; } });
54
+ Object.defineProperty(exports, "zSensitiveArray", { enumerable: true, get: function () { return collections_js_1.zSensitiveArray; } });
55
+ Object.defineProperty(exports, "zCredentialArray", { enumerable: true, get: function () { return collections_js_1.zCredentialArray; } });
56
+ Object.defineProperty(exports, "zSensitiveStringRecord", { enumerable: true, get: function () { return collections_js_1.zSensitiveStringRecord; } });
57
+ Object.defineProperty(exports, "zSensitiveRecord", { enumerable: true, get: function () { return collections_js_1.zSensitiveRecord; } });
58
+ Object.defineProperty(exports, "zCredentialRecord", { enumerable: true, get: function () { return collections_js_1.zCredentialRecord; } });
59
+ // Refinements over the raw value
60
+ var refine_js_1 = require("./refine.js");
61
+ Object.defineProperty(exports, "refineSensitive", { enumerable: true, get: function () { return refine_js_1.refineSensitive; } });
62
+ // Normalization before wrapping
63
+ var preprocessing_js_1 = require("./preprocessing.js");
64
+ Object.defineProperty(exports, "zSensitiveStringPreprocess", { enumerable: true, get: function () { return preprocessing_js_1.zSensitiveStringPreprocess; } });
65
+ Object.defineProperty(exports, "zSensitivePreprocess", { enumerable: true, get: function () { return preprocessing_js_1.zSensitivePreprocess; } });
66
+ Object.defineProperty(exports, "zCredentialPreprocess", { enumerable: true, get: function () { return preprocessing_js_1.zCredentialPreprocess; } });
67
+ // Sensitivity decided by a sibling field
68
+ var conditional_js_1 = require("./conditional.js");
69
+ Object.defineProperty(exports, "zConditionalSensitive", { enumerable: true, get: function () { return conditional_js_1.zConditionalSensitive; } });
70
+ // Default values
71
+ var defaults_js_1 = require("./defaults.js");
72
+ Object.defineProperty(exports, "zSensitiveDefault", { enumerable: true, get: function () { return defaults_js_1.zSensitiveDefault; } });
73
+ // Error handling that does not echo the input
74
+ var error_map_js_1 = require("./error-map.js");
75
+ Object.defineProperty(exports, "sensitiveErrorMap", { enumerable: true, get: function () { return error_map_js_1.sensitiveErrorMap; } });
76
+ Object.defineProperty(exports, "installSensitiveErrorMap", { enumerable: true, get: function () { return error_map_js_1.installSensitiveErrorMap; } });
77
+ Object.defineProperty(exports, "redactZodIssues", { enumerable: true, get: function () { return error_map_js_1.redactZodIssues; } });
78
+ Object.defineProperty(exports, "redactZodError", { enumerable: true, get: function () { return error_map_js_1.redactZodError; } });
79
+ Object.defineProperty(exports, "sensitiveParse", { enumerable: true, get: function () { return error_map_js_1.sensitiveParse; } });
80
+ Object.defineProperty(exports, "sensitiveSafeParse", { enumerable: true, get: function () { return error_map_js_1.sensitiveSafeParse; } });
81
+ Object.defineProperty(exports, "sensitiveSafeParseAsync", { enumerable: true, get: function () { return error_map_js_1.sensitiveSafeParseAsync; } });
82
+ Object.defineProperty(exports, "REDACTED_ISSUE_VALUE", { enumerable: true, get: function () { return error_map_js_1.REDACTED_ISSUE_VALUE; } });
83
+ // Re-export core types and utilities for convenience
84
+ var sensitive_string_core_1 = require("@platform-sec/sensitive-string-core");
85
+ Object.defineProperty(exports, "SensitiveString", { enumerable: true, get: function () { return sensitive_string_core_1.SensitiveString; } });
86
+ var sensitive_string_core_2 = require("@platform-sec/sensitive-string-core");
87
+ Object.defineProperty(exports, "withRevealContext", { enumerable: true, get: function () { return sensitive_string_core_2.withRevealContext; } });
88
+ Object.defineProperty(exports, "getCurrentRevealContext", { enumerable: true, get: function () { return sensitive_string_core_2.getCurrentRevealContext; } });
89
+ Object.defineProperty(exports, "safeLog", { enumerable: true, get: function () { return sensitive_string_core_2.safeLog; } });
90
+ Object.defineProperty(exports, "redactInStructure", { enumerable: true, get: function () { return sensitive_string_core_2.redactInStructure; } });
91
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;;;AAEH,wBAAwB;AACxB,qCAOmB;AANjB,2GAAA,gBAAgB,OAAA;AAChB,qGAAA,UAAU,OAAA;AACV,sGAAA,WAAW,OAAA;AACX,mHAAA,wBAAwB,OAAA;AACxB,6GAAA,kBAAkB,OAAA;AAClB,gHAAA,qBAAqB,OAAA;AAGvB,cAAc;AACd,mDAO0B;AANxB,uHAAA,qBAAqB,OAAA;AACrB,iHAAA,eAAe,OAAA;AACf,kHAAA,gBAAgB,OAAA;AAChB,wHAAA,sBAAsB,OAAA;AACtB,kHAAA,gBAAgB,OAAA;AAChB,mHAAA,iBAAiB,OAAA;AAInB,iCAAiC;AACjC,yCAA8C;AAArC,4GAAA,eAAe,OAAA;AAExB,gCAAgC;AAChC,uDAI4B;AAH1B,8HAAA,0BAA0B,OAAA;AAC1B,wHAAA,oBAAoB,OAAA;AACpB,yHAAA,qBAAqB,OAAA;AAIvB,yCAAyC;AACzC,mDAAyD;AAAhD,uHAAA,qBAAqB,OAAA;AAS9B,iBAAiB;AACjB,6CAAkD;AAAzC,gHAAA,iBAAiB,OAAA;AAE1B,8CAA8C;AAC9C,+CASwB;AARtB,iHAAA,iBAAiB,OAAA;AACjB,wHAAA,wBAAwB,OAAA;AACxB,+GAAA,eAAe,OAAA;AACf,8GAAA,cAAc,OAAA;AACd,8GAAA,cAAc,OAAA;AACd,kHAAA,kBAAkB,OAAA;AAClB,uHAAA,uBAAuB,OAAA;AACvB,oHAAA,oBAAoB,OAAA;AAYtB,qDAAqD;AACrD,6EAAsE;AAA7D,wHAAA,eAAe,OAAA;AAMxB,6EAK6C;AAJ3C,0HAAA,iBAAiB,OAAA;AACjB,gIAAA,uBAAuB,OAAA;AACvB,gHAAA,OAAO,OAAA;AACP,0HAAA,iBAAiB,OAAA"}
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Normalizing input before it is wrapped.
3
+ *
4
+ * Normalization has to happen before wrapping: once a value is a
5
+ * SensitiveString, trimming it means revealing it. Doing it here keeps the
6
+ * whole normalize-validate-wrap sequence on the raw string, inside the parse,
7
+ * with no reveal at all.
8
+ *
9
+ * Order is normalize, then validate, then wrap. That matches Zod's own
10
+ * `preprocess`, and it is the order callers expect: `' A@B.COM '` should pass
11
+ * an email check.
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+ import { z } from 'zod';
16
+ import { SensitivityClass } from '@platform-sec/sensitive-string-core';
17
+ import type { SensitiveSchema } from './types.js';
18
+ /**
19
+ * Declarative normalization steps, applied in the order listed here.
20
+ */
21
+ export interface PreprocessOptions {
22
+ /**
23
+ * Unicode normalization form, applied first so that later steps and any
24
+ * validation see one canonical encoding of the same text.
25
+ */
26
+ normalize?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD';
27
+ /** Collapse each run of whitespace to a single space. */
28
+ collapseWhitespace?: boolean;
29
+ /** Remove every whitespace character. Useful for keys pasted with line breaks. */
30
+ stripWhitespace?: boolean;
31
+ /** Remove leading and trailing whitespace. */
32
+ trim?: boolean;
33
+ /** Lowercase the value. Mutually exclusive with `uppercase`. */
34
+ lowercase?: boolean;
35
+ /** Uppercase the value. Mutually exclusive with `lowercase`. */
36
+ uppercase?: boolean;
37
+ }
38
+ /**
39
+ * What a caller may pass as the normalization to apply: the declarative option
40
+ * set, a single function, or a list of functions run left to right.
41
+ */
42
+ export type PreprocessSpec = PreprocessOptions | ((value: string) => string) | ReadonlyArray<(value: string) => string>;
43
+ /**
44
+ * Create a schema that normalizes the input, validates it, then wraps it.
45
+ *
46
+ * A non-string input is passed through untouched, so the inner string schema
47
+ * reports the usual `invalid_type` issue rather than the preprocessor throwing
48
+ * on it.
49
+ *
50
+ * The inner schema is any string-to-string schema, not specifically a
51
+ * `z.ZodString`, so that Zod 4's format constructors work: `z.email()` is a
52
+ * `ZodEmail` and is not a `ZodString`.
53
+ *
54
+ * @typeParam C - The sensitivity class for the resulting SensitiveString
55
+ * @param klass - The sensitivity classification to apply
56
+ * @param spec - Normalization options, a function, or a list of functions
57
+ * @param label - Optional label for audit/compliance
58
+ * @param schema - Optional string-to-string schema, validated after normalization
59
+ * @returns A schema that transforms normalized strings to SensitiveString<C>
60
+ * @throws TypeError If the spec is malformed.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const email = zSensitiveStringPreprocess(
65
+ * 'sensitive',
66
+ * { trim: true, lowercase: true },
67
+ * 'email',
68
+ * z.email()
69
+ * );
70
+ *
71
+ * email.parse(' Alice@Example.COM ').reveal(); // 'alice@example.com'
72
+ * ```
73
+ */
74
+ export declare function zSensitiveStringPreprocess<C extends SensitivityClass>(klass: C, spec: PreprocessSpec, label?: string, schema?: z.ZodType<string, string>): SensitiveSchema<C, string>;
75
+ /**
76
+ * Normalize, then wrap as sensitive data.
77
+ * Shorthand for zSensitiveStringPreprocess('sensitive', spec, label, schema).
78
+ *
79
+ * @param spec - Normalization options, a function, or a list of functions
80
+ * @param label - Optional label for audit/compliance
81
+ * @param schema - Optional string-to-string schema, validated after normalization
82
+ * @returns A schema producing SensitiveString<'sensitive'>
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * const schema = zSensitivePreprocess({ trim: true, lowercase: true }, 'email');
87
+ * ```
88
+ */
89
+ export declare function zSensitivePreprocess(spec: PreprocessSpec, label?: string, schema?: z.ZodType<string, string>): SensitiveSchema<'sensitive', string>;
90
+ /**
91
+ * Normalize, then wrap as a credential.
92
+ * Shorthand for zSensitiveStringPreprocess('credential', spec, label, schema).
93
+ *
94
+ * @param spec - Normalization options, a function, or a list of functions
95
+ * @param label - Optional label for audit/compliance
96
+ * @param schema - Optional string-to-string schema, validated after normalization
97
+ * @returns A schema producing SensitiveString<'credential'>
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * // An API key pasted from a console arrives with line breaks in it.
102
+ * const apiKey = zCredentialPreprocess({ stripWhitespace: true }, 'api_key');
103
+ * ```
104
+ */
105
+ export declare function zCredentialPreprocess(spec: PreprocessSpec, label?: string, schema?: z.ZodType<string, string>): SensitiveSchema<'credential', string>;
106
+ //# sourceMappingURL=preprocessing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preprocessing.d.ts","sourceRoot":"","sources":["../src/preprocessing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAmB,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAExF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,SAAS,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAC;IAC5C,yDAAyD;IACzD,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,kFAAkF;IAClF,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,8CAA8C;IAC9C,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,gEAAgE;IAChE,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gEAAgE;IAChE,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;GAGG;AACH,MAAM,MAAM,cAAc,GACxB,iBAAiB,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC,GAAG,aAAa,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM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