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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.ar.md +113 -0
  3. package/README.md +272 -2
  4. package/SECURITY.md +49 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +664 -0
  7. package/dist/core/contract-drift.d.ts +49 -0
  8. package/dist/core/contract-drift.js +312 -0
  9. package/dist/core/converters.d.ts +18 -0
  10. package/dist/core/converters.js +989 -0
  11. package/dist/core/cron.d.ts +33 -0
  12. package/dist/core/cron.js +309 -0
  13. package/dist/core/crypto.d.ts +59 -0
  14. package/dist/core/crypto.js +260 -0
  15. package/dist/core/curl.d.ts +17 -0
  16. package/dist/core/curl.js +174 -0
  17. package/dist/core/diff.d.ts +36 -0
  18. package/dist/core/diff.js +148 -0
  19. package/dist/core/encoding.d.ts +3 -0
  20. package/dist/core/encoding.js +143 -0
  21. package/dist/core/importers.d.ts +65 -0
  22. package/dist/core/importers.js +361 -0
  23. package/dist/core/jwt.d.ts +39 -0
  24. package/dist/core/jwt.js +269 -0
  25. package/dist/core/llm-tokens.d.ts +38 -0
  26. package/dist/core/llm-tokens.js +125 -0
  27. package/dist/core/log-analyzer.d.ts +30 -0
  28. package/dist/core/log-analyzer.js +155 -0
  29. package/dist/core/network.d.ts +72 -0
  30. package/dist/core/network.js +185 -0
  31. package/dist/core/oauth-protobuf.d.ts +74 -0
  32. package/dist/core/oauth-protobuf.js +396 -0
  33. package/dist/core/openapi.d.ts +27 -0
  34. package/dist/core/openapi.js +257 -0
  35. package/dist/core/pipeline.d.ts +28 -0
  36. package/dist/core/pipeline.js +154 -0
  37. package/dist/core/regex.d.ts +50 -0
  38. package/dist/core/regex.js +360 -0
  39. package/dist/core/runner.d.ts +53 -0
  40. package/dist/core/runner.js +250 -0
  41. package/dist/core/secrets.d.ts +87 -0
  42. package/dist/core/secrets.js +603 -0
  43. package/dist/core/security.d.ts +34 -0
  44. package/dist/core/security.js +301 -0
  45. package/dist/core/sql-explain.d.ts +50 -0
  46. package/dist/core/sql-explain.js +259 -0
  47. package/dist/core/tls.d.ts +44 -0
  48. package/dist/core/tls.js +169 -0
  49. package/dist/index.d.ts +31 -0
  50. package/dist/index.js +31 -0
  51. package/dist/server/app.d.ts +31 -0
  52. package/dist/server/app.js +359 -0
  53. package/dist/server/http-proxy.d.ts +55 -0
  54. package/dist/server/http-proxy.js +373 -0
  55. package/dist/server/http-utils.d.ts +28 -0
  56. package/dist/server/http-utils.js +118 -0
  57. package/dist/server/load-tester.d.ts +53 -0
  58. package/dist/server/load-tester.js +137 -0
  59. package/dist/server/mcp.d.ts +35 -0
  60. package/dist/server/mcp.js +470 -0
  61. package/dist/server/mock-store.d.ts +38 -0
  62. package/dist/server/mock-store.js +238 -0
  63. package/dist/server/plugin-loader.d.ts +61 -0
  64. package/dist/server/plugin-loader.js +305 -0
  65. package/dist/server/recorder-store.d.ts +35 -0
  66. package/dist/server/recorder-store.js +147 -0
  67. package/dist/server/routes/network-routes.d.ts +3 -0
  68. package/dist/server/routes/network-routes.js +441 -0
  69. package/dist/server/routes/tools-routes.d.ts +3 -0
  70. package/dist/server/routes/tools-routes.js +299 -0
  71. package/dist/server/routes/workspace-routes.d.ts +3 -0
  72. package/dist/server/routes/workspace-routes.js +262 -0
  73. package/dist/server/webhook-store.d.ts +29 -0
  74. package/dist/server/webhook-store.js +100 -0
  75. package/dist/server/workspace-store.d.ts +91 -0
  76. package/dist/server/workspace-store.js +448 -0
  77. package/dist/server/ws-probe.d.ts +34 -0
  78. package/dist/server/ws-probe.js +291 -0
  79. package/dist/ui/app.js +290 -0
  80. package/dist/ui/favicon.svg +14 -0
  81. package/dist/ui/index.html +83 -0
  82. package/dist/ui/logo.png +0 -0
  83. package/dist/ui/styles.css +694 -0
  84. package/dist/ui/tools-data.js +719 -0
  85. package/dist/ui/tools-network.js +769 -0
  86. package/dist/ui/tools-ops.js +299 -0
  87. package/dist/ui/tools-pro.js +500 -0
  88. package/dist/ui/tools-security.js +397 -0
  89. package/dist/ui/tools-v12.js +765 -0
  90. package/dist/ui/tools-v13.js +321 -0
  91. package/dist/ui/tools-v20.js +563 -0
  92. package/dist/ui/tools-v21.js +411 -0
  93. package/package.json +75 -4
