@vtex/api 6.52.0 → 6.52.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +50 -24
  2. package/lib/HttpClient/middlewares/cache.js +2 -2
  3. package/lib/HttpClient/middlewares/request/index.js +1 -1
  4. package/lib/HttpClient/middlewares/request/setupAxios/interceptors/tracing/spanSetup.js +1 -1
  5. package/lib/caches/MultilayeredCache.js +1 -1
  6. package/lib/service/logger/client.js +3 -3
  7. package/lib/service/logger/logger.d.ts +1 -1
  8. package/lib/service/logger/logger.js +3 -3
  9. package/lib/service/master.d.ts +0 -2
  10. package/lib/service/master.js +3 -15
  11. package/lib/service/metrics/requestMetricsMiddleware.js +4 -5
  12. package/lib/service/telemetry/client.js +18 -18
  13. package/lib/service/worker/index.d.ts +0 -1
  14. package/lib/service/worker/index.js +7 -17
  15. package/lib/service/worker/listeners.js +5 -3
  16. package/lib/service/worker/runtime/builtIn/middlewares.d.ts +1 -1
  17. package/lib/service/worker/runtime/builtIn/middlewares.js +2 -7
  18. package/lib/service/worker/runtime/graphql/middlewares/error.js +8 -2
  19. package/lib/service/worker/runtime/graphql/schema/schemaDirectives/Auth.js +2 -2
  20. package/lib/service/worker/runtime/http/middlewares/error.js +20 -2
  21. package/lib/service/worker/runtime/http/middlewares/sanitizeResponse.d.ts +37 -0
  22. package/lib/service/worker/runtime/http/middlewares/sanitizeResponse.js +143 -0
  23. package/lib/service/worker/runtime/statusTrack.js +1 -4
  24. package/lib/utils/buildFullPath.js +2 -2
  25. package/lib/utils/responseSanitizer.d.ts +52 -0
  26. package/lib/utils/responseSanitizer.js +354 -0
  27. package/lib/utils/stringRedactor.d.ts +19 -0
  28. package/lib/utils/stringRedactor.js +94 -0
  29. package/package.json +1 -1
  30. package/lib/service/metrics/clusterMetricsAggregator.d.ts +0 -72
  31. package/lib/service/metrics/clusterMetricsAggregator.js +0 -181
  32. package/lib/service/metrics/requestHandlerLabel.d.ts +0 -26
  33. package/lib/service/metrics/requestHandlerLabel.js +0 -30
