@zharp/node 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +36 -2
- package/dist/index.d.ts +36 -2
- package/dist/index.js +603 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +603 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -92,6 +92,602 @@ function warn(message) {
|
|
|
92
92
|
console.warn(`[Zharp] ${message}`);
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
// ../../internal/src/bodies.ts
|
|
96
|
+
var DEFAULT_MAX_BODY = 32 * 1024;
|
|
97
|
+
var MAX_BODY = 128 * 1024;
|
|
98
|
+
var FILTERED = "[Filtered]";
|
|
99
|
+
function rawLimit(settings) {
|
|
100
|
+
return Math.max(64 * 1024, settings.maxSize * 2);
|
|
101
|
+
}
|
|
102
|
+
var BODY_ATTRIBUTES = {
|
|
103
|
+
request: "http.request.body",
|
|
104
|
+
requestTruncated: "http.request.body.truncated",
|
|
105
|
+
requestType: "http.request.header.content-type",
|
|
106
|
+
response: "http.response.body",
|
|
107
|
+
responseTruncated: "http.response.body.truncated",
|
|
108
|
+
responseType: "http.response.header.content-type"
|
|
109
|
+
};
|
|
110
|
+
function bodySettings(option, env) {
|
|
111
|
+
let value = option;
|
|
112
|
+
if (value === void 0 && env) {
|
|
113
|
+
const e = env.trim().toLowerCase();
|
|
114
|
+
if (e === "errors" || e === "all") value = e;
|
|
115
|
+
else if (/^(true|1|yes|on)$/.test(e)) value = true;
|
|
116
|
+
}
|
|
117
|
+
if (!value) return null;
|
|
118
|
+
const o = value === true ? {} : typeof value === "string" ? { mode: value } : value;
|
|
119
|
+
const size = typeof o.maxSize === "number" && o.maxSize > 0 ? Math.min(Math.floor(o.maxSize), MAX_BODY) : DEFAULT_MAX_BODY;
|
|
120
|
+
return { mode: o.mode === "all" ? "all" : "errors", maxSize: size, extraKeys: o.redactKeys ?? [], urls: o.urls };
|
|
121
|
+
}
|
|
122
|
+
function wanted(settings, status) {
|
|
123
|
+
return settings.mode === "all" || !status || status >= 400;
|
|
124
|
+
}
|
|
125
|
+
var mime = (contentType) => (contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
126
|
+
function isEventStream(contentType) {
|
|
127
|
+
return mime(contentType) === "text/event-stream";
|
|
128
|
+
}
|
|
129
|
+
function isMultipart(contentType) {
|
|
130
|
+
return mime(contentType) === "multipart/form-data";
|
|
131
|
+
}
|
|
132
|
+
function isTextual(contentType) {
|
|
133
|
+
const type = mime(contentType);
|
|
134
|
+
if (!type) return true;
|
|
135
|
+
if (type === "text/event-stream") return false;
|
|
136
|
+
return type.startsWith("text/") || type.endsWith("+json") || type.endsWith("+xml") || /^application\/(json|xml|x-www-form-urlencoded|graphql|javascript|x-ndjson|ld\+json)$/.test(type);
|
|
137
|
+
}
|
|
138
|
+
function isForm(contentType) {
|
|
139
|
+
return mime(contentType) === "application/x-www-form-urlencoded";
|
|
140
|
+
}
|
|
141
|
+
function formatSize(bytes) {
|
|
142
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
143
|
+
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
|
144
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
145
|
+
}
|
|
146
|
+
function fileLabel(name, type, size, partial = false) {
|
|
147
|
+
const parts = [`file ${name || "blob"}`];
|
|
148
|
+
if (type) parts.push(type);
|
|
149
|
+
if (size !== void 0) parts.push(formatSize(size) + (partial ? "+" : ""));
|
|
150
|
+
return `[${parts.join(" \xB7 ")}]`;
|
|
151
|
+
}
|
|
152
|
+
function describeBody(contentType, size, partial = false) {
|
|
153
|
+
if (isEventStream(contentType)) return "[event stream]";
|
|
154
|
+
const parts = ["binary"];
|
|
155
|
+
const type = mime(contentType);
|
|
156
|
+
if (type) parts.push(type);
|
|
157
|
+
if (size !== void 0 && size > 0) parts.push(formatSize(size) + (partial ? "+" : ""));
|
|
158
|
+
return `[${parts.join(" \xB7 ")}]`;
|
|
159
|
+
}
|
|
160
|
+
var CONTAINS = [
|
|
161
|
+
"password",
|
|
162
|
+
"passwd",
|
|
163
|
+
"passphrase",
|
|
164
|
+
"secret",
|
|
165
|
+
"token",
|
|
166
|
+
"apikey",
|
|
167
|
+
"accesskey",
|
|
168
|
+
"privatekey",
|
|
169
|
+
"authorization",
|
|
170
|
+
"cookie",
|
|
171
|
+
"creditcard",
|
|
172
|
+
"cardnumber",
|
|
173
|
+
"cvv",
|
|
174
|
+
"cvc",
|
|
175
|
+
"ssn",
|
|
176
|
+
"iban",
|
|
177
|
+
"sessionid",
|
|
178
|
+
"signature",
|
|
179
|
+
"credential"
|
|
180
|
+
];
|
|
181
|
+
var EXACT = ["auth", "pin", "pwd", "otp", "card", "pan", "jwt", "sid", "codeverifier"];
|
|
182
|
+
var URL_EXACT = ["key", "sig", "code", "state", "session"];
|
|
183
|
+
var normalize = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
184
|
+
function isSecretKey(key, extra = []) {
|
|
185
|
+
const k = normalize(key);
|
|
186
|
+
if (!k) return false;
|
|
187
|
+
if (EXACT.includes(k) || CONTAINS.some((c) => k.includes(c))) return true;
|
|
188
|
+
return extra.some((p) => p instanceof RegExp ? p.test(key) : normalize(p) === k);
|
|
189
|
+
}
|
|
190
|
+
var DATA_URI = /^data:([\w.+-]+\/[\w.+-]+)?(?:;[\w=.+-]+)*;base64,([A-Za-z0-9+/=\s]*)$/;
|
|
191
|
+
var BASE64 = /^[A-Za-z0-9+/_-]{256,}={0,2}$/;
|
|
192
|
+
function shorten(value) {
|
|
193
|
+
if (value.length < 256) return value;
|
|
194
|
+
const uri = DATA_URI.exec(value);
|
|
195
|
+
if (uri) return `[${uri[1] || "data"} \xB7 ${formatSize(Math.floor(uri[2].length * 3 / 4))}]`;
|
|
196
|
+
if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 \xB7 ${formatSize(Math.floor(value.length * 3 / 4))}]`;
|
|
197
|
+
return value;
|
|
198
|
+
}
|
|
199
|
+
function filterAll(value, depth) {
|
|
200
|
+
if (depth > 20) return FILTERED;
|
|
201
|
+
if (value === null || value === "") return value;
|
|
202
|
+
if (Array.isArray(value)) return value.map((v) => filterAll(v, depth + 1));
|
|
203
|
+
if (typeof value === "object") {
|
|
204
|
+
const out = {};
|
|
205
|
+
for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth + 1);
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
return FILTERED;
|
|
209
|
+
}
|
|
210
|
+
function redactValue(value, extra, depth = 0) {
|
|
211
|
+
if (typeof value === "string") return shorten(value);
|
|
212
|
+
if (depth > 20 || value === null || typeof value !== "object") return value;
|
|
213
|
+
if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth + 1));
|
|
214
|
+
const out = {};
|
|
215
|
+
for (const [k, v] of Object.entries(value)) {
|
|
216
|
+
out[k] = isSecretKey(k, extra) ? filterAll(v, depth + 1) : redactValue(v, extra, depth + 1);
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
function redactLoose(text, extra) {
|
|
221
|
+
const runs = /"((?:data:[\w.+-]+\/[\w.+-]+(?:;[\w=.+-]+)*;base64,)?[A-Za-z0-9+/_=-]{256,})("?)/g;
|
|
222
|
+
return text.replace(runs, (match, run, close) => {
|
|
223
|
+
const short = shorten(run);
|
|
224
|
+
if (short === run) return match;
|
|
225
|
+
return close ? `"${short}"` : `"${short.slice(0, -1)}+]"`;
|
|
226
|
+
}).replace(
|
|
227
|
+
/("([^"\\]{1,100})"\s*:\s*)("(?:[^"\\]|\\.)*"?|-?\d[\d.eE+-]*|true|false)/g,
|
|
228
|
+
(match, prefix, key) => isSecretKey(key, extra) ? `${prefix}"${FILTERED}"` : match
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
function redactForm(text, extra) {
|
|
232
|
+
return text.split("&").map((pair) => {
|
|
233
|
+
const eq = pair.indexOf("=");
|
|
234
|
+
if (eq < 0) return pair;
|
|
235
|
+
let key = pair.slice(0, eq);
|
|
236
|
+
try {
|
|
237
|
+
key = decodeURIComponent(key.replace(/\+/g, " "));
|
|
238
|
+
} catch {
|
|
239
|
+
}
|
|
240
|
+
if (isSecretKey(key, extra)) return `${pair.slice(0, eq)}=${FILTERED}`;
|
|
241
|
+
const value = pair.slice(eq + 1);
|
|
242
|
+
return value.length >= 256 ? `${pair.slice(0, eq)}=${shortenEncoded(value)}` : pair;
|
|
243
|
+
}).join("&");
|
|
244
|
+
}
|
|
245
|
+
function shortenEncoded(value) {
|
|
246
|
+
try {
|
|
247
|
+
const decoded = decodeURIComponent(value.replace(/\+/g, " "));
|
|
248
|
+
const short = shorten(decoded);
|
|
249
|
+
return short === decoded ? value : short;
|
|
250
|
+
} catch {
|
|
251
|
+
return value;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function formatBody(text, contentType, settings, cut = false) {
|
|
255
|
+
if (text == null) return null;
|
|
256
|
+
let body = String(text);
|
|
257
|
+
if (!body.trim()) return null;
|
|
258
|
+
if (isForm(contentType)) body = redactForm(body, settings.extraKeys);
|
|
259
|
+
else {
|
|
260
|
+
let parsed2;
|
|
261
|
+
let ok = false;
|
|
262
|
+
const trimmed = body.trim();
|
|
263
|
+
if (!cut && (trimmed[0] === "{" || trimmed[0] === "[")) {
|
|
264
|
+
try {
|
|
265
|
+
parsed2 = JSON.parse(trimmed);
|
|
266
|
+
ok = true;
|
|
267
|
+
} catch {
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
body = ok ? JSON.stringify(redactValue(parsed2, settings.extraKeys)) : redactLoose(body, settings.extraKeys);
|
|
271
|
+
}
|
|
272
|
+
const truncated = cut || body.length > settings.maxSize;
|
|
273
|
+
return { value: body.length > settings.maxSize ? body.slice(0, settings.maxSize) : body, truncated };
|
|
274
|
+
}
|
|
275
|
+
function typeKey(side) {
|
|
276
|
+
return side === "request" ? BODY_ATTRIBUTES.requestType : BODY_ATTRIBUTES.responseType;
|
|
277
|
+
}
|
|
278
|
+
function bodyAttributes(side, text, contentType, settings, cut = false) {
|
|
279
|
+
if (!isTextual(contentType) && !isMultipart(contentType)) return {};
|
|
280
|
+
const formatted = formatBody(text, contentType, settings, cut);
|
|
281
|
+
if (!formatted) return {};
|
|
282
|
+
const attributes = { [BODY_ATTRIBUTES[side]]: formatted.value };
|
|
283
|
+
if (formatted.truncated) attributes[side === "request" ? BODY_ATTRIBUTES.requestTruncated : BODY_ATTRIBUTES.responseTruncated] = true;
|
|
284
|
+
if (contentType) attributes[typeKey(side)] = contentType;
|
|
285
|
+
return attributes;
|
|
286
|
+
}
|
|
287
|
+
function describedAttributes(side, contentType, size, partial = false) {
|
|
288
|
+
const attributes = { [BODY_ATTRIBUTES[side]]: describeBody(contentType, size, partial) };
|
|
289
|
+
if (contentType) attributes[typeKey(side)] = contentType;
|
|
290
|
+
return attributes;
|
|
291
|
+
}
|
|
292
|
+
function redactUrl(url, extra = []) {
|
|
293
|
+
if (!url) return url;
|
|
294
|
+
let out = url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
|
|
295
|
+
const q = out.indexOf("?");
|
|
296
|
+
if (q < 0) return out;
|
|
297
|
+
const hash = out.indexOf("#", q);
|
|
298
|
+
const query = out.slice(q + 1, hash < 0 ? void 0 : hash);
|
|
299
|
+
const redacted = redactQuery(query, extra);
|
|
300
|
+
if (redacted !== query) out = out.slice(0, q + 1) + redacted + (hash < 0 ? "" : out.slice(hash));
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
function redactQuery(query, extra = []) {
|
|
304
|
+
if (!query) return query;
|
|
305
|
+
return query.split("&").map((pair) => {
|
|
306
|
+
const eq = pair.indexOf("=");
|
|
307
|
+
if (eq < 0) return pair;
|
|
308
|
+
let key = pair.slice(0, eq);
|
|
309
|
+
try {
|
|
310
|
+
key = decodeURIComponent(key.replace(/\+/g, " "));
|
|
311
|
+
} catch {
|
|
312
|
+
}
|
|
313
|
+
const secret = isSecretKey(key, extra) || URL_EXACT.includes(normalize(key));
|
|
314
|
+
return secret && eq < pair.length - 1 ? `${pair.slice(0, eq)}=${FILTERED}` : pair;
|
|
315
|
+
}).join("&");
|
|
316
|
+
}
|
|
317
|
+
function urlMatches(url, patterns) {
|
|
318
|
+
let host = "";
|
|
319
|
+
let hostname = "";
|
|
320
|
+
try {
|
|
321
|
+
const parsed2 = new URL(url);
|
|
322
|
+
host = parsed2.host;
|
|
323
|
+
hostname = parsed2.hostname;
|
|
324
|
+
} catch {
|
|
325
|
+
}
|
|
326
|
+
return patterns.some((p) => {
|
|
327
|
+
if (p instanceof RegExp) return p.test(url);
|
|
328
|
+
if (!p) return false;
|
|
329
|
+
if (p.includes("://")) return url.startsWith(p);
|
|
330
|
+
return host === p || hostname === p;
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/bodies.ts
|
|
335
|
+
import { ClientRequest, IncomingMessage, ServerResponse } from "http";
|
|
336
|
+
import { brotliDecompressSync, constants, gunzipSync, inflateSync } from "zlib";
|
|
337
|
+
var TAP = /* @__PURE__ */ Symbol.for("zharp.body");
|
|
338
|
+
var MAX_FIELDS = 200;
|
|
339
|
+
var Multipart = class {
|
|
340
|
+
constructor(boundary, maxText) {
|
|
341
|
+
this.maxText = maxText;
|
|
342
|
+
this.first = Buffer.from(`--${boundary}`);
|
|
343
|
+
this.delimiter = Buffer.from(`\r
|
|
344
|
+
--${boundary}`);
|
|
345
|
+
}
|
|
346
|
+
maxText;
|
|
347
|
+
buf = Buffer.alloc(0);
|
|
348
|
+
state = "start";
|
|
349
|
+
first;
|
|
350
|
+
delimiter;
|
|
351
|
+
part = null;
|
|
352
|
+
count = 0;
|
|
353
|
+
fields = {};
|
|
354
|
+
cut = false;
|
|
355
|
+
push(chunk) {
|
|
356
|
+
if (this.state === "done") return;
|
|
357
|
+
this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;
|
|
358
|
+
for (; ; ) {
|
|
359
|
+
if (this.state === "start") {
|
|
360
|
+
const i = this.buf.indexOf(this.first);
|
|
361
|
+
if (i < 0) {
|
|
362
|
+
if (this.buf.length > 64 * 1024) this.state = "done";
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
this.buf = this.buf.subarray(i + this.first.length);
|
|
366
|
+
this.state = "after";
|
|
367
|
+
}
|
|
368
|
+
if (this.state === "after") {
|
|
369
|
+
if (this.buf.length < 2) return;
|
|
370
|
+
if (this.buf[0] === 45 && this.buf[1] === 45) {
|
|
371
|
+
this.state = "done";
|
|
372
|
+
this.buf = Buffer.alloc(0);
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
if (this.buf[0] === 13 && this.buf[1] === 10) this.buf = this.buf.subarray(2);
|
|
376
|
+
this.state = "headers";
|
|
377
|
+
}
|
|
378
|
+
if (this.state === "headers") {
|
|
379
|
+
const i = this.buf.indexOf("\r\n\r\n");
|
|
380
|
+
if (i < 0) {
|
|
381
|
+
if (this.buf.length > 16 * 1024) this.state = "done";
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
this.part = parsePartHeaders(this.buf.subarray(0, i).toString("utf8"));
|
|
385
|
+
this.buf = this.buf.subarray(i + 4);
|
|
386
|
+
this.state = "body";
|
|
387
|
+
}
|
|
388
|
+
if (this.state === "body") {
|
|
389
|
+
const i = this.buf.indexOf(this.delimiter);
|
|
390
|
+
if (i >= 0) {
|
|
391
|
+
this.consume(this.buf.subarray(0, i));
|
|
392
|
+
this.finish(false);
|
|
393
|
+
this.buf = this.buf.subarray(i + this.delimiter.length);
|
|
394
|
+
this.state = "after";
|
|
395
|
+
if (this.count >= MAX_FIELDS) {
|
|
396
|
+
this.state = "done";
|
|
397
|
+
this.cut = true;
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
const keep = this.delimiter.length - 1;
|
|
403
|
+
if (this.buf.length > keep) {
|
|
404
|
+
this.consume(this.buf.subarray(0, this.buf.length - keep));
|
|
405
|
+
this.buf = Buffer.from(this.buf.subarray(this.buf.length - keep));
|
|
406
|
+
}
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
consume(bytes) {
|
|
413
|
+
const part = this.part;
|
|
414
|
+
if (!part || !bytes.length) return;
|
|
415
|
+
part.size += bytes.length;
|
|
416
|
+
if (part.filename !== void 0) return;
|
|
417
|
+
const room = this.maxText - part.kept;
|
|
418
|
+
if (room > 0) {
|
|
419
|
+
const slice = bytes.subarray(0, room);
|
|
420
|
+
part.text.push(Buffer.from(slice));
|
|
421
|
+
part.kept += slice.length;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
finish(partial) {
|
|
425
|
+
const part = this.part;
|
|
426
|
+
this.part = null;
|
|
427
|
+
if (!part) return;
|
|
428
|
+
let value;
|
|
429
|
+
if (part.filename !== void 0) value = fileLabel(part.filename, part.type, part.size, partial);
|
|
430
|
+
else {
|
|
431
|
+
value = Buffer.concat(part.text).toString("utf8").replace(/�$/, "");
|
|
432
|
+
if (part.size > part.kept || partial) this.cut = true;
|
|
433
|
+
}
|
|
434
|
+
const existing = this.fields[part.name];
|
|
435
|
+
this.fields[part.name] = existing === void 0 ? value : Array.isArray(existing) ? [...existing, value] : [existing, value];
|
|
436
|
+
this.count++;
|
|
437
|
+
}
|
|
438
|
+
/** The fields so far, including a part the stream stopped inside. */
|
|
439
|
+
result() {
|
|
440
|
+
if (this.part) {
|
|
441
|
+
this.consume(this.state === "body" ? this.buf : Buffer.alloc(0));
|
|
442
|
+
this.buf = Buffer.alloc(0);
|
|
443
|
+
this.finish(true);
|
|
444
|
+
this.cut = true;
|
|
445
|
+
}
|
|
446
|
+
return { json: JSON.stringify(this.fields), cut: this.cut };
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
function parsePartHeaders(head) {
|
|
450
|
+
const disposition = /^content-disposition:(.*)$/im.exec(head)?.[1] ?? "";
|
|
451
|
+
const name = /\bname="([^"]*)"/i.exec(disposition)?.[1] ?? /\bname=([^;\s]+)/i.exec(disposition)?.[1] ?? "";
|
|
452
|
+
const filenameStar = /\bfilename\*=(?:UTF-8'')?([^;\s]+)/i.exec(disposition)?.[1];
|
|
453
|
+
let filename = /\bfilename="([^"]*)"/i.exec(disposition)?.[1];
|
|
454
|
+
if (filenameStar) {
|
|
455
|
+
try {
|
|
456
|
+
filename = decodeURIComponent(filenameStar);
|
|
457
|
+
} catch {
|
|
458
|
+
filename = filenameStar;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const type = /^content-type:\s*(.*)$/im.exec(head)?.[1]?.trim();
|
|
462
|
+
return { name, filename, type: filename !== void 0 ? type : void 0, size: 0, text: [], kept: 0 };
|
|
463
|
+
}
|
|
464
|
+
function boundaryOf(contentType) {
|
|
465
|
+
const m = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType ?? "");
|
|
466
|
+
return m ? m[1] ?? m[2] : void 0;
|
|
467
|
+
}
|
|
468
|
+
var Tap = class {
|
|
469
|
+
/** `typeOf` is asked once, at the first byte, when the content type is surely set. */
|
|
470
|
+
constructor(settings, typeOf2) {
|
|
471
|
+
this.settings = settings;
|
|
472
|
+
this.typeOf = typeOf2;
|
|
473
|
+
}
|
|
474
|
+
settings;
|
|
475
|
+
typeOf;
|
|
476
|
+
chunks = [];
|
|
477
|
+
kept = 0;
|
|
478
|
+
/** Every byte seen, kept or not. */
|
|
479
|
+
total = 0;
|
|
480
|
+
cut = false;
|
|
481
|
+
mode;
|
|
482
|
+
multipart;
|
|
483
|
+
add(chunk, encoding) {
|
|
484
|
+
if (chunk == null || typeof chunk === "function") return;
|
|
485
|
+
let buf;
|
|
486
|
+
if (typeof chunk === "string") buf = Buffer.from(chunk, typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8");
|
|
487
|
+
else if (chunk instanceof Uint8Array) buf = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
488
|
+
else return;
|
|
489
|
+
if (!buf.length) return;
|
|
490
|
+
this.total += buf.length;
|
|
491
|
+
if (this.mode === void 0) {
|
|
492
|
+
const type = this.typeOf();
|
|
493
|
+
const boundary = isMultipart(type) ? boundaryOf(type) : void 0;
|
|
494
|
+
if (boundary) {
|
|
495
|
+
this.mode = "multipart";
|
|
496
|
+
this.multipart = new Multipart(boundary, this.settings.maxSize);
|
|
497
|
+
} else this.mode = isTextual(type) ? "text" : "count";
|
|
498
|
+
}
|
|
499
|
+
if (this.mode === "multipart") return this.multipart.push(Buffer.from(buf));
|
|
500
|
+
if (this.mode === "count" || this.cut) return;
|
|
501
|
+
const room = rawLimit(this.settings) - this.kept;
|
|
502
|
+
if (buf.length > room) {
|
|
503
|
+
this.cut = true;
|
|
504
|
+
buf = buf.subarray(0, Math.max(0, room));
|
|
505
|
+
}
|
|
506
|
+
if (buf.length) {
|
|
507
|
+
this.chunks.push(Buffer.from(buf));
|
|
508
|
+
this.kept += buf.length;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/** The text, inflated if it was compressed; null when it cannot be read as text. */
|
|
512
|
+
text(encoding) {
|
|
513
|
+
let raw = Buffer.concat(this.chunks);
|
|
514
|
+
const enc = (encoding ?? "").toLowerCase().trim();
|
|
515
|
+
try {
|
|
516
|
+
const flush = { finishFlush: constants.Z_SYNC_FLUSH };
|
|
517
|
+
if (enc === "gzip" || enc === "x-gzip") raw = gunzipSync(raw, flush);
|
|
518
|
+
else if (enc === "deflate") raw = inflateSync(raw, flush);
|
|
519
|
+
else if (enc === "br") raw = brotliDecompressSync(raw, { finishFlush: constants.BROTLI_OPERATION_FLUSH });
|
|
520
|
+
else if (enc && enc !== "identity") return null;
|
|
521
|
+
} catch {
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
return raw.toString("utf8").replace(/�$/, "");
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
function sideAttributes(side, tap, type, encoding, settings) {
|
|
528
|
+
if (!tap || !tap.total) return {};
|
|
529
|
+
if (tap.multipart) {
|
|
530
|
+
const { json, cut } = tap.multipart.result();
|
|
531
|
+
return bodyAttributes(side, json, type, settings, cut);
|
|
532
|
+
}
|
|
533
|
+
if (!isTextual(type)) return describedAttributes(side, type, tap.total);
|
|
534
|
+
const text = tap.text(encoding);
|
|
535
|
+
if (text == null) return describedAttributes(side, type, tap.total);
|
|
536
|
+
return bodyAttributes(side, text, type, settings, tap.cut);
|
|
537
|
+
}
|
|
538
|
+
function tapReadable(stream, tap) {
|
|
539
|
+
const emit = stream.emit;
|
|
540
|
+
stream.emit = function(event, ...args) {
|
|
541
|
+
if (event === "data") {
|
|
542
|
+
try {
|
|
543
|
+
tap.add(args[0]);
|
|
544
|
+
} catch {
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return emit.call(this, event, ...args);
|
|
548
|
+
};
|
|
549
|
+
stream[TAP] = tap;
|
|
550
|
+
}
|
|
551
|
+
function tapWritable(stream, tap) {
|
|
552
|
+
const target = stream;
|
|
553
|
+
const write = target.write;
|
|
554
|
+
const end = target.end;
|
|
555
|
+
target.write = function(...args) {
|
|
556
|
+
try {
|
|
557
|
+
tap.add(args[0], args[1]);
|
|
558
|
+
} catch {
|
|
559
|
+
}
|
|
560
|
+
return write.apply(this, args);
|
|
561
|
+
};
|
|
562
|
+
target.end = function(...args) {
|
|
563
|
+
try {
|
|
564
|
+
tap.add(args[0], args[1]);
|
|
565
|
+
} catch {
|
|
566
|
+
}
|
|
567
|
+
return end.apply(this, args);
|
|
568
|
+
};
|
|
569
|
+
stream[TAP] = tap;
|
|
570
|
+
}
|
|
571
|
+
var tapOf = (stream) => stream?.[TAP];
|
|
572
|
+
function header(value) {
|
|
573
|
+
if (value == null) return void 0;
|
|
574
|
+
return Array.isArray(value) ? String(value[0]) : String(value);
|
|
575
|
+
}
|
|
576
|
+
function incomingUrl(req) {
|
|
577
|
+
const proto = req.socket?.encrypted ? "https" : "http";
|
|
578
|
+
return `${proto}://${req.headers.host ?? "localhost"}${req.url ?? "/"}`;
|
|
579
|
+
}
|
|
580
|
+
function sentHeader(res, name) {
|
|
581
|
+
const set = header(res.getHeader(name));
|
|
582
|
+
if (set) return set;
|
|
583
|
+
const head = res._header;
|
|
584
|
+
if (typeof head !== "string") return void 0;
|
|
585
|
+
const match = head.match(new RegExp(`^${name}:[ \\t]*(.*)$`, "im"));
|
|
586
|
+
return match ? match[1].trim() : void 0;
|
|
587
|
+
}
|
|
588
|
+
function outgoingUrl(req) {
|
|
589
|
+
const r = req;
|
|
590
|
+
return `${r.protocol ?? "http:"}//${r.host ?? "localhost"}${r.path ?? "/"}`;
|
|
591
|
+
}
|
|
592
|
+
function withBodyCapture(settings, config = {}) {
|
|
593
|
+
const allowed = (url) => !settings.urls || urlMatches(url, settings.urls);
|
|
594
|
+
return {
|
|
595
|
+
...config,
|
|
596
|
+
requestHook(span, request) {
|
|
597
|
+
config.requestHook?.(span, request);
|
|
598
|
+
try {
|
|
599
|
+
if (request instanceof IncomingMessage) {
|
|
600
|
+
if (allowed(incomingUrl(request))) tapReadable(request, new Tap(settings, () => header(request.headers["content-type"])));
|
|
601
|
+
} else if (request instanceof ClientRequest) {
|
|
602
|
+
if (allowed(outgoingUrl(request))) tapWritable(request, new Tap(settings, () => header(request.getHeader("content-type"))));
|
|
603
|
+
}
|
|
604
|
+
} catch {
|
|
605
|
+
}
|
|
606
|
+
},
|
|
607
|
+
responseHook(span, response) {
|
|
608
|
+
config.responseHook?.(span, response);
|
|
609
|
+
try {
|
|
610
|
+
if (response instanceof ServerResponse) {
|
|
611
|
+
if (tapOf(response.req) || allowed(incomingUrl(response.req))) tapWritable(response, new Tap(settings, () => sentHeader(response, "content-type")));
|
|
612
|
+
} else if (response instanceof IncomingMessage) {
|
|
613
|
+
const req = response.req;
|
|
614
|
+
if (!req || tapOf(req) || allowed(outgoingUrl(req))) tapReadable(response, new Tap(settings, () => header(response.headers["content-type"])));
|
|
615
|
+
}
|
|
616
|
+
} catch {
|
|
617
|
+
}
|
|
618
|
+
},
|
|
619
|
+
applyCustomAttributesOnSpan(span, request, response) {
|
|
620
|
+
config.applyCustomAttributesOnSpan?.(span, request, response);
|
|
621
|
+
try {
|
|
622
|
+
const status = Number(response?.statusCode) || 0;
|
|
623
|
+
if (!wanted(settings, status)) return;
|
|
624
|
+
const attributes = {};
|
|
625
|
+
if (request instanceof ClientRequest) {
|
|
626
|
+
Object.assign(
|
|
627
|
+
attributes,
|
|
628
|
+
sideAttributes("request", tapOf(request), header(request.getHeader("content-type")), header(request.getHeader("content-encoding")), settings)
|
|
629
|
+
);
|
|
630
|
+
const res = response;
|
|
631
|
+
Object.assign(
|
|
632
|
+
attributes,
|
|
633
|
+
sideAttributes("response", tapOf(res), header(res?.headers?.["content-type"]), header(res?.headers?.["content-encoding"]), settings)
|
|
634
|
+
);
|
|
635
|
+
} else if (request instanceof IncomingMessage) {
|
|
636
|
+
const sentType = header(request.headers["content-type"]);
|
|
637
|
+
const sent = tapOf(request);
|
|
638
|
+
if (sent && sent.total) {
|
|
639
|
+
Object.assign(attributes, sideAttributes("request", sent, sentType, header(request.headers["content-encoding"]), settings));
|
|
640
|
+
} else {
|
|
641
|
+
const parsed2 = request.body;
|
|
642
|
+
if (parsed2 != null && (typeof parsed2 === "string" || typeof parsed2 === "object" && !Buffer.isBuffer(parsed2))) {
|
|
643
|
+
const text = typeof parsed2 === "string" ? parsed2 : JSON.stringify(parsed2);
|
|
644
|
+
Object.assign(attributes, bodyAttributes("request", text, isTextual(sentType) ? sentType : "application/json", settings));
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
const res = response;
|
|
648
|
+
Object.assign(attributes, sideAttributes("response", tapOf(res), sentHeader(res, "content-type"), sentHeader(res, "content-encoding"), settings));
|
|
649
|
+
}
|
|
650
|
+
if (Object.keys(attributes).length) span.setAttributes(attributes);
|
|
651
|
+
} catch {
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// src/urls.ts
|
|
658
|
+
var URL_KEYS = ["url.full", "http.url", "http.target"];
|
|
659
|
+
var UrlRedactionSpanProcessor = class {
|
|
660
|
+
onStart() {
|
|
661
|
+
}
|
|
662
|
+
onEnding(span) {
|
|
663
|
+
try {
|
|
664
|
+
const attributes = span.attributes ?? {};
|
|
665
|
+
for (const key of URL_KEYS) {
|
|
666
|
+
const value = attributes[key];
|
|
667
|
+
if (typeof value === "string") {
|
|
668
|
+
const redacted = redactUrl(value);
|
|
669
|
+
if (redacted !== value) span.setAttribute(key, redacted);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
const query = attributes["url.query"];
|
|
673
|
+
if (typeof query === "string") {
|
|
674
|
+
const bare = query.startsWith("?") ? query.slice(1) : query;
|
|
675
|
+
const redacted = redactQuery(bare);
|
|
676
|
+
if (redacted !== bare) span.setAttribute("url.query", (query.startsWith("?") ? "?" : "") + redacted);
|
|
677
|
+
}
|
|
678
|
+
} catch {
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
onEnd(_span) {
|
|
682
|
+
}
|
|
683
|
+
forceFlush() {
|
|
684
|
+
return Promise.resolve();
|
|
685
|
+
}
|
|
686
|
+
shutdown() {
|
|
687
|
+
return Promise.resolve();
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
|
|
95
691
|
// src/context.ts
|
|
96
692
|
import { context as otelContext, propagation, trace } from "@opentelemetry/api";
|
|
97
693
|
var BAGGAGE_KEYS = ["enduser.id", "session.id"];
|
|
@@ -386,7 +982,7 @@ Caused by: ${cause.stack}`;
|
|
|
386
982
|
}
|
|
387
983
|
|
|
388
984
|
// src/version.ts
|
|
389
|
-
var VERSION = "0.
|
|
985
|
+
var VERSION = "0.2.0";
|
|
390
986
|
|
|
391
987
|
// src/zharp.ts
|
|
392
988
|
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
@@ -459,6 +1055,7 @@ var ZharpNode = class {
|
|
|
459
1055
|
const exporterOptions = { headers, compression: "gzip" };
|
|
460
1056
|
this.spanProcessors = tracing ? [
|
|
461
1057
|
new ContextSpanProcessor(this.store),
|
|
1058
|
+
new UrlRedactionSpanProcessor(),
|
|
462
1059
|
new DebugIdSpanProcessor(),
|
|
463
1060
|
new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
|
|
464
1061
|
] : [new ContextSpanProcessor(this.store)];
|
|
@@ -480,6 +1077,7 @@ var ZharpNode = class {
|
|
|
480
1077
|
const propagator = new CompositePropagator({
|
|
481
1078
|
propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()]
|
|
482
1079
|
});
|
|
1080
|
+
const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
|
|
483
1081
|
const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
484
1082
|
this.sdk = new NodeSDK({
|
|
485
1083
|
resource,
|
|
@@ -498,7 +1096,10 @@ var ZharpNode = class {
|
|
|
498
1096
|
"@opentelemetry/instrumentation-dns": { enabled: false },
|
|
499
1097
|
"@opentelemetry/instrumentation-net": { enabled: false },
|
|
500
1098
|
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
501
|
-
...options.instrumentations
|
|
1099
|
+
...options.instrumentations,
|
|
1100
|
+
...bodies && {
|
|
1101
|
+
"@opentelemetry/instrumentation-http": withBodyCapture(bodies, options.instrumentations?.["@opentelemetry/instrumentation-http"])
|
|
1102
|
+
}
|
|
502
1103
|
}) : logsOnlyInstrumentations(options),
|
|
503
1104
|
...options.extraInstrumentations ?? []
|
|
504
1105
|
]
|