devanvil 0.0.0-stage → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.ar.md +113 -0
- package/README.md +272 -2
- package/SECURITY.md +49 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +664 -0
- package/dist/core/contract-drift.d.ts +49 -0
- package/dist/core/contract-drift.js +312 -0
- package/dist/core/converters.d.ts +18 -0
- package/dist/core/converters.js +989 -0
- package/dist/core/cron.d.ts +33 -0
- package/dist/core/cron.js +309 -0
- package/dist/core/crypto.d.ts +59 -0
- package/dist/core/crypto.js +260 -0
- package/dist/core/curl.d.ts +17 -0
- package/dist/core/curl.js +174 -0
- package/dist/core/diff.d.ts +36 -0
- package/dist/core/diff.js +148 -0
- package/dist/core/encoding.d.ts +3 -0
- package/dist/core/encoding.js +143 -0
- package/dist/core/importers.d.ts +65 -0
- package/dist/core/importers.js +361 -0
- package/dist/core/jwt.d.ts +39 -0
- package/dist/core/jwt.js +269 -0
- package/dist/core/llm-tokens.d.ts +38 -0
- package/dist/core/llm-tokens.js +125 -0
- package/dist/core/log-analyzer.d.ts +30 -0
- package/dist/core/log-analyzer.js +155 -0
- package/dist/core/network.d.ts +72 -0
- package/dist/core/network.js +185 -0
- package/dist/core/oauth-protobuf.d.ts +74 -0
- package/dist/core/oauth-protobuf.js +396 -0
- package/dist/core/openapi.d.ts +27 -0
- package/dist/core/openapi.js +257 -0
- package/dist/core/pipeline.d.ts +28 -0
- package/dist/core/pipeline.js +154 -0
- package/dist/core/regex.d.ts +50 -0
- package/dist/core/regex.js +360 -0
- package/dist/core/runner.d.ts +53 -0
- package/dist/core/runner.js +250 -0
- package/dist/core/secrets.d.ts +87 -0
- package/dist/core/secrets.js +603 -0
- package/dist/core/security.d.ts +34 -0
- package/dist/core/security.js +301 -0
- package/dist/core/sql-explain.d.ts +50 -0
- package/dist/core/sql-explain.js +259 -0
- package/dist/core/tls.d.ts +44 -0
- package/dist/core/tls.js +169 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +31 -0
- package/dist/server/app.d.ts +31 -0
- package/dist/server/app.js +359 -0
- package/dist/server/http-proxy.d.ts +55 -0
- package/dist/server/http-proxy.js +373 -0
- package/dist/server/http-utils.d.ts +28 -0
- package/dist/server/http-utils.js +118 -0
- package/dist/server/load-tester.d.ts +53 -0
- package/dist/server/load-tester.js +137 -0
- package/dist/server/mcp.d.ts +35 -0
- package/dist/server/mcp.js +470 -0
- package/dist/server/mock-store.d.ts +38 -0
- package/dist/server/mock-store.js +238 -0
- package/dist/server/plugin-loader.d.ts +61 -0
- package/dist/server/plugin-loader.js +305 -0
- package/dist/server/recorder-store.d.ts +35 -0
- package/dist/server/recorder-store.js +147 -0
- package/dist/server/routes/network-routes.d.ts +3 -0
- package/dist/server/routes/network-routes.js +441 -0
- package/dist/server/routes/tools-routes.d.ts +3 -0
- package/dist/server/routes/tools-routes.js +299 -0
- package/dist/server/routes/workspace-routes.d.ts +3 -0
- package/dist/server/routes/workspace-routes.js +262 -0
- package/dist/server/webhook-store.d.ts +29 -0
- package/dist/server/webhook-store.js +100 -0
- package/dist/server/workspace-store.d.ts +91 -0
- package/dist/server/workspace-store.js +448 -0
- package/dist/server/ws-probe.d.ts +34 -0
- package/dist/server/ws-probe.js +291 -0
- package/dist/ui/app.js +290 -0
- package/dist/ui/favicon.svg +14 -0
- package/dist/ui/index.html +83 -0
- package/dist/ui/logo.png +0 -0
- package/dist/ui/styles.css +694 -0
- package/dist/ui/tools-data.js +719 -0
- package/dist/ui/tools-network.js +769 -0
- package/dist/ui/tools-ops.js +299 -0
- package/dist/ui/tools-pro.js +500 -0
- package/dist/ui/tools-security.js +397 -0
- package/dist/ui/tools-v12.js +765 -0
- package/dist/ui/tools-v13.js +321 -0
- package/dist/ui/tools-v20.js +563 -0
- package/dist/ui/tools-v21.js +411 -0
- package/package.json +75 -4
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { lookup } from 'node:dns/promises';
|
|
3
|
+
import { isIP } from 'node:net';
|
|
4
|
+
const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
5
|
+
export function isDangerousKey(key) {
|
|
6
|
+
return DANGEROUS_KEYS.has(key);
|
|
7
|
+
}
|
|
8
|
+
export const DEFAULT_MAX_BODY_BYTES = 2 * 1024 * 1024; // 2 MB
|
|
9
|
+
export const DEFAULT_MAX_DECOMPRESS_BYTES = 10 * 1024 * 1024; // 10 MB
|
|
10
|
+
/**
|
|
11
|
+
* Recursively clones plain data structures while stripping prototype-pollution keys.
|
|
12
|
+
*/
|
|
13
|
+
export function sanitizeObject(value, maxDepth = 64, depth = 0) {
|
|
14
|
+
if (depth > maxDepth) {
|
|
15
|
+
throw new Error(`Maximum nesting depth (${maxDepth}) exceeded`);
|
|
16
|
+
}
|
|
17
|
+
if (value === null || typeof value !== 'object') {
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
if (Array.isArray(value)) {
|
|
21
|
+
return value.map((item) => sanitizeObject(item, maxDepth, depth + 1));
|
|
22
|
+
}
|
|
23
|
+
const clean = Object.create(null);
|
|
24
|
+
for (const [key, val] of Object.entries(value)) {
|
|
25
|
+
if (DANGEROUS_KEYS.has(key))
|
|
26
|
+
continue;
|
|
27
|
+
clean[key] = sanitizeObject(val, maxDepth, depth + 1);
|
|
28
|
+
}
|
|
29
|
+
return Object.assign({}, clean);
|
|
30
|
+
}
|
|
31
|
+
export function safeJsonParse(input, maxBytes = DEFAULT_MAX_BODY_BYTES) {
|
|
32
|
+
if (Buffer.byteLength(input, 'utf8') > maxBytes) {
|
|
33
|
+
throw new Error(`Input exceeds maximum allowed size (${maxBytes} bytes)`);
|
|
34
|
+
}
|
|
35
|
+
const parsed = JSON.parse(input);
|
|
36
|
+
return sanitizeObject(parsed);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Constant-time string comparison that hides both content and length differences.
|
|
40
|
+
*/
|
|
41
|
+
export function timingSafeEqualStr(a, b) {
|
|
42
|
+
const hashA = createHash('sha256').update(a, 'utf8').digest();
|
|
43
|
+
const hashB = createHash('sha256').update(b, 'utf8').digest();
|
|
44
|
+
return timingSafeEqual(hashA, hashB) && a.length === b.length;
|
|
45
|
+
}
|
|
46
|
+
export function escapeHtml(input) {
|
|
47
|
+
return input
|
|
48
|
+
.replace(/&/g, '&')
|
|
49
|
+
.replace(/</g, '<')
|
|
50
|
+
.replace(/>/g, '>')
|
|
51
|
+
.replace(/"/g, '"')
|
|
52
|
+
.replace(/'/g, ''');
|
|
53
|
+
}
|
|
54
|
+
export function assertSafeChannelName(channel) {
|
|
55
|
+
const trimmed = channel.trim();
|
|
56
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(trimmed)) {
|
|
57
|
+
throw new Error('Channel name must be 1-64 characters using only letters, numbers, hyphens, or underscores');
|
|
58
|
+
}
|
|
59
|
+
return trimmed;
|
|
60
|
+
}
|
|
61
|
+
function parseIpv4ToInt(ip) {
|
|
62
|
+
const parts = ip.split('.');
|
|
63
|
+
if (parts.length !== 4)
|
|
64
|
+
return null;
|
|
65
|
+
let result = 0;
|
|
66
|
+
for (const part of parts) {
|
|
67
|
+
if (!/^\d{1,3}$/.test(part))
|
|
68
|
+
return null;
|
|
69
|
+
const num = Number(part);
|
|
70
|
+
if (num < 0 || num > 255)
|
|
71
|
+
return null;
|
|
72
|
+
result = ((result << 8) | num) >>> 0;
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
function isPrivateIpv4Int(ipInt) {
|
|
77
|
+
const a = (ipInt >>> 24) & 0xff;
|
|
78
|
+
const b = (ipInt >>> 16) & 0xff;
|
|
79
|
+
// 0.0.0.0/8 (unspecified / current network)
|
|
80
|
+
if (a === 0)
|
|
81
|
+
return true;
|
|
82
|
+
// 10.0.0.0/8 (RFC1918)
|
|
83
|
+
if (a === 10)
|
|
84
|
+
return true;
|
|
85
|
+
// 100.64.0.0/10 (CGNAT / Shared Address Space)
|
|
86
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
87
|
+
return true;
|
|
88
|
+
// 127.0.0.0/8 (Loopback)
|
|
89
|
+
if (a === 127)
|
|
90
|
+
return true;
|
|
91
|
+
// 169.254.0.0/16 (Link-local & Cloud metadata 169.254.169.254)
|
|
92
|
+
if (a === 169 && b === 254)
|
|
93
|
+
return true;
|
|
94
|
+
// 172.16.0.0/12 (RFC1918)
|
|
95
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
96
|
+
return true;
|
|
97
|
+
// 192.0.0.0/24 (IETF protocol assignments)
|
|
98
|
+
if (a === 192 && b === 0 && ((ipInt >>> 8) & 0xff) === 0)
|
|
99
|
+
return true;
|
|
100
|
+
// 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24 (TEST-NET-1/2/3)
|
|
101
|
+
if (a === 192 && b === 0 && ((ipInt >>> 8) & 0xff) === 2)
|
|
102
|
+
return true;
|
|
103
|
+
if (a === 198 && b === 51 && ((ipInt >>> 8) & 0xff) === 100)
|
|
104
|
+
return true;
|
|
105
|
+
if (a === 203 && b === 0 && ((ipInt >>> 8) & 0xff) === 113)
|
|
106
|
+
return true;
|
|
107
|
+
// 192.168.0.0/16 (RFC1918)
|
|
108
|
+
if (a === 192 && b === 168)
|
|
109
|
+
return true;
|
|
110
|
+
// 198.18.0.0/15 (Benchmarking)
|
|
111
|
+
if (a === 198 && (b === 18 || b === 19))
|
|
112
|
+
return true;
|
|
113
|
+
// 224.0.0.0/4 (Multicast) & 240.0.0.0/4 (Reserved / Broadcast 255.255.255.255)
|
|
114
|
+
if (a >= 224)
|
|
115
|
+
return true;
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
function expandIpv6(ip) {
|
|
119
|
+
const cleaned = ip.toLowerCase().split('%')[0] ?? '';
|
|
120
|
+
// Check IPv4-embedded tail e.g. ::ffff:127.0.0.1
|
|
121
|
+
let working = cleaned;
|
|
122
|
+
const lastColon = working.lastIndexOf(':');
|
|
123
|
+
if (lastColon !== -1 && working.slice(lastColon + 1).includes('.')) {
|
|
124
|
+
const v4Part = working.slice(lastColon + 1);
|
|
125
|
+
const v4Int = parseIpv4ToInt(v4Part);
|
|
126
|
+
if (v4Int === null)
|
|
127
|
+
return null;
|
|
128
|
+
const hi = ((v4Int >>> 16) & 0xffff).toString(16);
|
|
129
|
+
const lo = (v4Int & 0xffff).toString(16);
|
|
130
|
+
working = `${working.slice(0, lastColon)}:${hi}:${lo}`;
|
|
131
|
+
}
|
|
132
|
+
const halves = working.split('::');
|
|
133
|
+
if (halves.length > 2)
|
|
134
|
+
return null;
|
|
135
|
+
const left = halves[0] ? halves[0].split(':').filter(Boolean) : [];
|
|
136
|
+
const right = halves.length === 2 && halves[1] ? halves[1].split(':').filter(Boolean) : [];
|
|
137
|
+
const missing = halves.length === 2 ? 8 - (left.length + right.length) : 0;
|
|
138
|
+
if (missing < 0 || (halves.length === 1 && left.length !== 8))
|
|
139
|
+
return null;
|
|
140
|
+
const groups = [...left, ...Array(missing).fill('0'), ...right];
|
|
141
|
+
if (groups.length !== 8)
|
|
142
|
+
return null;
|
|
143
|
+
const nums = [];
|
|
144
|
+
for (const g of groups) {
|
|
145
|
+
if (!/^[0-9a-f]{1,4}$/.test(g))
|
|
146
|
+
return null;
|
|
147
|
+
nums.push(parseInt(g, 16));
|
|
148
|
+
}
|
|
149
|
+
return nums;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Checks whether an IPv4 or IPv6 address belongs to a private, loopback,
|
|
153
|
+
* link-local, metadata, multicast, or reserved network range.
|
|
154
|
+
*/
|
|
155
|
+
export function isPrivateIp(rawIp) {
|
|
156
|
+
const ip = rawIp.trim().replace(/^\[|\]$/g, '');
|
|
157
|
+
const version = isIP(ip);
|
|
158
|
+
if (version === 4) {
|
|
159
|
+
const v4 = parseIpv4ToInt(ip);
|
|
160
|
+
return v4 === null ? true : isPrivateIpv4Int(v4);
|
|
161
|
+
}
|
|
162
|
+
if (version === 6) {
|
|
163
|
+
const groups = expandIpv6(ip);
|
|
164
|
+
if (!groups)
|
|
165
|
+
return true;
|
|
166
|
+
const [g0 = 0, g1 = 0, g2 = 0, g3 = 0, g4 = 0, g5 = 0, g6 = 0, g7 = 0] = groups;
|
|
167
|
+
// :: (unspecified) and ::1 (loopback)
|
|
168
|
+
if (g0 === 0 && g1 === 0 && g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0 && g6 === 0 && (g7 === 0 || g7 === 1)) {
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
// ::ffff:0:0/96 (IPv4-mapped IPv6) and ::/96 (IPv4-compatible)
|
|
172
|
+
if (g0 === 0 && g1 === 0 && g2 === 0 && g3 === 0 && g4 === 0 && (g5 === 0xffff || g5 === 0)) {
|
|
173
|
+
const mappedV4 = (((g6 & 0xffff) << 16) | (g7 & 0xffff)) >>> 0;
|
|
174
|
+
return isPrivateIpv4Int(mappedV4);
|
|
175
|
+
}
|
|
176
|
+
// 64:ff9b::/96 (NAT64 well-known) & 64:ff9b:1::/48 (RFC 8215 NAT64 local-use)
|
|
177
|
+
if (g0 === 0x0064 && g1 === 0xff9b && g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0) {
|
|
178
|
+
const mappedV4 = (((g6 & 0xffff) << 16) | (g7 & 0xffff)) >>> 0;
|
|
179
|
+
return isPrivateIpv4Int(mappedV4);
|
|
180
|
+
}
|
|
181
|
+
if (g0 === 0x0064 && g1 === 0xff9b && g2 === 0x0001)
|
|
182
|
+
return true;
|
|
183
|
+
// 2002::/16 (6to4 — embeds arbitrary IPv4 in g1:g2, e.g. 2002:7f00:0001::1 -> 127.0.0.1)
|
|
184
|
+
if (g0 === 0x2002) {
|
|
185
|
+
const embeddedV4 = (((g1 & 0xffff) << 16) | (g2 & 0xffff)) >>> 0;
|
|
186
|
+
return isPrivateIpv4Int(embeddedV4);
|
|
187
|
+
}
|
|
188
|
+
// 100::/64 (RFC 6666 Discard-Only)
|
|
189
|
+
if (g0 === 0x0100 && g1 === 0 && g2 === 0 && g3 === 0)
|
|
190
|
+
return true;
|
|
191
|
+
// 2001::/32 (Teredo tunneling)
|
|
192
|
+
if (g0 === 0x2001 && g1 === 0x0000)
|
|
193
|
+
return true;
|
|
194
|
+
// fc00::/7 (Unique Local Address)
|
|
195
|
+
if ((g0 & 0xfe00) === 0xfc00)
|
|
196
|
+
return true;
|
|
197
|
+
// fe80::/10 (Link-local)
|
|
198
|
+
if ((g0 & 0xffc0) === 0xfe80)
|
|
199
|
+
return true;
|
|
200
|
+
// fec0::/10 (Deprecated site-local)
|
|
201
|
+
if ((g0 & 0xffc0) === 0xfec0)
|
|
202
|
+
return true;
|
|
203
|
+
// ff00::/8 (Multicast)
|
|
204
|
+
if ((g0 & 0xff00) === 0xff00)
|
|
205
|
+
return true;
|
|
206
|
+
// 2001:db8::/32 (Documentation)
|
|
207
|
+
if (g0 === 0x2001 && g1 === 0x0db8)
|
|
208
|
+
return true;
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
// Unparseable IP strings are treated as unsafe by default
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
const BLOCKED_HOSTNAMES = new Set([
|
|
215
|
+
'localhost',
|
|
216
|
+
'localhost.localdomain',
|
|
217
|
+
'ip6-localhost',
|
|
218
|
+
'ip6-loopback',
|
|
219
|
+
'metadata.google.internal',
|
|
220
|
+
'metadata.goog',
|
|
221
|
+
'instance-data',
|
|
222
|
+
]);
|
|
223
|
+
/**
|
|
224
|
+
* Validates an outbound proxy URL against SSRF, protocol smuggling, and DNS rebinding.
|
|
225
|
+
*/
|
|
226
|
+
export async function validateProxyTargetUrl(rawUrl, options = {}) {
|
|
227
|
+
const allowPrivate = Boolean(options.allowPrivate);
|
|
228
|
+
let url;
|
|
229
|
+
try {
|
|
230
|
+
url = new URL(rawUrl.trim());
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
throw new Error('Invalid URL format');
|
|
234
|
+
}
|
|
235
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
236
|
+
throw new Error(`Blocked protocol "${url.protocol}". Only http: and https: are allowed`);
|
|
237
|
+
}
|
|
238
|
+
if (url.username || url.password) {
|
|
239
|
+
throw new Error('Embedded URL credentials are not permitted; use the Authorization header instead');
|
|
240
|
+
}
|
|
241
|
+
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.+$/, '');
|
|
242
|
+
if (!hostname) {
|
|
243
|
+
throw new Error('URL hostname is required');
|
|
244
|
+
}
|
|
245
|
+
if (!allowPrivate) {
|
|
246
|
+
if (BLOCKED_HOSTNAMES.has(hostname) ||
|
|
247
|
+
hostname.endsWith('.localhost') ||
|
|
248
|
+
hostname.endsWith('.local') ||
|
|
249
|
+
hostname.endsWith('.internal')) {
|
|
250
|
+
throw new Error(`SSRF Guard: blocked private/internal hostname "${hostname}" (start server with --allow-private-proxy to enable local network requests)`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const ipVer = isIP(hostname);
|
|
254
|
+
if (ipVer === 4 || ipVer === 6) {
|
|
255
|
+
if (!allowPrivate && isPrivateIp(hostname)) {
|
|
256
|
+
throw new Error(`SSRF Guard: blocked private/loopback IP "${hostname}" (start server with --allow-private-proxy to allow)`);
|
|
257
|
+
}
|
|
258
|
+
return { url, resolvedAddress: hostname, family: ipVer };
|
|
259
|
+
}
|
|
260
|
+
let records;
|
|
261
|
+
try {
|
|
262
|
+
records = await lookup(hostname, { all: true, verbatim: true });
|
|
263
|
+
}
|
|
264
|
+
catch (err) {
|
|
265
|
+
throw new Error(`DNS resolution failed for "${hostname}": ${err.message}`);
|
|
266
|
+
}
|
|
267
|
+
if (!records.length) {
|
|
268
|
+
throw new Error(`DNS resolution returned no addresses for "${hostname}"`);
|
|
269
|
+
}
|
|
270
|
+
if (!allowPrivate) {
|
|
271
|
+
for (const rec of records) {
|
|
272
|
+
if (isPrivateIp(rec.address)) {
|
|
273
|
+
throw new Error(`SSRF Guard: "${hostname}" resolved to blocked private/internal address "${rec.address}"`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const first = records[0];
|
|
278
|
+
return {
|
|
279
|
+
url,
|
|
280
|
+
resolvedAddress: first.address,
|
|
281
|
+
family: first.family === 6 ? 6 : 4,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Same-origin guard for mutating API endpoints when browsers include an Origin header.
|
|
286
|
+
*/
|
|
287
|
+
export function isOriginAllowed(origin, hostHeader) {
|
|
288
|
+
if (!origin)
|
|
289
|
+
return true; // Non-browser clients (CLI/curl) omit Origin
|
|
290
|
+
if (origin === 'null')
|
|
291
|
+
return false;
|
|
292
|
+
if (!hostHeader)
|
|
293
|
+
return false;
|
|
294
|
+
try {
|
|
295
|
+
const parsedOrigin = new URL(origin);
|
|
296
|
+
return parsedOrigin.host.toLowerCase() === hostHeader.toLowerCase();
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return false;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export interface ExplainPlanNode {
|
|
2
|
+
id: number;
|
|
3
|
+
nodeType: string;
|
|
4
|
+
relation?: string;
|
|
5
|
+
indexName?: string;
|
|
6
|
+
startupCost?: number;
|
|
7
|
+
totalCost?: number;
|
|
8
|
+
planRows?: number;
|
|
9
|
+
actualRows?: number;
|
|
10
|
+
actualLoops: number;
|
|
11
|
+
inclusiveTimeMs: number;
|
|
12
|
+
exclusiveTimeMs: number;
|
|
13
|
+
percentOfTotal: number;
|
|
14
|
+
filter?: string;
|
|
15
|
+
rowsRemovedByFilter?: number;
|
|
16
|
+
sortMethod?: string;
|
|
17
|
+
sharedHitBlocks?: number;
|
|
18
|
+
sharedReadBlocks?: number;
|
|
19
|
+
warnings: string[];
|
|
20
|
+
children: ExplainPlanNode[];
|
|
21
|
+
}
|
|
22
|
+
export interface ExplainInsight {
|
|
23
|
+
severity: 'critical' | 'warning' | 'info';
|
|
24
|
+
nodeId: number;
|
|
25
|
+
nodeType: string;
|
|
26
|
+
title: string;
|
|
27
|
+
detail: string;
|
|
28
|
+
recommendation: string;
|
|
29
|
+
}
|
|
30
|
+
export interface SqlExplainReport {
|
|
31
|
+
engine: 'postgres-json' | 'sqlite-plan';
|
|
32
|
+
planningTimeMs?: number;
|
|
33
|
+
executionTimeMs: number;
|
|
34
|
+
totalNodes: number;
|
|
35
|
+
maxDepth: number;
|
|
36
|
+
root: ExplainPlanNode;
|
|
37
|
+
hottestNodes: Array<{
|
|
38
|
+
id: number;
|
|
39
|
+
nodeType: string;
|
|
40
|
+
relation?: string;
|
|
41
|
+
exclusiveTimeMs: number;
|
|
42
|
+
percentOfTotal: number;
|
|
43
|
+
}>;
|
|
44
|
+
insights: ExplainInsight[];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Parses PostgreSQL `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` or SQLite `EXPLAIN QUERY PLAN`
|
|
48
|
+
* into a structured execution tree with exclusive node times and automated optimization insights.
|
|
49
|
+
*/
|
|
50
|
+
export declare function analyzeSqlExplain(input: string): SqlExplainReport;
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { safeJsonParse } from './security.js';
|
|
2
|
+
function num(v) {
|
|
3
|
+
return typeof v === 'number' && Number.isFinite(v) ? v : undefined;
|
|
4
|
+
}
|
|
5
|
+
function str(v) {
|
|
6
|
+
return typeof v === 'string' && v.trim() ? v.trim() : undefined;
|
|
7
|
+
}
|
|
8
|
+
function parsePostgresJsonExplain(raw) {
|
|
9
|
+
const parsed = safeJsonParse(raw);
|
|
10
|
+
const top = Array.isArray(parsed) ? parsed[0] : parsed;
|
|
11
|
+
if (!top || typeof top !== 'object') {
|
|
12
|
+
throw new Error('Expected PostgreSQL EXPLAIN (FORMAT JSON) object or array');
|
|
13
|
+
}
|
|
14
|
+
const rootRaw = (top.Plan && typeof top.Plan === 'object' ? top.Plan : top);
|
|
15
|
+
if (typeof rootRaw['Node Type'] !== 'string') {
|
|
16
|
+
throw new Error('Missing PostgreSQL "Node Type" field in EXPLAIN JSON');
|
|
17
|
+
}
|
|
18
|
+
let nextId = 1;
|
|
19
|
+
let maxDepth = 0;
|
|
20
|
+
const flatNodes = [];
|
|
21
|
+
const insights = [];
|
|
22
|
+
function walk(rawNode, depth) {
|
|
23
|
+
if (depth > 32)
|
|
24
|
+
throw new Error('EXPLAIN plan nesting exceeds 32-level safety limit');
|
|
25
|
+
if (depth > maxDepth)
|
|
26
|
+
maxDepth = depth;
|
|
27
|
+
const id = nextId++;
|
|
28
|
+
const nodeType = String(rawNode['Node Type'] ?? 'Unknown');
|
|
29
|
+
const relation = str(rawNode['Relation Name']);
|
|
30
|
+
const indexName = str(rawNode['Index Name']);
|
|
31
|
+
const loops = Math.max(num(rawNode['Actual Loops']) ?? 1, 1);
|
|
32
|
+
const totalTimePerLoop = num(rawNode['Actual Total Time']);
|
|
33
|
+
const inclusiveTimeMs = totalTimePerLoop !== undefined ? Math.round(totalTimePerLoop * loops * 1000) / 1000 : 0;
|
|
34
|
+
const childRawList = Array.isArray(rawNode.Plans) ? rawNode.Plans : [];
|
|
35
|
+
const children = childRawList.map((c) => walk(c, depth + 1));
|
|
36
|
+
const childrenInclusive = children.reduce((acc, ch) => acc + ch.inclusiveTimeMs, 0);
|
|
37
|
+
const exclusiveTimeMs = Math.max(0, Math.round((inclusiveTimeMs - childrenInclusive) * 1000) / 1000);
|
|
38
|
+
const planRows = num(rawNode['Plan Rows']);
|
|
39
|
+
const actualRows = num(rawNode['Actual Rows']);
|
|
40
|
+
const rowsRemoved = num(rawNode['Rows Removed by Filter']);
|
|
41
|
+
const sortMethod = str(rawNode['Sort Method']);
|
|
42
|
+
const filter = str(rawNode['Filter']) ?? str(rawNode['Index Cond']) ?? str(rawNode['Hash Cond']);
|
|
43
|
+
const warnings = [];
|
|
44
|
+
// Automated bottleneck & anti-pattern rules
|
|
45
|
+
if (nodeType === 'Seq Scan' && ((actualRows ?? 0) >= 1000 || (rowsRemoved ?? 0) >= 500)) {
|
|
46
|
+
const msg = `Sequential Scan on "${relation ?? 'table'}" scanned ${(actualRows ?? 0) + (rowsRemoved ?? 0)} rows`;
|
|
47
|
+
warnings.push(msg);
|
|
48
|
+
insights.push({
|
|
49
|
+
severity: 'critical',
|
|
50
|
+
nodeId: id,
|
|
51
|
+
nodeType,
|
|
52
|
+
title: `Full Table Sequential Scan on ${relation ?? 'table'}`,
|
|
53
|
+
detail: `${msg}${rowsRemoved ? ` (${rowsRemoved} discarded by filter)` : ''}.`,
|
|
54
|
+
recommendation: filter
|
|
55
|
+
? `Add a B-Tree or GIN index matching filter: ${filter}`
|
|
56
|
+
: `Consider adding an index on frequently filtered columns of "${relation ?? 'table'}".`,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
if (sortMethod && /disk/i.test(sortMethod)) {
|
|
60
|
+
const msg = `Sort spilled to disk (${sortMethod})`;
|
|
61
|
+
warnings.push(msg);
|
|
62
|
+
insights.push({
|
|
63
|
+
severity: 'critical',
|
|
64
|
+
nodeId: id,
|
|
65
|
+
nodeType,
|
|
66
|
+
title: 'Sort Spilled to Disk',
|
|
67
|
+
detail: `${msg} — disk I/O severely degrades latency.`,
|
|
68
|
+
recommendation: 'Increase session work_mem or add an index matching the ORDER BY clause.',
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
if (planRows !== undefined && actualRows !== undefined && planRows > 0 && actualRows > 0) {
|
|
72
|
+
const ratio = Math.max(actualRows / planRows, planRows / actualRows);
|
|
73
|
+
if (ratio >= 10 && Math.max(actualRows, planRows) >= 100) {
|
|
74
|
+
const msg = `Row estimate off by ${ratio.toFixed(1)}x (planned ${planRows}, actual ${actualRows})`;
|
|
75
|
+
warnings.push(msg);
|
|
76
|
+
insights.push({
|
|
77
|
+
severity: 'warning',
|
|
78
|
+
nodeId: id,
|
|
79
|
+
nodeType,
|
|
80
|
+
title: 'Severe Planner Cardinality Misestimate',
|
|
81
|
+
detail: msg,
|
|
82
|
+
recommendation: `Run ANALYZE ${relation ?? '<table>'} or create extended statistics (CREATE STATISTICS).`,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (nodeType === 'Nested Loop' && loops >= 100) {
|
|
87
|
+
const msg = `Nested Loop executed ${loops} iterations`;
|
|
88
|
+
warnings.push(msg);
|
|
89
|
+
insights.push({
|
|
90
|
+
severity: 'warning',
|
|
91
|
+
nodeId: id,
|
|
92
|
+
nodeType,
|
|
93
|
+
title: 'High Nested Loop Iteration Count',
|
|
94
|
+
detail: `${msg} (${inclusiveTimeMs}ms inclusive).`,
|
|
95
|
+
recommendation: 'Ensure join keys are indexed or check if Hash/Merge Join is preferable.',
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
const node = {
|
|
99
|
+
id,
|
|
100
|
+
nodeType,
|
|
101
|
+
relation,
|
|
102
|
+
indexName,
|
|
103
|
+
startupCost: num(rawNode['Startup Cost']),
|
|
104
|
+
totalCost: num(rawNode['Total Cost']),
|
|
105
|
+
planRows,
|
|
106
|
+
actualRows,
|
|
107
|
+
actualLoops: loops,
|
|
108
|
+
inclusiveTimeMs,
|
|
109
|
+
exclusiveTimeMs,
|
|
110
|
+
percentOfTotal: 0,
|
|
111
|
+
filter,
|
|
112
|
+
rowsRemovedByFilter: rowsRemoved,
|
|
113
|
+
sortMethod,
|
|
114
|
+
sharedHitBlocks: num(rawNode['Shared Hit Blocks']),
|
|
115
|
+
sharedReadBlocks: num(rawNode['Shared Read Blocks']),
|
|
116
|
+
warnings,
|
|
117
|
+
children,
|
|
118
|
+
};
|
|
119
|
+
flatNodes.push(node);
|
|
120
|
+
return node;
|
|
121
|
+
}
|
|
122
|
+
const root = walk(rootRaw, 1);
|
|
123
|
+
const executionTimeMs = num(top['Execution Time']) ?? root.inclusiveTimeMs;
|
|
124
|
+
const denom = executionTimeMs > 0 ? executionTimeMs : root.inclusiveTimeMs > 0 ? root.inclusiveTimeMs : 1;
|
|
125
|
+
for (const n of flatNodes) {
|
|
126
|
+
n.percentOfTotal = Math.min(100, Math.round((n.exclusiveTimeMs / denom) * 1000) / 10);
|
|
127
|
+
}
|
|
128
|
+
const hottestNodes = [...flatNodes]
|
|
129
|
+
.sort((a, b) => b.exclusiveTimeMs - a.exclusiveTimeMs)
|
|
130
|
+
.slice(0, 5)
|
|
131
|
+
.map((n) => ({
|
|
132
|
+
id: n.id,
|
|
133
|
+
nodeType: n.nodeType,
|
|
134
|
+
relation: n.relation,
|
|
135
|
+
exclusiveTimeMs: n.exclusiveTimeMs,
|
|
136
|
+
percentOfTotal: n.percentOfTotal,
|
|
137
|
+
}));
|
|
138
|
+
if (insights.length === 0) {
|
|
139
|
+
insights.push({
|
|
140
|
+
severity: 'info',
|
|
141
|
+
nodeId: root.id,
|
|
142
|
+
nodeType: root.nodeType,
|
|
143
|
+
title: 'No Critical Anti-Patterns Detected',
|
|
144
|
+
detail: `Analyzed ${flatNodes.length} plan node(s) (${executionTimeMs}ms total execution).`,
|
|
145
|
+
recommendation: 'Query plan looks healthy — review hottest nodes if further tuning is required.',
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
engine: 'postgres-json',
|
|
150
|
+
planningTimeMs: num(top['Planning Time']),
|
|
151
|
+
executionTimeMs,
|
|
152
|
+
totalNodes: flatNodes.length,
|
|
153
|
+
maxDepth,
|
|
154
|
+
root,
|
|
155
|
+
hottestNodes,
|
|
156
|
+
insights,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function parseSqliteTextExplain(raw) {
|
|
160
|
+
const lines = raw
|
|
161
|
+
.split(/\r?\n/)
|
|
162
|
+
.map((l) => l.trim())
|
|
163
|
+
.filter((l) => l.length > 0 && !/^QUERY PLAN$/i.test(l));
|
|
164
|
+
if (lines.length === 0) {
|
|
165
|
+
throw new Error('Empty SQLite EXPLAIN QUERY PLAN input');
|
|
166
|
+
}
|
|
167
|
+
const insights = [];
|
|
168
|
+
const children = lines.map((line, idx) => {
|
|
169
|
+
const id = idx + 2;
|
|
170
|
+
const clean = line.replace(/^[`|\-\s]+/, '').trim();
|
|
171
|
+
const scanMatch = clean.match(/\bSCAN\s+(?:TABLE\s+)?([A-Za-z0-9_."]+)/i);
|
|
172
|
+
const warnings = [];
|
|
173
|
+
if (scanMatch && !/USING (?:COVERING )?INDEX/i.test(clean)) {
|
|
174
|
+
const tbl = scanMatch[1];
|
|
175
|
+
warnings.push(`Full table SCAN on ${tbl} without index`);
|
|
176
|
+
insights.push({
|
|
177
|
+
severity: 'critical',
|
|
178
|
+
nodeId: id,
|
|
179
|
+
nodeType: 'SCAN',
|
|
180
|
+
title: `SQLite Full Table Scan on ${tbl}`,
|
|
181
|
+
detail: clean,
|
|
182
|
+
recommendation: `Create an index covering WHERE / JOIN / ORDER BY columns on ${tbl}.`,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
if (/USE TEMP B-TREE FOR ORDER BY/i.test(clean)) {
|
|
186
|
+
warnings.push('Temp B-Tree created for ORDER BY');
|
|
187
|
+
insights.push({
|
|
188
|
+
severity: 'warning',
|
|
189
|
+
nodeId: id,
|
|
190
|
+
nodeType: 'TEMP B-TREE',
|
|
191
|
+
title: 'Temporary B-Tree Sort for ORDER BY',
|
|
192
|
+
detail: clean,
|
|
193
|
+
recommendation: 'Add a composite index matching the ORDER BY column order to avoid temp sorting.',
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
id,
|
|
198
|
+
nodeType: clean.split(/\s+/).slice(0, 2).join(' ') || 'STEP',
|
|
199
|
+
relation: scanMatch?.[1],
|
|
200
|
+
filter: clean,
|
|
201
|
+
actualLoops: 1,
|
|
202
|
+
inclusiveTimeMs: 0,
|
|
203
|
+
exclusiveTimeMs: 0,
|
|
204
|
+
percentOfTotal: Math.round((100 / lines.length) * 10) / 10,
|
|
205
|
+
warnings,
|
|
206
|
+
children: [],
|
|
207
|
+
};
|
|
208
|
+
});
|
|
209
|
+
const root = {
|
|
210
|
+
id: 1,
|
|
211
|
+
nodeType: 'SQLite Query Plan',
|
|
212
|
+
actualLoops: 1,
|
|
213
|
+
inclusiveTimeMs: 0,
|
|
214
|
+
exclusiveTimeMs: 0,
|
|
215
|
+
percentOfTotal: 100,
|
|
216
|
+
warnings: [],
|
|
217
|
+
children,
|
|
218
|
+
};
|
|
219
|
+
if (insights.length === 0) {
|
|
220
|
+
insights.push({
|
|
221
|
+
severity: 'info',
|
|
222
|
+
nodeId: 1,
|
|
223
|
+
nodeType: 'SQLite Query Plan',
|
|
224
|
+
title: 'Index-Backed Plan',
|
|
225
|
+
detail: `Analyzed ${children.length} SQLite plan step(s) with no unindexed full table scans.`,
|
|
226
|
+
recommendation: 'Plan uses indexes cleanly.',
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
return {
|
|
230
|
+
engine: 'sqlite-plan',
|
|
231
|
+
executionTimeMs: 0,
|
|
232
|
+
totalNodes: children.length + 1,
|
|
233
|
+
maxDepth: 2,
|
|
234
|
+
root,
|
|
235
|
+
hottestNodes: children.slice(0, 5).map((n) => ({
|
|
236
|
+
id: n.id,
|
|
237
|
+
nodeType: n.nodeType,
|
|
238
|
+
relation: n.relation,
|
|
239
|
+
exclusiveTimeMs: 0,
|
|
240
|
+
percentOfTotal: n.percentOfTotal,
|
|
241
|
+
})),
|
|
242
|
+
insights,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Parses PostgreSQL `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` or SQLite `EXPLAIN QUERY PLAN`
|
|
247
|
+
* into a structured execution tree with exclusive node times and automated optimization insights.
|
|
248
|
+
*/
|
|
249
|
+
export function analyzeSqlExplain(input) {
|
|
250
|
+
const trimmed = input.trim();
|
|
251
|
+
if (!trimmed)
|
|
252
|
+
throw new Error('SQL EXPLAIN output is required');
|
|
253
|
+
if (trimmed.length > 1_000_000)
|
|
254
|
+
throw new Error('EXPLAIN input exceeds 1 MB safety limit');
|
|
255
|
+
if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
|
|
256
|
+
return parsePostgresJsonExplain(trimmed);
|
|
257
|
+
}
|
|
258
|
+
return parseSqliteTextExplain(trimmed);
|
|
259
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export interface CertificateInspection {
|
|
2
|
+
subject: string;
|
|
3
|
+
issuer: string;
|
|
4
|
+
serialNumber: string;
|
|
5
|
+
validFrom: string;
|
|
6
|
+
validTo: string;
|
|
7
|
+
daysRemaining: number;
|
|
8
|
+
expired: boolean;
|
|
9
|
+
expiringSoon: boolean;
|
|
10
|
+
notYetValid: boolean;
|
|
11
|
+
isCa: boolean;
|
|
12
|
+
selfSigned: boolean;
|
|
13
|
+
subjectAltNames: string[];
|
|
14
|
+
publicKeyType: string;
|
|
15
|
+
publicKeyBits?: number;
|
|
16
|
+
fingerprint256: string;
|
|
17
|
+
warnings: string[];
|
|
18
|
+
}
|
|
19
|
+
export interface RemoteTlsInspection {
|
|
20
|
+
host: string;
|
|
21
|
+
port: number;
|
|
22
|
+
resolvedAddress: string;
|
|
23
|
+
tlsProtocol: string;
|
|
24
|
+
cipherName: string;
|
|
25
|
+
authorized: boolean;
|
|
26
|
+
authorizationError?: string;
|
|
27
|
+
handshakeMs: number;
|
|
28
|
+
leaf: CertificateInspection;
|
|
29
|
+
chain: CertificateInspection[];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Inspects one or more PEM-encoded X.509 certificates completely offline using Node's
|
|
33
|
+
* native `crypto.X509Certificate` API (zero runtime dependencies).
|
|
34
|
+
*/
|
|
35
|
+
export declare function inspectPemCertificates(pemInput: string): CertificateInspection[];
|
|
36
|
+
/**
|
|
37
|
+
* Performs an SSRF-guarded, DNS-pinned TLS handshake to inspect a remote host's live
|
|
38
|
+
* X.509 certificate chain, TLS protocol version, cipher suite, and expiration warnings.
|
|
39
|
+
*/
|
|
40
|
+
export declare function inspectRemoteTls(rawTarget: string, options?: {
|
|
41
|
+
port?: number;
|
|
42
|
+
allowPrivate?: boolean;
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
}): Promise<RemoteTlsInspection>;
|