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,238 @@
|
|
|
1
|
+
import { generateUuidV7 } from '../core/crypto.js';
|
|
2
|
+
const VALID_MOCK_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD', 'ANY']);
|
|
3
|
+
const MAX_MOCK_ROUTES = 100;
|
|
4
|
+
function normalizeMockPath(raw) {
|
|
5
|
+
const trimmed = raw.trim();
|
|
6
|
+
if (!trimmed)
|
|
7
|
+
throw new Error('Mock path is required');
|
|
8
|
+
const withSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
|
|
9
|
+
if (withSlash.length > 256)
|
|
10
|
+
throw new Error('Mock path exceeds 256 characters');
|
|
11
|
+
return withSlash.replace(/\/+$/, '') || '/';
|
|
12
|
+
}
|
|
13
|
+
function safeDecodeSegment(seg) {
|
|
14
|
+
try {
|
|
15
|
+
return decodeURIComponent(seg);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return seg;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const VALID_HTTP_HEADER_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
22
|
+
const BLOCKED_MOCK_HEADERS = new Set([
|
|
23
|
+
'content-security-policy',
|
|
24
|
+
'content-security-policy-report-only',
|
|
25
|
+
'x-frame-options',
|
|
26
|
+
'x-content-type-options',
|
|
27
|
+
'strict-transport-security',
|
|
28
|
+
'referrer-policy',
|
|
29
|
+
'permissions-policy',
|
|
30
|
+
'cross-origin-opener-policy',
|
|
31
|
+
'cross-origin-embedder-policy',
|
|
32
|
+
'set-cookie',
|
|
33
|
+
'transfer-encoding',
|
|
34
|
+
'content-length',
|
|
35
|
+
'connection',
|
|
36
|
+
'keep-alive',
|
|
37
|
+
'upgrade',
|
|
38
|
+
'te',
|
|
39
|
+
'trailer',
|
|
40
|
+
'host',
|
|
41
|
+
]);
|
|
42
|
+
function sanitizeHeadersMap(headers) {
|
|
43
|
+
const clean = {};
|
|
44
|
+
for (const [k, v] of Object.entries(headers ?? {})) {
|
|
45
|
+
const key = k.trim();
|
|
46
|
+
if (!key || !VALID_HTTP_HEADER_TOKEN.test(key))
|
|
47
|
+
continue;
|
|
48
|
+
if (BLOCKED_MOCK_HEADERS.has(key.toLowerCase()))
|
|
49
|
+
continue;
|
|
50
|
+
const val = String(v);
|
|
51
|
+
if (/[\r\n\0]/.test(val))
|
|
52
|
+
continue;
|
|
53
|
+
clean[key] = val;
|
|
54
|
+
}
|
|
55
|
+
return clean;
|
|
56
|
+
}
|
|
57
|
+
function sanitizeStatus(raw, fallback) {
|
|
58
|
+
const n = typeof raw === 'number' ? raw : Number(raw);
|
|
59
|
+
if (!Number.isFinite(n))
|
|
60
|
+
throw new Error('Mock status must be a valid HTTP status code (100-599)');
|
|
61
|
+
return Math.min(Math.max(Math.floor(n), 100), 599);
|
|
62
|
+
}
|
|
63
|
+
function sanitizeDelay(raw, fallback) {
|
|
64
|
+
const n = typeof raw === 'number' ? raw : Number(raw);
|
|
65
|
+
if (!Number.isFinite(n))
|
|
66
|
+
return fallback;
|
|
67
|
+
return Math.min(Math.max(Math.floor(n), 0), 5000);
|
|
68
|
+
}
|
|
69
|
+
function matchRoutePath(pattern, actualPath) {
|
|
70
|
+
const patSegs = pattern.split('/').filter(Boolean);
|
|
71
|
+
const actSegs = actualPath.split('/').filter(Boolean);
|
|
72
|
+
if (patSegs.length !== actSegs.length)
|
|
73
|
+
return null;
|
|
74
|
+
const params = {};
|
|
75
|
+
for (let i = 0; i < patSegs.length; i++) {
|
|
76
|
+
const p = patSegs[i];
|
|
77
|
+
const a = actSegs[i];
|
|
78
|
+
if (p.startsWith(':')) {
|
|
79
|
+
params[p.slice(1)] = safeDecodeSegment(a);
|
|
80
|
+
}
|
|
81
|
+
else if (p === '*') {
|
|
82
|
+
params[`wildcard_${i}`] = safeDecodeSegment(a);
|
|
83
|
+
}
|
|
84
|
+
else if (p !== a) {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return params;
|
|
89
|
+
}
|
|
90
|
+
export class MockStore {
|
|
91
|
+
routes = [];
|
|
92
|
+
constructor(seedDefaults = true) {
|
|
93
|
+
if (seedDefaults) {
|
|
94
|
+
this.create({
|
|
95
|
+
method: 'GET',
|
|
96
|
+
path: '/health',
|
|
97
|
+
status: 200,
|
|
98
|
+
headers: { 'Content-Type': 'application/json' },
|
|
99
|
+
body: JSON.stringify({ status: 'ok', service: 'devanvil-mock', timestamp: '{{timestamp}}', requestId: '{{uuid}}' }, null, 2),
|
|
100
|
+
delayMs: 0,
|
|
101
|
+
});
|
|
102
|
+
this.create({
|
|
103
|
+
method: 'GET',
|
|
104
|
+
path: '/users/:id',
|
|
105
|
+
status: 200,
|
|
106
|
+
headers: { 'Content-Type': 'application/json', 'X-Mock-Engine': 'DevAnvil' },
|
|
107
|
+
body: JSON.stringify({
|
|
108
|
+
id: '{{param.id}}',
|
|
109
|
+
name: 'Ada Lovelace',
|
|
110
|
+
role: 'Principal Engineer',
|
|
111
|
+
requestedAt: '{{timestamp}}',
|
|
112
|
+
}, null, 2),
|
|
113
|
+
delayMs: 40,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
list() {
|
|
118
|
+
return this.routes.map((r) => ({ ...r, headers: { ...r.headers } }));
|
|
119
|
+
}
|
|
120
|
+
create(input) {
|
|
121
|
+
if (this.routes.length >= MAX_MOCK_ROUTES) {
|
|
122
|
+
throw new Error(`Maximum mock route limit (${MAX_MOCK_ROUTES}) reached`);
|
|
123
|
+
}
|
|
124
|
+
const method = (input.method ?? 'GET').toUpperCase().trim();
|
|
125
|
+
if (!VALID_MOCK_METHODS.has(method)) {
|
|
126
|
+
throw new Error(`Invalid HTTP method "${method}"`);
|
|
127
|
+
}
|
|
128
|
+
const path = normalizeMockPath(input.path);
|
|
129
|
+
const status = input.status !== undefined ? sanitizeStatus(input.status, 200) : 200;
|
|
130
|
+
const delayMs = input.delayMs !== undefined ? sanitizeDelay(input.delayMs, 0) : 0;
|
|
131
|
+
const headers = sanitizeHeadersMap(input.headers ?? { 'Content-Type': 'application/json' });
|
|
132
|
+
const route = {
|
|
133
|
+
id: generateUuidV7(),
|
|
134
|
+
method,
|
|
135
|
+
path,
|
|
136
|
+
status,
|
|
137
|
+
headers,
|
|
138
|
+
body: typeof input.body === 'string' ? input.body : String(input.body ?? ''),
|
|
139
|
+
delayMs,
|
|
140
|
+
enabled: input.enabled !== false,
|
|
141
|
+
hits: 0,
|
|
142
|
+
createdAt: new Date().toISOString(),
|
|
143
|
+
};
|
|
144
|
+
this.routes.unshift(route);
|
|
145
|
+
return { ...route, headers: { ...route.headers } };
|
|
146
|
+
}
|
|
147
|
+
update(id, patch) {
|
|
148
|
+
const idx = this.routes.findIndex((r) => r.id === id);
|
|
149
|
+
if (idx === -1)
|
|
150
|
+
throw new Error('Mock route not found');
|
|
151
|
+
const current = this.routes[idx];
|
|
152
|
+
const method = patch.method !== undefined
|
|
153
|
+
? (typeof patch.method === 'string' ? patch.method.toUpperCase().trim() : '')
|
|
154
|
+
: current.method;
|
|
155
|
+
if (!VALID_MOCK_METHODS.has(method))
|
|
156
|
+
throw new Error(`Invalid HTTP method "${method}"`);
|
|
157
|
+
const updated = {
|
|
158
|
+
...current,
|
|
159
|
+
method,
|
|
160
|
+
path: patch.path !== undefined ? normalizeMockPath(String(patch.path)) : current.path,
|
|
161
|
+
status: patch.status !== undefined ? sanitizeStatus(patch.status, current.status) : current.status,
|
|
162
|
+
delayMs: patch.delayMs !== undefined ? sanitizeDelay(patch.delayMs, current.delayMs) : current.delayMs,
|
|
163
|
+
body: patch.body !== undefined ? String(patch.body) : current.body,
|
|
164
|
+
enabled: patch.enabled !== undefined ? Boolean(patch.enabled) : current.enabled,
|
|
165
|
+
headers: patch.headers !== undefined ? sanitizeHeadersMap(patch.headers) : current.headers,
|
|
166
|
+
};
|
|
167
|
+
this.routes[idx] = updated;
|
|
168
|
+
return { ...updated, headers: { ...updated.headers } };
|
|
169
|
+
}
|
|
170
|
+
delete(id) {
|
|
171
|
+
const before = this.routes.length;
|
|
172
|
+
this.routes = this.routes.filter((r) => r.id !== id);
|
|
173
|
+
return this.routes.length < before;
|
|
174
|
+
}
|
|
175
|
+
clear() {
|
|
176
|
+
this.routes = [];
|
|
177
|
+
}
|
|
178
|
+
importRoutes(inputs, replace = false) {
|
|
179
|
+
if (!Array.isArray(inputs)) {
|
|
180
|
+
throw new Error('Mock routes import expects an array');
|
|
181
|
+
}
|
|
182
|
+
if (replace)
|
|
183
|
+
this.routes = [];
|
|
184
|
+
const created = [];
|
|
185
|
+
for (const item of inputs) {
|
|
186
|
+
if (this.routes.length >= MAX_MOCK_ROUTES)
|
|
187
|
+
break;
|
|
188
|
+
created.push(this.create(item));
|
|
189
|
+
}
|
|
190
|
+
return created;
|
|
191
|
+
}
|
|
192
|
+
totalHits() {
|
|
193
|
+
return this.routes.reduce((sum, r) => sum + r.hits, 0);
|
|
194
|
+
}
|
|
195
|
+
match(method, relativePath, query) {
|
|
196
|
+
const cleanPath = normalizeMockPath(relativePath);
|
|
197
|
+
const upperMethod = method.toUpperCase();
|
|
198
|
+
for (const route of this.routes) {
|
|
199
|
+
if (!route.enabled)
|
|
200
|
+
continue;
|
|
201
|
+
if (route.method !== 'ANY' && route.method !== upperMethod)
|
|
202
|
+
continue;
|
|
203
|
+
const params = matchRoutePath(route.path, cleanPath);
|
|
204
|
+
if (params !== null) {
|
|
205
|
+
route.hits++;
|
|
206
|
+
const renderedBody = this.interpolateTemplate(route.body, {
|
|
207
|
+
method: upperMethod,
|
|
208
|
+
path: cleanPath,
|
|
209
|
+
params,
|
|
210
|
+
query,
|
|
211
|
+
});
|
|
212
|
+
return { route, renderedBody, params };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
interpolateTemplate(body, ctx) {
|
|
218
|
+
return body.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (match, token) => {
|
|
219
|
+
if (token === 'timestamp')
|
|
220
|
+
return new Date().toISOString();
|
|
221
|
+
if (token === 'uuid')
|
|
222
|
+
return generateUuidV7();
|
|
223
|
+
if (token === 'method')
|
|
224
|
+
return ctx.method;
|
|
225
|
+
if (token === 'path')
|
|
226
|
+
return ctx.path;
|
|
227
|
+
if (token.startsWith('param.')) {
|
|
228
|
+
const key = token.slice(6);
|
|
229
|
+
return Object.prototype.hasOwnProperty.call(ctx.params, key) ? (ctx.params[key] ?? '') : '';
|
|
230
|
+
}
|
|
231
|
+
if (token.startsWith('query.')) {
|
|
232
|
+
const key = token.slice(6);
|
|
233
|
+
return Object.prototype.hasOwnProperty.call(ctx.query, key) ? (ctx.query[key] ?? '') : '';
|
|
234
|
+
}
|
|
235
|
+
return match;
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export interface DevAnvilPluginManifest {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
version: string;
|
|
5
|
+
description: string;
|
|
6
|
+
author?: string;
|
|
7
|
+
inputPlaceholder?: string;
|
|
8
|
+
entry: string;
|
|
9
|
+
}
|
|
10
|
+
export interface LoadedPluginSummary extends DevAnvilPluginManifest {
|
|
11
|
+
dirPath: string;
|
|
12
|
+
}
|
|
13
|
+
export interface PluginRunResult {
|
|
14
|
+
pluginId: string;
|
|
15
|
+
output: string;
|
|
16
|
+
durationMs: number;
|
|
17
|
+
isolation: 'worker_threads+vm' | 'vm';
|
|
18
|
+
}
|
|
19
|
+
export declare function getDefaultPluginsDir(): string;
|
|
20
|
+
/**
|
|
21
|
+
* Zero-Trust Local Plugin Loader & Hardened Sandbox.
|
|
22
|
+
*
|
|
23
|
+
* Defense-in-depth guarantees:
|
|
24
|
+
* 1. Only primitive strings cross the host -> sandbox boundary (no host prototypes / Function constructor).
|
|
25
|
+
* 2. `codeGeneration: { strings: false, wasm: false }` blocks `eval`, `new Function`, and `constructor.constructor(...)`.
|
|
26
|
+
* 3. `runPluginAsync` executes inside an isolated `node:worker_threads` Worker with empty `env`,
|
|
27
|
+
* 48 MB heap cap, and hard `worker.terminate()` on timeout so runaway plugins cannot freeze the HTTP server.
|
|
28
|
+
* 4. Strict plugin ID regex and realpath confinement prevent path traversal and symlink escapes.
|
|
29
|
+
*/
|
|
30
|
+
export declare class PluginLoader {
|
|
31
|
+
private readonly pluginsDir;
|
|
32
|
+
constructor(pluginsDir?: string);
|
|
33
|
+
getPluginsDir(): string;
|
|
34
|
+
private resolveSafePlugin;
|
|
35
|
+
listPlugins(): LoadedPluginSummary[];
|
|
36
|
+
readPluginSource(pluginId: string): {
|
|
37
|
+
plugin: LoadedPluginSummary;
|
|
38
|
+
code: string;
|
|
39
|
+
};
|
|
40
|
+
savePluginSource(pluginId: string, code: string): {
|
|
41
|
+
plugin: LoadedPluginSummary;
|
|
42
|
+
bytes: number;
|
|
43
|
+
};
|
|
44
|
+
deletePlugin(pluginId: string): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Synchronous VM sandbox execution (ideal for CLI & single-shot scripts).
|
|
47
|
+
* Uses primitive-only JSON boundaries + `codeGeneration: { strings: false, wasm: false }`.
|
|
48
|
+
*/
|
|
49
|
+
runPlugin(pluginId: string, input: string, options?: Record<string, unknown>): PluginRunResult;
|
|
50
|
+
private activeWorkers;
|
|
51
|
+
/**
|
|
52
|
+
* Asynchronous hardened Worker Thread + VM sandbox execution (used by HTTP Server).
|
|
53
|
+
* Guarantees non-blocking event loop, empty worker env, capped V8 heap, concurrency cap, and hard terminate on timeout.
|
|
54
|
+
*/
|
|
55
|
+
runPluginAsync(pluginId: string, input: string, options?: Record<string, unknown>, timeoutMs?: number): Promise<PluginRunResult>;
|
|
56
|
+
scaffoldPlugin(rawId: string): {
|
|
57
|
+
dirPath: string;
|
|
58
|
+
manifestPath: string;
|
|
59
|
+
handlerPath: string;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as os from 'node:os';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import * as vm from 'node:vm';
|
|
5
|
+
import { Worker } from 'node:worker_threads';
|
|
6
|
+
import { safeJsonParse } from '../core/security.js';
|
|
7
|
+
const VALID_PLUGIN_ID = /^[a-z0-9][a-z0-9-_]{1,48}$/;
|
|
8
|
+
const MAX_PLUGIN_CODE_BYTES = 128 * 1024;
|
|
9
|
+
const PLUGIN_TIMEOUT_MS = 500;
|
|
10
|
+
const WORKER_KILL_BUFFER_MS = 250;
|
|
11
|
+
export function getDefaultPluginsDir() {
|
|
12
|
+
return path.join(os.homedir(), '.devanvil', 'plugins');
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Builds the wrapped plugin script using JSON-encoded string boundaries so NO host-realm
|
|
16
|
+
* objects (and therefore NO host Function constructor) ever cross into the sandbox context.
|
|
17
|
+
*/
|
|
18
|
+
function buildSandboxedScript(code, inputJson, optionsJson) {
|
|
19
|
+
return `
|
|
20
|
+
"use strict";
|
|
21
|
+
const __input = JSON.parse(${JSON.stringify(inputJson)});
|
|
22
|
+
const __options = JSON.parse(${JSON.stringify(optionsJson)});
|
|
23
|
+
${code}
|
|
24
|
+
if (typeof transform !== 'function') {
|
|
25
|
+
throw new Error('Plugin handler must define function transform(input, options)');
|
|
26
|
+
}
|
|
27
|
+
const __out = transform(__input, __options);
|
|
28
|
+
typeof __out === 'string' ? __out : JSON.stringify(__out, null, 2);
|
|
29
|
+
`;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Worker script executed inside an isolated node:worker_threads instance with empty env
|
|
33
|
+
* and capped V8 heap limits, running user plugin code inside a no-codegen node:vm context.
|
|
34
|
+
*/
|
|
35
|
+
const WORKER_RUNNER_CODE = `
|
|
36
|
+
'use strict';
|
|
37
|
+
const { parentPort, workerData } = require('node:worker_threads');
|
|
38
|
+
const vm = require('node:vm');
|
|
39
|
+
try {
|
|
40
|
+
const sandbox = Object.create(null);
|
|
41
|
+
const ctx = vm.createContext(sandbox, {
|
|
42
|
+
codeGeneration: { strings: false, wasm: false },
|
|
43
|
+
});
|
|
44
|
+
const script = new vm.Script(workerData.wrapped, {
|
|
45
|
+
filename: 'devanvil-plugin:' + workerData.pluginId,
|
|
46
|
+
});
|
|
47
|
+
const result = script.runInContext(ctx, { timeout: workerData.timeoutMs });
|
|
48
|
+
parentPort.postMessage({ ok: true, output: String(result ?? '') });
|
|
49
|
+
} catch (err) {
|
|
50
|
+
parentPort.postMessage({
|
|
51
|
+
ok: false,
|
|
52
|
+
error: err && typeof err.message === 'string' ? err.message : String(err),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
`;
|
|
56
|
+
/**
|
|
57
|
+
* Zero-Trust Local Plugin Loader & Hardened Sandbox.
|
|
58
|
+
*
|
|
59
|
+
* Defense-in-depth guarantees:
|
|
60
|
+
* 1. Only primitive strings cross the host -> sandbox boundary (no host prototypes / Function constructor).
|
|
61
|
+
* 2. `codeGeneration: { strings: false, wasm: false }` blocks `eval`, `new Function`, and `constructor.constructor(...)`.
|
|
62
|
+
* 3. `runPluginAsync` executes inside an isolated `node:worker_threads` Worker with empty `env`,
|
|
63
|
+
* 48 MB heap cap, and hard `worker.terminate()` on timeout so runaway plugins cannot freeze the HTTP server.
|
|
64
|
+
* 4. Strict plugin ID regex and realpath confinement prevent path traversal and symlink escapes.
|
|
65
|
+
*/
|
|
66
|
+
export class PluginLoader {
|
|
67
|
+
pluginsDir;
|
|
68
|
+
constructor(pluginsDir) {
|
|
69
|
+
this.pluginsDir = path.resolve(pluginsDir ?? getDefaultPluginsDir());
|
|
70
|
+
}
|
|
71
|
+
getPluginsDir() {
|
|
72
|
+
return this.pluginsDir;
|
|
73
|
+
}
|
|
74
|
+
resolveSafePlugin(pluginId) {
|
|
75
|
+
if (!VALID_PLUGIN_ID.test(pluginId)) {
|
|
76
|
+
throw new Error(`Invalid plugin id "${pluginId}"`);
|
|
77
|
+
}
|
|
78
|
+
const plugin = this.listPlugins().find((p) => p.id === pluginId);
|
|
79
|
+
if (!plugin) {
|
|
80
|
+
throw new Error(`Plugin "${pluginId}" not found in ${this.pluginsDir}`);
|
|
81
|
+
}
|
|
82
|
+
const codePath = path.resolve(plugin.dirPath, plugin.entry);
|
|
83
|
+
if (!codePath.startsWith(`${plugin.dirPath}${path.sep}`)) {
|
|
84
|
+
throw new Error('Blocked plugin entry path escape');
|
|
85
|
+
}
|
|
86
|
+
const lstat = fs.lstatSync(codePath);
|
|
87
|
+
if (lstat.isSymbolicLink() || !lstat.isFile()) {
|
|
88
|
+
throw new Error('Plugin entry must be a regular non-symlink file');
|
|
89
|
+
}
|
|
90
|
+
const realRoot = fs.realpathSync(this.pluginsDir);
|
|
91
|
+
const realCode = fs.realpathSync(codePath);
|
|
92
|
+
if (!realCode.startsWith(`${realRoot}${path.sep}`)) {
|
|
93
|
+
throw new Error('Blocked symlinked plugin directory escape');
|
|
94
|
+
}
|
|
95
|
+
if (lstat.size > MAX_PLUGIN_CODE_BYTES) {
|
|
96
|
+
throw new Error(`Plugin code exceeds ${MAX_PLUGIN_CODE_BYTES} byte safety limit`);
|
|
97
|
+
}
|
|
98
|
+
return { plugin, codePath };
|
|
99
|
+
}
|
|
100
|
+
listPlugins() {
|
|
101
|
+
if (!fs.existsSync(this.pluginsDir))
|
|
102
|
+
return [];
|
|
103
|
+
let entries;
|
|
104
|
+
try {
|
|
105
|
+
entries = fs.readdirSync(this.pluginsDir, { withFileTypes: true });
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return [];
|
|
109
|
+
}
|
|
110
|
+
const loaded = [];
|
|
111
|
+
for (const entry of entries) {
|
|
112
|
+
if (!entry.isDirectory() || entry.isSymbolicLink())
|
|
113
|
+
continue;
|
|
114
|
+
const dirPath = path.join(this.pluginsDir, entry.name);
|
|
115
|
+
const manifestPath = path.join(dirPath, 'plugin.json');
|
|
116
|
+
if (!fs.existsSync(manifestPath))
|
|
117
|
+
continue;
|
|
118
|
+
try {
|
|
119
|
+
const mStat = fs.lstatSync(manifestPath);
|
|
120
|
+
if (mStat.isSymbolicLink() || !mStat.isFile() || mStat.size > 32_768)
|
|
121
|
+
continue;
|
|
122
|
+
const raw = safeJsonParse(fs.readFileSync(manifestPath, 'utf8'));
|
|
123
|
+
const id = typeof raw.id === 'string' ? raw.id.trim() : '';
|
|
124
|
+
if (!VALID_PLUGIN_ID.test(id))
|
|
125
|
+
continue;
|
|
126
|
+
const entryFile = typeof raw.entry === 'string' && raw.entry.trim() ? raw.entry.trim() : 'handler.js';
|
|
127
|
+
if (entryFile.includes('..') || path.isAbsolute(entryFile))
|
|
128
|
+
continue;
|
|
129
|
+
const resolvedEntry = path.resolve(dirPath, entryFile);
|
|
130
|
+
if (!resolvedEntry.startsWith(`${dirPath}${path.sep}`) || !fs.existsSync(resolvedEntry))
|
|
131
|
+
continue;
|
|
132
|
+
if (fs.lstatSync(resolvedEntry).isSymbolicLink())
|
|
133
|
+
continue;
|
|
134
|
+
loaded.push({
|
|
135
|
+
id,
|
|
136
|
+
name: typeof raw.name === 'string' && raw.name.trim() ? raw.name.trim() : id,
|
|
137
|
+
version: typeof raw.version === 'string' ? raw.version : '1.0.0',
|
|
138
|
+
description: typeof raw.description === 'string' ? raw.description : 'Local DevAnvil Plugin',
|
|
139
|
+
author: typeof raw.author === 'string' ? raw.author : undefined,
|
|
140
|
+
inputPlaceholder: typeof raw.inputPlaceholder === 'string' ? raw.inputPlaceholder : undefined,
|
|
141
|
+
entry: entryFile,
|
|
142
|
+
dirPath,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
// Skip malformed plugin manifests safely
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return loaded.sort((a, b) => a.name.localeCompare(b.name));
|
|
150
|
+
}
|
|
151
|
+
readPluginSource(pluginId) {
|
|
152
|
+
const { plugin, codePath } = this.resolveSafePlugin(pluginId);
|
|
153
|
+
return {
|
|
154
|
+
plugin,
|
|
155
|
+
code: fs.readFileSync(codePath, 'utf8'),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
savePluginSource(pluginId, code) {
|
|
159
|
+
const { plugin, codePath } = this.resolveSafePlugin(pluginId);
|
|
160
|
+
const buf = Buffer.from(code, 'utf8');
|
|
161
|
+
if (buf.byteLength > MAX_PLUGIN_CODE_BYTES) {
|
|
162
|
+
throw new Error(`Plugin code exceeds ${MAX_PLUGIN_CODE_BYTES} byte safety limit`);
|
|
163
|
+
}
|
|
164
|
+
fs.writeFileSync(codePath, buf);
|
|
165
|
+
return { plugin, bytes: buf.byteLength };
|
|
166
|
+
}
|
|
167
|
+
deletePlugin(pluginId) {
|
|
168
|
+
if (!VALID_PLUGIN_ID.test(pluginId)) {
|
|
169
|
+
throw new Error(`Invalid plugin id "${pluginId}"`);
|
|
170
|
+
}
|
|
171
|
+
const plugin = this.listPlugins().find((p) => p.id === pluginId);
|
|
172
|
+
if (!plugin)
|
|
173
|
+
return false;
|
|
174
|
+
const resolvedDir = path.resolve(plugin.dirPath);
|
|
175
|
+
if (!resolvedDir.startsWith(`${this.pluginsDir}${path.sep}`)) {
|
|
176
|
+
throw new Error('Blocked plugin deletion outside plugins directory');
|
|
177
|
+
}
|
|
178
|
+
fs.rmSync(resolvedDir, { recursive: true, force: true });
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Synchronous VM sandbox execution (ideal for CLI & single-shot scripts).
|
|
183
|
+
* Uses primitive-only JSON boundaries + `codeGeneration: { strings: false, wasm: false }`.
|
|
184
|
+
*/
|
|
185
|
+
runPlugin(pluginId, input, options = {}) {
|
|
186
|
+
const { plugin, codePath } = this.resolveSafePlugin(pluginId);
|
|
187
|
+
const code = fs.readFileSync(codePath, 'utf8');
|
|
188
|
+
const wrapped = buildSandboxedScript(code, JSON.stringify(String(input)), JSON.stringify(options ?? {}));
|
|
189
|
+
const sandbox = Object.create(null);
|
|
190
|
+
const ctx = vm.createContext(sandbox, {
|
|
191
|
+
codeGeneration: { strings: false, wasm: false },
|
|
192
|
+
});
|
|
193
|
+
const t0 = performance.now();
|
|
194
|
+
const script = new vm.Script(wrapped, { filename: `devanvil-plugin:${plugin.id}` });
|
|
195
|
+
const out = script.runInContext(ctx, { timeout: PLUGIN_TIMEOUT_MS });
|
|
196
|
+
const durationMs = Math.round((performance.now() - t0) * 10) / 10;
|
|
197
|
+
return {
|
|
198
|
+
pluginId: plugin.id,
|
|
199
|
+
output: String(out ?? ''),
|
|
200
|
+
durationMs,
|
|
201
|
+
isolation: 'vm',
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
activeWorkers = 0;
|
|
205
|
+
/**
|
|
206
|
+
* Asynchronous hardened Worker Thread + VM sandbox execution (used by HTTP Server).
|
|
207
|
+
* Guarantees non-blocking event loop, empty worker env, capped V8 heap, concurrency cap, and hard terminate on timeout.
|
|
208
|
+
*/
|
|
209
|
+
async runPluginAsync(pluginId, input, options = {}, timeoutMs = PLUGIN_TIMEOUT_MS) {
|
|
210
|
+
if (this.activeWorkers >= 4) {
|
|
211
|
+
throw new Error('Too many concurrent plugin executions (max 4); please retry shortly');
|
|
212
|
+
}
|
|
213
|
+
const { plugin, codePath } = this.resolveSafePlugin(pluginId);
|
|
214
|
+
const code = fs.readFileSync(codePath, 'utf8');
|
|
215
|
+
const cappedTimeout = Math.min(Math.max(Math.trunc(timeoutMs), 50), 2000);
|
|
216
|
+
const wrapped = buildSandboxedScript(code, JSON.stringify(String(input)), JSON.stringify(options ?? {}));
|
|
217
|
+
const t0 = performance.now();
|
|
218
|
+
this.activeWorkers++;
|
|
219
|
+
return new Promise((resolve, reject) => {
|
|
220
|
+
let settled = false;
|
|
221
|
+
const release = () => {
|
|
222
|
+
this.activeWorkers = Math.max(0, this.activeWorkers - 1);
|
|
223
|
+
};
|
|
224
|
+
const worker = new Worker(WORKER_RUNNER_CODE, {
|
|
225
|
+
eval: true,
|
|
226
|
+
env: {},
|
|
227
|
+
workerData: {
|
|
228
|
+
pluginId: plugin.id,
|
|
229
|
+
wrapped,
|
|
230
|
+
timeoutMs: cappedTimeout,
|
|
231
|
+
},
|
|
232
|
+
resourceLimits: {
|
|
233
|
+
maxOldGenerationSizeMb: 48,
|
|
234
|
+
maxYoungGenerationSizeMb: 16,
|
|
235
|
+
codeRangeSizeMb: 16,
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
const killTimer = setTimeout(() => {
|
|
239
|
+
if (settled)
|
|
240
|
+
return;
|
|
241
|
+
settled = true;
|
|
242
|
+
release();
|
|
243
|
+
void worker.terminate();
|
|
244
|
+
reject(new Error(`Plugin "${plugin.id}" timed out after ${cappedTimeout}ms and was terminated`));
|
|
245
|
+
}, cappedTimeout + WORKER_KILL_BUFFER_MS);
|
|
246
|
+
killTimer.unref();
|
|
247
|
+
worker.once('message', (msg) => {
|
|
248
|
+
if (settled)
|
|
249
|
+
return;
|
|
250
|
+
settled = true;
|
|
251
|
+
clearTimeout(killTimer);
|
|
252
|
+
release();
|
|
253
|
+
void worker.terminate();
|
|
254
|
+
if (!msg.ok) {
|
|
255
|
+
reject(new Error(msg.error || 'Plugin execution failed'));
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
resolve({
|
|
259
|
+
pluginId: plugin.id,
|
|
260
|
+
output: String(msg.output ?? ''),
|
|
261
|
+
durationMs: Math.round((performance.now() - t0) * 10) / 10,
|
|
262
|
+
isolation: 'worker_threads+vm',
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
worker.once('error', (err) => {
|
|
266
|
+
if (settled)
|
|
267
|
+
return;
|
|
268
|
+
settled = true;
|
|
269
|
+
clearTimeout(killTimer);
|
|
270
|
+
release();
|
|
271
|
+
void worker.terminate();
|
|
272
|
+
reject(err);
|
|
273
|
+
});
|
|
274
|
+
worker.once('exit', (exitCode) => {
|
|
275
|
+
if (settled)
|
|
276
|
+
return;
|
|
277
|
+
settled = true;
|
|
278
|
+
clearTimeout(killTimer);
|
|
279
|
+
release();
|
|
280
|
+
reject(new Error(`Plugin worker exited unexpectedly (code ${exitCode})`));
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
scaffoldPlugin(rawId) {
|
|
285
|
+
const id = rawId.trim().toLowerCase().replace(/[^a-z0-9-_]+/g, '-');
|
|
286
|
+
if (!VALID_PLUGIN_ID.test(id)) {
|
|
287
|
+
throw new Error(`Invalid plugin id "${rawId}". Use lowercase letters, digits, hyphens (2-49 chars).`);
|
|
288
|
+
}
|
|
289
|
+
const dirPath = path.join(this.pluginsDir, id);
|
|
290
|
+
fs.mkdirSync(dirPath, { recursive: true });
|
|
291
|
+
const manifest = {
|
|
292
|
+
id,
|
|
293
|
+
name: id.replace(/[-_]+/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase()),
|
|
294
|
+
version: '1.0.0',
|
|
295
|
+
description: 'Zero-trust sandboxed local DevAnvil plugin',
|
|
296
|
+
inputPlaceholder: 'Enter text or JSON input…',
|
|
297
|
+
entry: 'handler.js',
|
|
298
|
+
};
|
|
299
|
+
const manifestPath = path.join(dirPath, 'plugin.json');
|
|
300
|
+
const handlerPath = path.join(dirPath, 'handler.js');
|
|
301
|
+
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
|
302
|
+
fs.writeFileSync(handlerPath, `// Runs inside DevAnvil's Zero-Trust Worker + VM Sandbox (no fs/process/network/eval, 500ms CPU cap)\nfunction transform(input, options) {\n const lines = String(input).split(/\\r?\\n/).filter(Boolean);\n return {\n plugin: ${JSON.stringify(id)},\n lineCount: lines.length,\n charCount: String(input).length,\n preview: lines.slice(0, 5),\n options,\n };\n}\n`, 'utf8');
|
|
303
|
+
return { dirPath, manifestPath, handlerPath };
|
|
304
|
+
}
|
|
305
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { SavedApiRequest } from '../core/importers.js';
|
|
2
|
+
import type { MockRouteInput } from './mock-store.js';
|
|
3
|
+
export interface RecordedTrafficEntry {
|
|
4
|
+
id: string;
|
|
5
|
+
recordedAt: string;
|
|
6
|
+
method: string;
|
|
7
|
+
url: string;
|
|
8
|
+
pathname: string;
|
|
9
|
+
requestHeaders: Record<string, string>;
|
|
10
|
+
requestBody?: string;
|
|
11
|
+
status: number;
|
|
12
|
+
responseContentType: string;
|
|
13
|
+
responseBody: string;
|
|
14
|
+
durationMs: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Bounded in-memory API Traffic Recorder.
|
|
18
|
+
* Captures proxied API Studio requests (with sensitive headers redacted) and exports them
|
|
19
|
+
* as Workspace Collections, Live Mock Routes, or an inferred OpenAPI 3.0.3 specification.
|
|
20
|
+
*/
|
|
21
|
+
export declare class RecorderStore {
|
|
22
|
+
private entries;
|
|
23
|
+
private enabled;
|
|
24
|
+
isEnabled(): boolean;
|
|
25
|
+
setEnabled(flag: boolean): boolean;
|
|
26
|
+
record(input: Omit<RecordedTrafficEntry, 'id' | 'recordedAt'>): RecordedTrafficEntry | null;
|
|
27
|
+
list(): RecordedTrafficEntry[];
|
|
28
|
+
clear(): void;
|
|
29
|
+
toSavedRequests(): SavedApiRequest[];
|
|
30
|
+
toMockRoutes(): MockRouteInput[];
|
|
31
|
+
/**
|
|
32
|
+
* Infers a clean OpenAPI 3.0.3 JSON specification directly from captured live traffic!
|
|
33
|
+
*/
|
|
34
|
+
inferOpenApiSpec(title?: string): Record<string, unknown>;
|
|
35
|
+
}
|