@platform-sec/sensitive-string-zod 0.0.0-stage → 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,48 @@
1
+ /**
2
+ * Default values for sensitive fields.
3
+ *
4
+ * The default is produced as a raw string and wrapped by the schema, so a
5
+ * caller never has to build a `SensitiveString` to describe a fallback, and a
6
+ * generated default is classified the same way a parsed one is.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import { SensitivityClass } from '@platform-sec/sensitive-string-core';
11
+ import type { SensitiveSchema } from './types.js';
12
+ /**
13
+ * Create a schema that falls back to a default when the field is absent.
14
+ *
15
+ * A function default is called lazily, once per parse that needs it, so a
16
+ * generated token is not shared between parses and a default read from the
17
+ * environment is read at parse time rather than at schema construction.
18
+ *
19
+ * `undefined` triggers the default; `null` and `''` do not. They are values a
20
+ * client sent, and treating them as absent would silently substitute a secret
21
+ * for input that should have been rejected.
22
+ *
23
+ * The fallback is held in the transform's closure rather than in a
24
+ * `.default()`, and that placement is the security-relevant part.
25
+ * `z.toJSONSchema(schema, { io: 'input' })` reads a schema definition's
26
+ * `default` and emits it verbatim, calling a function default to do so; every
27
+ * OpenAPI generator in the ecosystem takes that path. The documented example
28
+ * below reads `process.env.API_KEY`, so under a `.default()` the live key
29
+ * would be embedded in a document whose whole purpose is publication. A
30
+ * closure is not part of the definition and has nothing to read.
31
+ *
32
+ * @typeParam C - The sensitivity class for the resulting SensitiveString
33
+ * @param klass - The sensitivity classification to apply
34
+ * @param label - Optional label for audit/compliance
35
+ * @param defaultValue - The fallback string, or a function producing one
36
+ * @returns A schema producing SensitiveString<C>, with the field optional
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const Config = z.object({
41
+ * apiKey: zSensitiveDefault('credential', 'api_key', () => process.env.API_KEY ?? ''),
42
+ * });
43
+ *
44
+ * Config.parse({}).apiKey; // SensitiveString<'credential'>
45
+ * ```
46
+ */
47
+ export declare function zSensitiveDefault<C extends SensitivityClass>(klass: C, label: string | undefined, defaultValue: string | (() => string)): SensitiveSchema<C, string | undefined>;
48
+ //# sourceMappingURL=defaults.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../src/defaults.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAmB,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAExF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,gBAAgB,EAC1D,KAAK,EAAE,CAAC,EACR,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,YAAY,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,GACpC,eAAe,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,CAUxC"}
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ /**
3
+ * Default values for sensitive fields.
4
+ *
5
+ * The default is produced as a raw string and wrapped by the schema, so a
6
+ * caller never has to build a `SensitiveString` to describe a fallback, and a
7
+ * generated default is classified the same way a parsed one is.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.zSensitiveDefault = zSensitiveDefault;
13
+ const zod_1 = require("zod");
14
+ const sensitive_string_core_1 = require("@platform-sec/sensitive-string-core");
15
+ const refine_js_1 = require("./refine.js");
16
+ /**
17
+ * Create a schema that falls back to a default when the field is absent.
18
+ *
19
+ * A function default is called lazily, once per parse that needs it, so a
20
+ * generated token is not shared between parses and a default read from the
21
+ * environment is read at parse time rather than at schema construction.
22
+ *
23
+ * `undefined` triggers the default; `null` and `''` do not. They are values a
24
+ * client sent, and treating them as absent would silently substitute a secret
25
+ * for input that should have been rejected.
26
+ *
27
+ * The fallback is held in the transform's closure rather than in a
28
+ * `.default()`, and that placement is the security-relevant part.
29
+ * `z.toJSONSchema(schema, { io: 'input' })` reads a schema definition's
30
+ * `default` and emits it verbatim, calling a function default to do so; every
31
+ * OpenAPI generator in the ecosystem takes that path. The documented example
32
+ * below reads `process.env.API_KEY`, so under a `.default()` the live key
33
+ * would be embedded in a document whose whole purpose is publication. A
34
+ * closure is not part of the definition and has nothing to read.
35
+ *
36
+ * @typeParam C - The sensitivity class for the resulting SensitiveString
37
+ * @param klass - The sensitivity classification to apply
38
+ * @param label - Optional label for audit/compliance
39
+ * @param defaultValue - The fallback string, or a function producing one
40
+ * @returns A schema producing SensitiveString<C>, with the field optional
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const Config = z.object({
45
+ * apiKey: zSensitiveDefault('credential', 'api_key', () => process.env.API_KEY ?? ''),
46
+ * });
47
+ *
48
+ * Config.parse({}).apiKey; // SensitiveString<'credential'>
49
+ * ```
50
+ */
51
+ function zSensitiveDefault(klass, label, defaultValue) {
52
+ return (0, refine_js_1.withSensitiveMethods)(zod_1.z
53
+ .string()
54
+ .optional()
55
+ .transform((value) => {
56
+ const raw = value ?? (typeof defaultValue === 'function' ? defaultValue() : defaultValue);
57
+ return new sensitive_string_core_1.SensitiveString(raw, klass, label);
58
+ }));
59
+ }
60
+ //# sourceMappingURL=defaults.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaults.js","sourceRoot":"","sources":["../src/defaults.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AA0CH,8CAcC;AAtDD,6BAAwB;AACxB,+EAAwF;AACxF,2CAAmD;AAGnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,SAAgB,iBAAiB,CAC/B,KAAQ,EACR,KAAyB,EACzB,YAAqC;IAErC,OAAO,IAAA,gCAAoB,EACzB,OAAC;SACE,MAAM,EAAE;SACR,QAAQ,EAAE;SACV,SAAS,CAAC,CAAC,KAAK,EAAsB,EAAE;QACvC,MAAM,GAAG,GAAG,KAAK,IAAI,CAAC,OAAO,YAAY,KAAK,UAAU,CAAC,CAAC,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;QAC1F,OAAO,IAAI,uCAAe,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IAChD,CAAC,CAAC,CACL,CAAC;AACJ,CAAC"}
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Keeping the input out of validation errors.
3
+ *
4
+ * Most of Zod's built-in issues report the rule, not the string that failed it,
5
+ * and Zod 4 closed two leaks v3 had: `invalid_enum_value` and `invalid_literal`
6
+ * are both `invalid_value` now, which carries the *allowed* set rather than
7
+ * what arrived. What is left, measured against 4.5.4 with a canary:
8
+ *
9
+ * - `unrecognized_keys` puts unknown key names in `keys` and in the message.
10
+ * - `custom` carries whatever a `superRefine` caller attached to `params`.
11
+ * - `invalid_element` carries the offending map key in `key`.
12
+ * - every issue can carry `input`, the value itself. Zod drops it during
13
+ * finalization by default, but `{ reportInput: true }` in the parse options
14
+ * keeps it, and the raw issue an error function sees always has it.
15
+ * - `invalid_union`, `invalid_key`, and `invalid_element` nest issue lists, so
16
+ * any of the above can arrive one or more levels down.
17
+ *
18
+ * That splits the fix in two. An error map can only rewrite the message, so it
19
+ * handles what a caller sees in `error.message`. The `keys`, `params`, `key`,
20
+ * and `input` fields survive an error map untouched and reach anything that
21
+ * serializes the error, which is where structured logging picks them up. Use
22
+ * {@link sensitiveSafeParse} to get both, or {@link redactZodError} on an error
23
+ * you already hold.
24
+ *
25
+ * What is deliberately *not* covered is `issue.path`. A container keyed by a
26
+ * sensitive value puts that value in the path of every issue below it. Redacting
27
+ * it would collapse every field of a multi-issue error into one bucket and make
28
+ * `z.treeifyError` useless, so the answer is not to key a container by a secret:
29
+ * put it in the value position, which is what `zSensitiveRecord` does.
30
+ *
31
+ * One thing this module does not attempt at all: the guarantee is about the
32
+ * *input*, not about values a schema author embedded in their own schema.
33
+ * `invalid_value.values` echoes what `z.literal()` and `z.enum()` were given,
34
+ * and `invalid_format` echoes the argument to `startsWith`, `endsWith`, and
35
+ * `includes`. Those read as safe in the table above, and they are, with respect
36
+ * to the input. `z.literal(secret)` still puts the secret in every issue it
37
+ * produces, and there is nothing here that could tell it apart from a legitimate
38
+ * allowed value. Do not build a schema out of a secret.
39
+ *
40
+ * @packageDocumentation
41
+ */
42
+ import { z } from 'zod';
43
+ /**
44
+ * Stand-in written over any value stripped from an issue.
45
+ *
46
+ * Matches the core library's redaction marker so that one grep over a log
47
+ * finds every kind of redaction the library performs.
48
+ */
49
+ export declare const REDACTED_ISSUE_VALUE = "[REDACTED]";
50
+ /**
51
+ * The parse options accepted by the helpers in this module.
52
+ *
53
+ * Zod 4 renamed the per-call error map from `errorMap` to `error` and does not
54
+ * reject unknown keys, so a v3 spelling would be accepted at runtime and
55
+ * ignored. This alias is the v4 type, which rejects `errorMap` at compile time.
56
+ */
57
+ export type SensitiveParseOptions = z.core.ParseContext<z.core.$ZodIssue>;
58
+ /**
59
+ * A Zod error map that never echoes the input into a message.
60
+ *
61
+ * Install it globally with {@link installSensitiveErrorMap}, or pass it per
62
+ * call as `schema.safeParse(data, { error: sensitiveErrorMap })`.
63
+ *
64
+ * This rewrites messages only. The issue objects still carry `keys`, `params`,
65
+ * and `key`; see {@link redactZodError}.
66
+ *
67
+ * Returning `undefined` is how a v4 error map declines: there is no second
68
+ * `ctx` argument carrying a default message, and returning nothing hands the
69
+ * issue back to Zod's own message resolution.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const schema = z.object({ a: z.string() }).strict();
74
+ * const result = schema.safeParse({ a: 'x', [secret]: 1 }, { error: sensitiveErrorMap });
75
+ * // "Unrecognized key(s) in object: 1 not allowed" - and nothing about the key
76
+ * ```
77
+ */
78
+ export declare const sensitiveErrorMap: z.core.$ZodErrorMap;
79
+ /**
80
+ * Install {@link sensitiveErrorMap} as Zod's global error map.
81
+ *
82
+ * Global on purpose: the leaking issue codes come from schemas this package
83
+ * knows nothing about, most often a strict object sitting beside a sensitive
84
+ * field. Scoping the map to sensitive schemas would miss exactly the cases it
85
+ * exists for.
86
+ *
87
+ * It is not installed on import. A library that reaches into a process's
88
+ * global Zod configuration behind the application's back is worse than one
89
+ * that asks for a line of setup.
90
+ *
91
+ * `z.config()` reads the configuration back, so a caller who needs to undo this
92
+ * can capture `z.config().customError` first and restore it afterwards.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * // Once, during startup.
97
+ * installSensitiveErrorMap();
98
+ * ```
99
+ */
100
+ export declare function installSensitiveErrorMap(): void;
101
+ /**
102
+ * Copy a list of issues with every input value stripped out.
103
+ *
104
+ * The originals are not modified: a caller may still be holding the unredacted
105
+ * error, and silently mutating it would change what an already-written handler
106
+ * reports.
107
+ *
108
+ * @param issues - The issues to copy
109
+ * @returns Issues safe to log or serialize
110
+ */
111
+ export declare function redactZodIssues(issues: readonly z.core.$ZodIssue[]): z.core.$ZodIssue[];
112
+ /**
113
+ * Copy a ZodError with every input value stripped out, including from the
114
+ * issues nested inside a union, key, or element issue.
115
+ *
116
+ * @param error - The error to copy
117
+ * @returns A new ZodError safe to log or serialize
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * try {
122
+ * schema.parse(payload);
123
+ * } catch (err) {
124
+ * if (err instanceof z.ZodError) {
125
+ * logger.warn('validation failed', { issues: redactZodError(err).issues });
126
+ * }
127
+ * }
128
+ * ```
129
+ */
130
+ export declare function redactZodError<T>(error: z.ZodError<T>): z.ZodError<T>;
131
+ /**
132
+ * `safeParse` with both halves of the fix applied: the error map rewrites the
133
+ * messages, and the returned issues are redacted.
134
+ *
135
+ * @typeParam Output - What the schema produces
136
+ * @typeParam Input - What the schema accepts
137
+ * @param schema - The schema to parse with
138
+ * @param data - The input
139
+ * @param params - Additional Zod parse options; a supplied `error` map wins
140
+ * @returns Zod's usual safe-parse result, with a redacted error on failure
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * const result = sensitiveSafeParse(LoginSchema, req.body);
145
+ * if (!result.success) {
146
+ * res.status(400).json({ issues: result.error.issues }); // no input echoed
147
+ * }
148
+ * ```
149
+ */
150
+ export declare function sensitiveSafeParse<Output, Input>(schema: z.ZodType<Output, Input>, data: unknown, params?: SensitiveParseOptions): z.ZodSafeParseResult<Output>;
151
+ /**
152
+ * The async counterpart of {@link sensitiveSafeParse}, for schemas carrying an
153
+ * async refinement.
154
+ *
155
+ * @typeParam Output - What the schema produces
156
+ * @typeParam Input - What the schema accepts
157
+ * @param schema - The schema to parse with
158
+ * @param data - The input
159
+ * @param params - Additional Zod parse options; a supplied `error` map wins
160
+ * @returns Zod's usual safe-parse result, with a redacted error on failure
161
+ */
162
+ export declare function sensitiveSafeParseAsync<Output, Input>(schema: z.ZodType<Output, Input>, data: unknown, params?: SensitiveParseOptions): Promise<z.ZodSafeParseResult<Output>>;
163
+ /**
164
+ * `parse` that throws a redacted ZodError.
165
+ *
166
+ * Anything else raised during parsing, such as an error thrown from inside a
167
+ * `transform`, propagates untouched. This helper cannot know what such an
168
+ * error's message contains, and pretending to have sanitized it would be worse
169
+ * than passing it through.
170
+ *
171
+ * @typeParam Output - What the schema produces
172
+ * @typeParam Input - What the schema accepts
173
+ * @param schema - The schema to parse with
174
+ * @param data - The input
175
+ * @param params - Additional Zod parse options; a supplied `error` map wins
176
+ * @returns The parsed value
177
+ * @throws z.ZodError Redacted, if validation fails.
178
+ */
179
+ export declare function sensitiveParse<Output, Input>(schema: z.ZodType<Output, Input>, data: unknown, params?: SensitiveParseOptions): Output;
180
+ //# sourceMappingURL=error-map.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-map.d.ts","sourceRoot":"","sources":["../src/error-map.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,eAAe,CAAC;AAEjD;;;;;;GAMG;AACH,MAAM,MAAM,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,KAAK,CAAC,EAChC,IAAI,EAAE,OAAO,EACb,MAAM,CAAC,EAAE,qBAAqB,GAC7B,MAAM,CAMR"}
@@ -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,GAAG,YAAY,CAAC;AAWjD;;;;;;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