@@ -0,0 +1,37 @@
1
+ import { ServiceContext } from '../../typings';
2
+ /**
3
+ * Setting this environment variable to `off` disables the sanitizer.
4
+ */
5
+ export declare const RESPONSE_SANITIZER_SWITCH = "VTEX_IO_RESPONSE_SANITIZER";
6
+ /**
7
+ * Sent when the body could not be sanitized: it is not known whether it is safe, so it is withheld.
8
+ */
9
+ export declare const WITHHELD_BODY: {
10
+ code: string;
11
+ message: string;
12
+ };
13
+ export declare enum SanitizerReason {
14
+ ErrorRemoved = "error_object_removed",
15
+ SecretRemoved = "secret_removed",
16
+ LimitReached = "limit_reached",
17
+ Failed = "sanitizer_failed"
18
+ }
19
+ /**
20
+ * Removes error objects (`Error`, `AxiosError`) from the response body, so apps that write a caught
21
+ * error to `ctx.body` do not expose the request configuration (credentials), the stack and the
22
+ * connection internals to the caller.
23
+ *
24
+ * String bodies are also covered, for errors that were turned into text: the credentials in them
25
+ * (the ones of the request, the credential headers, `Bearer` tokens) are replaced.
26
+ *
27
+ * It must be registered after `compress()`, which serializes the body: it needs to see the object,
28
+ * and to change it before it is serialized.
29
+ *
30
+ * The body is also sanitized when the downstream handlers throw after having set it, as the error
31
+ * middleware keeps an existing body. If the sanitizer itself fails the body is withheld. If it
32
+ * cannot inspect the whole body, the response is sent and the limit is reported. It never throws.
33
+ *
34
+ * It is a backstop for apps that return errors by mistake. It is not a boundary against an app that
35
+ * wants to disclose its own credentials, which has them.
36
+ */
37
+ export declare function sanitizeResponse(ctx: ServiceContext, next: () => Promise<void>): Promise<void>;
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sanitizeResponse = exports.SanitizerReason = exports.WITHHELD_BODY = exports.RESPONSE_SANITIZER_SWITCH = void 0;
4
+ const constants_1 = require("../../../../../constants");
5
+ const responseSanitizer_1 = require("../../../../../utils/responseSanitizer");
6
+ const stringRedactor_1 = require("../../../../../utils/stringRedactor");
7
+ /**
8
+ * Setting this environment variable to `off` disables the sanitizer.
9
+ */
10
+ exports.RESPONSE_SANITIZER_SWITCH = 'VTEX_IO_RESPONSE_SANITIZER';
11
+ /**
12
+ * Sent when the body could not be sanitized: it is not known whether it is safe, so it is withheld.
13
+ */
14
+ exports.WITHHELD_BODY = {
15
+ code: 'E_RESPONSE_WITHHELD',
16
+ message: 'The response could not be safely returned.',
17
+ };
18
+ var SanitizerReason;
19
+ (function (SanitizerReason) {
20
+ SanitizerReason["ErrorRemoved"] = "error_object_removed";
21
+ SanitizerReason["SecretRemoved"] = "secret_removed";
22
+ SanitizerReason["LimitReached"] = "limit_reached";
23
+ SanitizerReason["Failed"] = "sanitizer_failed";
24
+ })(SanitizerReason = exports.SanitizerReason || (exports.SanitizerReason = {}));
25
+ // Only the class of the error is reported: its message may carry what is being kept out.
26
+ const errorName = (err) => err === null || err === void 0 ? void 0 : err.name;
27
+ const warn = (ctx, reason, fields = {}) => {
28
+ var _a, _b, _c;
29
+ const payload = {
30
+ message: `response-sanitizer: ${reason}`,
31
+ reason,
32
+ routeId: (_b = (_a = ctx.vtex) === null || _a === void 0 ? void 0 : _a.route) === null || _b === void 0 ? void 0 : _b.id,
33
+ ...fields,
34
+ };
35
+ try {
36
+ if ((_c = ctx.vtex) === null || _c === void 0 ? void 0 : _c.logger) {
37
+ ctx.vtex.logger.warn(payload);
38
+ }
39
+ else {
40
+ console.warn(JSON.stringify(payload));
41
+ }
42
+ }
43
+ catch (err) {
44
+ // Logging must never break the response: the event goes to the process output instead.
45
+ console.warn(JSON.stringify({ ...payload, loggerErrorName: errorName(err) }));
46
+ }
47
+ };
48
+ const withholdBody = (ctx) => {
49
+ try {
50
+ if (ctx.status < 400) {
51
+ ctx.status = 500;
52
+ }
53
+ ctx.body = exports.WITHHELD_BODY;
54
+ }
55
+ catch (err) {
56
+ // There is nothing else that can be done safely: as a last resort the response is emptied.
57
+ ctx.body = null;
58
+ warn(ctx, SanitizerReason.Failed, { withholdErrorName: errorName(err) });
59
+ }
60
+ };
61
+ // A string body can hold an error that was turned into text (`JSON.stringify(error)`), which has
62
+ // no error object left to find. What can be told apart is the credential itself.
63
+ const redactStringBody = (ctx, body) => {
64
+ var _a;
65
+ const { authToken, adminUserAuthToken, storeUserAuthToken } = (_a = ctx.vtex) !== null && _a !== void 0 ? _a : {};
66
+ const { value, redacted } = (0, stringRedactor_1.redactSecrets)(body, [authToken, adminUserAuthToken, storeUserAuthToken]);
67
+ if (redacted === 0) {
68
+ return;
69
+ }
70
+ // Koa keeps the type already set when the body is a string, and updates the length.
71
+ ctx.body = value;
72
+ warn(ctx, SanitizerReason.SecretRemoved, { redactions: redacted });
73
+ };
74
+ const sanitizeCtxBody = (ctx) => {
75
+ try {
76
+ if (process.env[exports.RESPONSE_SANITIZER_SWITCH] === 'off') {
77
+ return;
78
+ }
79
+ const body = ctx.body;
80
+ if (typeof body === 'string') {
81
+ redactStringBody(ctx, body);
82
+ return;
83
+ }
84
+ if (body === null || typeof body !== 'object' || Buffer.isBuffer(body) || typeof body.pipe === 'function') {
85
+ return;
86
+ }
87
+ // Most bodies have no error. A scan decides that without the copying walk; the walk runs only
88
+ // once an error has been found, or the scan could not finish.
89
+ const scan = (0, responseSanitizer_1.scanForErrors)(body);
90
+ if (scan === 'clean') {
91
+ return;
92
+ }
93
+ const { value, replaced, truncated } = (0, responseSanitizer_1.sanitizeErrors)(body, { linked: constants_1.LINKED });
94
+ if (truncated) {
95
+ // What is beyond the limit is left as it is, outside an error. The response is still sent:
96
+ // withholding it would break the large legitimate responses. It is reported to be measured.
97
+ warn(ctx, SanitizerReason.LimitReached);
98
+ }
99
+ if (value === body) {
100
+ return;
101
+ }
102
+ // Koa sets `Content-Type: application/json` whenever an object is assigned to the body, which
103
+ // would override a type chosen by the app.
104
+ const contentType = ctx.response.get('Content-Type');
105
+ ctx.body = value;
106
+ if (contentType) {
107
+ ctx.set('Content-Type', contentType);
108
+ }
109
+ warn(ctx, SanitizerReason.ErrorRemoved, { errors: replaced });
110
+ }
111
+ catch (err) {
112
+ // Fails closed: whatever made it fail may also be hiding a credential.
113
+ withholdBody(ctx);
114
+ warn(ctx, SanitizerReason.Failed, { errorName: errorName(err) });
115
+ }
116
+ };
117
+ /**
118
+ * Removes error objects (`Error`, `AxiosError`) from the response body, so apps that write a caught
119
+ * error to `ctx.body` do not expose the request configuration (credentials), the stack and the
120
+ * connection internals to the caller.
121
+ *
122
+ * String bodies are also covered, for errors that were turned into text: the credentials in them
123
+ * (the ones of the request, the credential headers, `Bearer` tokens) are replaced.
124
+ *
125
+ * It must be registered after `compress()`, which serializes the body: it needs to see the object,
126
+ * and to change it before it is serialized.
127
+ *
128
+ * The body is also sanitized when the downstream handlers throw after having set it, as the error
129
+ * middleware keeps an existing body. If the sanitizer itself fails the body is withheld. If it
130
+ * cannot inspect the whole body, the response is sent and the limit is reported. It never throws.
131
+ *
132
+ * It is a backstop for apps that return errors by mistake. It is not a boundary against an app that
133
+ * wants to disclose its own credentials, which has them.
134
+ */
135
+ async function sanitizeResponse(ctx, next) {
136
+ try {
137
+ await next();
138
+ }
139
+ finally {
140
+ sanitizeCtxBody(ctx);
141
+ }
142
+ }
143
+ exports.sanitizeResponse = sanitizeResponse;
@@ -14,10 +14,7 @@ const isStatusTrackBroadcast = (message) => message === BROADCAST_STATUS_TRACK;
14
14
  exports.isStatusTrackBroadcast = isStatusTrackBroadcast;
