devanvil 0.0.0-stage → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +659 -0
- package/dist/core/contract-drift.d.ts +49 -0
- package/dist/core/contract-drift.js +302 -0
- package/dist/core/converters.d.ts +18 -0
- package/dist/core/converters.js +981 -0
- package/dist/core/cron.d.ts +33 -0
- package/dist/core/cron.js +306 -0
- package/dist/core/crypto.d.ts +59 -0
- package/dist/core/crypto.js +250 -0
- package/dist/core/curl.d.ts +17 -0
- package/dist/core/curl.js +170 -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 +256 -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 +390 -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 +351 -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 +599 -0
- package/dist/core/security.d.ts +34 -0
- package/dist/core/security.js +284 -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 +166 -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 +348 -0
- package/dist/server/http-proxy.d.ts +55 -0
- package/dist/server/http-proxy.js +364 -0
- package/dist/server/http-utils.d.ts +28 -0
- package/dist/server/http-utils.js +106 -0
- package/dist/server/load-tester.d.ts +53 -0
- package/dist/server/load-tester.js +134 -0
- package/dist/server/mcp.d.ts +35 -0
- package/dist/server/mcp.js +466 -0
- package/dist/server/mock-store.d.ts +38 -0
- package/dist/server/mock-store.js +197 -0
- package/dist/server/plugin-loader.d.ts +60 -0
- package/dist/server/plugin-loader.js +285 -0
- package/dist/server/recorder-store.d.ts +35 -0
- package/dist/server/recorder-store.js +146 -0
- package/dist/server/routes/network-routes.d.ts +3 -0
- package/dist/server/routes/network-routes.js +391 -0
- package/dist/server/routes/tools-routes.d.ts +3 -0
- package/dist/server/routes/tools-routes.js +292 -0
- package/dist/server/routes/workspace-routes.d.ts +3 -0
- package/dist/server/routes/workspace-routes.js +240 -0
- package/dist/server/webhook-store.d.ts +29 -0
- package/dist/server/webhook-store.js +90 -0
- package/dist/server/workspace-store.d.ts +91 -0
- package/dist/server/workspace-store.js +447 -0
- package/dist/server/ws-probe.d.ts +34 -0
- package/dist/server/ws-probe.js +283 -0
- package/dist/ui/app.js +274 -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 +704 -0
- package/dist/ui/tools-network.js +727 -0
- package/dist/ui/tools-ops.js +295 -0
- package/dist/ui/tools-pro.js +500 -0
- package/dist/ui/tools-security.js +389 -0
- package/dist/ui/tools-v12.js +745 -0
- package/dist/ui/tools-v13.js +321 -0
- package/dist/ui/tools-v20.js +563 -0
- package/dist/ui/tools-v21.js +395 -0
- package/package.json +75 -4
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import { isDangerousKey, safeJsonParse } from './security.js';
|
|
2
|
+
function makeReqId(idx, name) {
|
|
3
|
+
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 24) || 'req';
|
|
4
|
+
return `req_${idx + 1}_${slug}`;
|
|
5
|
+
}
|
|
6
|
+
function safeHeaderMap(entries) {
|
|
7
|
+
const out = Object.create(null);
|
|
8
|
+
for (const item of entries) {
|
|
9
|
+
if (!item || item.disabled === true)
|
|
10
|
+
continue;
|
|
11
|
+
const rawKey = typeof item.key === 'string' ? item.key : typeof item.name === 'string' ? item.name : '';
|
|
12
|
+
const key = rawKey.trim();
|
|
13
|
+
if (!key || isDangerousKey(key) || key.startsWith(':'))
|
|
14
|
+
continue;
|
|
15
|
+
if (/[\r\n]/.test(key))
|
|
16
|
+
continue;
|
|
17
|
+
const val = typeof item.value === 'string' ? item.value : String(item.value ?? '');
|
|
18
|
+
if (/[\r\n]/.test(val))
|
|
19
|
+
continue;
|
|
20
|
+
out[key] = val;
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Resolves `{{VAR_NAME}}` and `{{env.SYSTEM_VAR}}` placeholders across request URL, headers,
|
|
26
|
+
* and body. System `{{env.*}}` variables are only resolved when `options.processEnv` is provided
|
|
27
|
+
* so secrets never need to be stored in plaintext inside `devanvil.json`.
|
|
28
|
+
*/
|
|
29
|
+
export function interpolateEnvString(input, variables, options) {
|
|
30
|
+
if (!input || !input.includes('{{'))
|
|
31
|
+
return input;
|
|
32
|
+
return input.replace(/\{\{\s*([A-Za-z0-9_.-]{1,64})\s*\}\}/g, (match, key) => {
|
|
33
|
+
if (isDangerousKey(key))
|
|
34
|
+
return match;
|
|
35
|
+
if (key.startsWith('env.')) {
|
|
36
|
+
const envKey = key.slice(4);
|
|
37
|
+
if (!envKey || isDangerousKey(envKey) || !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(envKey)) {
|
|
38
|
+
return match;
|
|
39
|
+
}
|
|
40
|
+
const envMap = options?.processEnv;
|
|
41
|
+
if (envMap && Object.prototype.hasOwnProperty.call(envMap, envKey) && envMap[envKey] !== undefined) {
|
|
42
|
+
return envMap[envKey];
|
|
43
|
+
}
|
|
44
|
+
return match;
|
|
45
|
+
}
|
|
46
|
+
if (Object.prototype.hasOwnProperty.call(variables, key)) {
|
|
47
|
+
return variables[key];
|
|
48
|
+
}
|
|
49
|
+
return match;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
export function interpolateRequestWithEnv(req, variables, options) {
|
|
53
|
+
const headers = Object.create(null);
|
|
54
|
+
for (const [k, v] of Object.entries(req.headers ?? {})) {
|
|
55
|
+
if (isDangerousKey(k))
|
|
56
|
+
continue;
|
|
57
|
+
headers[k] = interpolateEnvString(v, variables, options);
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
method: req.method,
|
|
61
|
+
url: interpolateEnvString(req.url, variables, options),
|
|
62
|
+
headers,
|
|
63
|
+
body: interpolateEnvString(req.body ?? '', variables, options),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Parses a Postman v2.0 / v2.1 Collection JSON into DevAnvil requests and optional Mock routes
|
|
68
|
+
* (from saved Postman example responses).
|
|
69
|
+
*/
|
|
70
|
+
export function importPostmanCollection(rawJson) {
|
|
71
|
+
const parsed = safeJsonParse(rawJson);
|
|
72
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
73
|
+
throw new Error('Invalid Postman collection JSON');
|
|
74
|
+
}
|
|
75
|
+
const info = (parsed.info && typeof parsed.info === 'object' ? parsed.info : {});
|
|
76
|
+
const collectionName = typeof info.name === 'string' && info.name.trim() ? info.name.trim() : 'Imported Postman Collection';
|
|
77
|
+
const items = Array.isArray(parsed.item) ? parsed.item : null;
|
|
78
|
+
if (!items) {
|
|
79
|
+
throw new Error('Expected Postman Collection JSON with top-level "item" array');
|
|
80
|
+
}
|
|
81
|
+
const requests = [];
|
|
82
|
+
const mockRoutes = [];
|
|
83
|
+
const warnings = [];
|
|
84
|
+
function extractUrl(urlField) {
|
|
85
|
+
if (typeof urlField === 'string')
|
|
86
|
+
return urlField;
|
|
87
|
+
if (urlField && typeof urlField === 'object') {
|
|
88
|
+
const u = urlField;
|
|
89
|
+
if (typeof u.raw === 'string' && u.raw.trim())
|
|
90
|
+
return u.raw.trim();
|
|
91
|
+
const proto = typeof u.protocol === 'string' ? u.protocol : 'https';
|
|
92
|
+
const host = Array.isArray(u.host) ? u.host.join('.') : typeof u.host === 'string' ? u.host : 'example.com';
|
|
93
|
+
const pth = Array.isArray(u.path) ? `/${u.path.join('/')}` : typeof u.path === 'string' ? u.path : '/';
|
|
94
|
+
return `${proto}://${host}${pth}`;
|
|
95
|
+
}
|
|
96
|
+
return '';
|
|
97
|
+
}
|
|
98
|
+
function walk(list, folderPrefix, depth) {
|
|
99
|
+
if (depth > 12 || requests.length >= 200)
|
|
100
|
+
return;
|
|
101
|
+
for (const rawItem of list) {
|
|
102
|
+
if (!rawItem || typeof rawItem !== 'object')
|
|
103
|
+
continue;
|
|
104
|
+
const item = rawItem;
|
|
105
|
+
const itemName = typeof item.name === 'string' ? item.name.trim() : 'Unnamed Request';
|
|
106
|
+
// Folder containing nested items
|
|
107
|
+
if (Array.isArray(item.item)) {
|
|
108
|
+
const nextFolder = folderPrefix ? `${folderPrefix} / ${itemName}` : itemName;
|
|
109
|
+
walk(item.item, nextFolder, depth + 1);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (!item.request || typeof item.request !== 'object')
|
|
113
|
+
continue;
|
|
114
|
+
const req = item.request;
|
|
115
|
+
const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';
|
|
116
|
+
const url = extractUrl(req.url);
|
|
117
|
+
if (!url) {
|
|
118
|
+
warnings.push(`Skipped "${itemName}": missing URL`);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const headers = Array.isArray(req.header)
|
|
122
|
+
? safeHeaderMap(req.header)
|
|
123
|
+
: Object.create(null);
|
|
124
|
+
// Extract Postman Bearer / API Key / Basic Auth cleanly
|
|
125
|
+
if (req.auth && typeof req.auth === 'object') {
|
|
126
|
+
const auth = req.auth;
|
|
127
|
+
if (auth.type === 'bearer' && Array.isArray(auth.bearer)) {
|
|
128
|
+
const tok = auth.bearer.find((b) => b.key === 'token');
|
|
129
|
+
if (tok && typeof tok.value === 'string' && tok.value) {
|
|
130
|
+
headers['Authorization'] = `Bearer ${tok.value}`;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
else if (auth.type === 'apikey' && Array.isArray(auth.apikey)) {
|
|
134
|
+
const kEntry = auth.apikey.find((b) => b.key === 'key');
|
|
135
|
+
const vEntry = auth.apikey.find((b) => b.key === 'value');
|
|
136
|
+
if (kEntry && vEntry && typeof kEntry.value === 'string' && typeof vEntry.value === 'string' && !isDangerousKey(kEntry.value)) {
|
|
137
|
+
headers[kEntry.value] = vEntry.value;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
let body = '';
|
|
142
|
+
if (req.body && typeof req.body === 'object') {
|
|
143
|
+
const b = req.body;
|
|
144
|
+
if (b.mode === 'raw' && typeof b.raw === 'string') {
|
|
145
|
+
body = b.raw;
|
|
146
|
+
}
|
|
147
|
+
else if (b.mode === 'urlencoded' && Array.isArray(b.urlencoded)) {
|
|
148
|
+
const params = new URLSearchParams();
|
|
149
|
+
for (const kv of b.urlencoded) {
|
|
150
|
+
if (kv.disabled === true || typeof kv.key !== 'string')
|
|
151
|
+
continue;
|
|
152
|
+
params.append(kv.key, typeof kv.value === 'string' ? kv.value : '');
|
|
153
|
+
}
|
|
154
|
+
body = params.toString();
|
|
155
|
+
headers['Content-Type'] ??= 'application/x-www-form-urlencoded';
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
requests.push({
|
|
159
|
+
id: makeReqId(requests.length, itemName),
|
|
160
|
+
name: itemName,
|
|
161
|
+
folder: folderPrefix || undefined,
|
|
162
|
+
method,
|
|
163
|
+
url,
|
|
164
|
+
headers,
|
|
165
|
+
body: body || undefined,
|
|
166
|
+
notes: typeof req.description === 'string' ? req.description : undefined,
|
|
167
|
+
});
|
|
168
|
+
// Extract first saved example response -> Live Mock route!
|
|
169
|
+
if (Array.isArray(item.response) && item.response.length > 0 && mockRoutes.length < 100) {
|
|
170
|
+
const sample = item.response[0];
|
|
171
|
+
if (sample && typeof sample === 'object') {
|
|
172
|
+
let mockPath = '/imported';
|
|
173
|
+
try {
|
|
174
|
+
const parsedUrl = new URL(url.replace(/\{\{[^}]+\}\}/g, 'http://placeholder.local'));
|
|
175
|
+
mockPath = parsedUrl.pathname || '/';
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
const idx = url.indexOf('/');
|
|
179
|
+
mockPath = idx >= 0 ? url.slice(idx).split('?')[0] || '/' : '/';
|
|
180
|
+
}
|
|
181
|
+
mockRoutes.push({
|
|
182
|
+
method,
|
|
183
|
+
path: mockPath.startsWith('/') ? mockPath : `/${mockPath}`,
|
|
184
|
+
status: typeof sample.code === 'number' ? sample.code : 200,
|
|
185
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
186
|
+
body: typeof sample.body === 'string' ? sample.body : JSON.stringify({ ok: true }),
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
walk(items, '', 0);
|
|
193
|
+
return {
|
|
194
|
+
format: 'postman-v2.1',
|
|
195
|
+
collectionName,
|
|
196
|
+
requests,
|
|
197
|
+
mockRoutes,
|
|
198
|
+
warnings,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Parses a browser DevTools HAR 1.2 archive into replayable DevAnvil API requests
|
|
203
|
+
* AND instant offline Mock routes capturing real status codes and JSON/text responses!
|
|
204
|
+
*/
|
|
205
|
+
export function importHarArchive(rawJson) {
|
|
206
|
+
const parsed = safeJsonParse(rawJson);
|
|
207
|
+
const log = parsed?.log && typeof parsed.log === 'object' ? parsed.log : null;
|
|
208
|
+
const entries = log && Array.isArray(log.entries) ? log.entries : null;
|
|
209
|
+
if (!entries) {
|
|
210
|
+
throw new Error('Expected HAR 1.2 JSON with top-level "log.entries" array');
|
|
211
|
+
}
|
|
212
|
+
const requests = [];
|
|
213
|
+
const mockRoutes = [];
|
|
214
|
+
const seenMockKeys = new Set();
|
|
215
|
+
const warnings = [];
|
|
216
|
+
for (const rawEntry of entries) {
|
|
217
|
+
if (requests.length >= 200) {
|
|
218
|
+
warnings.push('Truncated HAR import at 200 entries');
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
if (!rawEntry || typeof rawEntry !== 'object')
|
|
222
|
+
continue;
|
|
223
|
+
const entry = rawEntry;
|
|
224
|
+
const req = entry.request && typeof entry.request === 'object' ? entry.request : null;
|
|
225
|
+
if (!req || typeof req.url !== 'string')
|
|
226
|
+
continue;
|
|
227
|
+
const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';
|
|
228
|
+
const url = req.url;
|
|
229
|
+
// Skip static assets (.png, .css, .js, .woff2) so API requests stay clean
|
|
230
|
+
let pathname = '/';
|
|
231
|
+
try {
|
|
232
|
+
pathname = new URL(url).pathname;
|
|
233
|
+
if (/\.(?:png|jpe?g|gif|webp|svg|ico|css|woff2?|ttf|map)$/i.test(pathname))
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const rawHeaders = Array.isArray(req.headers)
|
|
240
|
+
? req.headers
|
|
241
|
+
: [];
|
|
242
|
+
const headers = safeHeaderMap(rawHeaders.filter((h) => {
|
|
243
|
+
const n = typeof h?.name === 'string' ? h.name.toLowerCase() : '';
|
|
244
|
+
return n !== 'host' && n !== 'content-length' && n !== 'accept-encoding' && n !== 'connection';
|
|
245
|
+
}));
|
|
246
|
+
const postData = req.postData && typeof req.postData === 'object' ? req.postData : null;
|
|
247
|
+
const body = postData && typeof postData.text === 'string' ? postData.text : undefined;
|
|
248
|
+
requests.push({
|
|
249
|
+
id: makeReqId(requests.length, `${method}_${pathname}`),
|
|
250
|
+
name: `${method} ${pathname}`,
|
|
251
|
+
method,
|
|
252
|
+
url,
|
|
253
|
+
headers,
|
|
254
|
+
body,
|
|
255
|
+
});
|
|
256
|
+
// Capture real response -> Instant Record-and-Replay Mock Route!
|
|
257
|
+
const resp = entry.response && typeof entry.response === 'object' ? entry.response : null;
|
|
258
|
+
const mockKey = `${method} ${pathname}`;
|
|
259
|
+
if (resp && !seenMockKeys.has(mockKey) && mockRoutes.length < 100) {
|
|
260
|
+
const content = resp.content && typeof resp.content === 'object' ? resp.content : null;
|
|
261
|
+
const mime = typeof content?.mimeType === 'string' ? content.mimeType : 'application/json; charset=utf-8';
|
|
262
|
+
let respText = typeof content?.text === 'string' ? content.text : '';
|
|
263
|
+
if (content?.encoding === 'base64' && respText) {
|
|
264
|
+
try {
|
|
265
|
+
respText = Buffer.from(respText, 'base64').toString('utf8');
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
respText = '';
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (respText.length <= 200_000) {
|
|
272
|
+
seenMockKeys.add(mockKey);
|
|
273
|
+
mockRoutes.push({
|
|
274
|
+
method,
|
|
275
|
+
path: pathname,
|
|
276
|
+
status: typeof resp.status === 'number' && resp.status >= 100 && resp.status <= 599 ? resp.status : 200,
|
|
277
|
+
headers: { 'Content-Type': mime.split(';')[0].trim() || 'application/json' },
|
|
278
|
+
body: respText || JSON.stringify({ replayedFromHar: true, path: pathname }),
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
format: 'har-1.2',
|
|
285
|
+
collectionName: 'Imported HAR Capture',
|
|
286
|
+
requests,
|
|
287
|
+
mockRoutes,
|
|
288
|
+
warnings,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Parses standard `.http` / `.rest` files (VS Code REST Client / JetBrains HTTP Client).
|
|
293
|
+
*/
|
|
294
|
+
export function importHttpFile(rawText) {
|
|
295
|
+
const blocks = rawText.split(/^###.*$/m);
|
|
296
|
+
const requests = [];
|
|
297
|
+
const warnings = [];
|
|
298
|
+
for (const rawBlock of blocks) {
|
|
299
|
+
const lines = rawBlock.replace(/\r\n/g, '\n').split('\n');
|
|
300
|
+
let name = '';
|
|
301
|
+
let i = 0;
|
|
302
|
+
// Leading comments or blank lines
|
|
303
|
+
while (i < lines.length) {
|
|
304
|
+
const t = lines[i].trim();
|
|
305
|
+
if (!t) {
|
|
306
|
+
i++;
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (t.startsWith('#') || t.startsWith('//')) {
|
|
310
|
+
if (!name)
|
|
311
|
+
name = t.replace(/^(?:#+|\/\/)\s*/, '').trim();
|
|
312
|
+
i++;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
if (i >= lines.length)
|
|
318
|
+
continue;
|
|
319
|
+
const reqLine = lines[i].trim();
|
|
320
|
+
const match = reqLine.match(/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)(?:\s+HTTP\/[\d.]+)?$/i);
|
|
321
|
+
if (!match) {
|
|
322
|
+
warnings.push(`Skipped unrecognized request line: "${reqLine.slice(0, 60)}"`);
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
const method = match[1].toUpperCase();
|
|
326
|
+
const url = match[2];
|
|
327
|
+
i++;
|
|
328
|
+
const headers = Object.create(null);
|
|
329
|
+
while (i < lines.length) {
|
|
330
|
+
const line = lines[i];
|
|
331
|
+
if (line.trim() === '') {
|
|
332
|
+
i++;
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
const colon = line.indexOf(':');
|
|
336
|
+
if (colon > 0) {
|
|
337
|
+
const key = line.slice(0, colon).trim();
|
|
338
|
+
const val = line.slice(colon + 1).trim();
|
|
339
|
+
if (key && !isDangerousKey(key))
|
|
340
|
+
headers[key] = val;
|
|
341
|
+
}
|
|
342
|
+
i++;
|
|
343
|
+
}
|
|
344
|
+
const body = lines.slice(i).join('\n').trim();
|
|
345
|
+
requests.push({
|
|
346
|
+
id: makeReqId(requests.length, name || `${method}_${url}`),
|
|
347
|
+
name: name || `${method} ${url}`,
|
|
348
|
+
method,
|
|
349
|
+
url,
|
|
350
|
+
headers,
|
|
351
|
+
body: body || undefined,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
format: 'http-file',
|
|
356
|
+
collectionName: 'Imported .http File',
|
|
357
|
+
requests,
|
|
358
|
+
mockRoutes: [],
|
|
359
|
+
warnings,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export type JwtAlgorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'ES256';
|
|
2
|
+
export interface JwtAuditFinding {
|
|
3
|
+
severity: 'critical' | 'warning' | 'info' | 'pass';
|
|
4
|
+
code: string;
|
|
5
|
+
message: string;
|
|
6
|
+
}
|
|
7
|
+
export interface JwtDecodedResult {
|
|
8
|
+
header: Record<string, unknown>;
|
|
9
|
+
payload: Record<string, unknown>;
|
|
10
|
+
signature: string;
|
|
11
|
+
algorithm: string;
|
|
12
|
+
timestamps: {
|
|
13
|
+
iat?: string;
|
|
14
|
+
nbf?: string;
|
|
15
|
+
exp?: string;
|
|
16
|
+
expired?: boolean;
|
|
17
|
+
notYetValid?: boolean;
|
|
18
|
+
expiresInSeconds?: number;
|
|
19
|
+
};
|
|
20
|
+
audit: JwtAuditFinding[];
|
|
21
|
+
}
|
|
22
|
+
export declare function decodeJwt(token: string, nowSec?: number): JwtDecodedResult;
|
|
23
|
+
export declare function signJwt(payload: Record<string, unknown>, secretOrPrivateKey: string, options?: {
|
|
24
|
+
alg?: JwtAlgorithm;
|
|
25
|
+
expiresInSeconds?: number;
|
|
26
|
+
headerExtra?: Record<string, unknown>;
|
|
27
|
+
}): string;
|
|
28
|
+
export interface JwtVerifyResult {
|
|
29
|
+
valid: boolean;
|
|
30
|
+
signatureValid: boolean;
|
|
31
|
+
claimsValid: boolean;
|
|
32
|
+
reason?: string;
|
|
33
|
+
decoded: JwtDecodedResult;
|
|
34
|
+
}
|
|
35
|
+
export declare function verifyJwt(token: string, secretOrPublicKey: string, options?: {
|
|
36
|
+
allowedAlgorithms?: JwtAlgorithm[];
|
|
37
|
+
clockToleranceSec?: number;
|
|
38
|
+
nowSec?: number;
|
|
39
|
+
}): JwtVerifyResult;
|
package/dist/core/jwt.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { createHmac, sign as cryptoSign, verify as cryptoVerify } from 'node:crypto';
|
|
2
|
+
import { safeJsonParse, timingSafeEqualStr } from './security.js';
|
|
3
|
+
const HMAC_ALGOS = {
|
|
4
|
+
HS256: 'sha256',
|
|
5
|
+
HS384: 'sha384',
|
|
6
|
+
HS512: 'sha512',
|
|
7
|
+
};
|
|
8
|
+
const ASYMMETRIC_ALGOS = {
|
|
9
|
+
RS256: { digest: 'RSA-SHA256' },
|
|
10
|
+
ES256: { digest: 'SHA256', dsaEncoding: 'ieee-p1363' },
|
|
11
|
+
};
|
|
12
|
+
const SENSITIVE_CLAIM_RE = /(pass(word|wd)?|secret|private[_-]?key|api[_-]?key|ssn|credit[_-]?card|cvv|pin)/i;
|
|
13
|
+
function decodeBase64UrlJson(part, label) {
|
|
14
|
+
if (!/^[A-Za-z0-9_-]+$/.test(part)) {
|
|
15
|
+
throw new Error(`Invalid Base64URL encoding in JWT ${label}`);
|
|
16
|
+
}
|
|
17
|
+
const raw = Buffer.from(part, 'base64url').toString('utf8');
|
|
18
|
+
const parsed = safeJsonParse(raw);
|
|
19
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
20
|
+
throw new Error(`JWT ${label} must be a JSON object`);
|
|
21
|
+
}
|
|
22
|
+
return parsed;
|
|
23
|
+
}
|
|
24
|
+
export function decodeJwt(token, nowSec = Math.floor(Date.now() / 1000)) {
|
|
25
|
+
const trimmed = token.trim().replace(/^Bearer\s+/i, '');
|
|
26
|
+
const parts = trimmed.split('.');
|
|
27
|
+
if (parts.length !== 3) {
|
|
28
|
+
throw new Error('Malformed JWT: expected 3 dot-separated segments (header.payload.signature)');
|
|
29
|
+
}
|
|
30
|
+
const [headerPart, payloadPart, signaturePart] = parts;
|
|
31
|
+
const header = decodeBase64UrlJson(headerPart, 'header');
|
|
32
|
+
const payload = decodeBase64UrlJson(payloadPart, 'payload');
|
|
33
|
+
const algorithm = typeof header.alg === 'string' ? header.alg : 'unknown';
|
|
34
|
+
const timestamps = {};
|
|
35
|
+
const audit = [];
|
|
36
|
+
// Algorithm security checks
|
|
37
|
+
if (algorithm.toLowerCase() === 'none') {
|
|
38
|
+
audit.push({
|
|
39
|
+
severity: 'critical',
|
|
40
|
+
code: 'ALG_NONE',
|
|
41
|
+
message: 'Token uses "alg: none" (unsigned). Servers MUST reject unsigned JWTs.',
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
else if (algorithm in HMAC_ALGOS || algorithm in ASYMMETRIC_ALGOS) {
|
|
45
|
+
audit.push({
|
|
46
|
+
severity: 'pass',
|
|
47
|
+
code: 'ALG_SUPPORTED',
|
|
48
|
+
message: `Uses standard signing algorithm ${algorithm}.`,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
audit.push({
|
|
53
|
+
severity: 'warning',
|
|
54
|
+
code: 'ALG_UNCOMMON',
|
|
55
|
+
message: `Algorithm "${algorithm}" is uncommon or unrecognized by DevAnvil verifier.`,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (!signaturePart) {
|
|
59
|
+
audit.push({
|
|
60
|
+
severity: 'critical',
|
|
61
|
+
code: 'EMPTY_SIGNATURE',
|
|
62
|
+
message: 'JWT signature segment is empty.',
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
if (typeof payload.iat === 'number') {
|
|
66
|
+
timestamps.iat = new Date(payload.iat * 1000).toISOString();
|
|
67
|
+
}
|
|
68
|
+
if (typeof payload.nbf === 'number') {
|
|
69
|
+
timestamps.nbf = new Date(payload.nbf * 1000).toISOString();
|
|
70
|
+
timestamps.notYetValid = nowSec < payload.nbf;
|
|
71
|
+
if (timestamps.notYetValid) {
|
|
72
|
+
audit.push({
|
|
73
|
+
severity: 'warning',
|
|
74
|
+
code: 'NOT_YET_VALID',
|
|
75
|
+
message: `Token is not valid yet (nbf: ${timestamps.nbf}).`,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (typeof payload.exp === 'number') {
|
|
80
|
+
timestamps.exp = new Date(payload.exp * 1000).toISOString();
|
|
81
|
+
timestamps.expiresInSeconds = payload.exp - nowSec;
|
|
82
|
+
timestamps.expired = nowSec >= payload.exp;
|
|
83
|
+
if (timestamps.expired) {
|
|
84
|
+
audit.push({
|
|
85
|
+
severity: 'warning',
|
|
86
|
+
code: 'TOKEN_EXPIRED',
|
|
87
|
+
message: `Token expired at ${timestamps.exp}.`,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
else if (typeof payload.iat === 'number' && payload.exp - payload.iat > 86400 * 30) {
|
|
91
|
+
audit.push({
|
|
92
|
+
severity: 'warning',
|
|
93
|
+
code: 'LONG_LIFETIME',
|
|
94
|
+
message: 'Token lifetime exceeds 30 days; prefer short-lived access tokens with refresh rotation.',
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
audit.push({
|
|
99
|
+
severity: 'pass',
|
|
100
|
+
code: 'VALID_EXP',
|
|
101
|
+
message: `Expiration claim set (${timestamps.exp}).`,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
audit.push({
|
|
107
|
+
severity: 'warning',
|
|
108
|
+
code: 'MISSING_EXP',
|
|
109
|
+
message: 'Token has no "exp" (expiration) claim; non-expiring tokens increase breach blast radius.',
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
// Detect sensitive payload fields (JWT payloads are readable by anyone!)
|
|
113
|
+
const sensitiveKeys = Object.keys(payload).filter((k) => SENSITIVE_CLAIM_RE.test(k));
|
|
114
|
+
if (sensitiveKeys.length > 0) {
|
|
115
|
+
audit.push({
|
|
116
|
+
severity: 'warning',
|
|
117
|
+
code: 'SENSITIVE_PAYLOAD_DATA',
|
|
118
|
+
message: `Potentially sensitive claim(s) in plaintext JWT payload: ${sensitiveKeys.join(', ')}. JWTs are Base64-encoded, not encrypted.`,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
header,
|
|
123
|
+
payload,
|
|
124
|
+
signature: signaturePart,
|
|
125
|
+
algorithm,
|
|
126
|
+
timestamps,
|
|
127
|
+
audit,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
export function signJwt(payload, secretOrPrivateKey, options = {}) {
|
|
131
|
+
const alg = options.alg ?? 'HS256';
|
|
132
|
+
if (!(alg in HMAC_ALGOS) && !(alg in ASYMMETRIC_ALGOS)) {
|
|
133
|
+
throw new Error(`Unsupported JWT signing algorithm: ${String(alg)}`);
|
|
134
|
+
}
|
|
135
|
+
if (!secretOrPrivateKey) {
|
|
136
|
+
throw new Error('Secret or private key is required to sign a JWT');
|
|
137
|
+
}
|
|
138
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
139
|
+
const fullPayload = { ...payload };
|
|
140
|
+
if (fullPayload.iat === undefined) {
|
|
141
|
+
fullPayload.iat = nowSec;
|
|
142
|
+
}
|
|
143
|
+
if (options.expiresInSeconds !== undefined && options.expiresInSeconds > 0 && fullPayload.exp === undefined) {
|
|
144
|
+
fullPayload.exp = nowSec + Math.floor(options.expiresInSeconds);
|
|
145
|
+
}
|
|
146
|
+
const header = {
|
|
147
|
+
...(options.headerExtra ?? {}),
|
|
148
|
+
alg,
|
|
149
|
+
typ: 'JWT',
|
|
150
|
+
};
|
|
151
|
+
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf8').toString('base64url');
|
|
152
|
+
const encodedPayload = Buffer.from(JSON.stringify(fullPayload), 'utf8').toString('base64url');
|
|
153
|
+
const signingInput = `${encodedHeader}.${encodedPayload}`;
|
|
154
|
+
let signatureB64;
|
|
155
|
+
if (alg in HMAC_ALGOS) {
|
|
156
|
+
const hashAlg = HMAC_ALGOS[alg];
|
|
157
|
+
signatureB64 = createHmac(hashAlg, secretOrPrivateKey).update(signingInput, 'utf8').digest('base64url');
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
const cfg = ASYMMETRIC_ALGOS[alg];
|
|
161
|
+
const sigBuf = cryptoSign(cfg.digest, Buffer.from(signingInput, 'utf8'), cfg.dsaEncoding
|
|
162
|
+
? { key: secretOrPrivateKey, dsaEncoding: cfg.dsaEncoding }
|
|
163
|
+
: secretOrPrivateKey);
|
|
164
|
+
signatureB64 = sigBuf.toString('base64url');
|
|
165
|
+
}
|
|
166
|
+
return `${signingInput}.${signatureB64}`;
|
|
167
|
+
}
|
|
168
|
+
export function verifyJwt(token, secretOrPublicKey, options = {}) {
|
|
169
|
+
const nowSec = options.nowSec ?? Math.floor(Date.now() / 1000);
|
|
170
|
+
const tolerance = Math.max(options.clockToleranceSec ?? 0, 0);
|
|
171
|
+
const decoded = decodeJwt(token, nowSec);
|
|
172
|
+
const alg = decoded.algorithm;
|
|
173
|
+
// Hard rejection of alg: none
|
|
174
|
+
if (alg.toLowerCase() === 'none') {
|
|
175
|
+
return {
|
|
176
|
+
valid: false,
|
|
177
|
+
signatureValid: false,
|
|
178
|
+
claimsValid: false,
|
|
179
|
+
reason: 'Rejected unsigned token ("alg: none")',
|
|
180
|
+
decoded,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
const allowed = options.allowedAlgorithms ?? ['HS256', 'HS384', 'HS512', 'RS256', 'ES256'];
|
|
184
|
+
if (!allowed.includes(alg)) {
|
|
185
|
+
return {
|
|
186
|
+
valid: false,
|
|
187
|
+
signatureValid: false,
|
|
188
|
+
claimsValid: false,
|
|
189
|
+
reason: `Algorithm "${alg}" is not in allowed algorithms [${allowed.join(', ')}]`,
|
|
190
|
+
decoded,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// Prevent RSA/EC public-key-as-HMAC algorithm confusion when PEM key is passed with HS*
|
|
194
|
+
if (alg in HMAC_ALGOS && /-----BEGIN (PUBLIC|RSA PUBLIC|EC PUBLIC|CERTIFICATE) KEY-----/.test(secretOrPublicKey)) {
|
|
195
|
+
return {
|
|
196
|
+
valid: false,
|
|
197
|
+
signatureValid: false,
|
|
198
|
+
claimsValid: false,
|
|
199
|
+
reason: 'Algorithm confusion blocked: refusing to use an asymmetric PEM public key as an HMAC secret',
|
|
200
|
+
decoded,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
const trimmed = token.trim().replace(/^Bearer\s+/i, '');
|
|
204
|
+
const parts = trimmed.split('.');
|
|
205
|
+
const signingInput = `${parts[0]}.${parts[1]}`;
|
|
206
|
+
const signaturePart = parts[2] ?? '';
|
|
207
|
+
let signatureValid = false;
|
|
208
|
+
try {
|
|
209
|
+
if (alg in HMAC_ALGOS) {
|
|
210
|
+
const expected = createHmac(HMAC_ALGOS[alg], secretOrPublicKey).update(signingInput, 'utf8').digest('base64url');
|
|
211
|
+
signatureValid = timingSafeEqualStr(signaturePart, expected);
|
|
212
|
+
}
|
|
213
|
+
else if (alg in ASYMMETRIC_ALGOS) {
|
|
214
|
+
const cfg = ASYMMETRIC_ALGOS[alg];
|
|
215
|
+
const sigBuf = Buffer.from(signaturePart, 'base64url');
|
|
216
|
+
signatureValid = cryptoVerify(cfg.digest, Buffer.from(signingInput, 'utf8'), cfg.dsaEncoding
|
|
217
|
+
? { key: secretOrPublicKey, dsaEncoding: cfg.dsaEncoding }
|
|
218
|
+
: secretOrPublicKey, sigBuf);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch (err) {
|
|
222
|
+
return {
|
|
223
|
+
valid: false,
|
|
224
|
+
signatureValid: false,
|
|
225
|
+
claimsValid: false,
|
|
226
|
+
reason: `Cryptographic verification error: ${err.message}`,
|
|
227
|
+
decoded,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
if (!signatureValid) {
|
|
231
|
+
return {
|
|
232
|
+
valid: false,
|
|
233
|
+
signatureValid: false,
|
|
234
|
+
claimsValid: false,
|
|
235
|
+
reason: 'Invalid cryptographic signature',
|
|
236
|
+
decoded,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
let claimsValid = true;
|
|
240
|
+
let reason;
|
|
241
|
+
if (typeof decoded.payload.exp === 'number' && nowSec >= decoded.payload.exp + tolerance) {
|
|
242
|
+
claimsValid = false;
|
|
243
|
+
reason = `Token expired at ${decoded.timestamps.exp}`;
|
|
244
|
+
}
|
|
245
|
+
else if (typeof decoded.payload.nbf === 'number' && nowSec + tolerance < decoded.payload.nbf) {
|
|
246
|
+
claimsValid = false;
|
|
247
|
+
reason = `Token not active until ${decoded.timestamps.nbf}`;
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
valid: signatureValid && claimsValid,
|
|
251
|
+
signatureValid,
|
|
252
|
+
claimsValid,
|
|
253
|
+
...(reason ? { reason } : {}),
|
|
254
|
+
decoded,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export interface ModelBudgetEstimate {
|
|
2
|
+
model: string;
|
|
3
|
+
provider: string;
|
|
4
|
+
estimatedTokens: number;
|
|
5
|
+
contextWindow: number;
|
|
6
|
+
contextUsagePct: number;
|
|
7
|
+
inputCostPer1KCallsUsd: number;
|
|
8
|
+
}
|
|
9
|
+
export interface LlmTokenAnalysis {
|
|
10
|
+
characters: number;
|
|
11
|
+
bytes: number;
|
|
12
|
+
words: number;
|
|
13
|
+
lines: number;
|
|
14
|
+
estimatedBaseTokens: number;
|
|
15
|
+
codeDensity: 'prose' | 'mixed' | 'code-heavy';
|
|
16
|
+
models: ModelBudgetEstimate[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Offline BPE-calibrated tokenizer estimator handling English, Arabic/UTF-8, CJK,
|
|
20
|
+
* punctuation runs, numbers, and source code symbols more accurately than chars/4.
|
|
21
|
+
*/
|
|
22
|
+
export declare function estimateBpeTokens(text: string): number;
|
|
23
|
+
export declare function analyzeLlmText(text: string): LlmTokenAnalysis;
|
|
24
|
+
export interface CompactResult {
|
|
25
|
+
compacted: string;
|
|
26
|
+
originalTokens: number;
|
|
27
|
+
compactedTokens: number;
|
|
28
|
+
tokensSaved: number;
|
|
29
|
+
savingsPct: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Compacts prompt/code context by removing trailing whitespace, collapsing blank lines,
|
|
33
|
+
* and optionally stripping single-line // comments and minifying JSON blocks.
|
|
34
|
+
*/
|
|
35
|
+
export declare function compactContextText(input: string, options?: {
|
|
36
|
+
stripLineComments?: boolean;
|
|
37
|
+
minifyJson?: boolean;
|
|
38
|
+
}): CompactResult;
|