@@ -0,0 +1,169 @@
1
+ import * as crypto from 'node:crypto';
2
+ import * as net from 'node:net';
3
+ import * as tls from 'node:tls';
4
+ import { validateProxyTargetUrl } from './security.js';
5
+ function parseSanList(raw) {
6
+ if (!raw)
7
+ return [];
8
+ return raw
9
+ .split(',')
10
+ .map((s) => s.trim())
11
+ .filter(Boolean);
12
+ }
13
+ function inspectX509Object(cert) {
14
+ const nowMs = Date.now();
15
+ const validFromMs = Date.parse(cert.validFrom);
16
+ const validToMs = Date.parse(cert.validTo);
17
+ const daysRemaining = Number.isFinite(validToMs)
18
+ ? Math.floor((validToMs - nowMs) / 86_400_000)
19
+ : 0;
20
+ const expired = Number.isFinite(validToMs) && validToMs < nowMs;
21
+ const notYetValid = Number.isFinite(validFromMs) && validFromMs > nowMs;
22
+ const expiringSoon = !expired && daysRemaining <= 30;
23
+ const selfSigned = cert.subject === cert.issuer;
24
+ const keyDetails = cert.publicKey.asymmetricKeyDetails;
25
+ const publicKeyType = cert.publicKey.asymmetricKeyType ?? 'unknown';
26
+ const publicKeyBits = typeof keyDetails?.modulusLength === 'number'
27
+ ? keyDetails.modulusLength
28
+ : typeof keyDetails?.namedCurve === 'string'
29
+ ? keyDetails.namedCurve.includes('384')
30
+ ? 384
31
+ : keyDetails.namedCurve.includes('521')
32
+ ? 521
33
+ : 256
34
+ : undefined;
35
+ const warnings = [];
36
+ if (expired)
37
+ warnings.push(`Certificate expired ${Math.abs(daysRemaining)} day(s) ago`);
38
+ else if (expiringSoon)
39
+ warnings.push(`Certificate expires soon (${daysRemaining} day(s) remaining)`);
40
+ if (notYetValid)
41
+ warnings.push('Certificate validFrom timestamp is in the future');
42
+ if (selfSigned)
43
+ warnings.push('Certificate is self-signed (subject equals issuer)');
44
+ if (publicKeyType === 'rsa' && publicKeyBits !== undefined && publicKeyBits < 2048) {
45
+ warnings.push(`Weak RSA key size (${publicKeyBits} bits; minimum 2048 bits recommended)`);
46
+ }
47
+ return {
48
+ subject: cert.subject,
49
+ issuer: cert.issuer,
50
+ serialNumber: cert.serialNumber,
51
+ validFrom: Number.isFinite(validFromMs) ? new Date(validFromMs).toISOString() : cert.validFrom,
52
+ validTo: Number.isFinite(validToMs) ? new Date(validToMs).toISOString() : cert.validTo,
53
+ daysRemaining,
54
+ expired,
55
+ expiringSoon,
56
+ notYetValid,
57
+ isCa: cert.ca,
58
+ selfSigned,
59
+ subjectAltNames: parseSanList(cert.subjectAltName),
60
+ publicKeyType,
61
+ publicKeyBits,
62
+ fingerprint256: cert.fingerprint256,
63
+ warnings,
64
+ };
65
+ }
66
+ /**
67
+ * Inspects one or more PEM-encoded X.509 certificates completely offline using Node's
68
+ * native `crypto.X509Certificate` API (zero runtime dependencies).
69
+ */
70
+ export function inspectPemCertificates(pemInput) {
71
+ const matches = pemInput.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);
72
+ if (!matches || matches.length === 0) {
73
+ throw new Error('No valid PEM certificate block (-----BEGIN CERTIFICATE-----) found');
74
+ }
75
+ if (matches.length > 12) {
76
+ throw new Error('PEM chain exceeds 12-certificate safety limit');
77
+ }
78
+ return matches.map((block) => inspectX509Object(new crypto.X509Certificate(block)));
79
+ }
80
+ /**
81
+ * Performs an SSRF-guarded, DNS-pinned TLS handshake to inspect a remote host's live
82
+ * X.509 certificate chain, TLS protocol version, cipher suite, and expiration warnings.
83
+ */
84
+ export async function inspectRemoteTls(rawTarget, options = {}) {
85
+ const trimmed = rawTarget.trim();
86
+ if (!trimmed)
87
+ throw new Error('Target domain or HTTPS URL is required');
88
+ const urlCandidate = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
89
+ const parsed = new URL(urlCandidate);
90
+ if (parsed.username || parsed.password) {
91
+ throw new Error('Embedded URL credentials are not permitted in TLS inspection target');
92
+ }
93
+ const port = options.port ?? (parsed.port ? Number(parsed.port) : 443);
94
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
95
+ throw new Error(`Invalid TCP port "${port}"`);
96
+ }
97
+ const target = await validateProxyTargetUrl(`https://${parsed.hostname}:${port}`, {
98
+ allowPrivate: options.allowPrivate,
99
+ });
100
+ const timeoutMs = Math.min(Math.max(options.timeoutMs ?? 6000, 500), 15_000);
101
+ const startedAt = performance.now();
102
+ return new Promise((resolve, reject) => {
103
+ let settled = false;
104
+ const finishErr = (err) => {
105
+ if (settled)
106
+ return;
107
+ settled = true;
108
+ socket.destroy();
109
+ reject(err);
110
+ };
111
+ const cleanHost = parsed.hostname.replace(/^\[|\]$/g, '');
112
+ const socket = tls.connect({
113
+ host: target.resolvedAddress,
114
+ port,
115
+ ...(net.isIP(cleanHost) === 0 ? { servername: cleanHost } : {}),
116
+ rejectUnauthorized: false,
117
+ timeout: timeoutMs,
118
+ }, () => {
119
+ if (settled)
120
+ return;
121
+ settled = true;
122
+ try {
123
+ const handshakeMs = Math.round((performance.now() - startedAt) * 10) / 10;
124
+ const peer = socket.getPeerCertificate(true);
125
+ if (!peer || !peer.raw) {
126
+ socket.destroy();
127
+ reject(new Error('Remote server did not present an X.509 certificate'));
128
+ return;
129
+ }
130
+ const chain = [];
131
+ const seen = new Set();
132
+ let cursor = peer;
133
+ let depth = 0;
134
+ while (cursor && cursor.raw && depth < 10) {
135
+ const x509 = new crypto.X509Certificate(cursor.raw);
136
+ if (seen.has(x509.fingerprint256))
137
+ break;
138
+ seen.add(x509.fingerprint256);
139
+ chain.push(inspectX509Object(x509));
140
+ cursor = cursor.issuerCertificate;
141
+ depth++;
142
+ }
143
+ const cipher = socket.getCipher();
144
+ const result = {
145
+ host: parsed.hostname,
146
+ port,
147
+ resolvedAddress: target.resolvedAddress,
148
+ tlsProtocol: socket.getProtocol() ?? 'unknown',
149
+ cipherName: cipher?.name ?? 'unknown',
150
+ authorized: socket.authorized,
151
+ authorizationError: socket.authorizationError
152
+ ? String(socket.authorizationError)
153
+ : undefined,
154
+ handshakeMs,
155
+ leaf: chain[0],
156
+ chain,
157
+ };
158
+ socket.end();
159
+ resolve(result);
160
+ }
161
+ catch (err) {
162
+ socket.destroy();
163
+ reject(err instanceof Error ? err : new Error(String(err)));
164
+ }
165
+ });
166
+ socket.on('timeout', () => finishErr(new Error(`TLS handshake timed out after ${timeoutMs}ms`)));
167
+ socket.on('error', (err) => finishErr(err));
168
+ });
169
+ }
@@ -0,0 +1,31 @@
1
+ export * from './core/security.js';
2
+ export * from './core/encoding.js';
3
+ export * from './core/crypto.js';
4
+ export * from './core/jwt.js';
5
+ export * from './core/converters.js';
6
+ export * from './core/diff.js';
7
+ export * from './core/regex.js';
8
+ export * from './core/cron.js';
9
+ export * from './core/network.js';
10
+ export * from './core/curl.js';
11
+ export * from './core/pipeline.js';
12
+ export * from './core/secrets.js';
13
+ export * from './core/openapi.js';
14
+ export * from './core/llm-tokens.js';
15
+ export * from './core/importers.js';
16
+ export * from './core/tls.js';
17
+ export * from './core/runner.js';
18
+ export * from './core/sql-explain.js';
19
+ export * from './core/log-analyzer.js';
20
+ export * from './core/contract-drift.js';
21
+ export * from './core/oauth-protobuf.js';
22
+ export { createDevAnvilServer, DEVANVIL_VERSION, type DevAnvilInstance, type DevAnvilServerOptions } from './server/app.js';
23
+ export { executeProxyRequest, executeSseStreamRequest, type ProxyRequestInput, type ProxyResponseResult, type SseCapturedEvent, type SseStreamResult, } from './server/http-proxy.js';
24
+ export { executeLoadTest, type LatencyBucket, type LoadTestInput, type LoadTestReport, type LoadTestThresholds, } from './server/load-tester.js';
25
+ export { RecorderStore, type RecordedTrafficEntry } from './server/recorder-store.js';
26
+ export { executeWebSocketProbe, GRAPHQL_INTROSPECTION_QUERY, type WsProbeMessage, type WsProbeResult, } from './server/ws-probe.js';
27
+ export { getDefaultPluginsDir, PluginLoader, type DevAnvilPluginManifest, type LoadedPluginSummary, type PluginRunResult, } from './server/plugin-loader.js';
28
+ export { MockStore, type MockRoute, type MockRouteInput } from './server/mock-store.js';
29
+ export { WebhookStore, type WebhookEvent } from './server/webhook-store.js';
30
+ export { WorkspaceStore, type DevAnvilWorkspaceData, type EncryptedWorkspaceBundle, type WorkspaceCollection, type WorkspaceEnvironment, type WorkspaceSecretWarning, } from './server/workspace-store.js';
31
+ export { executeMcpTool, handleMcpMessage, MCP_PROTOCOL_VERSION, MCP_TOOLS, startMcpStdioServer, type JsonRpcRequest, type JsonRpcResponse, type McpToolDefinition, } from './server/mcp.js';
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ export * from './core/security.js';
2
+ export * from './core/encoding.js';
3
+ export * from './core/crypto.js';
4
+ export * from './core/jwt.js';
5
+ export * from './core/converters.js';
6
+ export * from './core/diff.js';
7
+ export * from './core/regex.js';
8
+ export * from './core/cron.js';
9
+ export * from './core/network.js';
10
+ export * from './core/curl.js';
11
+ export * from './core/pipeline.js';
12
+ export * from './core/secrets.js';
13
+ export * from './core/openapi.js';
14
+ export * from './core/llm-tokens.js';
15
+ export * from './core/importers.js';
16
+ export * from './core/tls.js';
17
+ export * from './core/runner.js';
18
+ export * from './core/sql-explain.js';
19
+ export * from './core/log-analyzer.js';
20
+ export * from './core/contract-drift.js';
21
+ export * from './core/oauth-protobuf.js';
22
+ export { createDevAnvilServer, DEVANVIL_VERSION } from './server/app.js';
23
+ export { executeProxyRequest, executeSseStreamRequest, } from './server/http-proxy.js';
24
+ export { executeLoadTest, } from './server/load-tester.js';
25
+ export { RecorderStore } from './server/recorder-store.js';
26
+ export { executeWebSocketProbe, GRAPHQL_INTROSPECTION_QUERY, } from './server/ws-probe.js';
27
+ export { getDefaultPluginsDir, PluginLoader, } from './server/plugin-loader.js';
28
+ export { MockStore } from './server/mock-store.js';
29
+ export { WebhookStore } from './server/webhook-store.js';
30
+ export { WorkspaceStore, } from './server/workspace-store.js';
31
+ export { executeMcpTool, handleMcpMessage, MCP_PROTOCOL_VERSION, MCP_TOOLS, startMcpStdioServer, } from './server/mcp.js';
@@ -0,0 +1,31 @@
1
+ import type { Server } from 'node:http';
2
+ import { MockStore } from './mock-store.js';
3
+ import { PluginLoader } from './plugin-loader.js';
4
+ import { RecorderStore } from './recorder-store.js';
5
+ import { WebhookStore } from './webhook-store.js';
6
+ import { WorkspaceStore } from './workspace-store.js';
7
+ export declare const DEVANVIL_VERSION = "2.1.1";
8
+ export interface DevAnvilServerOptions {
9
+ host?: string;
10
+ port?: number;
11
+ allowPrivateProxy?: boolean;
12
+ denyIframe?: boolean;
13
+ uiDir?: string;
14
+ workspaceFile?: string;
15
+ pluginsDir?: string;
16
+ }
17
+ export interface DevAnvilInstance {
18
+ server: Server;
19
+ mockStore: MockStore;
20
+ webhookStore: WebhookStore;
21
+ workspaceStore: WorkspaceStore;
22
+ pluginLoader: PluginLoader;
23
+ recorderStore: RecorderStore;
24
+ start: () => Promise<{
25
+ host: string;
26
+ port: number;
27
+ url: string;
28
+ }>;
29
+ stop: () => Promise<void>;
30
+ }
31
+ export declare function createDevAnvilServer(options?: DevAnvilServerOptions): DevAnvilInstance;
@@ -0,0 +1,359 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import * as http from 'node:http';
4
+ import { createRequire } from 'node:module';
5
+ import { dirname, extname, join, resolve, sep } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { gzipSync } from 'node:zlib';
8
+ import { assertSafeChannelName, isOriginAllowed } from '../core/security.js';
9
+ import { applySecurityHeaders, readBody, sendJson } from './http-utils.js';
10
+ import { MockStore } from './mock-store.js';
11
+ import { PluginLoader } from './plugin-loader.js';
12
+ import { RecorderStore } from './recorder-store.js';
13
+ import { handleNetworkRoutes } from './routes/network-routes.js';
14
+ import { handleToolRoutes } from './routes/tools-routes.js';
15
+ import { handleWorkspaceAndPluginRoutes } from './routes/workspace-routes.js';
16
+ import { WebhookStore } from './webhook-store.js';
17
+ import { WorkspaceStore } from './workspace-store.js';
18
+ export const DEVANVIL_VERSION = '2.1.1';
19
+ const MIME_TYPES = {
20
+ '.html': 'text/html; charset=utf-8',
21
+ '.css': 'text/css; charset=utf-8',
22
+ '.js': 'application/javascript; charset=utf-8',
23
+ '.mjs': 'application/javascript; charset=utf-8',
24
+ '.json': 'application/json; charset=utf-8',
25
+ '.svg': 'image/svg+xml',
26
+ '.png': 'image/png',
27
+ '.ico': 'image/x-icon',
28
+ '.txt': 'text/plain; charset=utf-8',
29
+ };
30
+ const COMPRESSIBLE_EXTS = new Set(['.html', '.css', '.js', '.mjs', '.json', '.svg', '.txt']);
31
+ function getSeaModule() {
32
+ try {
33
+ const req = createRequire(import.meta.url);
34
+ const sea = req('node:sea');
35
+ if (sea && typeof sea.isSea === 'function' && sea.isSea()) {
36
+ return sea;
37
+ }
38
+ }
39
+ catch {
40
+ // Not running inside a Node SEA binary
41
+ }
42
+ return null;
43
+ }
44
+ function resolveUiDir(customDir) {
45
+ if (customDir)
46
+ return resolve(customDir);
47
+ try {
48
+ const here = dirname(fileURLToPath(import.meta.url));
49
+ const candidateDist = resolve(here, '..', 'ui');
50
+ if (existsSync(join(candidateDist, 'index.html')))
51
+ return candidateDist;
52
+ }
53
+ catch {
54
+ // Fallback for bundled CJS/SEA environments
55
+ }
56
+ const candidateSrc = resolve(process.cwd(), 'src', 'ui');
57
+ if (existsSync(join(candidateSrc, 'index.html')))
58
+ return candidateSrc;
59
+ return resolve(process.cwd(), 'dist', 'ui');
60
+ }
61
+ export function createDevAnvilServer(options = {}) {
62
+ const bindHost = options.host ?? '127.0.0.1';
63
+ const bindPort = options.port ?? 4321;
64
+ const allowPrivateProxy = Boolean(options.allowPrivateProxy);
65
+ const denyIframe = Boolean(options.denyIframe);
66
+ const uiRoot = resolveUiDir(options.uiDir);
67
+ const realUiRoot = existsSync(uiRoot) ? realpathSync(uiRoot) : uiRoot;
68
+ const sea = getSeaModule();
69
+ const startedAt = Date.now();
70
+ const workspaceStore = new WorkspaceStore(options.workspaceFile);
71
+ const savedMocks = workspaceStore.getSnapshot().mockRoutes;
72
+ const mockStore = new MockStore(savedMocks.length === 0);
73
+ if (savedMocks.length > 0) {
74
+ mockStore.importRoutes(savedMocks, true);
75
+ }
76
+ const webhookStore = new WebhookStore();
77
+ const pluginLoader = new PluginLoader(options.pluginsDir);
78
+ const recorderStore = new RecorderStore();
79
+ const assetCache = new Map();
80
+ const routeCtx = {
81
+ version: DEVANVIL_VERSION,
82
+ bindHost,
83
+ startedAt,
84
+ allowPrivateProxy,
85
+ denyIframe,
86
+ mockStore,
87
+ webhookStore,
88
+ workspaceStore,
89
+ pluginLoader,
90
+ recorderStore,
91
+ };
92
+ const server = http.createServer((req, res) => {
93
+ void handleRequest(req, res).catch((err) => {
94
+ if (!res.headersSent) {
95
+ const status = err.statusCode && err.statusCode >= 400 && err.statusCode < 600 ? err.statusCode : 400;
96
+ sendJson(res, status, { error: err.message || 'Internal server error' }, denyIframe);
97
+ }
98
+ else if (!res.writableEnded) {
99
+ res.end();
100
+ }
101
+ });
102
+ });
103
+ // Slowloris & connection exhaustion hardening
104
+ server.headersTimeout = 10_000;
105
+ server.requestTimeout = 30_000;
106
+ server.keepAliveTimeout = 5_000;
107
+ server.maxHeadersCount = 64;
108
+ async function handleRequest(req, res) {
109
+ const method = (req.method ?? 'GET').toUpperCase();
110
+ const rawUrl = req.url ?? '/';
111
+ // Parse against a constant local origin and normalize leading slashes to prevent protocol-relative or malformed Host errors
112
+ const normalizedRawUrl = rawUrl.startsWith('//') ? `/${rawUrl.replace(/^\/+/, '')}` : rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`;
113
+ let urlObj;
114
+ try {
115
+ urlObj = new URL(normalizedRawUrl, 'http://localhost');
116
+ }
117
+ catch {
118
+ sendJson(res, 400, { error: 'Malformed request URL' }, denyIframe);
119
+ return;
120
+ }
121
+ const pathname = urlObj.pathname;
122
+ // 1. Live Mock API Server: /mock/*
123
+ if (pathname === '/mock' || pathname.startsWith('/mock/')) {
124
+ const relativePath = pathname.slice(5) || '/';
125
+ const query = {};
126
+ urlObj.searchParams.forEach((v, k) => {
127
+ query[k] = v;
128
+ });
129
+ await readBody(req, 512 * 1024);
130
+ const matched = mockStore.match(method, relativePath, query);
131
+ if (!matched) {
132
+ sendJson(res, 404, {
133
+ error: 'No matching DevAnvil mock route',
134
+ method,
135
+ path: relativePath,
136
+ hint: 'Create a route in Mock & Webhooks or import an OpenAPI spec.',
137
+ }, denyIframe);
138
+ return;
139
+ }
140
+ if (matched.route.delayMs > 0) {
141
+ await new Promise((r) => setTimeout(r, matched.route.delayMs));
142
+ }
143
+ // Set custom mock headers first, then re-apply security headers so mock routes can never weaken CSP/XFO/nosniff
144
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
145
+ for (const [hk, hv] of Object.entries(matched.route.headers)) {
146
+ res.setHeader(hk, hv);
147
+ }
148
+ applySecurityHeaders(res, denyIframe);
149
+ res.writeHead(matched.route.status);
150
+ res.end(matched.renderedBody);
151
+ return;
152
+ }
153
+ // 2. Live Webhook Catcher: /hook/:channel(/*)?
154
+ if (pathname.startsWith('/hook/')) {
155
+ const rest = pathname.slice(6);
156
+ const slashIdx = rest.indexOf('/');
157
+ const rawChannel = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
158
+ const channel = assertSafeChannelName(rawChannel);
159
+ const subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
160
+ const rawBody = await readBody(req, 512 * 1024);
161
+ const query = {};
162
+ urlObj.searchParams.forEach((v, k) => {
163
+ query[k] = v;
164
+ });
165
+ const headers = {};
166
+ for (const [k, v] of Object.entries(req.headers)) {
167
+ if (v !== undefined)
168
+ headers[k] = Array.isArray(v) ? v.join(', ') : v;
169
+ }
170
+ const event = webhookStore.capture({
171
+ channel,
172
+ method,
173
+ path: subPath,
174
+ query,
175
+ headers,
176
+ body: rawBody,
177
+ contentType: headers['content-type'] ?? 'text/plain',
178
+ sizeBytes: Buffer.byteLength(rawBody, 'utf8'),
179
+ remoteAddress: req.socket.remoteAddress ?? 'unknown',
180
+ });
181
+ sendJson(res, 200, { captured: true, id: event.id, channel, receivedAt: event.receivedAt }, denyIframe);
182
+ return;
183
+ }
184
+ // 3. Internal Workbench API: /api/*
185
+ if (pathname.startsWith('/api/')) {
186
+ if (method !== 'GET' && method !== 'HEAD') {
187
+ if (!isOriginAllowed(req.headers.origin, req.headers.host)) {
188
+ sendJson(res, 403, { error: 'Forbidden: cross-origin API mutation blocked by DevAnvil Origin Guard' }, denyIframe);
189
+ return;
190
+ }
191
+ }
192
+ await handleApiRoute(method, pathname, urlObj, req, res);
193
+ return;
194
+ }
195
+ // 4. Static Web Studio UI (Disk or embedded Node SEA assets + ETag + Gzip)
196
+ if (method !== 'GET' && method !== 'HEAD') {
197
+ sendJson(res, 405, { error: 'Method Not Allowed' }, denyIframe);
198
+ return;
199
+ }
200
+ serveStaticUi(rawUrl, pathname, req, res);
201
+ }
202
+ async function handleApiRoute(method, pathname, urlObj, req, res) {
203
+ if (method === 'GET' && pathname === '/api/health') {
204
+ const mem = process.memoryUsage();
205
+ sendJson(res, 200, {
206
+ name: 'DevAnvil',
207
+ version: DEVANVIL_VERSION,
208
+ status: 'ok',
209
+ uptimeSeconds: Math.floor((Date.now() - startedAt) / 1000),
210
+ nodeVersion: process.version,
211
+ runtimeDependencies: 0,
212
+ metrics: {
213
+ memoryRssMb: Math.round((mem.rss / 1024 / 1024) * 10) / 10,
214
+ heapUsedMb: Math.round((mem.heapUsed / 1024 / 1024) * 10) / 10,
215
+ mockRoutesCount: mockStore.list().length,
216
+ totalMockHits: mockStore.totalHits(),
217
+ webhookChannelsCount: webhookStore.listChannels().length,
218
+ activeSseClients: webhookStore.totalListeners(),
219
+ workspacePersistent: workspaceStore.isPersistent(),
220
+ collectionsCount: workspaceStore.getSnapshot().collections.length,
221
+ recordedTrafficCount: recorderStore.list().length,
222
+ },
223
+ security: {
224
+ ssrfGuard: allowPrivateProxy ? 'permissive (private IPs enabled)' : 'strict (private/metadata IPs blocked)',
225
+ originGuard: 'active',
226
+ csp: 'strict-self',
227
+ pluginSandbox: 'worker_threads+vm (no codegen, 48MB cap)',
228
+ slowlorisTimeouts: 'active',
229
+ bindHost,
230
+ },
231
+ }, denyIframe);
232
+ return;
233
+ }
234
+ if (await handleNetworkRoutes(method, pathname, req, res, routeCtx))
235
+ return;
236
+ if (await handleWorkspaceAndPluginRoutes(method, pathname, req, res, routeCtx))
237
+ return;
238
+ if (await handleToolRoutes(method, pathname, urlObj, req, res, routeCtx))
239
+ return;
240
+ sendJson(res, 404, { error: `Unknown API endpoint: ${method} ${pathname}` }, denyIframe);
241
+ }
242
+ function buildAssetEntry(key, raw, mtimeMs) {
243
+ const ext = extname(key).toLowerCase();
244
+ const etag = `"${createHash('sha256').update(raw).digest('base64url').slice(0, 20)}"`;
245
+ return {
246
+ mtimeMs,
247
+ mime: MIME_TYPES[ext] ?? 'application/octet-stream',
248
+ etag,
249
+ raw,
250
+ isHtml: ext === '.html',
251
+ ...(COMPRESSIBLE_EXTS.has(ext) && raw.length > 512 ? { gzipped: gzipSync(raw) } : {}),
252
+ };
253
+ }
254
+ function loadAsset(relPath) {
255
+ // Prefer embedded Node SEA assets when running as a standalone binary
256
+ if (sea && typeof sea.getRawAsset === 'function') {
257
+ const seaKey = `ui/${relPath}`;
258
+ const cached = assetCache.get(seaKey);
259
+ if (cached)
260
+ return cached;
261
+ try {
262
+ const ab = sea.getRawAsset(seaKey);
263
+ const entry = buildAssetEntry(relPath, Buffer.from(ab), 0);
264
+ assetCache.set(seaKey, entry);
265
+ return entry;
266
+ }
267
+ catch {
268
+ return null;
269
+ }
270
+ }
271
+ const fullPath = resolve(uiRoot, relPath);
272
+ if (fullPath !== uiRoot && !fullPath.startsWith(uiRoot + sep))
273
+ return null;
274
+ if (!existsSync(fullPath) || !statSync(fullPath).isFile())
275
+ return null;
276
+ const realFile = realpathSync(fullPath);
277
+ if (realFile !== realUiRoot && !realFile.startsWith(realUiRoot + sep))
278
+ return null;
279
+ const st = statSync(realFile);
280
+ const existing = assetCache.get(realFile);
281
+ if (existing && existing.mtimeMs === st.mtimeMs)
282
+ return existing;
283
+ const entry = buildAssetEntry(realFile, readFileSync(realFile), st.mtimeMs);
284
+ assetCache.set(realFile, entry);
285
+ return entry;
286
+ }
287
+ function serveStaticUi(rawUrl, pathname, req, res) {
288
+ const rawPathPart = rawUrl.split('?')[0] ?? '/';
289
+ if (rawPathPart.includes('\0') || pathname.includes('\0')) {
290
+ sendJson(res, 400, { error: 'Invalid path' }, denyIframe);
291
+ return;
292
+ }
293
+ if (/(^|[\\/])\.\.([\\/]|$)/i.test(rawPathPart) || /%2e%2e/i.test(rawPathPart) || /%5c/i.test(rawPathPart)) {
294
+ sendJson(res, 403, { error: 'Path traversal denied' }, denyIframe);
295
+ return;
296
+ }
297
+ let decodedPath;
298
+ try {
299
+ decodedPath = decodeURIComponent(pathname);
300
+ }
301
+ catch {
302
+ sendJson(res, 400, { error: 'Malformed URI encoding' }, denyIframe);
303
+ return;
304
+ }
305
+ if (decodedPath.includes('..') || decodedPath.includes('\\')) {
306
+ sendJson(res, 403, { error: 'Path traversal denied' }, denyIframe);
307
+ return;
308
+ }
309
+ const relPath = decodedPath === '/' ? 'index.html' : decodedPath.replace(/^\/+/, '');
310
+ const asset = loadAsset(relPath);
311
+ if (!asset) {
312
+ sendJson(res, 404, { error: 'Not Found' }, denyIframe);
313
+ return;
314
+ }
315
+ applySecurityHeaders(res, denyIframe);
316
+ if (req.headers['if-none-match'] === asset.etag) {
317
+ res.writeHead(304, { ETag: asset.etag });
318
+ res.end();
319
+ return;
320
+ }
321
+ const acceptsGzip = /\bgzip\b/i.test(String(req.headers['accept-encoding'] ?? ''));
322
+ const useGzip = Boolean(acceptsGzip && asset.gzipped);
323
+ const body = useGzip ? asset.gzipped : asset.raw;
324
+ res.writeHead(200, {
325
+ 'Content-Type': asset.mime,
326
+ 'Content-Length': body.length,
327
+ ETag: asset.etag,
328
+ Vary: 'Accept-Encoding',
329
+ 'Cache-Control': asset.isHtml ? 'no-cache' : 'public, max-age=300',
330
+ ...(useGzip ? { 'Content-Encoding': 'gzip' } : {}),
331
+ });
332
+ if (req.method === 'HEAD') {
333
+ res.end();
334
+ return;
335
+ }
336
+ res.end(body);
337
+ }
338
+ return {
339
+ server,
340
+ mockStore,
341
+ webhookStore,
342
+ workspaceStore,
343
+ pluginLoader,
344
+ recorderStore,
345
+ start: () => new Promise((resolveStart, rejectStart) => {
346
+ server.once('error', rejectStart);
347
+ server.listen(bindPort, bindHost, () => {
348
+ server.off('error', rejectStart);
349
+ const addr = server.address();
350
+ const actualPort = typeof addr === 'object' && addr ? addr.port : bindPort;
351
+ const displayHost = bindHost === '0.0.0.0' ? 'localhost' : bindHost;
352
+ resolveStart({ host: bindHost, port: actualPort, url: `http://${displayHost}:${actualPort}` });
353
+ });
354
+ }),
355
+ stop: () => new Promise((resolveStop, rejectStop) => {
356
+ server.close((err) => (err ? rejectStop(err) : resolveStop()));
357
+ }),
358
+ };
359
+ }
@@ -0,0 +1,55 @@
1
+ export interface ProxyRequestInput {
2
+ method: string;
3
+ url: string;
4
+ headers?: Record<string, string>;
5
+ body?: string;
6
+ timeoutMs?: number;
7
+ followRedirects?: boolean;
8
+ }
9
+ export interface ProxyResponseResult {
10
+ status: number;
11
+ statusText: string;
12
+ finalUrl: string;
13
+ redirects: number;
14
+ headers: Record<string, string>;
15
+ body: string;
16
+ contentType: string;
17
+ sizeBytes: number;
18
+ truncated: boolean;
19
+ timings: {
20
+ dnsValidateMs: number;
21
+ ttfbMs: number;
22
+ totalMs: number;
23
+ };
24
+ }
25
+ export declare function executeProxyRequest(input: ProxyRequestInput, options?: {
26
+ allowPrivate?: boolean;
27
+ }): Promise<ProxyResponseResult>;
28
+ export interface SseCapturedEvent {
29
+ index: number;
30
+ event: string;
31
+ id?: string;
32
+ data: string;
33
+ deltaMs: number;
34
+ }
35
+ export interface SseStreamResult {
36
+ status: number;
37
+ contentType: string;
38
+ finalUrl: string;
39
+ ttfbMs: number;
40
+ totalMs: number;
41
+ eventCount: number;
42
+ bytesReceived: number;
43
+ stoppedReason: 'eof' | 'max-events' | 'timeout' | 'max-bytes';
44
+ events: SseCapturedEvent[];
45
+ }
46
+ /**
47
+ * Connects to an SSE (Server-Sent Events) stream (e.g. AI LLM streaming APIs or live hooks)
48
+ * with the same SSRF + DNS-pinning guard, capturing events + Time-To-First-Token (TTFT).
49
+ */
50
+ export declare function executeSseStreamRequest(input: ProxyRequestInput & {
51
+ maxEvents?: number;
52
+ maxDurationMs?: number;
53
+ }, options?: {
54
+ allowPrivate?: boolean;
55
+ }): Promise<SseStreamResult>;