15
15
  const statusTrackHandler = async (ctx) => {
16
16
  var _a, _b, _c;
17
- // Parity with the other builtin handlers: name the request so its samples don't
18
- // land in the catch-all `handler="undefined"` bucket.
19
- ctx.requestHandlerName = 'builtin:status-track';
20
- (_b = (_a = ctx.tracing) === null || _a === void 0 ? void 0 : _a.currentSpan) === null || _b === void 0 ? void 0 : _b.setOperationName(ctx.requestHandlerName);
17
+ (_b = (_a = ctx.tracing) === null || _a === void 0 ? void 0 : _a.currentSpan) === null || _b === void 0 ? void 0 : _b.setOperationName('builtin:status-track');
21
18
  if (!constants_1.LINKED) {
22
19
  (_c = process.send) === null || _c === void 0 ? void 0 : _c.call(process, BROADCAST_STATUS_TRACK);
23
20
  }
@@ -19,8 +19,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
19
19
  * @returns {string} The combined full path
20
20
  */
21
21
  function default_1(baseURL, requestedURL, allowAbsoluteUrls) {
22
- let isRelativeUrl = !isAbsoluteURL(requestedURL);
23
- if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
22
+ const isRelativeUrl = !isAbsoluteURL(requestedURL);
23
+ if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
24
24
  return combineURLs(baseURL, requestedURL);
25
25
  }
26
26
  return requestedURL;
@@ -0,0 +1,52 @@
1
+ export interface SanitizeErrorsOptions {
2
+ /**
3
+ * When true (linked apps in development, and logs) the stack is kept to help debugging.
4
+ */
5
+ linked: boolean;
6
+ maxDepth?: number;
7
+ maxNodes?: number;
8
+ /**
9
+ * Total length of the arrays and objects visited, so that the cost of a long flat array is
10
+ * bounded the same as the number of containers.
11
+ */
12
+ maxValues?: number;
13
+ }
14
+ export interface SanitizeErrorsResult<T> {
15
+ /**
16
+ * The same reference received when nothing had to change.
17
+ */
18
+ value: T;
19
+ /**
20
+ * Number of error instances replaced by their safe representation.
21
+ */
22
+ replaced: number;
23
+ /**
24
+ * True when a limit (depth, containers, values) stopped the walk early. Outside an error the part
25
+ * not visited is left as it is. Inside an error it is replaced by a marker.
26
+ */
27
+ truncated: boolean;
28
+ }
29
+ /**
30
+ * Finds `Error` instances (including `AxiosError`) in a response body, at any depth of plain
31
+ * objects and arrays, and replaces each one by a safe representation: the message, name, code and
32
+ * status are kept, while the request config, the Node request, the agents, the upstream headers
33
+ * and, unless linked, the stack are removed.
34
+ *
35
+ * Strings, buffers, streams and class instances other than errors are returned untouched.
36
+ */
37
+ export declare const sanitizeErrors: <T>(value: T, options: SanitizeErrorsOptions) => SanitizeErrorsResult<T>;
38
+ export type ErrorScan = 'clean' | 'has-error' | 'truncated';
39
+ /**
40
+ * Says whether `value` contains an `Error`, without copying it. The copying walk is only needed
41
+ * when this returns `has-error`. `truncated` means a budget (depth, containers, or the values they
42
+ * hold) was spent before the value was fully inspected, so whatever was not visited must not be sent.
43
+ */
44
+ export declare const scanForErrors: (value: object, options?: Pick<SanitizeErrorsOptions, 'maxDepth' | 'maxNodes' | 'maxValues'>) => ErrorScan;
45
+ /**
46
+ * The same as `sanitizeErrors` for what is written to the process output, where the stack is
47
+ * useful and kept. A thrown `Error` stays an error, so it is printed as one (stack, then its
48
+ * properties), without the request config, the request and the agents.
49
+ *
50
+ * It never throws.
51
+ */
52
+ export declare const toLoggableError: (value: unknown) => unknown;
@@ -0,0 +1,354 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toLoggableError = exports.scanForErrors = exports.sanitizeErrors = void 0;
4
+ const error_1 = require("./error");
5
+ /**
6
+ * Properties of an error that hold HTTP-client internals: the request config (headers carry
7
+ * credentials), the Node request object, and the connection agents. They are never serialized.
8
+ * `response` is rebuilt separately, so that its headers and request are left out too.
9
+ */
10
+ const INTERNAL_ERROR_KEYS = new Set(['config', 'request', 'httpAgent', 'httpsAgent', 'response']);
11
+ const DEFAULT_MAX_DEPTH = 32;
12
+ const DEFAULT_MAX_NODES = 200000;
13
+ // What the containers hold, counted by their length. About 35 ms to go through on a laptop, which
14
+ // is far past a legitimate response.
15
+ const DEFAULT_MAX_VALUES = 5000000;
16
+ const TRUNCATED = '[Truncated]';
17
+ const CIRCULAR = '[Circular]';
18
+ // `instanceof` is not enough for errors that come from another realm (a `vm` context), which
19
+ // `Object.prototype.toString` still identifies.
20
+ const isError = (node) => node instanceof Error || Object.prototype.toString.call(node) === '[object Error]';
21
+ // Buffers and typed arrays, which have one entry per byte when walked as objects.
22
+ const isBinary = (node) => Buffer.isBuffer(node) || ArrayBuffer.isView(node) || node instanceof ArrayBuffer;
23
+ const isPlainObject = (node) => {
24
+ const proto = Object.getPrototypeOf(node);
25
+ return proto === Object.prototype || proto === null;
26
+ };
27
+ /**
28
+ * What is shown instead of a value that is kept out of an error: binary data, streams and
29
+ * instances of classes, which can hold large or circular graphs (sockets, agents, handles).
30
+ */
31
+ const describeOpaque = (node) => {
32
+ var _a;
33
+ if (node instanceof Date) {
34
+ return Number.isNaN(node.getTime()) ? '[Invalid Date]' : node.toISOString();
35
+ }
36
+ const name = ((_a = node === null || node === void 0 ? void 0 : node.constructor) === null || _a === void 0 ? void 0 : _a.name) || 'Object';
37
+ if (isBinary(node)) {
38
+ return `[${name} ${node.byteLength} bytes]`;
39
+ }
40
+ return `[${name}]`;
41
+ };
42
+ class ErrorSanitizer {
43
+ constructor({ linked, maxDepth, maxNodes, maxValues }) {
44
+ this.replaced = 0;
45
+ this.truncated = false;
46
+ this.nodes = 0;
47
+ this.values = 0;
48
+ this.insideError = 0;
49
+ // The containers being walked, from the root. At most `maxDepth` + 1 of them, so searching it is
50
+ // cheaper than maintaining a set.
51
+ this.ancestors = [];
52
+ this.linked = linked;
53
+ this.maxDepth = maxDepth !== null && maxDepth !== void 0 ? maxDepth : DEFAULT_MAX_DEPTH;
54
+ this.maxNodes = maxNodes !== null && maxNodes !== void 0 ? maxNodes : DEFAULT_MAX_NODES;
55
+ this.maxValues = maxValues !== null && maxValues !== void 0 ? maxValues : DEFAULT_MAX_VALUES;
56
+ }
57
+ /**
58
+ * Copy-on-write walk: containers are copied only when something below them changed, and the
59
+ * received objects are never mutated (they may be frozen, cached or still in use by the app).
60
+ */
61
+ walk(node, depth) {
62
+ if (node === null || typeof node !== 'object') {
63
+ return node;
64
+ }
65
+ if (this.ancestors.includes(node)) {
66
+ // A cycle. Inside an error it must not lead back to the received error, which has the config
67
+ // and the request. In a body, serializing it fails regardless of this walk.
68
+ return this.insideError > 0 ? CIRCULAR : node;
69
+ }
70
+ if (depth > this.maxDepth || this.nodes >= this.maxNodes) {
71
+ // Not inspected. Inside an error it must not be returned (it may hold the config). Outside
72
+ // one it is left as it is: withholding the whole body would break the large responses.
73
+ this.truncated = true;
74
+ return this.insideError > 0 ? TRUNCATED : node;
75
+ }
76
+ this.nodes++;
77
+ // Arrays and plain objects are by far the most common, and cannot be errors, binary data or
78
+ // streams: they are checked first.
79
+ if (Array.isArray(node)) {
80
+ return this.walkArray(node, depth);
81
+ }
82
+ if (isPlainObject(node)) {
83
+ return this.walkObject(node, depth);
84
+ }
85
+ return this.walkOther(node, depth);
86
+ }
87
+ // Charged per container, when it is entered, so the loops that visit the values have no counter.
88
+ spend(values) {
89
+ this.values += values;
90
+ if (this.values > this.maxValues) {
91
+ this.truncated = true;
92
+ return false;
93
+ }
94
+ return true;
95
+ }
96
+ walkArray(node, depth) {
97
+ if (!this.spend(node.length)) {
98
+ return this.insideError > 0 ? TRUNCATED : node;
99
+ }
100
+ this.ancestors.push(node);
101
+ let result = node;
102
+ for (let i = 0; i < node.length; i++) {
103
+ const value = node[i];
104
+ const safe = this.walkValue(value, depth);
105
+ if (safe !== value) {
106
+ result = result === node ? node.slice() : result;
107
+ result[i] = safe;
108
+ }
109
+ }
110
+ this.ancestors.pop();
111
+ return result;
112
+ }
113
+ walkObject(node, depth) {
114
+ const keys = Object.keys(node);
115
+ if (!this.spend(keys.length)) {
116
+ return this.insideError > 0 ? TRUNCATED : node;
117
+ }
118
+ this.ancestors.push(node);
119
+ let result = node;
120
+ for (const key of keys) {
121
+ const value = node[key];
122
+ const safe = this.walkValue(value, depth);
123
+ if (safe !== value) {
124
+ result = result === node ? { ...node } : result;
125
+ result[key] = safe;
126
+ }
127
+ }
128
+ this.ancestors.pop();
129
+ return result;
130
+ }
131
+ // Most values are primitives: skipping them here avoids a call per value.
132
+ walkValue(value, depth) {
133
+ return value === null || typeof value !== 'object' ? value : this.walk(value, depth + 1);
134
+ }
135
+ // Errors, and what is neither a plain object nor an array: buffers, streams, class instances.
136
+ walkOther(node, depth) {
137
+ if (isError(node)) {
138
+ this.replaced++;
139
+ return this.toSafeError(node, depth);
140
+ }
141
+ return this.insideError > 0 ? describeOpaque(node) : node;
142
+ }
143
+ /**
144
+ * Builds the object that is exposed instead of the error. It is made from a shallow copy that
145
+ * leaves out the HTTP-client internals, so those are never traversed nor serialized, and goes
146
+ * through `cleanError` to keep the output consistent with the one of the global error handler
147
+ * (circular references, private and function properties, long strings).
148
+ *
149
+ * What reaches `cleanError` is bounded: values beyond the limits, binary data and class
150
+ * instances were replaced by markers while walking, because `cleanError` has no limits of its own.
151
+ */
152
+ toSafeError(error, depth) {
153
+ this.ancestors.push(error);
154
+ this.insideError++;
155
+ const source = error;
156
+ const copy = this.copyErrorProperties(source, depth);
157
+ const { response } = source;
158
+ if (response !== null && typeof response === 'object') {
159
+ copy.response = this.copyResponse(response, depth);
160
+ }
161
+ const safe = (0, error_1.cleanError)(copy);
162
+ // `cleanError` picks a fixed set of response properties, which leaves `statusText` out.
163
+ if (safe.response && typeof (response === null || response === void 0 ? void 0 : response.statusText) === 'string') {
164
+ safe.response.statusText = response.statusText;
165
+ }
166
+ this.insideError--;
167
+ this.ancestors.pop();
168
+ return safe;
169
+ }
170
+ copyErrorProperties(source, depth) {
171
+ const copy = {};
172
+ for (const key of Object.keys(source)) {
173
+ if (!INTERNAL_ERROR_KEYS.has(key)) {
174
+ copy[key] = this.walk(source[key], depth + 1);
175
+ }
176
+ }
177
+ for (const property of ['name', 'message', 'code']) {
178
+ if (typeof source[property] === 'string') {
179
+ copy[property] = source[property];
180
+ }
181
+ }
182
+ if (this.linked && typeof source.stack === 'string') {
183
+ copy.stack = source.stack;
184
+ }
185
+ return copy;
186
+ }
187
+ // Only what the upstream answered. Its headers (cookies, tokens) and the request that originated
188
+ // it are not exposed.
189
+ copyResponse(response, depth) {
190
+ return {
191
+ data: this.walk(response.data, depth + 1),
192
+ status: response.status,
193
+ };
194
+ }
195
+ }
196
+ /**
197
+ * Finds `Error` instances (including `AxiosError`) in a response body, at any depth of plain
198
+ * objects and arrays, and replaces each one by a safe representation: the message, name, code and
199
+ * status are kept, while the request config, the Node request, the agents, the upstream headers
200
+ * and, unless linked, the stack are removed.
201
+ *
202
+ * Strings, buffers, streams and class instances other than errors are returned untouched.
203
+ */
204
+ const sanitizeErrors = (value, options) => {
205
+ const sanitizer = new ErrorSanitizer(options);
206
+ const sanitized = sanitizer.walk(value, 0);
207
+ return {
208
+ replaced: sanitizer.replaced,
209
+ truncated: sanitizer.truncated,
210
+ value: sanitized,
211
+ };
212
+ };
213
+ exports.sanitizeErrors = sanitizeErrors;
214
+ const isPrimitiveValue = (value) => value === null || typeof value !== 'object';
215
+ const enter = (budget, values) => {
216
+ if (budget.nodes >= budget.maxNodes) {
217
+ return false;
218
+ }
219
+ budget.nodes++;
220
+ budget.values += values;
221
+ return budget.values <= budget.maxValues;
222
+ };
223
+ // How far the linear pass may nest, in arrays and in objects alike. Deeper bodies fall through to
224
+ // the scan below, which also enforces the depth limit.
225
+ const SHALLOW_DEPTH = 4;
226
+ // Lists of plain records, and an object wrapping them, are the common large payload. One pass
227
+ // proves they hold no Error, which is cheaper than the copying walk and stops at the same budget.
228
+ const shallowValue = (value, budget, depth) => {
229
+ // Arrays and plain objects first: they are the common case and cannot be errors.
230
+ if (Array.isArray(value)) {
231
+ return shallowArray(value, budget, depth);
232
+ }
233
+ if (isPlainObject(value)) {
234
+ return shallowRecord(value, budget, depth);
235
+ }
236
+ if (isError(value)) {
237
+ return 'has-error';
238
+ }
239
+ return enter(budget, 0) ? 'clean' : 'truncated';
240
+ };
241
+ // What is below a container that is not a primitive. Recursion stops at the cutoff, whatever the
242
+ // container is, so its depth is bounded.
243
+ const shallowChild = (child, budget, depth) => depth >= SHALLOW_DEPTH ? undefined : shallowValue(child, budget, depth + 1);
244
+ const shallowArray = (items, budget, depth) => {
245
+ if (!enter(budget, items.length)) {
246
+ return 'truncated';
247
+ }
248
+ for (const item of items) {
249
+ if (isPrimitiveValue(item)) {
250
+ continue;
251
+ }
252
+ const found = shallowChild(item, budget, depth);
253
+ if (found !== 'clean') {
254
+ return found;
255
+ }
256
+ }
257
+ return 'clean';
258
+ };
259
+ const shallowRecord = (record, budget, depth) => {
260
+ const keys = Object.keys(record);
261
+ if (!enter(budget, keys.length)) {
262
+ return 'truncated';
263
+ }
264
+ for (const key of keys) {
265
+ const value = record[key];
266
+ if (isPrimitiveValue(value)) {
267
+ continue;
268
+ }
269
+ const found = shallowChild(value, budget, depth);
270
+ if (found !== 'clean') {
271
+ return found;
272
+ }
273
+ }
274
+ return 'clean';
275
+ };
276
+ const scanChildren = (node, depth, state) => {
277
+ const isArray = Array.isArray(node);
278
+ const record = node;
279
+ const keys = isArray ? undefined : Object.keys(record);
280
+ const length = keys ? keys.length : node.length;
281
+ state.values += length;
282
+ if (state.values > state.maxValues) {
283
+ state.truncated = true;
284
+ return;
285
+ }
286
+ state.ancestors.push(node);
287
+ for (let i = 0; i < length && !state.found && !state.truncated; i++) {
288
+ const child = keys ? record[keys[i]] : node[i];
289
+ if (child !== null && typeof child === 'object') {
290
+ scanNode(child, depth + 1, state);
291
+ }
292
+ }
293
+ state.ancestors.pop();
294
+ };
295
+ const scanNode = (node, depth, state) => {
296
+ if (state.found || state.truncated || state.ancestors.includes(node)) {
297
+ return;
298
+ }
299
+ if (depth > state.maxDepth || state.nodes >= state.maxNodes) {
300
+ state.truncated = true;
301
+ return;
302
+ }
303
+ state.nodes++;
304
+ if (Array.isArray(node) || isPlainObject(node)) {
305
+ scanChildren(node, depth, state);
306
+ }
307
+ else if (isError(node)) {
308
+ state.found = true;
309
+ }
310
+ };
311
+ const deepScan = (value, maxDepth, maxNodes, maxValues) => {
312
+ const state = { ancestors: [], found: false, maxDepth, maxNodes, maxValues, nodes: 0, truncated: false, values: 0 };
313
+ scanNode(value, 0, state);
314
+ if (state.truncated) {
315
+ return 'truncated';
316
+ }
317
+ return state.found ? 'has-error' : 'clean';
318
+ };
319
+ /**
320
+ * Says whether `value` contains an `Error`, without copying it. The copying walk is only needed
321
+ * when this returns `has-error`. `truncated` means a budget (depth, containers, or the values they
322
+ * hold) was spent before the value was fully inspected, so whatever was not visited must not be sent.
323
+ */
324
+ const scanForErrors = (value, options = {}) => {
325
+ var _a, _b, _c;
326
+ const maxNodes = (_a = options.maxNodes) !== null && _a !== void 0 ? _a : DEFAULT_MAX_NODES;
327
+ const maxValues = (_b = options.maxValues) !== null && _b !== void 0 ? _b : DEFAULT_MAX_VALUES;
328
+ const shallow = shallowValue(value, { maxNodes, maxValues, nodes: 0, values: 0 }, 0);
329
+ if (shallow !== undefined) {
330
+ return shallow;
331
+ }
332
+ return deepScan(value, (_c = options.maxDepth) !== null && _c !== void 0 ? _c : DEFAULT_MAX_DEPTH, maxNodes, maxValues);
333
+ };
334
+ exports.scanForErrors = scanForErrors;
335
+ /**
336
+ * The same as `sanitizeErrors` for what is written to the process output, where the stack is
337
+ * useful and kept. A thrown `Error` stays an error, so it is printed as one (stack, then its
338
+ * properties), without the request config, the request and the agents.
339
+ *
340
+ * It never throws.
341
+ */
342
+ const toLoggableError = (value) => {
343
+ try {
344
+ const { value: safe } = (0, exports.sanitizeErrors)(value, { linked: true });
345
+ if (safe !== value && value !== null && typeof value === 'object' && isError(value)) {
346
+ return Object.assign(Object.create(Object.getPrototypeOf(value)), safe);
347
+ }
348
+ return safe;
349
+ }
350
+ catch (err) {
351
+ return `[error omitted: it could not be sanitized (${err === null || err === void 0 ? void 0 : err.name})]`;
352
+ }
353
+ };
354
+ exports.toLoggableError = toLoggableError;
@@ -0,0 +1,19 @@
1
+ export declare const REDACTED = "[Redacted]";
2
+ export interface RedactResult {
3
+ value: string;
4
+ /**
5
+ * How many occurrences were replaced. Zero means `value` is the received string.
6
+ */
7
+ redacted: number;
8
+ }
9
+ /**
10
+ * Replaces credentials in a text: the given secrets wherever they appear, the value of the
11
+ * credential headers in JSON text and in header lines, `Cookie` and `Set-Cookie` lines, the VTEX
12
+ * ID cookie, and `Bearer` tokens.
13
+ * The rest of the text is kept.
14
+ *
15
+ * It is for text that was built from an error, where the error object is no longer there to
16
+ * detect. It does not inspect anything else: a credential that is neither one of the secrets nor
17
+ * under one of those names is not found.
18
+ */
19
+ export declare const redactSecrets: (text: string, secrets?: Array<string | undefined>) => RedactResult;