midline-agent 0.3.0 → 0.4.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.
Files changed (41) hide show
  1. package/README.md +89 -4
  2. package/browser/package.json +8 -0
  3. package/dist/browser/client.d.ts +59 -0
  4. package/dist/browser/client.js +608 -0
  5. package/dist/browser/index.d.ts +34 -0
  6. package/dist/browser/index.js +65 -0
  7. package/dist/browser/instrument.d.ts +39 -0
  8. package/dist/browser/instrument.js +217 -0
  9. package/dist/browser/transport.d.ts +43 -0
  10. package/dist/browser/transport.js +168 -0
  11. package/dist/browser/types.d.ts +94 -0
  12. package/dist/browser/types.js +2 -0
  13. package/dist/browser/version.d.ts +2 -0
  14. package/dist/browser/version.js +5 -0
  15. package/dist/browser/vitals.d.ts +16 -0
  16. package/dist/browser/vitals.js +135 -0
  17. package/dist/cli.js +0 -0
  18. package/dist/esm/browser/client.js +601 -0
  19. package/dist/esm/browser/index.js +52 -0
  20. package/dist/esm/browser/instrument.js +210 -0
  21. package/dist/esm/browser/transport.js +164 -0
  22. package/dist/esm/browser/types.js +1 -0
  23. package/dist/esm/browser/version.js +2 -0
  24. package/dist/esm/browser/vitals.js +132 -0
  25. package/dist/esm/package.json +1 -0
  26. package/dist/esm/redact.js +224 -0
  27. package/dist/esm/types.js +1 -0
  28. package/dist/redact.d.ts +3 -0
  29. package/dist/redact.js +12 -6
  30. package/package.json +27 -4
  31. package/scripts/mark-esm.js +6 -0
  32. package/src/browser/client.ts +686 -0
  33. package/src/browser/index.ts +74 -0
  34. package/src/browser/instrument.ts +275 -0
  35. package/src/browser/transport.ts +184 -0
  36. package/src/browser/types.ts +105 -0
  37. package/src/browser/version.ts +2 -0
  38. package/src/browser/vitals.ts +149 -0
  39. package/src/redact.ts +12 -6
  40. package/test/browser.test.js +328 -0
  41. package/tsconfig.esm.json +14 -0
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Shared by the Node agent and the browser SDK, so nothing here may touch a
3
+ * Node-only global (Buffer, process) — TextEncoder and URLSearchParams exist in both.
4
+ *
5
+ * Redaction happens in the host process, before an event is queued. Whatever is
6
+ * removed here never reaches a socket, a log line or the Midline server.
7
+ *
8
+ * Matching is on a normalised key — lower-cased with punctuation stripped — so
9
+ * `X-API-Key`, `api_key` and `apiKey` are all the same key.
10
+ */
11
+ export const REDACTED = "[REDACTED]";
12
+ /** Substrings: any key containing one of these is sensitive. */
13
+ const SENSITIVE_KEY_PARTS = [
14
+ "password",
15
+ "passwd",
16
+ "passphrase",
17
+ "secret",
18
+ "token",
19
+ "apikey",
20
+ "accesskey",
21
+ "privatekey",
22
+ "authorization",
23
+ "cookie",
24
+ "session",
25
+ "credential",
26
+ "csrf",
27
+ "xsrf",
28
+ "signature",
29
+ "creditcard",
30
+ "cardnumber",
31
+ "cvv",
32
+ "cvc",
33
+ "ssn",
34
+ "socialsecurity",
35
+ ];
36
+ /** Whole keys only — as substrings these would hit words like "author" or "spinner". */
37
+ const SENSITIVE_KEYS_EXACT = new Set(["auth", "pwd", "pin", "otp", "sid", "jwt", "bearer"]);
38
+ /** Always redacted by name, even if a user-supplied list somehow unmatched them. */
39
+ export const DEFAULT_SENSITIVE_HEADERS = [
40
+ "authorization",
41
+ "proxy-authorization",
42
+ "cookie",
43
+ "set-cookie",
44
+ "x-api-key",
45
+ "api-key",
46
+ "x-auth-token",
47
+ "x-access-token",
48
+ "x-refresh-token",
49
+ "x-csrf-token",
50
+ "x-xsrf-token",
51
+ "x-amz-security-token",
52
+ ];
53
+ const VALUE_PATTERNS = [
54
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, REDACTED],
55
+ [/\b(Bearer|Basic|Digest|Token)\s+[A-Za-z0-9._~+\/=-]{8,}/gi, `$1 ${REDACTED}`],
56
+ [/\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g, REDACTED],
57
+ [/\bak_[A-Fa-f0-9]{16,}\b/g, REDACTED],
58
+ [/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,}\b/g, REDACTED],
59
+ [/\bAKIA[0-9A-Z]{16}\b/g, REDACTED],
60
+ [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s\/@:]+:[^\s\/@]+@/gi, `$1${REDACTED}@`],
61
+ ];
62
+ /** `key=value` / `key: value` in query strings, log lines and error messages. */
63
+ const KEY_VALUE_PAIR = /(^|[?&;,\s(\[{])([A-Za-z0-9_.%-]{1,64})(\s*[=:]\s*)("[^"]*"|'[^']*'|[^\s&#,;)\]}]+)/g;
64
+ /** `"key": value` in JSON text, including JSON that was cut off mid-value. */
65
+ const JSON_PAIR = /"([^"\\]{1,100})"\s*:\s*("(?:[^"\\]|\\.)*"?|-?\d+(?:\.\d+)?|true|false|null)/g;
66
+ export function normalizeKey(key) {
67
+ return key.toLowerCase().replace(/[^a-z0-9]/g, "");
68
+ }
69
+ export class Redactor {
70
+ constructor(extraFields = [], extraHeaders = []) {
71
+ this.extraKeys = extraFields.map(normalizeKey).filter(Boolean);
72
+ this.headerNames = new Set([...DEFAULT_SENSITIVE_HEADERS, ...extraHeaders].map((name) => name.toLowerCase()));
73
+ }
74
+ isSensitiveKey(key) {
75
+ const normalized = normalizeKey(key);
76
+ if (!normalized)
77
+ return false;
78
+ if (SENSITIVE_KEYS_EXACT.has(normalized))
79
+ return true;
80
+ if (SENSITIVE_KEY_PARTS.some((part) => normalized.includes(part)))
81
+ return true;
82
+ return this.extraKeys.some((part) => normalized.includes(part));
83
+ }
84
+ /** Masks credentials embedded in free text: bearer tokens, JWTs, key formats, URL userinfo and query params. */
85
+ string(value, maxLength = 2048) {
86
+ let out = value.length > maxLength * 4 ? value.slice(0, maxLength * 4) : value;
87
+ for (const [pattern, replacement] of VALUE_PATTERNS) {
88
+ out = out.replace(pattern, replacement);
89
+ }
90
+ if (out.includes("=") || out.includes(":")) {
91
+ out = out.replace(KEY_VALUE_PAIR, (match, sep, key, delimiter) => {
92
+ let decoded = key;
93
+ try {
94
+ decoded = decodeURIComponent(key);
95
+ }
96
+ catch {
97
+ // keep the raw key
98
+ }
99
+ return this.isSensitiveKey(decoded) ? `${sep}${key}${delimiter}${REDACTED}` : match;
100
+ });
101
+ }
102
+ if (out.includes('"')) {
103
+ out = out.replace(JSON_PAIR, (match, key) => this.isSensitiveKey(key) ? `"${key}":"${REDACTED}"` : match);
104
+ }
105
+ // The ellipsis counts toward the limit: servers validate these lengths exactly.
106
+ return out.length > maxLength ? `${out.slice(0, Math.max(0, maxLength - 1))}…` : out;
107
+ }
108
+ /** Deep copy with sensitive keys and values masked. Bounded in depth, breadth and string length. */
109
+ value(input, depth = 0, seen = new WeakSet()) {
110
+ if (input === null || input === undefined)
111
+ return input;
112
+ if (typeof input === "string")
113
+ return this.string(input);
114
+ if (typeof input === "number" || typeof input === "boolean")
115
+ return input;
116
+ if (typeof input === "bigint")
117
+ return input.toString();
118
+ if (typeof input === "function" || typeof input === "symbol")
119
+ return undefined;
120
+ if (input instanceof Date)
121
+ return Number.isNaN(input.getTime()) ? null : input.toISOString();
122
+ // Buffer is a Uint8Array, so this also covers it without naming a Node-only global.
123
+ if (ArrayBuffer.isView(input)) {
124
+ return `[Binary ${input.byteLength} bytes]`;
125
+ }
126
+ if (typeof input !== "object")
127
+ return undefined;
128
+ if (seen.has(input))
129
+ return "[Circular]";
130
+ if (depth >= 8)
131
+ return "[Truncated]";
132
+ seen.add(input);
133
+ if (Array.isArray(input)) {
134
+ const items = input.slice(0, 100).map((item) => this.value(item, depth + 1, seen));
135
+ if (input.length > 100)
136
+ items.push(`[${input.length - 100} more]`);
137
+ return items;
138
+ }
139
+ const out = {};
140
+ let count = 0;
141
+ for (const [key, nested] of Object.entries(input)) {
142
+ if (count++ >= 200) {
143
+ out["[truncated]"] = "too many keys";
144
+ break;
145
+ }
146
+ out[key] = this.isSensitiveKey(key) ? REDACTED : this.value(nested, depth + 1, seen);
147
+ }
148
+ return out;
149
+ }
150
+ headers(headers) {
151
+ if (!headers)
152
+ return undefined;
153
+ const out = {};
154
+ for (const [rawName, rawValue] of Object.entries(headers)) {
155
+ if (rawValue === undefined)
156
+ continue;
157
+ const name = rawName.toLowerCase();
158
+ if (this.headerNames.has(name) || this.isSensitiveKey(name)) {
159
+ out[name] = REDACTED;
160
+ continue;
161
+ }
162
+ const joined = Array.isArray(rawValue) ? rawValue.join(", ") : String(rawValue);
163
+ out[name] = this.string(joined, 1024);
164
+ }
165
+ return out;
166
+ }
167
+ query(search) {
168
+ if (!search)
169
+ return undefined;
170
+ const out = {};
171
+ const params = new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
172
+ for (const key of new Set(params.keys())) {
173
+ const values = params.getAll(key).map((value) => this.isSensitiveKey(key) ? REDACTED : this.string(value, 512));
174
+ out[key] = values.length === 1 ? values[0] : values;
175
+ }
176
+ return out;
177
+ }
178
+ /**
179
+ * Redacts a captured body. Structured content is parsed and redacted by key;
180
+ * text that cannot be parsed (usually because it was truncated) gets key/value
181
+ * pattern masking instead, so a cut-off JSON body still loses its passwords.
182
+ */
183
+ body(raw, contentType, maxBytes) {
184
+ if (raw === undefined || raw === null || maxBytes <= 0)
185
+ return {};
186
+ const type = (contentType || "").toLowerCase();
187
+ if (typeof raw === "object" && !ArrayBuffer.isView(raw)) {
188
+ return this.fit(this.value(raw), maxBytes);
189
+ }
190
+ const text = ArrayBuffer.isView(raw)
191
+ ? new TextDecoder().decode(raw)
192
+ : String(raw);
193
+ if (type.includes("json")) {
194
+ try {
195
+ return this.fit(this.value(JSON.parse(text)), maxBytes);
196
+ }
197
+ catch {
198
+ return this.cut(this.string(text, text.length), maxBytes);
199
+ }
200
+ }
201
+ if (type.includes("application/x-www-form-urlencoded")) {
202
+ return this.fit(this.query(text) ?? {}, maxBytes);
203
+ }
204
+ if (!type || type.startsWith("text/") || type.includes("xml") || type.includes("graphql")) {
205
+ return this.cut(this.string(text, maxBytes * 2), maxBytes);
206
+ }
207
+ return { omitted: `content-type ${type.split(";")[0]}` };
208
+ }
209
+ fit(value, maxBytes) {
210
+ const serialized = JSON.stringify(value) ?? "";
211
+ if (new TextEncoder().encode(serialized).length <= maxBytes) {
212
+ return { body: value };
213
+ }
214
+ return this.cut(serialized, maxBytes);
215
+ }
216
+ cut(text, maxBytes) {
217
+ const bytes = new TextEncoder().encode(text);
218
+ if (bytes.length <= maxBytes) {
219
+ return { body: text };
220
+ }
221
+ // Slicing bytes can split a multi-byte character; the replacement char is harmless here.
222
+ return { body: new TextDecoder().decode(bytes.subarray(0, maxBytes)), truncated: true };
223
+ }
224
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/redact.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  /**
2
+ * Shared by the Node agent and the browser SDK, so nothing here may touch a
3
+ * Node-only global (Buffer, process) — TextEncoder and URLSearchParams exist in both.
4
+ *
2
5
  * Redaction happens in the host process, before an event is queued. Whatever is
3
6
  * removed here never reaches a socket, a log line or the Midline server.
4
7
  *
package/dist/redact.js CHANGED
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
2
  /**
3
+ * Shared by the Node agent and the browser SDK, so nothing here may touch a
4
+ * Node-only global (Buffer, process) — TextEncoder and URLSearchParams exist in both.
5
+ *
3
6
  * Redaction happens in the host process, before an event is queued. Whatever is
4
7
  * removed here never reaches a socket, a log line or the Midline server.
5
8
  *
@@ -120,7 +123,8 @@ class Redactor {
120
123
  return undefined;
121
124
  if (input instanceof Date)
122
125
  return Number.isNaN(input.getTime()) ? null : input.toISOString();
123
- if (Buffer.isBuffer(input) || ArrayBuffer.isView(input)) {
126
+ // Buffer is a Uint8Array, so this also covers it without naming a Node-only global.
127
+ if (ArrayBuffer.isView(input)) {
124
128
  return `[Binary ${input.byteLength} bytes]`;
125
129
  }
126
130
  if (typeof input !== "object")
@@ -184,10 +188,12 @@ class Redactor {
184
188
  if (raw === undefined || raw === null || maxBytes <= 0)
185
189
  return {};
186
190
  const type = (contentType || "").toLowerCase();
187
- if (typeof raw === "object" && !Buffer.isBuffer(raw)) {
191
+ if (typeof raw === "object" && !ArrayBuffer.isView(raw)) {
188
192
  return this.fit(this.value(raw), maxBytes);
189
193
  }
190
- const text = Buffer.isBuffer(raw) ? raw.toString("utf8") : String(raw);
194
+ const text = ArrayBuffer.isView(raw)
195
+ ? new TextDecoder().decode(raw)
196
+ : String(raw);
191
197
  if (type.includes("json")) {
192
198
  try {
193
199
  return this.fit(this.value(JSON.parse(text)), maxBytes);
@@ -206,18 +212,18 @@ class Redactor {
206
212
  }
207
213
  fit(value, maxBytes) {
208
214
  const serialized = JSON.stringify(value) ?? "";
209
- if (Buffer.byteLength(serialized) <= maxBytes) {
215
+ if (new TextEncoder().encode(serialized).length <= maxBytes) {
210
216
  return { body: value };
211
217
  }
212
218
  return this.cut(serialized, maxBytes);
213
219
  }
214
220
  cut(text, maxBytes) {
215
- const bytes = Buffer.from(text);
221
+ const bytes = new TextEncoder().encode(text);
216
222
  if (bytes.length <= maxBytes) {
217
223
  return { body: text };
218
224
  }
219
225
  // Slicing bytes can split a multi-byte character; the replacement char is harmless here.
220
- return { body: bytes.subarray(0, maxBytes).toString("utf8"), truncated: true };
226
+ return { body: new TextDecoder().decode(bytes.subarray(0, maxBytes)), truncated: true };
221
227
  }
222
228
  }
223
229
  exports.Redactor = Redactor;
package/package.json CHANGED
@@ -1,9 +1,29 @@
1
1
  {
2
2
  "name": "midline-agent",
3
- "version": "0.3.0",
4
- "description": "Midline — request & error monitoring with security detection",
3
+ "version": "0.4.0",
4
+ "description": "Midline — request, error and security monitoring for Node, and error, network and Web Vitals monitoring for browsers",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./browser": {
13
+ "types": "./dist/browser/index.d.ts",
14
+ "import": "./dist/esm/browser/index.js",
15
+ "default": "./dist/browser/index.js"
16
+ },
17
+ "./package.json": "./package.json",
18
+ "./dist/*": "./dist/*"
19
+ },
20
+ "typesVersions": {
21
+ "*": {
22
+ "browser": [
23
+ "dist/browser/index.d.ts"
24
+ ]
25
+ }
26
+ },
7
27
  "bin": {
8
28
  "midline-agent": "dist/cli.js"
9
29
  },
@@ -11,7 +31,7 @@
11
31
  "node": ">=18"
12
32
  },
13
33
  "scripts": {
14
- "build": "tsc",
34
+ "build": "tsc && tsc -p tsconfig.esm.json && node scripts/mark-esm.js",
15
35
  "prepare": "npm run build",
16
36
  "clean": "rm -rf dist",
17
37
  "test": "npm run build && node --test test/*.test.js"
@@ -24,7 +44,10 @@
24
44
  "security",
25
45
  "request",
26
46
  "errors",
27
- "proxy"
47
+ "proxy",
48
+ "browser",
49
+ "web-vitals",
50
+ "frontend"
28
51
  ],
29
52
  "author": "Your Name",
30
53
  "license": "MIT",
@@ -0,0 +1,6 @@
1
+ // dist/esm holds the browser build as ES modules. Marking the folder as a module
2
+ // scope lets bundlers and Node treat those .js files as ESM without renaming them.
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+
6
+ fs.writeFileSync(path.join(__dirname, "..", "dist", "esm", "package.json"), '{ "type": "module" }\n');