@tracegraph/trace-sanitizer 0.1.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 ADDED
@@ -0,0 +1,181 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other derivative
42
+ works represent, as a whole, an original work of authorship. For the
43
+ purposes of this License, Derivative Works shall not include works
44
+ that remain separable from, or merely link (or bind by name) to the
45
+ interfaces of, the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the
50
+ purposes of this definition, "submitted" means any form of electronic,
51
+ verbal, or written communication sent to the Licensor or its
52
+ representatives, including but not limited to communication on
53
+ electronic mailing lists, source code control systems, and issue
54
+ tracking systems that are managed by, or on behalf of, the Licensor
55
+ for the purpose of discussing and improving the Work, but excluding
56
+ communication that is conspicuously marked or designated in writing
57
+ by the copyright owner as "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combined work to with their
78
+ Contribution(s) was submitted. If You institute patent litigation
79
+ against any entity (including a cross-claim or counterclaim in a
80
+ lawsuit) alleging that the Work or any Contribution embodied within
81
+ the Work constitutes direct or contributory patent infringement,
82
+ then any patent licenses granted to You under this License for that
83
+ Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative
91
+ Works a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the
104
+ attribution notices contained within such NOTICE file, in
105
+ at least one of the following places: within a NOTICE text
106
+ file distributed as part of the Derivative Works; within
107
+ the Source form or documentation, if provided along with the
108
+ Derivative Works; or, within a display generated by the
109
+ Derivative Works, if and wherever such third-party notices
110
+ normally appear. The contents of the NOTICE file are for
111
+ informational purposes only and do not modify the License.
112
+ You may add Your own attribution notices within Derivative
113
+ Works that You distribute, alongside or as an addendum to
114
+ the NOTICE text from the Work, provided that such additional
115
+ attribution notices cannot be construed as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, copy, modify, merge,
119
+ publish, distribute, sublicense, and/or sell copies of the
120
+ Derivative Works, and to permit persons to whom the Derivative
121
+ Works is furnished to do so.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any conditions of TITLE,
141
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
142
+ PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or all other
155
+ commercial damages or losses), even if such Contributor has been
156
+ advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may offer
163
+ only conditions consistent with this License, in a way that does
164
+ not create a new obligation for any Contributor to provide such
165
+ acceptance.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ Copyright 2026 TraceGraph Contributors
170
+
171
+ Licensed under the Apache License, Version 2.0 (the "License");
172
+ you may not use this file except in compliance with the License.
173
+ You may obtain a copy of the License at
174
+
175
+ http://www.apache.org/licenses/LICENSE-2.0
176
+
177
+ Unless required by applicable law or agreed to in writing, software
178
+ distributed under the License is distributed on an "AS IS" BASIS,
179
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
180
+ See the License for the specific language governing permissions and
181
+ limitations under the License.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * TraceGraph — Trace Sanitizer
3
+ *
4
+ * Redacts sensitive fields and enforces size limits on values before
5
+ * they enter the trace pipeline. Must run on ALL user-controlled data
6
+ * (request bodies, response bodies, function arguments, DB rows).
7
+ *
8
+ * ARCHITECTURE.md §8: Behaviour Diff — Volatile Value Normalisation
9
+ */
10
+ type SanitizerConfig = {
11
+ /** Maximum object nesting depth. Default: 4 */
12
+ maxDepth?: number;
13
+ /** Maximum array length (excess items dropped). Default: 50 */
14
+ maxArrayLength?: number;
15
+ /** Maximum string length (excess characters replaced with [TRUNCATED]). Default: 500 */
16
+ maxStringLength?: number;
17
+ /** Maximum number of object keys (excess keys replaced with a summary). Default: 100 */
18
+ maxObjectKeys?: number;
19
+ /** Additional keys to redact (merged with the built-in list). */
20
+ redactKeys?: string[];
21
+ };
22
+ type SanitizedValue = string | number | boolean | null | undefined | SanitizedObject | SanitizedArray;
23
+ type SanitizedObject = {
24
+ [key: string]: SanitizedValue;
25
+ };
26
+ type SanitizedArray = SanitizedValue[];
27
+ /**
28
+ * Recursively redact sensitive keys and enforce size limits on a value.
29
+ *
30
+ * This function is a pure transform — it never mutates the input.
31
+ */
32
+ declare function sanitize(value: unknown, config?: SanitizerConfig, _depth?: number): SanitizedValue;
33
+ /**
34
+ * Sanitize HTTP headers: redact auth/cookie headers, keep informational ones.
35
+ *
36
+ * Any header not in the safe list and not explicitly redacted is retained as-is
37
+ * but truncated to maxStringLength if it's a string.
38
+ */
39
+ declare function sanitizeHeaders(headers: Record<string, unknown>, config?: SanitizerConfig): Record<string, SanitizedValue>;
40
+ /**
41
+ * Replace volatile values (UUIDs, timestamps, numeric IDs, JWTs) with stable
42
+ * placeholders so that behaviour diffs don't flag constant structural changes.
43
+ *
44
+ * Used during baseline comparison (M2+), not during event capture.
45
+ */
46
+ declare function normaliseForDiff(value: unknown): unknown;
47
+
48
+ export { type SanitizedValue, type SanitizerConfig, normaliseForDiff, sanitize, sanitizeHeaders };
@@ -0,0 +1,48 @@
1
+ /**
2
+ * TraceGraph — Trace Sanitizer
3
+ *
4
+ * Redacts sensitive fields and enforces size limits on values before
5
+ * they enter the trace pipeline. Must run on ALL user-controlled data
6
+ * (request bodies, response bodies, function arguments, DB rows).
7
+ *
8
+ * ARCHITECTURE.md §8: Behaviour Diff — Volatile Value Normalisation
9
+ */
10
+ type SanitizerConfig = {
11
+ /** Maximum object nesting depth. Default: 4 */
12
+ maxDepth?: number;
13
+ /** Maximum array length (excess items dropped). Default: 50 */
14
+ maxArrayLength?: number;
15
+ /** Maximum string length (excess characters replaced with [TRUNCATED]). Default: 500 */
16
+ maxStringLength?: number;
17
+ /** Maximum number of object keys (excess keys replaced with a summary). Default: 100 */
18
+ maxObjectKeys?: number;
19
+ /** Additional keys to redact (merged with the built-in list). */
20
+ redactKeys?: string[];
21
+ };
22
+ type SanitizedValue = string | number | boolean | null | undefined | SanitizedObject | SanitizedArray;
23
+ type SanitizedObject = {
24
+ [key: string]: SanitizedValue;
25
+ };
26
+ type SanitizedArray = SanitizedValue[];
27
+ /**
28
+ * Recursively redact sensitive keys and enforce size limits on a value.
29
+ *
30
+ * This function is a pure transform — it never mutates the input.
31
+ */
32
+ declare function sanitize(value: unknown, config?: SanitizerConfig, _depth?: number): SanitizedValue;
33
+ /**
34
+ * Sanitize HTTP headers: redact auth/cookie headers, keep informational ones.
35
+ *
36
+ * Any header not in the safe list and not explicitly redacted is retained as-is
37
+ * but truncated to maxStringLength if it's a string.
38
+ */
39
+ declare function sanitizeHeaders(headers: Record<string, unknown>, config?: SanitizerConfig): Record<string, SanitizedValue>;
40
+ /**
41
+ * Replace volatile values (UUIDs, timestamps, numeric IDs, JWTs) with stable
42
+ * placeholders so that behaviour diffs don't flag constant structural changes.
43
+ *
44
+ * Used during baseline comparison (M2+), not during event capture.
45
+ */
46
+ declare function normaliseForDiff(value: unknown): unknown;
47
+
48
+ export { type SanitizedValue, type SanitizerConfig, normaliseForDiff, sanitize, sanitizeHeaders };
package/dist/index.js ADDED
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ normaliseForDiff: () => normaliseForDiff,
24
+ sanitize: () => sanitize,
25
+ sanitizeHeaders: () => sanitizeHeaders
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+ var BUILTIN_REDACT_KEYS = /* @__PURE__ */ new Set([
29
+ "password",
30
+ "passwd",
31
+ "pass",
32
+ "token",
33
+ "accesstoken",
34
+ "refreshtoken",
35
+ "idtoken",
36
+ "authorization",
37
+ "authorisation",
38
+ "cookie",
39
+ "set-cookie",
40
+ "session",
41
+ "sessionid",
42
+ "sessid",
43
+ "secret",
44
+ "apisecret",
45
+ "clientsecret",
46
+ "apikey",
47
+ "api_key",
48
+ "x-api-key",
49
+ "privatekey",
50
+ "private_key",
51
+ "cardnumber",
52
+ "card_number",
53
+ "creditcard",
54
+ "credit_card",
55
+ "cvv",
56
+ "cvc",
57
+ "securitycode",
58
+ "pin",
59
+ "otp",
60
+ "ssn",
61
+ "socialsecuritynumber",
62
+ "dob",
63
+ "dateofbirth",
64
+ "x-auth-token",
65
+ "x_auth_token"
66
+ ]);
67
+ var REDACTED = "[REDACTED]";
68
+ var TRUNCATED_SUFFIX = "\u2026[TRUNCATED]";
69
+ var MAX_DEPTH_MARKER = "[MAX_DEPTH]";
70
+ var UNSUPPORTED_MARKER = "[UNSUPPORTED]";
71
+ function sanitize(value, config = {}, _depth = 0) {
72
+ const {
73
+ maxDepth = 4,
74
+ maxArrayLength = 50,
75
+ maxStringLength = 500,
76
+ maxObjectKeys = 100,
77
+ redactKeys = []
78
+ } = config;
79
+ if (_depth >= maxDepth) return MAX_DEPTH_MARKER;
80
+ if (value === null || value === void 0) return value;
81
+ if (typeof value === "boolean") return value;
82
+ if (typeof value === "number") {
83
+ return Number.isFinite(value) ? value : String(value);
84
+ }
85
+ if (typeof value === "string") {
86
+ return value.length > maxStringLength ? value.slice(0, maxStringLength) + TRUNCATED_SUFFIX : value;
87
+ }
88
+ if (Array.isArray(value)) {
89
+ const sliced = value.slice(0, maxArrayLength);
90
+ return sliced.map((item) => sanitize(item, config, _depth + 1));
91
+ }
92
+ if (value instanceof Date) return value.toISOString();
93
+ if (value instanceof RegExp) return value.toString();
94
+ if (typeof value === "object") {
95
+ const extraKeys = redactKeys.map((k) => k.toLowerCase());
96
+ const allRedact = extraKeys.length > 0 ? /* @__PURE__ */ new Set([...BUILTIN_REDACT_KEYS, ...extraKeys]) : BUILTIN_REDACT_KEYS;
97
+ const result = {};
98
+ const entries = Object.entries(value);
99
+ let count = 0;
100
+ for (const [k, v] of entries) {
101
+ if (count >= maxObjectKeys) {
102
+ result["[KEYS_TRUNCATED]"] = `\u2026${entries.length - maxObjectKeys} more key(s) omitted`;
103
+ break;
104
+ }
105
+ result[k] = allRedact.has(k.toLowerCase()) ? REDACTED : sanitize(v, config, _depth + 1);
106
+ count++;
107
+ }
108
+ return result;
109
+ }
110
+ return UNSUPPORTED_MARKER;
111
+ }
112
+ var ALWAYS_REDACT_HEADERS = /* @__PURE__ */ new Set([
113
+ "authorization",
114
+ "cookie",
115
+ "set-cookie",
116
+ "x-api-key",
117
+ "x-auth-token",
118
+ "x-csrf-token",
119
+ "proxy-authorization"
120
+ ]);
121
+ function sanitizeHeaders(headers, config = {}) {
122
+ const result = {};
123
+ const maxLen = config.maxStringLength ?? 500;
124
+ for (const [key, value] of Object.entries(headers)) {
125
+ const lk = key.toLowerCase();
126
+ if (ALWAYS_REDACT_HEADERS.has(lk)) {
127
+ result[key] = REDACTED;
128
+ } else if (typeof value === "string" && value.length > maxLen) {
129
+ result[key] = value.slice(0, maxLen) + TRUNCATED_SUFFIX;
130
+ } else {
131
+ result[key] = value;
132
+ }
133
+ }
134
+ return result;
135
+ }
136
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
137
+ var ISO_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
138
+ var NUMERIC_ID_RE = /^\d{1,18}$/;
139
+ var JWT_RE = /^ey[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
140
+ function normaliseForDiff(value) {
141
+ if (typeof value === "string") {
142
+ if (UUID_RE.test(value)) return "<uuid>";
143
+ if (ISO_TS_RE.test(value)) return "<timestamp>";
144
+ if (JWT_RE.test(value)) return "<token>";
145
+ if (NUMERIC_ID_RE.test(value)) return "<id>";
146
+ return value;
147
+ }
148
+ if (typeof value === "number") {
149
+ if (value > 1e12) return "<timestamp>";
150
+ return value;
151
+ }
152
+ if (Array.isArray(value)) return value.map(normaliseForDiff);
153
+ if (value && typeof value === "object") {
154
+ return Object.fromEntries(
155
+ Object.entries(value).map(([k, v]) => [k, normaliseForDiff(v)])
156
+ );
157
+ }
158
+ return value;
159
+ }
160
+ // Annotate the CommonJS export names for ESM import in node:
161
+ 0 && (module.exports = {
162
+ normaliseForDiff,
163
+ sanitize,
164
+ sanitizeHeaders
165
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,138 @@
1
+ // src/index.ts
2
+ var BUILTIN_REDACT_KEYS = /* @__PURE__ */ new Set([
3
+ "password",
4
+ "passwd",
5
+ "pass",
6
+ "token",
7
+ "accesstoken",
8
+ "refreshtoken",
9
+ "idtoken",
10
+ "authorization",
11
+ "authorisation",
12
+ "cookie",
13
+ "set-cookie",
14
+ "session",
15
+ "sessionid",
16
+ "sessid",
17
+ "secret",
18
+ "apisecret",
19
+ "clientsecret",
20
+ "apikey",
21
+ "api_key",
22
+ "x-api-key",
23
+ "privatekey",
24
+ "private_key",
25
+ "cardnumber",
26
+ "card_number",
27
+ "creditcard",
28
+ "credit_card",
29
+ "cvv",
30
+ "cvc",
31
+ "securitycode",
32
+ "pin",
33
+ "otp",
34
+ "ssn",
35
+ "socialsecuritynumber",
36
+ "dob",
37
+ "dateofbirth",
38
+ "x-auth-token",
39
+ "x_auth_token"
40
+ ]);
41
+ var REDACTED = "[REDACTED]";
42
+ var TRUNCATED_SUFFIX = "\u2026[TRUNCATED]";
43
+ var MAX_DEPTH_MARKER = "[MAX_DEPTH]";
44
+ var UNSUPPORTED_MARKER = "[UNSUPPORTED]";
45
+ function sanitize(value, config = {}, _depth = 0) {
46
+ const {
47
+ maxDepth = 4,
48
+ maxArrayLength = 50,
49
+ maxStringLength = 500,
50
+ maxObjectKeys = 100,
51
+ redactKeys = []
52
+ } = config;
53
+ if (_depth >= maxDepth) return MAX_DEPTH_MARKER;
54
+ if (value === null || value === void 0) return value;
55
+ if (typeof value === "boolean") return value;
56
+ if (typeof value === "number") {
57
+ return Number.isFinite(value) ? value : String(value);
58
+ }
59
+ if (typeof value === "string") {
60
+ return value.length > maxStringLength ? value.slice(0, maxStringLength) + TRUNCATED_SUFFIX : value;
61
+ }
62
+ if (Array.isArray(value)) {
63
+ const sliced = value.slice(0, maxArrayLength);
64
+ return sliced.map((item) => sanitize(item, config, _depth + 1));
65
+ }
66
+ if (value instanceof Date) return value.toISOString();
67
+ if (value instanceof RegExp) return value.toString();
68
+ if (typeof value === "object") {
69
+ const extraKeys = redactKeys.map((k) => k.toLowerCase());
70
+ const allRedact = extraKeys.length > 0 ? /* @__PURE__ */ new Set([...BUILTIN_REDACT_KEYS, ...extraKeys]) : BUILTIN_REDACT_KEYS;
71
+ const result = {};
72
+ const entries = Object.entries(value);
73
+ let count = 0;
74
+ for (const [k, v] of entries) {
75
+ if (count >= maxObjectKeys) {
76
+ result["[KEYS_TRUNCATED]"] = `\u2026${entries.length - maxObjectKeys} more key(s) omitted`;
77
+ break;
78
+ }
79
+ result[k] = allRedact.has(k.toLowerCase()) ? REDACTED : sanitize(v, config, _depth + 1);
80
+ count++;
81
+ }
82
+ return result;
83
+ }
84
+ return UNSUPPORTED_MARKER;
85
+ }
86
+ var ALWAYS_REDACT_HEADERS = /* @__PURE__ */ new Set([
87
+ "authorization",
88
+ "cookie",
89
+ "set-cookie",
90
+ "x-api-key",
91
+ "x-auth-token",
92
+ "x-csrf-token",
93
+ "proxy-authorization"
94
+ ]);
95
+ function sanitizeHeaders(headers, config = {}) {
96
+ const result = {};
97
+ const maxLen = config.maxStringLength ?? 500;
98
+ for (const [key, value] of Object.entries(headers)) {
99
+ const lk = key.toLowerCase();
100
+ if (ALWAYS_REDACT_HEADERS.has(lk)) {
101
+ result[key] = REDACTED;
102
+ } else if (typeof value === "string" && value.length > maxLen) {
103
+ result[key] = value.slice(0, maxLen) + TRUNCATED_SUFFIX;
104
+ } else {
105
+ result[key] = value;
106
+ }
107
+ }
108
+ return result;
109
+ }
110
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
111
+ var ISO_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
112
+ var NUMERIC_ID_RE = /^\d{1,18}$/;
113
+ var JWT_RE = /^ey[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
114
+ function normaliseForDiff(value) {
115
+ if (typeof value === "string") {
116
+ if (UUID_RE.test(value)) return "<uuid>";
117
+ if (ISO_TS_RE.test(value)) return "<timestamp>";
118
+ if (JWT_RE.test(value)) return "<token>";
119
+ if (NUMERIC_ID_RE.test(value)) return "<id>";
120
+ return value;
121
+ }
122
+ if (typeof value === "number") {
123
+ if (value > 1e12) return "<timestamp>";
124
+ return value;
125
+ }
126
+ if (Array.isArray(value)) return value.map(normaliseForDiff);
127
+ if (value && typeof value === "object") {
128
+ return Object.fromEntries(
129
+ Object.entries(value).map(([k, v]) => [k, normaliseForDiff(v)])
130
+ );
131
+ }
132
+ return value;
133
+ }
134
+ export {
135
+ normaliseForDiff,
136
+ sanitize,
137
+ sanitizeHeaders
138
+ };
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@tracegraph/trace-sanitizer",
3
+ "version": "0.1.0",
4
+ "description": "Value redaction and size-limiting for TraceGraph events",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "scripts": {
22
+ "build": "tsup src/index.ts --format cjs,esm --dts",
23
+ "typecheck": "tsc --noEmit"
24
+ }
25
+ }