vibecode-anything 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +239 -67
- package/dist/cli.js +2140 -73
- package/dist/core/adapters.d.ts +26 -3
- package/dist/core/adapters.js +411 -25
- package/dist/core/agent-adapter.d.ts +67 -0
- package/dist/core/agent-adapter.js +312 -0
- package/dist/core/anti-cheat.d.ts +6 -0
- package/dist/core/anti-cheat.js +372 -0
- package/dist/core/badge.d.ts +18 -0
- package/dist/core/badge.js +360 -0
- package/dist/core/cache.d.ts +47 -0
- package/dist/core/cache.js +403 -0
- package/dist/core/ci-export.d.ts +35 -0
- package/dist/core/ci-export.js +796 -0
- package/dist/core/ci-formats.d.ts +21 -0
- package/dist/core/ci-formats.js +388 -0
- package/dist/core/client-codegen.d.ts +36 -0
- package/dist/core/client-codegen.js +2538 -0
- package/dist/core/compose.d.ts +71 -0
- package/dist/core/compose.js +1088 -0
- package/dist/core/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +21 -1
- package/dist/core/doctor.js +234 -21
- package/dist/core/exec.d.ts +26 -2
- package/dist/core/exec.js +235 -8
- package/dist/core/fixtures.d.ts +153 -0
- package/dist/core/fixtures.js +2245 -0
- package/dist/core/format.d.ts +77 -0
- package/dist/core/format.js +632 -0
- package/dist/core/fs-snapshot.d.ts +37 -0
- package/dist/core/fs-snapshot.js +216 -0
- package/dist/core/graphql-export.d.ts +34 -0
- package/dist/core/graphql-export.js +2482 -0
- package/dist/core/har-export.d.ts +29 -0
- package/dist/core/har-export.js +988 -0
- package/dist/core/html-report.d.ts +27 -0
- package/dist/core/html-report.js +1535 -0
- package/dist/core/http-export.d.ts +31 -0
- package/dist/core/http-export.js +726 -0
- package/dist/core/impact.d.ts +80 -0
- package/dist/core/impact.js +1412 -0
- package/dist/core/lint.d.ts +38 -0
- package/dist/core/lint.js +1111 -0
- package/dist/core/load-export.d.ts +37 -0
- package/dist/core/load-export.js +1813 -0
- package/dist/core/mcp-export.d.ts +35 -0
- package/dist/core/mcp-export.js +1736 -0
- package/dist/core/mock-server.d.ts +47 -0
- package/dist/core/mock-server.js +1722 -0
- package/dist/core/openapi-export.d.ts +44 -0
- package/dist/core/openapi-export.js +1074 -0
- package/dist/core/parity.d.ts +6 -1
- package/dist/core/parity.js +36 -1
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.js +45 -9
- package/dist/core/regression.d.ts +54 -0
- package/dist/core/regression.js +529 -0
- package/dist/core/responsive.d.ts +86 -0
- package/dist/core/responsive.js +606 -0
- package/dist/core/run.d.ts +74 -0
- package/dist/core/run.js +696 -0
- package/dist/core/scheduler.d.ts +24 -0
- package/dist/core/scheduler.js +162 -0
- package/dist/core/schema-export.d.ts +29 -0
- package/dist/core/schema-export.js +2215 -0
- package/dist/core/schema.d.ts +3 -2
- package/dist/core/schema.js +460 -17
- package/dist/core/security.d.ts +233 -0
- package/dist/core/security.js +1839 -0
- package/dist/core/server-export.d.ts +38 -0
- package/dist/core/server-export.js +3198 -0
- package/dist/core/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +11 -2
- package/dist/core/store.js +128 -8
- package/dist/core/target-map.d.ts +34 -0
- package/dist/core/target-map.js +262 -0
- package/dist/core/test-exporter.d.ts +25 -0
- package/dist/core/test-exporter.js +1918 -0
- package/dist/core/types.d.ts +182 -14
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.js +65 -16
- package/dist/core/watch.d.ts +28 -3
- package/dist/core/watch.js +222 -12
- package/dist/core/yaml.d.ts +5 -0
- package/dist/core/yaml.js +1009 -0
- package/dist/diagnostics/diagnose.d.ts +53 -0
- package/dist/diagnostics/diagnose.js +1083 -0
- package/dist/diagnostics/flake.d.ts +71 -0
- package/dist/diagnostics/flake.js +608 -0
- package/dist/diagnostics/mutation-audit.d.ts +69 -0
- package/dist/diagnostics/mutation-audit.js +769 -0
- package/dist/diagnostics/spatial.d.ts +42 -0
- package/dist/diagnostics/spatial.js +346 -0
- package/dist/diagnostics/trends.d.ts +122 -0
- package/dist/diagnostics/trends.js +1190 -0
- package/dist/discovery/discover.d.ts +111 -0
- package/dist/discovery/discover.js +2017 -0
- package/dist/discovery/lock.d.ts +116 -0
- package/dist/discovery/lock.js +1505 -0
- package/dist/discovery/routes.d.ts +36 -0
- package/dist/discovery/routes.js +1494 -0
- package/dist/discovery/test-importer.d.ts +92 -0
- package/dist/discovery/test-importer.js +4952 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +99 -0
- package/dist/ingestors/api-collections.d.ts +28 -0
- package/dist/ingestors/api-collections.js +2335 -0
- package/dist/ingestors/api-repo.d.ts +2 -1
- package/dist/ingestors/api-repo.js +483 -85
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +2 -0
- package/dist/ingestors/bridges.js +702 -0
- package/dist/ingestors/cli.d.ts +2 -1
- package/dist/ingestors/cli.js +234 -46
- package/dist/ingestors/curl.d.ts +14 -0
- package/dist/ingestors/curl.js +1024 -0
- package/dist/ingestors/graphql.d.ts +56 -0
- package/dist/ingestors/graphql.js +1852 -0
- package/dist/ingestors/http-file.d.ts +20 -0
- package/dist/ingestors/http-file.js +923 -0
- package/dist/ingestors/index.js +486 -6
- package/dist/ingestors/openrpc.d.ts +29 -0
- package/dist/ingestors/openrpc.js +1807 -0
- package/dist/ingestors/proto.d.ts +47 -0
- package/dist/ingestors/proto.js +2690 -0
- package/dist/ingestors/trace.d.ts +10 -0
- package/dist/ingestors/trace.js +599 -0
- package/dist/ingestors/video.d.ts +4 -1
- package/dist/ingestors/video.js +86 -36
- package/dist/ingestors/web.d.ts +16 -1
- package/dist/ingestors/web.js +474 -32
- package/dist/mcp/server.js +3532 -67
- package/dist/oracles/api-repo.js +102 -30
- package/dist/oracles/cli.js +65 -17
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.js +178 -28
- package/dist/oracles/index.d.ts +3 -1
- package/dist/oracles/index.js +243 -14
- package/dist/oracles/perf-budget.d.ts +90 -0
- package/dist/oracles/perf-budget.js +1329 -0
- package/dist/oracles/stream.d.ts +94 -0
- package/dist/oracles/stream.js +1268 -0
- package/dist/oracles/ui-states.d.ts +49 -0
- package/dist/oracles/ui-states.js +894 -0
- package/dist/oracles/video.d.ts +1 -1
- package/dist/oracles/video.js +232 -16
- package/dist/oracles/web.js +464 -73
- package/dist/plugins/builtins.d.ts +12 -0
- package/dist/plugins/builtins.js +1052 -0
- package/dist/plugins/registry.d.ts +86 -0
- package/dist/plugins/registry.js +554 -0
- package/dist/setup/index.js +145 -33
- package/package.json +56 -47
- package/skills/vibecode-anything/SKILL.md +75 -52
|
@@ -0,0 +1,2105 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { VibecodeError, errorMessage } from "../core/errors.js";
|
|
4
|
+
import { validateContract } from "../core/schema.js";
|
|
5
|
+
import { parseYaml } from "../core/yaml.js";
|
|
6
|
+
import { isSensitiveHeader, isSensitiveQueryParam, mergeHeaders, redactHeaders } from "./trace.js";
|
|
7
|
+
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
|
8
|
+
const MAX_REF_DEPTH = 12;
|
|
9
|
+
const MAX_SCHEMA_DEPTH = 16;
|
|
10
|
+
const MAX_CHANNELS = 50;
|
|
11
|
+
const MAX_SAMPLE_DEPTH = 10;
|
|
12
|
+
const MAX_SANITIZE_DEPTH = 32;
|
|
13
|
+
const MAX_SCHEMA_KEYS = 200;
|
|
14
|
+
const MAX_NODE_BUDGET = 2500;
|
|
15
|
+
const VALID_HTTP_METHODS = new Set([
|
|
16
|
+
"GET",
|
|
17
|
+
"POST",
|
|
18
|
+
"PUT",
|
|
19
|
+
"PATCH",
|
|
20
|
+
"DELETE",
|
|
21
|
+
"HEAD",
|
|
22
|
+
"OPTIONS"
|
|
23
|
+
]);
|
|
24
|
+
const ASYNCAPI_VERSION_RE = /^([23])\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?$/;
|
|
25
|
+
const ASYNCAPI_YAML_HEADER_RE = /^\s*['"]?asyncapi['"]?\s*:\s*['"]?[23]\.\d+/m;
|
|
26
|
+
const OPENAPI_YAML_HEADER_RE = /^\s*['"]?(?:openapi|swagger)['"]?\s*:/m;
|
|
27
|
+
const INSOMNIA_YAML_HEADER_RE = /^\s*_type\s*:\s*['"]?export['"]?\s*$/m;
|
|
28
|
+
const HEADER_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
29
|
+
const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
|
|
30
|
+
const CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f]+/g;
|
|
31
|
+
const SENSITIVE_HEADER_RE = /(?:^x-hub-signature(?:-256)?$|^x-signature(?:-256|-sha256|-hmac)?$|^x-webhook-signature$|^x-webhook-secret$|^x-hmac(?:-signature|-sha256)?$|signature|hmac|secret|token|password|passwd|api[-_]?key|apikey|auth|jwt|cookie|csrf|xsrf|private[-_]?key|signing[-_]?key|credential)/i;
|
|
32
|
+
const SENSITIVE_FIELD_RE = /(?:secret|hmac|signature|signing[-_]?key|api[-_]?key|apikey|access[-_]?token|refresh[-_]?token|auth[-_]?token|id[-_]?token|password|passwd|passphrase|private[-_]?key|client[-_]?secret|webhook[-_]?secret|vault[-_]?path|bearer|jwt|credential|cookie|set[-_]?cookie|session[-_]?id|authorization|proxy[-_]?authorization|csrf|xsrf)/i;
|
|
33
|
+
const SENSITIVE_QUERY_RE = /(?:hmac|webhook[-_]?secret|signing[-_]?key|secret|token|signature|sig|api[-_]?key|apikey|password|passwd|auth|jwt|credential)/i;
|
|
34
|
+
const SENSITIVE_HEADER_VALUE_RE = /^\s*(?:Bearer|Basic|Token|Digest|ApiKey|HMAC)\s+\S+|^(?:hmac-)?(?:sha512|sha256|sha1)=[0-9a-fA-F]{8,}|^t=\d+,v\d+=[0-9a-fA-F]{8,}|\b(?:whsec|sk_live|sk_test|gh[pousr])_[A-Za-z0-9_=-]{4,}/i;
|
|
35
|
+
const INLINE_AUTH_VALUE_RE = /\b(Bearer|Basic|Token|Digest|ApiKey|HMAC)\s+([^\s"'`<>]+)/gi;
|
|
36
|
+
const INLINE_TOKEN_RE = /\b(?:whsec|sk_live|sk_test|gh[pousr])_[A-Za-z0-9_=-]{4,}/g;
|
|
37
|
+
const INLINE_HMAC_SIG_RE = /\b(?:hmac-)?(?:sha512|sha256|sha1)=[0-9a-fA-F]{8,}|\bt=\d+,v\d+=[0-9a-fA-F]{8,}/gi;
|
|
38
|
+
const VAULT_PATH_RE = /(?:file:\/\/)?(?:[A-Za-z]:)?(?:[\\/][^\\/\s"'`<>|]*)*[\\/]?\.vibecode-vault(?:[\\/][^\\/\s"'`<>|]*)*/gi;
|
|
39
|
+
// Greedy userinfo capture before the authority delimiter so multi-@ and non-HTTP URL credentials are stripped.
|
|
40
|
+
const URL_USERINFO_RE = /([a-z][a-z0-9+.-]*:\/\/|(?:^|[\s"'`(\[{=])\/\/)([^/\s"'`<>]+)@/gi;
|
|
41
|
+
const INLINE_URL_RE = /[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>)\]}]+/gi;
|
|
42
|
+
const INLINE_SENSITIVE_QUERY_RE = /([?&])([^=&\s#"'`<>]+)=([^&\s#"'`<>]+)/g;
|
|
43
|
+
const INLINE_SENSITIVE_HEADER_RE = /\b(?:(Cookie|Set-Cookie)\s*[:=]\s*[^\s,\r\n;]+(?:\s*;\s*[A-Za-z0-9_.-]+(?:=[^\s,\r\n;]+)?)*|(Authorization|Proxy-Authorization)\s*[:=]\s*(?:[A-Za-z][A-Za-z0-9_-]*\s+(?:\[REDACTED\]|[^\s,;]+)|\[REDACTED\]|[^\s,;]+)|(X-API-Key|X-Auth-Token|X-Access-Token|X-Session-Token|X-Secret|X-CSRF-Token|X-XSRF-Token|CSRF-Token|XSRF-Token|X-Hub-Signature(?:-256)?|X-HMAC(?:-SHA256|-Signature)?|X-Webhook-(?:Signature|Secret))\s*[:=]\s*(?:(?:Bearer|Basic|Token|ApiKey|Digest|HMAC)\s+(?:\[REDACTED\]|[^\s,;]+)|\[REDACTED\]|[^\s,;]+))/gi;
|
|
44
|
+
const INLINE_JSON_SECRET_KV_RE = /(["'])([A-Za-z_][A-Za-z0-9_.-]*)\1\s*:\s*(?:(")((?:\\.|[^"\\\r\n])*)"|(')((?:\\.|[^'\\\r\n])*)')/g;
|
|
45
|
+
const ENV_SECRET_ASSIGN_RE = /\b([A-Z0-9_]*(?:SECRET|HMAC|TOKEN|API_KEY|APIKEY|PASSWORD|PASSWD|PRIVATE_KEY|SIGNING_KEY|WEBHOOK_KEY|CREDENTIAL)[A-Z0-9_]*)\s*=\s*([^\s"'`,;]+)/gi;
|
|
46
|
+
function hasOwn(obj, key) {
|
|
47
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
48
|
+
}
|
|
49
|
+
function isObject(value) {
|
|
50
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
51
|
+
}
|
|
52
|
+
function isUnsafeKey(key) {
|
|
53
|
+
return key === "__proto__" || key === "constructor" || key === "prototype";
|
|
54
|
+
}
|
|
55
|
+
function safeGet(obj, key) {
|
|
56
|
+
if (!key || isUnsafeKey(key) || !hasOwn(obj, key))
|
|
57
|
+
return undefined;
|
|
58
|
+
return obj[key];
|
|
59
|
+
}
|
|
60
|
+
function stripBom(raw) {
|
|
61
|
+
return raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
|
|
62
|
+
}
|
|
63
|
+
function pushWarning(ctx, message) {
|
|
64
|
+
const clean = message.trim();
|
|
65
|
+
if (!clean || ctx.warningSet.has(clean))
|
|
66
|
+
return;
|
|
67
|
+
ctx.warningSet.add(clean);
|
|
68
|
+
ctx.warnings.push(clean);
|
|
69
|
+
}
|
|
70
|
+
function isAsyncApiSensitiveHeader(name) {
|
|
71
|
+
const lower = name.trim().toLowerCase();
|
|
72
|
+
if (!lower)
|
|
73
|
+
return false;
|
|
74
|
+
return isSensitiveHeader(lower) || SENSITIVE_HEADER_RE.test(lower);
|
|
75
|
+
}
|
|
76
|
+
function isSensitiveFieldName(name) {
|
|
77
|
+
const trimmed = name.trim();
|
|
78
|
+
if (!trimmed)
|
|
79
|
+
return false;
|
|
80
|
+
return SENSITIVE_FIELD_RE.test(trimmed);
|
|
81
|
+
}
|
|
82
|
+
function isAsyncApiSensitiveQueryParam(name) {
|
|
83
|
+
const trimmed = name.trim();
|
|
84
|
+
if (!trimmed)
|
|
85
|
+
return false;
|
|
86
|
+
return isSensitiveQueryParam(trimmed) || SENSITIVE_QUERY_RE.test(trimmed);
|
|
87
|
+
}
|
|
88
|
+
function recordSecretValue(secretValues, raw) {
|
|
89
|
+
if (typeof raw !== "string")
|
|
90
|
+
return;
|
|
91
|
+
const trimmed = raw.trim();
|
|
92
|
+
if (!trimmed || trimmed === "[REDACTED]")
|
|
93
|
+
return;
|
|
94
|
+
if (trimmed.length >= 3) {
|
|
95
|
+
secretValues.add(trimmed);
|
|
96
|
+
}
|
|
97
|
+
const schemeMatch = /^(?:Bearer|Basic|Token|Digest|ApiKey|HMAC)\s+(.+)$/i.exec(trimmed);
|
|
98
|
+
if (schemeMatch && schemeMatch[1].trim().length >= 3) {
|
|
99
|
+
secretValues.add(schemeMatch[1].trim());
|
|
100
|
+
}
|
|
101
|
+
const sigMatch = /^(?:sha256|sha1)=([0-9a-fA-F]{6,})$/i.exec(trimmed);
|
|
102
|
+
if (sigMatch && sigMatch[1]) {
|
|
103
|
+
secretValues.add(sigMatch[1]);
|
|
104
|
+
}
|
|
105
|
+
if (trimmed.includes("=")) {
|
|
106
|
+
for (const part of trimmed.split(/[;,]/)) {
|
|
107
|
+
const eqIdx = part.indexOf("=");
|
|
108
|
+
if (eqIdx > 0) {
|
|
109
|
+
const val = part.slice(eqIdx + 1).trim();
|
|
110
|
+
if (val.length >= 3 && val !== "[REDACTED]") {
|
|
111
|
+
secretValues.add(val);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function sanitizeParsedValue(value, depth = 0) {
|
|
118
|
+
if (depth >= MAX_SANITIZE_DEPTH)
|
|
119
|
+
return null;
|
|
120
|
+
if (value === null || typeof value !== "object")
|
|
121
|
+
return value;
|
|
122
|
+
if (Array.isArray(value)) {
|
|
123
|
+
return value.map((item) => sanitizeParsedValue(item, depth + 1));
|
|
124
|
+
}
|
|
125
|
+
const src = value;
|
|
126
|
+
const out = {};
|
|
127
|
+
for (const key of Object.keys(src)) {
|
|
128
|
+
if (isUnsafeKey(key))
|
|
129
|
+
continue;
|
|
130
|
+
out[key] = sanitizeParsedValue(src[key], depth + 1);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
function sanitizeUrlString(rawUrl, secretValues, options = {}) {
|
|
135
|
+
let redacted = false;
|
|
136
|
+
let cleaned = rawUrl.trim().replace(CONTROL_CHAR_GLOBAL_RE, "");
|
|
137
|
+
if (!cleaned) {
|
|
138
|
+
return { safeUrl: "", origin: "", pathname: "", redacted: false, valid: false };
|
|
139
|
+
}
|
|
140
|
+
// Strip raw userinfo before URL parsing in case the URL contains templates
|
|
141
|
+
cleaned = cleaned.replace(URL_USERINFO_RE, (_m, scheme, userinfo) => {
|
|
142
|
+
redacted = true;
|
|
143
|
+
const colonIdx = userinfo.indexOf(":");
|
|
144
|
+
const rawUser = colonIdx >= 0 ? userinfo.slice(0, colonIdx) : userinfo;
|
|
145
|
+
const rawPass = colonIdx >= 0 ? userinfo.slice(colonIdx + 1) : "";
|
|
146
|
+
try {
|
|
147
|
+
recordSecretValue(secretValues, decodeURIComponent(userinfo));
|
|
148
|
+
recordSecretValue(secretValues, decodeURIComponent(rawUser));
|
|
149
|
+
if (rawPass)
|
|
150
|
+
recordSecretValue(secretValues, decodeURIComponent(rawPass));
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
recordSecretValue(secretValues, userinfo);
|
|
154
|
+
recordSecretValue(secretValues, rawUser);
|
|
155
|
+
if (rawPass)
|
|
156
|
+
recordSecretValue(secretValues, rawPass);
|
|
157
|
+
}
|
|
158
|
+
recordSecretValue(secretValues, rawUser);
|
|
159
|
+
if (rawPass) {
|
|
160
|
+
recordSecretValue(secretValues, rawPass);
|
|
161
|
+
const lastColon = rawPass.lastIndexOf(":");
|
|
162
|
+
if (lastColon >= 0)
|
|
163
|
+
recordSecretValue(secretValues, rawPass.slice(lastColon + 1));
|
|
164
|
+
}
|
|
165
|
+
return scheme;
|
|
166
|
+
});
|
|
167
|
+
if (cleaned.includes("#")) {
|
|
168
|
+
const hashIdx = cleaned.indexOf("#");
|
|
169
|
+
const fragment = cleaned.slice(hashIdx + 1);
|
|
170
|
+
if (fragment.length > 0) {
|
|
171
|
+
redacted = true;
|
|
172
|
+
recordSecretValue(secretValues, fragment);
|
|
173
|
+
}
|
|
174
|
+
cleaned = cleaned.slice(0, hashIdx);
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const normalized = /^[a-z][a-z0-9+.-]*:\/\//i.test(cleaned) ? cleaned : `https://${cleaned}`;
|
|
178
|
+
const parsed = new URL(normalized);
|
|
179
|
+
if (options.requireHttp !== false && parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
180
|
+
return { safeUrl: "", origin: "", pathname: "", redacted, valid: false };
|
|
181
|
+
}
|
|
182
|
+
if (parsed.username || parsed.password) {
|
|
183
|
+
redacted = true;
|
|
184
|
+
recordSecretValue(secretValues, parsed.username);
|
|
185
|
+
recordSecretValue(secretValues, parsed.password);
|
|
186
|
+
parsed.username = "";
|
|
187
|
+
parsed.password = "";
|
|
188
|
+
}
|
|
189
|
+
if (parsed.hash) {
|
|
190
|
+
redacted = true;
|
|
191
|
+
recordSecretValue(secretValues, parsed.hash.slice(1));
|
|
192
|
+
parsed.hash = "";
|
|
193
|
+
}
|
|
194
|
+
const safeParams = new URLSearchParams();
|
|
195
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
196
|
+
if (isUnsafeKey(k))
|
|
197
|
+
continue;
|
|
198
|
+
if (isAsyncApiSensitiveQueryParam(k) || SENSITIVE_HEADER_VALUE_RE.test(v)) {
|
|
199
|
+
redacted = true;
|
|
200
|
+
recordSecretValue(secretValues, v);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
safeParams.append(k, v);
|
|
204
|
+
}
|
|
205
|
+
const queryStr = safeParams.toString();
|
|
206
|
+
const basePath = parsed.pathname.replace(/\/+$/, "");
|
|
207
|
+
const safeUrl = `${parsed.origin}${basePath}${queryStr ? `?${queryStr}` : ""}`;
|
|
208
|
+
return {
|
|
209
|
+
safeUrl,
|
|
210
|
+
origin: parsed.origin,
|
|
211
|
+
pathname: parsed.pathname || "/",
|
|
212
|
+
redacted,
|
|
213
|
+
valid: true
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return { safeUrl: "", origin: "", pathname: "", redacted, valid: false };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
function scrubText(text, secretValues) {
|
|
221
|
+
let redacted = false;
|
|
222
|
+
let out = text.replace(VAULT_PATH_RE, () => {
|
|
223
|
+
redacted = true;
|
|
224
|
+
return "[REDACTED]";
|
|
225
|
+
});
|
|
226
|
+
out = out.replace(INLINE_URL_RE, (rawMatch) => {
|
|
227
|
+
const res = sanitizeUrlString(rawMatch, secretValues, { requireHttp: false });
|
|
228
|
+
if (res.redacted)
|
|
229
|
+
redacted = true;
|
|
230
|
+
if (res.valid && res.redacted)
|
|
231
|
+
return res.safeUrl;
|
|
232
|
+
const hashIdx = rawMatch.indexOf("#");
|
|
233
|
+
let fallback = hashIdx >= 0 ? (recordSecretValue(secretValues, rawMatch.slice(hashIdx + 1)), rawMatch.slice(0, hashIdx)) : rawMatch;
|
|
234
|
+
if (hashIdx >= 0 && rawMatch.length > hashIdx + 1)
|
|
235
|
+
redacted = true;
|
|
236
|
+
fallback = fallback.replace(URL_USERINFO_RE, (_m, scheme, userinfo) => {
|
|
237
|
+
redacted = true;
|
|
238
|
+
recordSecretValue(secretValues, userinfo);
|
|
239
|
+
const colonIdx = userinfo.indexOf(":");
|
|
240
|
+
if (colonIdx >= 0) {
|
|
241
|
+
const rawPass = userinfo.slice(colonIdx + 1);
|
|
242
|
+
recordSecretValue(secretValues, rawPass);
|
|
243
|
+
const lastColon = rawPass.lastIndexOf(":");
|
|
244
|
+
if (lastColon >= 0)
|
|
245
|
+
recordSecretValue(secretValues, rawPass.slice(lastColon + 1));
|
|
246
|
+
}
|
|
247
|
+
return `${scheme}[REDACTED]@`;
|
|
248
|
+
});
|
|
249
|
+
fallback = fallback.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, qKey, qVal) => {
|
|
250
|
+
if (!isAsyncApiSensitiveQueryParam(qKey) && !SENSITIVE_HEADER_VALUE_RE.test(qVal))
|
|
251
|
+
return match;
|
|
252
|
+
redacted = true;
|
|
253
|
+
recordSecretValue(secretValues, qVal);
|
|
254
|
+
return `${sep}${qKey}=[REDACTED]`;
|
|
255
|
+
});
|
|
256
|
+
return fallback;
|
|
257
|
+
});
|
|
258
|
+
out = out.replace(URL_USERINFO_RE, (_m, scheme, userinfo) => {
|
|
259
|
+
redacted = true;
|
|
260
|
+
recordSecretValue(secretValues, userinfo);
|
|
261
|
+
const colonIdx = userinfo.indexOf(":");
|
|
262
|
+
if (colonIdx >= 0) {
|
|
263
|
+
recordSecretValue(secretValues, userinfo.slice(0, colonIdx));
|
|
264
|
+
const rawPass = userinfo.slice(colonIdx + 1);
|
|
265
|
+
recordSecretValue(secretValues, rawPass);
|
|
266
|
+
const lastColon = rawPass.lastIndexOf(":");
|
|
267
|
+
if (lastColon >= 0)
|
|
268
|
+
recordSecretValue(secretValues, rawPass.slice(lastColon + 1));
|
|
269
|
+
}
|
|
270
|
+
return `${scheme}[REDACTED]@`;
|
|
271
|
+
});
|
|
272
|
+
out = out.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, qKey, qVal) => {
|
|
273
|
+
if (!isAsyncApiSensitiveQueryParam(qKey) && !SENSITIVE_HEADER_VALUE_RE.test(qVal))
|
|
274
|
+
return match;
|
|
275
|
+
redacted = true;
|
|
276
|
+
recordSecretValue(secretValues, qVal);
|
|
277
|
+
return `${sep}${qKey}=[REDACTED]`;
|
|
278
|
+
});
|
|
279
|
+
out = out.replace(INLINE_AUTH_VALUE_RE, (match, scheme, val) => {
|
|
280
|
+
if (val === "[REDACTED]")
|
|
281
|
+
return match;
|
|
282
|
+
redacted = true;
|
|
283
|
+
recordSecretValue(secretValues, val);
|
|
284
|
+
return `${scheme} [REDACTED]`;
|
|
285
|
+
});
|
|
286
|
+
out = out.replace(INLINE_SENSITIVE_HEADER_RE, (match, cookieHdr, authHdr, otherHdr) => {
|
|
287
|
+
redacted = true;
|
|
288
|
+
const hdrName = cookieHdr || authHdr || otherHdr || "Authorization";
|
|
289
|
+
const sepIdx = match.search(/[:=]/);
|
|
290
|
+
if (sepIdx >= 0) {
|
|
291
|
+
recordSecretValue(secretValues, match.slice(sepIdx + 1));
|
|
292
|
+
}
|
|
293
|
+
return `${hdrName}: [REDACTED]`;
|
|
294
|
+
});
|
|
295
|
+
out = out.replace(INLINE_TOKEN_RE, (match) => {
|
|
296
|
+
redacted = true;
|
|
297
|
+
recordSecretValue(secretValues, match);
|
|
298
|
+
return "[REDACTED]";
|
|
299
|
+
});
|
|
300
|
+
out = out.replace(INLINE_HMAC_SIG_RE, (match) => {
|
|
301
|
+
redacted = true;
|
|
302
|
+
recordSecretValue(secretValues, match);
|
|
303
|
+
return "[REDACTED]";
|
|
304
|
+
});
|
|
305
|
+
out = out.replace(INLINE_JSON_SECRET_KV_RE, (match, q1, key, dq, dv, sq, sv) => {
|
|
306
|
+
if (!isSensitiveFieldName(key))
|
|
307
|
+
return match;
|
|
308
|
+
redacted = true;
|
|
309
|
+
const q2 = dq ?? sq ?? '"';
|
|
310
|
+
const innerVal = dv ?? sv ?? "";
|
|
311
|
+
if (innerVal && innerVal !== "[REDACTED]") {
|
|
312
|
+
recordSecretValue(secretValues, innerVal);
|
|
313
|
+
}
|
|
314
|
+
return `${q1}${key}${q1}: ${q2}[REDACTED]${q2}`;
|
|
315
|
+
});
|
|
316
|
+
out = out.replace(ENV_SECRET_ASSIGN_RE, (match, envName, envVal) => {
|
|
317
|
+
if (envVal === "[REDACTED]")
|
|
318
|
+
return match;
|
|
319
|
+
redacted = true;
|
|
320
|
+
recordSecretValue(secretValues, envVal);
|
|
321
|
+
return `${envName}=[REDACTED]`;
|
|
322
|
+
});
|
|
323
|
+
const sorted = [...secretValues]
|
|
324
|
+
.filter((s) => s.length >= 3 && s !== "[REDACTED]")
|
|
325
|
+
.sort((a, b) => b.length - a.length);
|
|
326
|
+
for (const secret of sorted) {
|
|
327
|
+
if (out.includes(secret)) {
|
|
328
|
+
out = out.replaceAll(secret, "[REDACTED]");
|
|
329
|
+
redacted = true;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return { value: out, redacted };
|
|
333
|
+
}
|
|
334
|
+
function scrubValueDeep(value, secretValues, depth = 0, isSensitiveParent = false) {
|
|
335
|
+
if (depth >= MAX_SANITIZE_DEPTH)
|
|
336
|
+
return { value: null, redacted: false };
|
|
337
|
+
if (typeof value === "string") {
|
|
338
|
+
if (isSensitiveParent) {
|
|
339
|
+
if (value && value !== "[REDACTED]") {
|
|
340
|
+
recordSecretValue(secretValues, value);
|
|
341
|
+
return { value: "[REDACTED]", redacted: true };
|
|
342
|
+
}
|
|
343
|
+
return { value: "[REDACTED]", redacted: false };
|
|
344
|
+
}
|
|
345
|
+
const trimmedJson = value.trim();
|
|
346
|
+
if (depth + 1 < MAX_SANITIZE_DEPTH &&
|
|
347
|
+
trimmedJson.length <= 65536 &&
|
|
348
|
+
((trimmedJson.startsWith("{") && trimmedJson.endsWith("}")) ||
|
|
349
|
+
(trimmedJson.startsWith("[") && trimmedJson.endsWith("]")))) {
|
|
350
|
+
try {
|
|
351
|
+
const parsedJson = JSON.parse(trimmedJson);
|
|
352
|
+
if (parsedJson !== null && typeof parsedJson === "object") {
|
|
353
|
+
const nested = scrubValueDeep(parsedJson, secretValues, depth + 1, false);
|
|
354
|
+
if (nested.redacted) {
|
|
355
|
+
return { value: JSON.stringify(nested.value), redacted: true };
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
// Fall through to text scrubbing
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return scrubText(value, secretValues);
|
|
364
|
+
}
|
|
365
|
+
if (value === null || typeof value !== "object") {
|
|
366
|
+
return { value, redacted: false };
|
|
367
|
+
}
|
|
368
|
+
if (Array.isArray(value)) {
|
|
369
|
+
let redacted = false;
|
|
370
|
+
const arr = value.map((item) => {
|
|
371
|
+
const res = scrubValueDeep(item, secretValues, depth + 1, isSensitiveParent);
|
|
372
|
+
if (res.redacted)
|
|
373
|
+
redacted = true;
|
|
374
|
+
return res.value;
|
|
375
|
+
});
|
|
376
|
+
return { value: arr, redacted };
|
|
377
|
+
}
|
|
378
|
+
const src = value;
|
|
379
|
+
const out = {};
|
|
380
|
+
let redacted = false;
|
|
381
|
+
for (const key of Object.keys(src)) {
|
|
382
|
+
if (isUnsafeKey(key))
|
|
383
|
+
continue;
|
|
384
|
+
const childSensitive = isSensitiveParent || isSensitiveFieldName(key);
|
|
385
|
+
const res = scrubValueDeep(src[key], secretValues, depth + 1, childSensitive);
|
|
386
|
+
if (res.redacted)
|
|
387
|
+
redacted = true;
|
|
388
|
+
out[key] = res.value;
|
|
389
|
+
}
|
|
390
|
+
return { value: out, redacted };
|
|
391
|
+
}
|
|
392
|
+
function scrubSchemaDeep(schema, secretValues, depth = 0, inSensitiveProp = false) {
|
|
393
|
+
if (depth >= MAX_SANITIZE_DEPTH)
|
|
394
|
+
return undefined;
|
|
395
|
+
if (Array.isArray(schema)) {
|
|
396
|
+
return schema.map((item) => scrubSchemaDeep(item, secretValues, depth + 1, inSensitiveProp));
|
|
397
|
+
}
|
|
398
|
+
if (!isObject(schema))
|
|
399
|
+
return schema;
|
|
400
|
+
const out = {};
|
|
401
|
+
for (const key of Object.keys(schema)) {
|
|
402
|
+
if (isUnsafeKey(key))
|
|
403
|
+
continue;
|
|
404
|
+
const val = schema[key];
|
|
405
|
+
if ((key === "properties" || key === "$defs" || key === "definitions") && isObject(val)) {
|
|
406
|
+
const cleanedMap = {};
|
|
407
|
+
for (const propKey of Object.keys(val)) {
|
|
408
|
+
if (isUnsafeKey(propKey))
|
|
409
|
+
continue;
|
|
410
|
+
cleanedMap[propKey] = scrubSchemaDeep(val[propKey], secretValues, depth + 1, isSensitiveFieldName(propKey));
|
|
411
|
+
}
|
|
412
|
+
out[key] = cleanedMap;
|
|
413
|
+
}
|
|
414
|
+
else if (key === "items" || key === "not" || key === "allOf" || key === "anyOf" || key === "oneOf") {
|
|
415
|
+
out[key] = scrubSchemaDeep(val, secretValues, depth + 1, inSensitiveProp);
|
|
416
|
+
}
|
|
417
|
+
else if (key === "additionalProperties") {
|
|
418
|
+
out[key] = typeof val === "boolean" ? val : scrubSchemaDeep(val, secretValues, depth + 1, false);
|
|
419
|
+
}
|
|
420
|
+
else if (key === "const" || key === "default" || key === "example" || key === "examples" || key === "enum") {
|
|
421
|
+
if (inSensitiveProp) {
|
|
422
|
+
scrubValueDeep(val, secretValues, 0, true);
|
|
423
|
+
}
|
|
424
|
+
else {
|
|
425
|
+
out[key] = scrubValueDeep(val, secretValues).value;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
else if (key === "description" || key === "title" || key === "$comment" || key === "$ref") {
|
|
429
|
+
out[key] = typeof val === "string" ? scrubText(val, secretValues).value : val;
|
|
430
|
+
}
|
|
431
|
+
else if (typeof val === "string" || typeof val === "number" || typeof val === "boolean" || val === null) {
|
|
432
|
+
out[key] = val;
|
|
433
|
+
}
|
|
434
|
+
else if (Array.isArray(val)) {
|
|
435
|
+
out[key] = val.map((item) => typeof item === "string" ? scrubText(item, secretValues).value : item);
|
|
436
|
+
}
|
|
437
|
+
else if (isObject(val)) {
|
|
438
|
+
out[key] = scrubSchemaDeep(val, secretValues, depth + 1, false);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return out;
|
|
442
|
+
}
|
|
443
|
+
function sanitizeHeaderEntry(rawName, rawValue, ctx) {
|
|
444
|
+
let hadControl = false;
|
|
445
|
+
if (CONTROL_CHAR_RE.test(rawName) || CONTROL_CHAR_RE.test(rawValue)) {
|
|
446
|
+
hadControl = true;
|
|
447
|
+
}
|
|
448
|
+
// Prevent CRLF header smuggling by truncating header name at CR/LF first
|
|
449
|
+
const nameLine = rawName.split(/[\r\n]/)[0] ?? "";
|
|
450
|
+
const cleanName = nameLine.replace(CONTROL_CHAR_GLOBAL_RE, "").trim();
|
|
451
|
+
if (!cleanName || isUnsafeKey(cleanName) || !HEADER_TOKEN_RE.test(cleanName)) {
|
|
452
|
+
if (hadControl) {
|
|
453
|
+
pushWarning(ctx, "Dropped header with invalid or control characters to prevent header injection.");
|
|
454
|
+
}
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
const rawValueNoCtrl = rawValue.replace(CONTROL_CHAR_GLOBAL_RE, "").trim();
|
|
458
|
+
if (hadControl) {
|
|
459
|
+
pushWarning(ctx, `Stripped control/CRLF characters from header "${cleanName}".`);
|
|
460
|
+
}
|
|
461
|
+
if (isAsyncApiSensitiveHeader(cleanName) || SENSITIVE_HEADER_VALUE_RE.test(rawValueNoCtrl)) {
|
|
462
|
+
ctx.redactedSecrets = true;
|
|
463
|
+
recordSecretValue(ctx.secretValues, rawValueNoCtrl);
|
|
464
|
+
return null;
|
|
465
|
+
}
|
|
466
|
+
// Also check if rawValue had smuggled lines containing sensitive tokens
|
|
467
|
+
if (rawValue.includes("\r") || rawValue.includes("\n")) {
|
|
468
|
+
const lines = rawValue.split(/[\r\n]+/);
|
|
469
|
+
for (let i = 1; i < lines.length; i += 1) {
|
|
470
|
+
const smuggledLine = lines[i]?.trim();
|
|
471
|
+
if (!smuggledLine)
|
|
472
|
+
continue;
|
|
473
|
+
const colonIdx = smuggledLine.indexOf(":");
|
|
474
|
+
if (colonIdx > 0) {
|
|
475
|
+
const smuggledName = smuggledLine.slice(0, colonIdx).trim();
|
|
476
|
+
const smuggledVal = smuggledLine.slice(colonIdx + 1).trim();
|
|
477
|
+
if (isAsyncApiSensitiveHeader(smuggledName) || SENSITIVE_HEADER_VALUE_RE.test(smuggledVal)) {
|
|
478
|
+
ctx.redactedSecrets = true;
|
|
479
|
+
recordSecretValue(ctx.secretValues, smuggledVal);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
// Keep only the first line so smuggled headers cannot leak into value
|
|
484
|
+
const firstLine = (lines[0] ?? "").replace(CONTROL_CHAR_GLOBAL_RE, "").trim();
|
|
485
|
+
const scrubbed = scrubText(firstLine, ctx.secretValues);
|
|
486
|
+
if (scrubbed.redacted)
|
|
487
|
+
ctx.redactedSecrets = true;
|
|
488
|
+
return { name: cleanName, value: scrubbed.value };
|
|
489
|
+
}
|
|
490
|
+
const scrubbed = scrubText(rawValueNoCtrl, ctx.secretValues);
|
|
491
|
+
if (scrubbed.redacted)
|
|
492
|
+
ctx.redactedSecrets = true;
|
|
493
|
+
return { name: cleanName, value: scrubbed.value };
|
|
494
|
+
}
|
|
495
|
+
function hasHeaderCaseInsensitive(headers, name) {
|
|
496
|
+
const lower = name.toLowerCase();
|
|
497
|
+
return Object.keys(headers).some((k) => k.toLowerCase() === lower);
|
|
498
|
+
}
|
|
499
|
+
function setHeaderCaseInsensitive(headers, name, value) {
|
|
500
|
+
const lower = name.toLowerCase();
|
|
501
|
+
for (const k of Object.keys(headers)) {
|
|
502
|
+
if (k.toLowerCase() === lower && k !== name) {
|
|
503
|
+
delete headers[k];
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
headers[name] = value;
|
|
507
|
+
}
|
|
508
|
+
function deleteHeaderCaseInsensitive(headers, name) {
|
|
509
|
+
const lower = name.toLowerCase();
|
|
510
|
+
for (const k of Object.keys(headers)) {
|
|
511
|
+
if (k.toLowerCase() === lower) {
|
|
512
|
+
delete headers[k];
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function decodeJsonPointerSegment(seg) {
|
|
517
|
+
return seg.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
518
|
+
}
|
|
519
|
+
function resolveJsonPointer(doc, ref) {
|
|
520
|
+
if (typeof ref !== "string" || !ref.startsWith("#/"))
|
|
521
|
+
return undefined;
|
|
522
|
+
const rawParts = ref.slice(2).split("/");
|
|
523
|
+
let cur = doc;
|
|
524
|
+
for (const rawPart of rawParts) {
|
|
525
|
+
if (cur === null || cur === undefined)
|
|
526
|
+
return undefined;
|
|
527
|
+
const decoded = decodeJsonPointerSegment(rawPart);
|
|
528
|
+
if (isUnsafeKey(decoded))
|
|
529
|
+
return undefined;
|
|
530
|
+
if (Array.isArray(cur)) {
|
|
531
|
+
const idx = Number(decoded);
|
|
532
|
+
if (!Number.isInteger(idx) || idx < 0 || idx >= cur.length)
|
|
533
|
+
return undefined;
|
|
534
|
+
cur = cur[idx];
|
|
535
|
+
}
|
|
536
|
+
else if (isObject(cur)) {
|
|
537
|
+
if (hasOwn(cur, decoded)) {
|
|
538
|
+
cur = cur[decoded];
|
|
539
|
+
}
|
|
540
|
+
else {
|
|
541
|
+
let uriDecoded = decoded;
|
|
542
|
+
try {
|
|
543
|
+
uriDecoded = decodeJsonPointerSegment(decodeURIComponent(rawPart));
|
|
544
|
+
}
|
|
545
|
+
catch {
|
|
546
|
+
return undefined;
|
|
547
|
+
}
|
|
548
|
+
if (isUnsafeKey(uriDecoded) || !hasOwn(cur, uriDecoded))
|
|
549
|
+
return undefined;
|
|
550
|
+
cur = cur[uriDecoded];
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
else {
|
|
554
|
+
return undefined;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return cur;
|
|
558
|
+
}
|
|
559
|
+
function resolveObjectRef(value, ctx, visitedRefs = new Set(), depth = 0) {
|
|
560
|
+
if (!isObject(value))
|
|
561
|
+
return undefined;
|
|
562
|
+
const ref = safeGet(value, "$ref");
|
|
563
|
+
if (typeof ref !== "string")
|
|
564
|
+
return value;
|
|
565
|
+
if (depth >= MAX_REF_DEPTH) {
|
|
566
|
+
pushWarning(ctx, `Max $ref resolution depth (${MAX_REF_DEPTH}) exceeded at "${ref}".`);
|
|
567
|
+
return undefined;
|
|
568
|
+
}
|
|
569
|
+
if (!ref.startsWith("#/")) {
|
|
570
|
+
pushWarning(ctx, `Skipped external $ref "${scrubText(ref, ctx.secretValues).value}" (only local #/ refs are resolved).`);
|
|
571
|
+
return undefined;
|
|
572
|
+
}
|
|
573
|
+
if (visitedRefs.has(ref)) {
|
|
574
|
+
pushWarning(ctx, `Circular $ref detected at "${ref}".`);
|
|
575
|
+
return undefined;
|
|
576
|
+
}
|
|
577
|
+
const target = resolveJsonPointer(ctx.doc, ref);
|
|
578
|
+
if (!isObject(target)) {
|
|
579
|
+
pushWarning(ctx, `Unresolved local $ref "${ref}".`);
|
|
580
|
+
return undefined;
|
|
581
|
+
}
|
|
582
|
+
const nextVisited = new Set(visitedRefs);
|
|
583
|
+
nextVisited.add(ref);
|
|
584
|
+
const resolvedTarget = resolveObjectRef(target, ctx, nextVisited, depth + 1);
|
|
585
|
+
if (!resolvedTarget)
|
|
586
|
+
return undefined;
|
|
587
|
+
const merged = { ...resolvedTarget };
|
|
588
|
+
for (const key of Object.keys(value)) {
|
|
589
|
+
if (key === "$ref" || isUnsafeKey(key))
|
|
590
|
+
continue;
|
|
591
|
+
merged[key] = value[key];
|
|
592
|
+
}
|
|
593
|
+
return merged;
|
|
594
|
+
}
|
|
595
|
+
function mergeJsonSchemas(base, extra) {
|
|
596
|
+
const out = {};
|
|
597
|
+
for (const key of Object.keys(base)) {
|
|
598
|
+
if (!isUnsafeKey(key))
|
|
599
|
+
out[key] = base[key];
|
|
600
|
+
}
|
|
601
|
+
for (const key of Object.keys(extra)) {
|
|
602
|
+
if (!isUnsafeKey(key))
|
|
603
|
+
out[key] = extra[key];
|
|
604
|
+
}
|
|
605
|
+
const baseReq = Array.isArray(base.required) ? base.required.map(String).filter((k) => !isUnsafeKey(k)) : [];
|
|
606
|
+
const extraReq = Array.isArray(extra.required) ? extra.required.map(String).filter((k) => !isUnsafeKey(k)) : [];
|
|
607
|
+
const req = [...new Set([...baseReq, ...extraReq])];
|
|
608
|
+
if (req.length > 0)
|
|
609
|
+
out.required = req;
|
|
610
|
+
if (isObject(base.properties) || isObject(extra.properties)) {
|
|
611
|
+
const props = {};
|
|
612
|
+
if (isObject(base.properties)) {
|
|
613
|
+
for (const k of Object.keys(base.properties)) {
|
|
614
|
+
if (!isUnsafeKey(k))
|
|
615
|
+
props[k] = base.properties[k];
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
if (isObject(extra.properties)) {
|
|
619
|
+
for (const k of Object.keys(extra.properties)) {
|
|
620
|
+
if (!isUnsafeKey(k))
|
|
621
|
+
props[k] = extra.properties[k];
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
out.properties = props;
|
|
625
|
+
}
|
|
626
|
+
if (isObject(base.items) && isObject(extra.items)) {
|
|
627
|
+
out.items = mergeJsonSchemas(base.items, extra.items);
|
|
628
|
+
}
|
|
629
|
+
return out;
|
|
630
|
+
}
|
|
631
|
+
function unwrapMultiFormatSchema(raw) {
|
|
632
|
+
if (!isObject(raw))
|
|
633
|
+
return raw;
|
|
634
|
+
if (hasOwn(raw, "schemaFormat") && isObject(raw.schema)) {
|
|
635
|
+
return raw.schema;
|
|
636
|
+
}
|
|
637
|
+
return raw;
|
|
638
|
+
}
|
|
639
|
+
function resolveSchemaInternal(rawSchema, ctx, visitedRefs, refDepth, schemaDepth, fieldName = "") {
|
|
640
|
+
if (ctx.nodeBudget.remaining <= 0) {
|
|
641
|
+
pushWarning(ctx, "Schema node expansion budget reached; truncated remaining nested schema.");
|
|
642
|
+
return {};
|
|
643
|
+
}
|
|
644
|
+
ctx.nodeBudget.remaining -= 1;
|
|
645
|
+
const unwrapped = unwrapMultiFormatSchema(rawSchema);
|
|
646
|
+
if (!isObject(unwrapped))
|
|
647
|
+
return {};
|
|
648
|
+
if (schemaDepth > MAX_SCHEMA_DEPTH) {
|
|
649
|
+
pushWarning(ctx, `Max schema nesting depth (${MAX_SCHEMA_DEPTH}) exceeded; truncated nested schema.`);
|
|
650
|
+
return {};
|
|
651
|
+
}
|
|
652
|
+
const ref = safeGet(unwrapped, "$ref");
|
|
653
|
+
if (typeof ref === "string") {
|
|
654
|
+
if (refDepth >= MAX_REF_DEPTH) {
|
|
655
|
+
pushWarning(ctx, `Max $ref resolution depth (${MAX_REF_DEPTH}) exceeded at "${ref}".`);
|
|
656
|
+
return {};
|
|
657
|
+
}
|
|
658
|
+
if (!ref.startsWith("#/")) {
|
|
659
|
+
pushWarning(ctx, `Skipped external schema $ref "${scrubText(ref, ctx.secretValues).value}".`);
|
|
660
|
+
return {};
|
|
661
|
+
}
|
|
662
|
+
if (visitedRefs.has(ref)) {
|
|
663
|
+
pushWarning(ctx, `Circular schema $ref detected at "${ref}".`);
|
|
664
|
+
return {};
|
|
665
|
+
}
|
|
666
|
+
const target = resolveJsonPointer(ctx.doc, ref);
|
|
667
|
+
if (!isObject(target)) {
|
|
668
|
+
pushWarning(ctx, `Unresolved schema $ref "${ref}".`);
|
|
669
|
+
return {};
|
|
670
|
+
}
|
|
671
|
+
const nextVisited = new Set(visitedRefs);
|
|
672
|
+
nextVisited.add(ref);
|
|
673
|
+
const resolvedTarget = resolveSchemaInternal(target, ctx, nextVisited, refDepth + 1, schemaDepth, fieldName);
|
|
674
|
+
const siblingKeys = Object.keys(unwrapped).filter((k) => k !== "$ref" && !isUnsafeKey(k));
|
|
675
|
+
if (siblingKeys.length === 0) {
|
|
676
|
+
return resolvedTarget;
|
|
677
|
+
}
|
|
678
|
+
const siblingObj = {};
|
|
679
|
+
for (const k of siblingKeys) {
|
|
680
|
+
siblingObj[k] = unwrapped[k];
|
|
681
|
+
}
|
|
682
|
+
const resolvedSibling = resolveSchemaInternal(siblingObj, ctx, nextVisited, refDepth + 1, schemaDepth, fieldName);
|
|
683
|
+
return mergeJsonSchemas(resolvedTarget, resolvedSibling);
|
|
684
|
+
}
|
|
685
|
+
if (Array.isArray(unwrapped.allOf)) {
|
|
686
|
+
let merged = {};
|
|
687
|
+
for (const part of unwrapped.allOf) {
|
|
688
|
+
const resolvedPart = resolveSchemaInternal(part, ctx, visitedRefs, refDepth, schemaDepth + 1, fieldName);
|
|
689
|
+
merged = mergeJsonSchemas(merged, resolvedPart);
|
|
690
|
+
}
|
|
691
|
+
const restKeys = Object.keys(unwrapped).filter((k) => k !== "allOf" && !isUnsafeKey(k));
|
|
692
|
+
if (restKeys.length === 0)
|
|
693
|
+
return merged;
|
|
694
|
+
const restObj = {};
|
|
695
|
+
for (const k of restKeys)
|
|
696
|
+
restObj[k] = unwrapped[k];
|
|
697
|
+
const resolvedRest = resolveSchemaInternal(restObj, ctx, visitedRefs, refDepth, schemaDepth + 1, fieldName);
|
|
698
|
+
return mergeJsonSchemas(merged, resolvedRest);
|
|
699
|
+
}
|
|
700
|
+
const sensitiveField = isSensitiveFieldName(fieldName);
|
|
701
|
+
const out = {};
|
|
702
|
+
for (const key of Object.keys(unwrapped)) {
|
|
703
|
+
if (isUnsafeKey(key))
|
|
704
|
+
continue;
|
|
705
|
+
const val = unwrapped[key];
|
|
706
|
+
if (key === "properties" && isObject(val)) {
|
|
707
|
+
const props = {};
|
|
708
|
+
let count = 0;
|
|
709
|
+
for (const propKey of Object.keys(val)) {
|
|
710
|
+
if (isUnsafeKey(propKey))
|
|
711
|
+
continue;
|
|
712
|
+
if (count >= MAX_SCHEMA_KEYS) {
|
|
713
|
+
pushWarning(ctx, `Schema properties truncated at ${MAX_SCHEMA_KEYS} keys.`);
|
|
714
|
+
break;
|
|
715
|
+
}
|
|
716
|
+
props[propKey] = resolveSchemaInternal(val[propKey], ctx, visitedRefs, refDepth, schemaDepth + 1, propKey);
|
|
717
|
+
count += 1;
|
|
718
|
+
}
|
|
719
|
+
out.properties = props;
|
|
720
|
+
}
|
|
721
|
+
else if (key === "items") {
|
|
722
|
+
if (Array.isArray(val)) {
|
|
723
|
+
out.items = val.map((item) => resolveSchemaInternal(item, ctx, visitedRefs, refDepth, schemaDepth + 1));
|
|
724
|
+
}
|
|
725
|
+
else if (isObject(val)) {
|
|
726
|
+
out.items = resolveSchemaInternal(val, ctx, visitedRefs, refDepth, schemaDepth + 1);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
else if (key === "additionalProperties") {
|
|
730
|
+
if (typeof val === "boolean") {
|
|
731
|
+
out.additionalProperties = val;
|
|
732
|
+
}
|
|
733
|
+
else if (isObject(val)) {
|
|
734
|
+
out.additionalProperties = resolveSchemaInternal(val, ctx, visitedRefs, refDepth, schemaDepth + 1);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
else if (key === "not" && isObject(val)) {
|
|
738
|
+
out.not = resolveSchemaInternal(val, ctx, visitedRefs, refDepth, schemaDepth + 1);
|
|
739
|
+
}
|
|
740
|
+
else if ((key === "anyOf" || key === "oneOf") && Array.isArray(val)) {
|
|
741
|
+
out[key] = val.map((branch) => resolveSchemaInternal(branch, ctx, visitedRefs, refDepth, schemaDepth + 1, fieldName));
|
|
742
|
+
}
|
|
743
|
+
else if (key === "required" && Array.isArray(val)) {
|
|
744
|
+
out.required = val.map(String).filter((r) => !isUnsafeKey(r));
|
|
745
|
+
}
|
|
746
|
+
else if (key === "example" || key === "default" || key === "const") {
|
|
747
|
+
if (sensitiveField) {
|
|
748
|
+
ctx.redactedSecrets = true;
|
|
749
|
+
if (typeof val === "string")
|
|
750
|
+
recordSecretValue(ctx.secretValues, val);
|
|
751
|
+
else if (isObject(val) || Array.isArray(val)) {
|
|
752
|
+
scrubValueDeep(val, ctx.secretValues, 0, true);
|
|
753
|
+
}
|
|
754
|
+
// Omit concrete secret values from emitted schema
|
|
755
|
+
}
|
|
756
|
+
else {
|
|
757
|
+
const scrubbed = scrubValueDeep(val, ctx.secretValues);
|
|
758
|
+
if (scrubbed.redacted)
|
|
759
|
+
ctx.redactedSecrets = true;
|
|
760
|
+
out[key] = scrubbed.value;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
else if (key === "examples" && Array.isArray(val)) {
|
|
764
|
+
if (sensitiveField) {
|
|
765
|
+
ctx.redactedSecrets = true;
|
|
766
|
+
scrubValueDeep(val, ctx.secretValues, 0, true);
|
|
767
|
+
}
|
|
768
|
+
else {
|
|
769
|
+
const scrubbed = scrubValueDeep(val, ctx.secretValues);
|
|
770
|
+
if (scrubbed.redacted)
|
|
771
|
+
ctx.redactedSecrets = true;
|
|
772
|
+
out.examples = scrubbed.value;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
else if (key === "enum" && Array.isArray(val)) {
|
|
776
|
+
if (sensitiveField) {
|
|
777
|
+
ctx.redactedSecrets = true;
|
|
778
|
+
scrubValueDeep(val, ctx.secretValues, 0, true);
|
|
779
|
+
}
|
|
780
|
+
else {
|
|
781
|
+
const scrubbed = scrubValueDeep(val, ctx.secretValues);
|
|
782
|
+
if (scrubbed.redacted)
|
|
783
|
+
ctx.redactedSecrets = true;
|
|
784
|
+
out.enum = scrubbed.value;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
else if (typeof val === "string") {
|
|
788
|
+
const scrubbed = scrubText(val, ctx.secretValues);
|
|
789
|
+
if (scrubbed.redacted)
|
|
790
|
+
ctx.redactedSecrets = true;
|
|
791
|
+
out[key] = scrubbed.value;
|
|
792
|
+
}
|
|
793
|
+
else if (typeof val === "number" || typeof val === "boolean" || val === null) {
|
|
794
|
+
out[key] = val;
|
|
795
|
+
}
|
|
796
|
+
else if (Array.isArray(val)) {
|
|
797
|
+
const scrubbed = scrubValueDeep(val, ctx.secretValues);
|
|
798
|
+
if (scrubbed.redacted)
|
|
799
|
+
ctx.redactedSecrets = true;
|
|
800
|
+
out[key] = scrubbed.value;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return out;
|
|
804
|
+
}
|
|
805
|
+
function resolveSchema(rawSchema, ctx) {
|
|
806
|
+
if (!isObject(rawSchema))
|
|
807
|
+
return undefined;
|
|
808
|
+
const resolved = resolveSchemaInternal(rawSchema, ctx, new Set(), 0, 0, "");
|
|
809
|
+
return Object.keys(resolved).length > 0 ? resolved : undefined;
|
|
810
|
+
}
|
|
811
|
+
function sampleStringForFormat(format, minLength) {
|
|
812
|
+
switch (format) {
|
|
813
|
+
case "uuid":
|
|
814
|
+
return "00000000-0000-4000-8000-000000000000";
|
|
815
|
+
case "date-time":
|
|
816
|
+
return "2026-01-01T00:00:00Z";
|
|
817
|
+
case "date":
|
|
818
|
+
return "2026-01-01";
|
|
819
|
+
case "time":
|
|
820
|
+
return "00:00:00Z";
|
|
821
|
+
case "email":
|
|
822
|
+
return "webhook@example.com";
|
|
823
|
+
case "uri":
|
|
824
|
+
case "url":
|
|
825
|
+
return "https://example.com/resource";
|
|
826
|
+
case "hostname":
|
|
827
|
+
return "webhooks.example.com";
|
|
828
|
+
case "ipv4":
|
|
829
|
+
return "127.0.0.1";
|
|
830
|
+
default: {
|
|
831
|
+
const base = "sample";
|
|
832
|
+
if (typeof minLength === "number" && Number.isFinite(minLength) && minLength > base.length) {
|
|
833
|
+
return base.padEnd(Math.min(Math.floor(minLength), 64), "x");
|
|
834
|
+
}
|
|
835
|
+
return base;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
function synthesizeSampleFromSchema(schema, ctx, depth = 0, fieldName = "") {
|
|
840
|
+
if (!isObject(schema) || depth > MAX_SAMPLE_DEPTH)
|
|
841
|
+
return undefined;
|
|
842
|
+
const sensitive = isSensitiveFieldName(fieldName);
|
|
843
|
+
if (!sensitive) {
|
|
844
|
+
if (hasOwn(schema, "const") && schema.const !== undefined) {
|
|
845
|
+
const s = scrubValueDeep(schema.const, ctx.secretValues);
|
|
846
|
+
if (s.redacted)
|
|
847
|
+
ctx.redactedSecrets = true;
|
|
848
|
+
return s.value;
|
|
849
|
+
}
|
|
850
|
+
if (hasOwn(schema, "example") && schema.example !== undefined) {
|
|
851
|
+
const s = scrubValueDeep(schema.example, ctx.secretValues);
|
|
852
|
+
if (s.redacted)
|
|
853
|
+
ctx.redactedSecrets = true;
|
|
854
|
+
return s.value;
|
|
855
|
+
}
|
|
856
|
+
if (Array.isArray(schema.examples) && schema.examples.length > 0) {
|
|
857
|
+
const s = scrubValueDeep(schema.examples[0], ctx.secretValues);
|
|
858
|
+
if (s.redacted)
|
|
859
|
+
ctx.redactedSecrets = true;
|
|
860
|
+
return s.value;
|
|
861
|
+
}
|
|
862
|
+
if (hasOwn(schema, "default") && schema.default !== undefined) {
|
|
863
|
+
const s = scrubValueDeep(schema.default, ctx.secretValues);
|
|
864
|
+
if (s.redacted)
|
|
865
|
+
ctx.redactedSecrets = true;
|
|
866
|
+
return s.value;
|
|
867
|
+
}
|
|
868
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
869
|
+
const s = scrubValueDeep(schema.enum[0], ctx.secretValues);
|
|
870
|
+
if (s.redacted)
|
|
871
|
+
ctx.redactedSecrets = true;
|
|
872
|
+
return s.value;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
else {
|
|
876
|
+
ctx.redactedSecrets = true;
|
|
877
|
+
const rawSensType = schema.type;
|
|
878
|
+
const sensType = Array.isArray(rawSensType)
|
|
879
|
+
? (rawSensType.find((t) => t !== "null") ?? rawSensType[0])
|
|
880
|
+
: rawSensType;
|
|
881
|
+
if (sensType === "integer" || sensType === "number")
|
|
882
|
+
return 0;
|
|
883
|
+
if (sensType === "boolean")
|
|
884
|
+
return false;
|
|
885
|
+
return "[REDACTED]";
|
|
886
|
+
}
|
|
887
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
888
|
+
const candidate = schema.oneOf.find((b) => isObject(b) && b.type !== "null") ?? schema.oneOf[0];
|
|
889
|
+
return synthesizeSampleFromSchema(candidate, ctx, depth + 1, fieldName);
|
|
890
|
+
}
|
|
891
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
892
|
+
const candidate = schema.anyOf.find((b) => isObject(b) && b.type !== "null") ?? schema.anyOf[0];
|
|
893
|
+
return synthesizeSampleFromSchema(candidate, ctx, depth + 1, fieldName);
|
|
894
|
+
}
|
|
895
|
+
const rawType = schema.type;
|
|
896
|
+
const primaryType = Array.isArray(rawType)
|
|
897
|
+
? (rawType.find((t) => t !== "null") ?? rawType[0])
|
|
898
|
+
: rawType;
|
|
899
|
+
if (primaryType === "object" || isObject(schema.properties)) {
|
|
900
|
+
const out = {};
|
|
901
|
+
if (isObject(schema.properties)) {
|
|
902
|
+
let count = 0;
|
|
903
|
+
for (const propKey of Object.keys(schema.properties)) {
|
|
904
|
+
if (isUnsafeKey(propKey))
|
|
905
|
+
continue;
|
|
906
|
+
if (count >= MAX_SCHEMA_KEYS)
|
|
907
|
+
break;
|
|
908
|
+
const propVal = synthesizeSampleFromSchema(schema.properties[propKey], ctx, depth + 1, propKey);
|
|
909
|
+
if (propVal !== undefined) {
|
|
910
|
+
out[propKey] = propVal;
|
|
911
|
+
}
|
|
912
|
+
else if (Array.isArray(schema.required) && schema.required.includes(propKey)) {
|
|
913
|
+
out[propKey] = isSensitiveFieldName(propKey) ? "[REDACTED]" : "sample";
|
|
914
|
+
}
|
|
915
|
+
count += 1;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
return out;
|
|
919
|
+
}
|
|
920
|
+
if (primaryType === "array") {
|
|
921
|
+
if (Array.isArray(schema.items)) {
|
|
922
|
+
return schema.items
|
|
923
|
+
.map((item) => synthesizeSampleFromSchema(item, ctx, depth + 1))
|
|
924
|
+
.filter((v) => v !== undefined);
|
|
925
|
+
}
|
|
926
|
+
if (isObject(schema.items) && Object.keys(schema.items).length > 0) {
|
|
927
|
+
const itemVal = synthesizeSampleFromSchema(schema.items, ctx, depth + 1);
|
|
928
|
+
return itemVal === undefined ? [] : [itemVal];
|
|
929
|
+
}
|
|
930
|
+
return [];
|
|
931
|
+
}
|
|
932
|
+
if (primaryType === "integer") {
|
|
933
|
+
const min = typeof schema.minimum === "number" && Number.isFinite(schema.minimum) ? Math.ceil(schema.minimum) : 1;
|
|
934
|
+
return min;
|
|
935
|
+
}
|
|
936
|
+
if (primaryType === "number") {
|
|
937
|
+
const min = typeof schema.minimum === "number" && Number.isFinite(schema.minimum) ? schema.minimum : 1;
|
|
938
|
+
return min;
|
|
939
|
+
}
|
|
940
|
+
if (primaryType === "boolean")
|
|
941
|
+
return true;
|
|
942
|
+
if (primaryType === "null")
|
|
943
|
+
return null;
|
|
944
|
+
if (primaryType === "string") {
|
|
945
|
+
const fmt = typeof schema.format === "string" ? schema.format : undefined;
|
|
946
|
+
const minLen = typeof schema.minLength === "number" ? schema.minLength : undefined;
|
|
947
|
+
return sampleStringForFormat(fmt, minLen);
|
|
948
|
+
}
|
|
949
|
+
return {};
|
|
950
|
+
}
|
|
951
|
+
function substituteTemplateVariables(template, variables, ctx, encodeValue) {
|
|
952
|
+
return template.replace(/\{([^{}]+)\}/g, (_full, rawName) => {
|
|
953
|
+
const name = rawName.trim();
|
|
954
|
+
if (!name || isUnsafeKey(name))
|
|
955
|
+
return "sample";
|
|
956
|
+
const rawVar = variables ? safeGet(variables, name) : undefined;
|
|
957
|
+
const resolvedVar = resolveObjectRef(rawVar, ctx) ?? (isObject(rawVar) ? rawVar : undefined);
|
|
958
|
+
if (isSensitiveFieldName(name)) {
|
|
959
|
+
ctx.redactedSecrets = true;
|
|
960
|
+
if (resolvedVar) {
|
|
961
|
+
for (const k of ["default", "example"]) {
|
|
962
|
+
const sv = safeGet(resolvedVar, k);
|
|
963
|
+
if (typeof sv === "string")
|
|
964
|
+
recordSecretValue(ctx.secretValues, sv);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
return "redacted";
|
|
968
|
+
}
|
|
969
|
+
let chosen = undefined;
|
|
970
|
+
if (resolvedVar) {
|
|
971
|
+
if (hasOwn(resolvedVar, "default") && resolvedVar.default !== undefined) {
|
|
972
|
+
chosen = resolvedVar.default;
|
|
973
|
+
}
|
|
974
|
+
else if (Array.isArray(resolvedVar.enum) && resolvedVar.enum.length > 0) {
|
|
975
|
+
chosen = resolvedVar.enum[0];
|
|
976
|
+
}
|
|
977
|
+
else if (hasOwn(resolvedVar, "example") && resolvedVar.example !== undefined) {
|
|
978
|
+
chosen = resolvedVar.example;
|
|
979
|
+
}
|
|
980
|
+
else if (Array.isArray(resolvedVar.examples) && resolvedVar.examples.length > 0) {
|
|
981
|
+
chosen = resolvedVar.examples[0];
|
|
982
|
+
}
|
|
983
|
+
else if (isObject(resolvedVar.schema)) {
|
|
984
|
+
const schema = resolveSchema(resolvedVar.schema, ctx);
|
|
985
|
+
chosen = synthesizeSampleFromSchema(schema, ctx, 0, name);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
const strVal = chosen !== undefined && chosen !== null && typeof chosen !== "object" ? String(chosen) : "sample";
|
|
989
|
+
const cleanVal = strVal.replace(CONTROL_CHAR_GLOBAL_RE, "");
|
|
990
|
+
const scrubbed = scrubText(cleanVal, ctx.secretValues);
|
|
991
|
+
if (scrubbed.redacted)
|
|
992
|
+
ctx.redactedSecrets = true;
|
|
993
|
+
const finalVal = scrubbed.value || "sample";
|
|
994
|
+
return encodeValue ? encodeURIComponent(finalVal) : finalVal;
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
function extractBaseUrlFromServers(doc, ctx) {
|
|
998
|
+
const servers = safeGet(doc, "servers");
|
|
999
|
+
if (!isObject(servers))
|
|
1000
|
+
return undefined;
|
|
1001
|
+
const candidates = [];
|
|
1002
|
+
for (const serverKey of Object.keys(servers)) {
|
|
1003
|
+
if (isUnsafeKey(serverKey))
|
|
1004
|
+
continue;
|
|
1005
|
+
const rawServer = safeGet(servers, serverKey);
|
|
1006
|
+
const server = resolveObjectRef(rawServer, ctx);
|
|
1007
|
+
if (!server)
|
|
1008
|
+
continue;
|
|
1009
|
+
const protocol = typeof server.protocol === "string" ? server.protocol.trim().toLowerCase() : "";
|
|
1010
|
+
const vars = isObject(server.variables) ? server.variables : undefined;
|
|
1011
|
+
const rawUrlField = typeof server.url === "string" ? server.url.trim() : "";
|
|
1012
|
+
const rawHostField = typeof server.host === "string" ? server.host.trim() : "";
|
|
1013
|
+
const rawPathname = typeof server.pathname === "string" ? server.pathname.trim() : "";
|
|
1014
|
+
let assembled = "";
|
|
1015
|
+
if (rawUrlField) {
|
|
1016
|
+
const substituted = substituteTemplateVariables(rawUrlField, vars, ctx, false);
|
|
1017
|
+
if (/^https?:\/\//i.test(substituted)) {
|
|
1018
|
+
assembled = substituted;
|
|
1019
|
+
}
|
|
1020
|
+
else if (protocol === "http" || protocol === "https") {
|
|
1021
|
+
assembled = `${protocol}://${substituted.replace(/^\/+/, "")}`;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
else if (rawHostField) {
|
|
1025
|
+
const hostSub = substituteTemplateVariables(rawHostField, vars, ctx, false);
|
|
1026
|
+
const pathSub = rawPathname ? substituteTemplateVariables(rawPathname, vars, ctx, false) : "";
|
|
1027
|
+
const normPath = pathSub ? (pathSub.startsWith("/") ? pathSub : `/${pathSub}`) : "";
|
|
1028
|
+
if (/^https?:\/\//i.test(hostSub)) {
|
|
1029
|
+
assembled = `${hostSub.replace(/\/+$/, "")}${normPath}`;
|
|
1030
|
+
}
|
|
1031
|
+
else if (protocol === "http" || protocol === "https") {
|
|
1032
|
+
assembled = `${protocol}://${hostSub.replace(/\/+$/, "")}${normPath}`;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
if (!assembled)
|
|
1036
|
+
continue;
|
|
1037
|
+
const score = protocol === "https" || protocol === "http" ? 2 : 1;
|
|
1038
|
+
candidates.push({ score, rawUrl: assembled });
|
|
1039
|
+
}
|
|
1040
|
+
candidates.sort((a, b) => b.score - a.score);
|
|
1041
|
+
for (const cand of candidates) {
|
|
1042
|
+
const sanitized = sanitizeUrlString(cand.rawUrl, ctx.secretValues, { requireHttp: true });
|
|
1043
|
+
if (sanitized.redacted)
|
|
1044
|
+
ctx.redactedSecrets = true;
|
|
1045
|
+
if (sanitized.valid && sanitized.safeUrl) {
|
|
1046
|
+
return sanitized.safeUrl;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
return undefined;
|
|
1050
|
+
}
|
|
1051
|
+
function normalizeChannelPath(rawChannel, parameters, ctx) {
|
|
1052
|
+
const noCtrl = rawChannel.trim().replace(CONTROL_CHAR_GLOBAL_RE, "");
|
|
1053
|
+
if (!noCtrl)
|
|
1054
|
+
return "/";
|
|
1055
|
+
let working = noCtrl;
|
|
1056
|
+
if (/^https?:\/\//i.test(working)) {
|
|
1057
|
+
const sanitized = sanitizeUrlString(working, ctx.secretValues, { requireHttp: true });
|
|
1058
|
+
if (sanitized.redacted)
|
|
1059
|
+
ctx.redactedSecrets = true;
|
|
1060
|
+
working = sanitized.valid ? sanitized.pathname : "/";
|
|
1061
|
+
}
|
|
1062
|
+
else {
|
|
1063
|
+
// Strip fragment and any embedded query string from channel path
|
|
1064
|
+
const hashIdx = working.indexOf("#");
|
|
1065
|
+
if (hashIdx >= 0) {
|
|
1066
|
+
const frag = working.slice(hashIdx + 1);
|
|
1067
|
+
if (frag) {
|
|
1068
|
+
ctx.redactedSecrets = true;
|
|
1069
|
+
recordSecretValue(ctx.secretValues, frag);
|
|
1070
|
+
}
|
|
1071
|
+
working = working.slice(0, hashIdx);
|
|
1072
|
+
}
|
|
1073
|
+
const queryIdx = working.indexOf("?");
|
|
1074
|
+
if (queryIdx >= 0) {
|
|
1075
|
+
const rawQuery = working.slice(queryIdx + 1);
|
|
1076
|
+
const params = new URLSearchParams(rawQuery);
|
|
1077
|
+
for (const [k, v] of params.entries()) {
|
|
1078
|
+
if (isAsyncApiSensitiveQueryParam(k) || SENSITIVE_HEADER_VALUE_RE.test(v)) {
|
|
1079
|
+
ctx.redactedSecrets = true;
|
|
1080
|
+
recordSecretValue(ctx.secretValues, v);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
working = working.slice(0, queryIdx);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
working = substituteTemplateVariables(working, parameters, ctx, true);
|
|
1087
|
+
const scrubbed = scrubText(working, ctx.secretValues);
|
|
1088
|
+
if (scrubbed.redacted)
|
|
1089
|
+
ctx.redactedSecrets = true;
|
|
1090
|
+
working = scrubbed.value;
|
|
1091
|
+
// Normalize slashes and strip path traversal segments
|
|
1092
|
+
const rawSegments = working.split("/").filter((s) => s.length > 0 && s !== "." && s !== "..");
|
|
1093
|
+
if (rawSegments.length === 0)
|
|
1094
|
+
return "/";
|
|
1095
|
+
return `/${rawSegments.join("/")}`;
|
|
1096
|
+
}
|
|
1097
|
+
function extractHttpBinding(obj, ctx) {
|
|
1098
|
+
if (!obj)
|
|
1099
|
+
return undefined;
|
|
1100
|
+
const bindings = safeGet(obj, "bindings");
|
|
1101
|
+
const resolvedBindings = resolveObjectRef(bindings, ctx);
|
|
1102
|
+
if (!resolvedBindings)
|
|
1103
|
+
return undefined;
|
|
1104
|
+
const httpBinding = safeGet(resolvedBindings, "http");
|
|
1105
|
+
return resolveObjectRef(httpBinding, ctx);
|
|
1106
|
+
}
|
|
1107
|
+
function extractMethodFromBindings(bindingsList) {
|
|
1108
|
+
for (const b of bindingsList) {
|
|
1109
|
+
if (!b)
|
|
1110
|
+
continue;
|
|
1111
|
+
const rawMethod = safeGet(b, "method");
|
|
1112
|
+
if (typeof rawMethod === "string") {
|
|
1113
|
+
const upper = rawMethod.trim().toUpperCase();
|
|
1114
|
+
if (VALID_HTTP_METHODS.has(upper)) {
|
|
1115
|
+
return upper;
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
return "POST";
|
|
1120
|
+
}
|
|
1121
|
+
function extractStatusCodeFromObject(obj) {
|
|
1122
|
+
if (!obj)
|
|
1123
|
+
return undefined;
|
|
1124
|
+
for (const key of ["statusCode", "status", "x-expected-status", "expectedStatus"]) {
|
|
1125
|
+
const val = safeGet(obj, key);
|
|
1126
|
+
const num = typeof val === "number" ? val : typeof val === "string" ? Number(val) : NaN;
|
|
1127
|
+
if (Number.isInteger(num) && num >= 100 && num <= 599) {
|
|
1128
|
+
return num;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
return undefined;
|
|
1132
|
+
}
|
|
1133
|
+
function extractResponseMeta(sources, bindingsList, replyObj, ctx) {
|
|
1134
|
+
let explicitStatus;
|
|
1135
|
+
let responseSchema;
|
|
1136
|
+
for (const b of bindingsList) {
|
|
1137
|
+
if (!b)
|
|
1138
|
+
continue;
|
|
1139
|
+
if (explicitStatus === undefined) {
|
|
1140
|
+
explicitStatus = extractStatusCodeFromObject(b);
|
|
1141
|
+
}
|
|
1142
|
+
const rawResp = safeGet(b, "response");
|
|
1143
|
+
const respObj = resolveObjectRef(rawResp, ctx);
|
|
1144
|
+
if (respObj) {
|
|
1145
|
+
if (explicitStatus === undefined) {
|
|
1146
|
+
explicitStatus = extractStatusCodeFromObject(respObj);
|
|
1147
|
+
}
|
|
1148
|
+
if (!responseSchema) {
|
|
1149
|
+
const schemaCandidate = safeGet(respObj, "schema") ?? safeGet(respObj, "payload") ?? respObj;
|
|
1150
|
+
if (isObject(schemaCandidate) && hasSchemaKeywords(schemaCandidate)) {
|
|
1151
|
+
responseSchema = resolveSchema(schemaCandidate, ctx);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
for (const src of sources) {
|
|
1157
|
+
if (!src)
|
|
1158
|
+
continue;
|
|
1159
|
+
if (explicitStatus === undefined) {
|
|
1160
|
+
explicitStatus = extractStatusCodeFromObject(src);
|
|
1161
|
+
}
|
|
1162
|
+
for (const extKey of ["x-response", "x-ack"]) {
|
|
1163
|
+
const rawExt = safeGet(src, extKey);
|
|
1164
|
+
const extObj = resolveObjectRef(rawExt, ctx);
|
|
1165
|
+
if (!extObj)
|
|
1166
|
+
continue;
|
|
1167
|
+
if (explicitStatus === undefined) {
|
|
1168
|
+
explicitStatus = extractStatusCodeFromObject(extObj);
|
|
1169
|
+
}
|
|
1170
|
+
if (!responseSchema) {
|
|
1171
|
+
const schemaCandidate = safeGet(extObj, "schema") ?? safeGet(extObj, "payload") ?? extObj;
|
|
1172
|
+
if (isObject(schemaCandidate) && hasSchemaKeywords(schemaCandidate)) {
|
|
1173
|
+
responseSchema = resolveSchema(schemaCandidate, ctx);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
if (replyObj) {
|
|
1179
|
+
const replyBinding = extractHttpBinding(replyObj, ctx);
|
|
1180
|
+
if (explicitStatus === undefined) {
|
|
1181
|
+
explicitStatus = extractStatusCodeFromObject(replyBinding) ?? extractStatusCodeFromObject(replyObj);
|
|
1182
|
+
}
|
|
1183
|
+
if (!responseSchema) {
|
|
1184
|
+
responseSchema = extractSchemaFromReply(replyObj, ctx);
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return { explicitStatus, responseSchema };
|
|
1188
|
+
}
|
|
1189
|
+
function hasSchemaKeywords(obj) {
|
|
1190
|
+
return (hasOwn(obj, "$ref") ||
|
|
1191
|
+
hasOwn(obj, "type") ||
|
|
1192
|
+
hasOwn(obj, "properties") ||
|
|
1193
|
+
hasOwn(obj, "items") ||
|
|
1194
|
+
hasOwn(obj, "required") ||
|
|
1195
|
+
hasOwn(obj, "allOf") ||
|
|
1196
|
+
hasOwn(obj, "anyOf") ||
|
|
1197
|
+
hasOwn(obj, "oneOf") ||
|
|
1198
|
+
hasOwn(obj, "enum") ||
|
|
1199
|
+
hasOwn(obj, "const") ||
|
|
1200
|
+
hasOwn(obj, "schemaFormat"));
|
|
1201
|
+
}
|
|
1202
|
+
function extractSchemaFromReply(replyObj, ctx) {
|
|
1203
|
+
const rawMessages = safeGet(replyObj, "messages");
|
|
1204
|
+
if (Array.isArray(rawMessages)) {
|
|
1205
|
+
for (const rawMsg of rawMessages) {
|
|
1206
|
+
const msg = resolveMessageObject(rawMsg, ctx);
|
|
1207
|
+
if (msg && isObject(msg.payload)) {
|
|
1208
|
+
const schema = resolveSchema(msg.payload, ctx);
|
|
1209
|
+
if (schema)
|
|
1210
|
+
return schema;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
const rawChannel = safeGet(replyObj, "channel");
|
|
1215
|
+
const replyChannel = resolveObjectRef(rawChannel, ctx);
|
|
1216
|
+
if (replyChannel) {
|
|
1217
|
+
const channelMsgs = safeGet(replyChannel, "messages");
|
|
1218
|
+
if (isObject(channelMsgs)) {
|
|
1219
|
+
for (const msgKey of Object.keys(channelMsgs)) {
|
|
1220
|
+
if (isUnsafeKey(msgKey))
|
|
1221
|
+
continue;
|
|
1222
|
+
const msg = resolveMessageObject(channelMsgs[msgKey], ctx);
|
|
1223
|
+
if (msg && isObject(msg.payload)) {
|
|
1224
|
+
const schema = resolveSchema(msg.payload, ctx);
|
|
1225
|
+
if (schema)
|
|
1226
|
+
return schema;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
return undefined;
|
|
1232
|
+
}
|
|
1233
|
+
function mergeTraits(target, ctx) {
|
|
1234
|
+
const rawTraits = safeGet(target, "traits");
|
|
1235
|
+
if (!Array.isArray(rawTraits) || rawTraits.length === 0)
|
|
1236
|
+
return target;
|
|
1237
|
+
let merged = {};
|
|
1238
|
+
for (const rawTrait of rawTraits) {
|
|
1239
|
+
const trait = resolveObjectRef(rawTrait, ctx);
|
|
1240
|
+
if (!trait)
|
|
1241
|
+
continue;
|
|
1242
|
+
for (const k of Object.keys(trait)) {
|
|
1243
|
+
if (isUnsafeKey(k) || k === "traits")
|
|
1244
|
+
continue;
|
|
1245
|
+
merged[k] = trait[k];
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
for (const k of Object.keys(target)) {
|
|
1249
|
+
if (isUnsafeKey(k) || k === "traits")
|
|
1250
|
+
continue;
|
|
1251
|
+
merged[k] = target[k];
|
|
1252
|
+
}
|
|
1253
|
+
return merged;
|
|
1254
|
+
}
|
|
1255
|
+
function resolveMessageObject(rawMsg, ctx) {
|
|
1256
|
+
const resolved = resolveObjectRef(rawMsg, ctx);
|
|
1257
|
+
if (!resolved)
|
|
1258
|
+
return undefined;
|
|
1259
|
+
return mergeTraits(resolved, ctx);
|
|
1260
|
+
}
|
|
1261
|
+
function extractHeadersFromContainer(rawHeaders, ctx, target) {
|
|
1262
|
+
const resolved = resolveObjectRef(rawHeaders, ctx);
|
|
1263
|
+
if (!resolved)
|
|
1264
|
+
return;
|
|
1265
|
+
const isSchemaObj = resolved.type === "object" ||
|
|
1266
|
+
isObject(resolved.properties) ||
|
|
1267
|
+
hasOwn(resolved, "allOf") ||
|
|
1268
|
+
hasOwn(resolved, "$ref");
|
|
1269
|
+
if (isSchemaObj) {
|
|
1270
|
+
const schema = resolveSchema(resolved, ctx);
|
|
1271
|
+
if (!schema || !isObject(schema.properties))
|
|
1272
|
+
return;
|
|
1273
|
+
for (const propKey of Object.keys(schema.properties)) {
|
|
1274
|
+
if (isUnsafeKey(propKey))
|
|
1275
|
+
continue;
|
|
1276
|
+
const propSchema = schema.properties[propKey];
|
|
1277
|
+
const rawVal = synthesizeSampleFromSchema(propSchema, ctx, 0, propKey);
|
|
1278
|
+
const valStr = rawVal !== undefined && rawVal !== null && typeof rawVal !== "object" ? String(rawVal) : "sample";
|
|
1279
|
+
const sanitized = sanitizeHeaderEntry(propKey, valStr, ctx);
|
|
1280
|
+
if (sanitized) {
|
|
1281
|
+
setHeaderCaseInsensitive(target, sanitized.name, sanitized.value);
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
for (const key of Object.keys(resolved)) {
|
|
1287
|
+
if (isUnsafeKey(key))
|
|
1288
|
+
continue;
|
|
1289
|
+
const val = resolved[key];
|
|
1290
|
+
if (val === undefined || val === null || typeof val === "object")
|
|
1291
|
+
continue;
|
|
1292
|
+
const sanitized = sanitizeHeaderEntry(key, String(val), ctx);
|
|
1293
|
+
if (sanitized) {
|
|
1294
|
+
setHeaderCaseInsensitive(target, sanitized.name, sanitized.value);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
function extractSamplePayloadAndHeadersFromMessage(msg, payloadSchema, ctx, headersOut) {
|
|
1299
|
+
if (msg) {
|
|
1300
|
+
extractHeadersFromContainer(safeGet(msg, "headers"), ctx, headersOut);
|
|
1301
|
+
const examples = safeGet(msg, "examples");
|
|
1302
|
+
if (Array.isArray(examples) && examples.length > 0) {
|
|
1303
|
+
for (const ex of examples) {
|
|
1304
|
+
if (!isObject(ex))
|
|
1305
|
+
continue;
|
|
1306
|
+
if (isObject(ex.headers)) {
|
|
1307
|
+
extractHeadersFromContainer(ex.headers, ctx, headersOut);
|
|
1308
|
+
}
|
|
1309
|
+
if (hasOwn(ex, "payload") && ex.payload !== undefined) {
|
|
1310
|
+
const scrubbed = scrubValueDeep(ex.payload, ctx.secretValues);
|
|
1311
|
+
if (scrubbed.redacted)
|
|
1312
|
+
ctx.redactedSecrets = true;
|
|
1313
|
+
return scrubbed.value;
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
if (payloadSchema) {
|
|
1319
|
+
return synthesizeSampleFromSchema(payloadSchema, ctx, 0, "");
|
|
1320
|
+
}
|
|
1321
|
+
return undefined;
|
|
1322
|
+
}
|
|
1323
|
+
function slugify(text, fallback = "channel") {
|
|
1324
|
+
const s = text
|
|
1325
|
+
.toLowerCase()
|
|
1326
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
1327
|
+
.replace(/^-+|-+$/g, "")
|
|
1328
|
+
.slice(0, 64);
|
|
1329
|
+
return s || fallback;
|
|
1330
|
+
}
|
|
1331
|
+
function uniqueChannelId(seed, used) {
|
|
1332
|
+
const base = slugify(seed, "channel");
|
|
1333
|
+
if (!used.has(base)) {
|
|
1334
|
+
used.add(base);
|
|
1335
|
+
return base;
|
|
1336
|
+
}
|
|
1337
|
+
let n = 2;
|
|
1338
|
+
while (used.has(`${base}-${n}`))
|
|
1339
|
+
n += 1;
|
|
1340
|
+
const out = `${base}-${n}`;
|
|
1341
|
+
used.add(out);
|
|
1342
|
+
return out;
|
|
1343
|
+
}
|
|
1344
|
+
function buildChannelRecord(params) {
|
|
1345
|
+
const { channelKey, address, channelObj, operationObj, operationId, direction, messageObj, messageLabel, defaultContentType, usedIds, ctx } = params;
|
|
1346
|
+
const channelBinding = extractHttpBinding(channelObj, ctx);
|
|
1347
|
+
const opBinding = extractHttpBinding(operationObj, ctx);
|
|
1348
|
+
const msgBinding = extractHttpBinding(messageObj, ctx);
|
|
1349
|
+
const bindingsList = [opBinding, msgBinding, channelBinding];
|
|
1350
|
+
const method = extractMethodFromBindings(bindingsList);
|
|
1351
|
+
const channelParams = isObject(channelObj.parameters) ? channelObj.parameters : undefined;
|
|
1352
|
+
const normalizedPath = normalizeChannelPath(address, channelParams, ctx);
|
|
1353
|
+
const rawPayload = messageObj ? safeGet(messageObj, "payload") : undefined;
|
|
1354
|
+
const payloadSchema = rawPayload !== undefined ? resolveSchema(rawPayload, ctx) : undefined;
|
|
1355
|
+
const headers = {};
|
|
1356
|
+
if (channelBinding)
|
|
1357
|
+
extractHeadersFromContainer(safeGet(channelBinding, "headers"), ctx, headers);
|
|
1358
|
+
if (opBinding)
|
|
1359
|
+
extractHeadersFromContainer(safeGet(opBinding, "headers"), ctx, headers);
|
|
1360
|
+
if (msgBinding)
|
|
1361
|
+
extractHeadersFromContainer(safeGet(msgBinding, "headers"), ctx, headers);
|
|
1362
|
+
const samplePayload = extractSamplePayloadAndHeadersFromMessage(messageObj, payloadSchema, ctx, headers);
|
|
1363
|
+
const rawContentType = (messageObj && typeof messageObj.contentType === "string" ? messageObj.contentType : undefined) ??
|
|
1364
|
+
defaultContentType;
|
|
1365
|
+
if (rawContentType && !hasHeaderCaseInsensitive(headers, "content-type")) {
|
|
1366
|
+
const ct = sanitizeHeaderEntry("content-type", rawContentType, ctx);
|
|
1367
|
+
if (ct)
|
|
1368
|
+
setHeaderCaseInsensitive(headers, ct.name, ct.value);
|
|
1369
|
+
}
|
|
1370
|
+
deleteHeaderCaseInsensitive(headers, "host");
|
|
1371
|
+
const replyObj = operationObj ? resolveObjectRef(safeGet(operationObj, "reply"), ctx) : undefined;
|
|
1372
|
+
const { explicitStatus, responseSchema } = extractResponseMeta([operationObj, messageObj, channelObj], bindingsList, replyObj, ctx);
|
|
1373
|
+
const expectedStatus = explicitStatus ?? (responseSchema ? 200 : 202);
|
|
1374
|
+
const rawSummary = (operationObj && typeof operationObj.summary === "string" ? operationObj.summary : undefined) ??
|
|
1375
|
+
(messageObj && typeof messageObj.summary === "string" ? messageObj.summary : undefined) ??
|
|
1376
|
+
(messageObj && typeof messageObj.title === "string" ? messageObj.title : undefined) ??
|
|
1377
|
+
(typeof channelObj.summary === "string" ? channelObj.summary : undefined) ??
|
|
1378
|
+
(operationObj && typeof operationObj.description === "string" ? operationObj.description : undefined) ??
|
|
1379
|
+
(typeof channelObj.description === "string" ? channelObj.description : undefined);
|
|
1380
|
+
let summary;
|
|
1381
|
+
if (rawSummary && rawSummary.trim()) {
|
|
1382
|
+
const cleanSummary = scrubText(rawSummary.replace(CONTROL_CHAR_GLOBAL_RE, " ").trim(), ctx.secretValues);
|
|
1383
|
+
if (cleanSummary.redacted)
|
|
1384
|
+
ctx.redactedSecrets = true;
|
|
1385
|
+
summary = cleanSummary.value;
|
|
1386
|
+
}
|
|
1387
|
+
const scrubbedChannel = scrubText(channelKey.replace(CONTROL_CHAR_GLOBAL_RE, ""), ctx.secretValues);
|
|
1388
|
+
if (scrubbedChannel.redacted)
|
|
1389
|
+
ctx.redactedSecrets = true;
|
|
1390
|
+
const cleanOpId = operationId
|
|
1391
|
+
? scrubText(operationId.replace(CONTROL_CHAR_GLOBAL_RE, "").trim(), ctx.secretValues).value
|
|
1392
|
+
: undefined;
|
|
1393
|
+
const idSeed = [cleanOpId || scrubbedChannel.value, direction, messageLabel].filter(Boolean).join("-");
|
|
1394
|
+
const id = uniqueChannelId(idSeed, usedIds);
|
|
1395
|
+
const parsed = {
|
|
1396
|
+
id,
|
|
1397
|
+
channel: scrubbedChannel.value || normalizedPath,
|
|
1398
|
+
...(cleanOpId ? { operationId: cleanOpId } : {}),
|
|
1399
|
+
direction,
|
|
1400
|
+
method,
|
|
1401
|
+
path: normalizedPath,
|
|
1402
|
+
...(summary ? { summary } : {}),
|
|
1403
|
+
headers,
|
|
1404
|
+
...(payloadSchema ? { payloadSchema } : {}),
|
|
1405
|
+
...(samplePayload !== undefined ? { samplePayload } : {}),
|
|
1406
|
+
expectedStatus,
|
|
1407
|
+
...(responseSchema ? { responseSchema } : {})
|
|
1408
|
+
};
|
|
1409
|
+
return { parsed, explicitStatus };
|
|
1410
|
+
}
|
|
1411
|
+
function extractV2Messages(rawMessage, ctx) {
|
|
1412
|
+
if (!isObject(rawMessage))
|
|
1413
|
+
return [];
|
|
1414
|
+
const oneOf = safeGet(rawMessage, "oneOf");
|
|
1415
|
+
if (Array.isArray(oneOf)) {
|
|
1416
|
+
const results = [];
|
|
1417
|
+
for (let i = 0; i < oneOf.length; i += 1) {
|
|
1418
|
+
const resolved = resolveMessageObject(oneOf[i], ctx);
|
|
1419
|
+
if (!resolved)
|
|
1420
|
+
continue;
|
|
1421
|
+
const label = (typeof resolved.name === "string" && resolved.name.trim()) ||
|
|
1422
|
+
(typeof resolved.messageId === "string" && resolved.messageId.trim()) ||
|
|
1423
|
+
`msg-${i + 1}`;
|
|
1424
|
+
results.push({ label, msg: resolved });
|
|
1425
|
+
}
|
|
1426
|
+
return results;
|
|
1427
|
+
}
|
|
1428
|
+
const single = resolveMessageObject(rawMessage, ctx);
|
|
1429
|
+
if (!single)
|
|
1430
|
+
return [];
|
|
1431
|
+
return [{ msg: single }];
|
|
1432
|
+
}
|
|
1433
|
+
function parseAsyncApiV2Channels(doc, defaultContentType, ctx) {
|
|
1434
|
+
const rawChannels = safeGet(doc, "channels");
|
|
1435
|
+
if (!isObject(rawChannels))
|
|
1436
|
+
return [];
|
|
1437
|
+
const records = [];
|
|
1438
|
+
const usedIds = new Set();
|
|
1439
|
+
for (const channelKey of Object.keys(rawChannels)) {
|
|
1440
|
+
if (isUnsafeKey(channelKey))
|
|
1441
|
+
continue;
|
|
1442
|
+
if (records.length >= MAX_CHANNELS) {
|
|
1443
|
+
pushWarning(ctx, `AsyncAPI specification exceeded maximum of ${MAX_CHANNELS} channels; remaining channels were skipped.`);
|
|
1444
|
+
break;
|
|
1445
|
+
}
|
|
1446
|
+
const channelObj = resolveObjectRef(safeGet(rawChannels, channelKey), ctx);
|
|
1447
|
+
if (!channelObj)
|
|
1448
|
+
continue;
|
|
1449
|
+
for (const dir of ["publish", "subscribe"]) {
|
|
1450
|
+
const rawOp = safeGet(channelObj, dir);
|
|
1451
|
+
const opObjRaw = resolveObjectRef(rawOp, ctx);
|
|
1452
|
+
if (!opObjRaw)
|
|
1453
|
+
continue;
|
|
1454
|
+
if (records.length >= MAX_CHANNELS) {
|
|
1455
|
+
pushWarning(ctx, `AsyncAPI specification exceeded maximum of ${MAX_CHANNELS} channels; remaining operations were skipped.`);
|
|
1456
|
+
break;
|
|
1457
|
+
}
|
|
1458
|
+
const opObj = mergeTraits(opObjRaw, ctx);
|
|
1459
|
+
const operationId = typeof opObj.operationId === "string" && opObj.operationId.trim() ? opObj.operationId.trim() : undefined;
|
|
1460
|
+
const messages = extractV2Messages(safeGet(opObj, "message"), ctx);
|
|
1461
|
+
if (messages.length === 0) {
|
|
1462
|
+
records.push(buildChannelRecord({
|
|
1463
|
+
channelKey,
|
|
1464
|
+
address: channelKey,
|
|
1465
|
+
channelObj,
|
|
1466
|
+
operationObj: opObj,
|
|
1467
|
+
operationId,
|
|
1468
|
+
direction: dir,
|
|
1469
|
+
defaultContentType,
|
|
1470
|
+
usedIds,
|
|
1471
|
+
ctx
|
|
1472
|
+
}));
|
|
1473
|
+
}
|
|
1474
|
+
else {
|
|
1475
|
+
for (const entry of messages) {
|
|
1476
|
+
if (records.length >= MAX_CHANNELS)
|
|
1477
|
+
break;
|
|
1478
|
+
records.push(buildChannelRecord({
|
|
1479
|
+
channelKey,
|
|
1480
|
+
address: channelKey,
|
|
1481
|
+
channelObj,
|
|
1482
|
+
operationObj: opObj,
|
|
1483
|
+
operationId,
|
|
1484
|
+
direction: dir,
|
|
1485
|
+
messageObj: entry.msg,
|
|
1486
|
+
messageLabel: messages.length > 1 ? entry.label : undefined,
|
|
1487
|
+
defaultContentType,
|
|
1488
|
+
usedIds,
|
|
1489
|
+
ctx
|
|
1490
|
+
}));
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
return records;
|
|
1496
|
+
}
|
|
1497
|
+
function resolveV3ChannelKeyFromRef(rawChannel) {
|
|
1498
|
+
if (!isObject(rawChannel))
|
|
1499
|
+
return undefined;
|
|
1500
|
+
const ref = safeGet(rawChannel, "$ref");
|
|
1501
|
+
if (typeof ref === "string" && ref.startsWith("#/channels/")) {
|
|
1502
|
+
const seg = ref.slice("#/channels/".length).split("/")[0];
|
|
1503
|
+
if (seg) {
|
|
1504
|
+
const decoded = decodeJsonPointerSegment(seg);
|
|
1505
|
+
if (!isUnsafeKey(decoded))
|
|
1506
|
+
return decoded;
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
return undefined;
|
|
1510
|
+
}
|
|
1511
|
+
function extractV3ChannelMessages(channelObj, ctx) {
|
|
1512
|
+
const rawMsgs = safeGet(channelObj, "messages");
|
|
1513
|
+
if (!isObject(rawMsgs))
|
|
1514
|
+
return [];
|
|
1515
|
+
const out = [];
|
|
1516
|
+
for (const key of Object.keys(rawMsgs)) {
|
|
1517
|
+
if (isUnsafeKey(key))
|
|
1518
|
+
continue;
|
|
1519
|
+
const msg = resolveMessageObject(rawMsgs[key], ctx);
|
|
1520
|
+
if (msg)
|
|
1521
|
+
out.push({ label: key, msg });
|
|
1522
|
+
}
|
|
1523
|
+
return out;
|
|
1524
|
+
}
|
|
1525
|
+
function parseAsyncApiV3Channels(doc, defaultContentType, ctx) {
|
|
1526
|
+
const records = [];
|
|
1527
|
+
const usedIds = new Set();
|
|
1528
|
+
const rawOperations = safeGet(doc, "operations");
|
|
1529
|
+
if (isObject(rawOperations) && Object.keys(rawOperations).some((k) => !isUnsafeKey(k))) {
|
|
1530
|
+
for (const opKey of Object.keys(rawOperations)) {
|
|
1531
|
+
if (isUnsafeKey(opKey))
|
|
1532
|
+
continue;
|
|
1533
|
+
if (records.length >= MAX_CHANNELS) {
|
|
1534
|
+
pushWarning(ctx, `AsyncAPI specification exceeded maximum of ${MAX_CHANNELS} operations; remaining operations were skipped.`);
|
|
1535
|
+
break;
|
|
1536
|
+
}
|
|
1537
|
+
const opRaw = resolveObjectRef(safeGet(rawOperations, opKey), ctx);
|
|
1538
|
+
if (!opRaw)
|
|
1539
|
+
continue;
|
|
1540
|
+
const opObj = mergeTraits(opRaw, ctx);
|
|
1541
|
+
const rawAction = typeof opObj.action === "string" ? opObj.action.trim().toLowerCase() : "";
|
|
1542
|
+
const direction = rawAction === "receive" ? "receive" : "send";
|
|
1543
|
+
const rawChannelRef = safeGet(opObj, "channel");
|
|
1544
|
+
const channelObj = resolveObjectRef(rawChannelRef, ctx);
|
|
1545
|
+
if (!channelObj) {
|
|
1546
|
+
pushWarning(ctx, `AsyncAPI 3.0 operation "${opKey}" references missing channel.`);
|
|
1547
|
+
continue;
|
|
1548
|
+
}
|
|
1549
|
+
const channelKey = resolveV3ChannelKeyFromRef(rawChannelRef) ?? opKey;
|
|
1550
|
+
const address = (typeof channelObj.address === "string" && channelObj.address.trim()) ||
|
|
1551
|
+
channelKey;
|
|
1552
|
+
const messages = [];
|
|
1553
|
+
const rawOpMessages = safeGet(opObj, "messages");
|
|
1554
|
+
if (Array.isArray(rawOpMessages) && rawOpMessages.length > 0) {
|
|
1555
|
+
for (let i = 0; i < rawOpMessages.length; i += 1) {
|
|
1556
|
+
const msg = resolveMessageObject(rawOpMessages[i], ctx);
|
|
1557
|
+
if (!msg)
|
|
1558
|
+
continue;
|
|
1559
|
+
const label = (typeof msg.name === "string" && msg.name.trim()) ||
|
|
1560
|
+
(typeof msg.title === "string" && msg.title.trim()) ||
|
|
1561
|
+
`msg-${i + 1}`;
|
|
1562
|
+
messages.push({ label, msg });
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
else {
|
|
1566
|
+
messages.push(...extractV3ChannelMessages(channelObj, ctx));
|
|
1567
|
+
}
|
|
1568
|
+
if (messages.length === 0) {
|
|
1569
|
+
records.push(buildChannelRecord({
|
|
1570
|
+
channelKey,
|
|
1571
|
+
address,
|
|
1572
|
+
channelObj,
|
|
1573
|
+
operationObj: opObj,
|
|
1574
|
+
operationId: opKey,
|
|
1575
|
+
direction,
|
|
1576
|
+
defaultContentType,
|
|
1577
|
+
usedIds,
|
|
1578
|
+
ctx
|
|
1579
|
+
}));
|
|
1580
|
+
}
|
|
1581
|
+
else {
|
|
1582
|
+
for (const entry of messages) {
|
|
1583
|
+
if (records.length >= MAX_CHANNELS)
|
|
1584
|
+
break;
|
|
1585
|
+
records.push(buildChannelRecord({
|
|
1586
|
+
channelKey,
|
|
1587
|
+
address,
|
|
1588
|
+
channelObj,
|
|
1589
|
+
operationObj: opObj,
|
|
1590
|
+
operationId: opKey,
|
|
1591
|
+
direction,
|
|
1592
|
+
messageObj: entry.msg,
|
|
1593
|
+
messageLabel: messages.length > 1 ? entry.label : undefined,
|
|
1594
|
+
defaultContentType,
|
|
1595
|
+
usedIds,
|
|
1596
|
+
ctx
|
|
1597
|
+
}));
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
// Fallback: if no operations yielded channels, inspect channels directly
|
|
1603
|
+
if (records.length === 0) {
|
|
1604
|
+
const rawChannels = safeGet(doc, "channels");
|
|
1605
|
+
if (isObject(rawChannels)) {
|
|
1606
|
+
for (const channelKey of Object.keys(rawChannels)) {
|
|
1607
|
+
if (isUnsafeKey(channelKey))
|
|
1608
|
+
continue;
|
|
1609
|
+
if (records.length >= MAX_CHANNELS) {
|
|
1610
|
+
pushWarning(ctx, `AsyncAPI specification exceeded maximum of ${MAX_CHANNELS} channels; remaining channels were skipped.`);
|
|
1611
|
+
break;
|
|
1612
|
+
}
|
|
1613
|
+
const channelObj = resolveObjectRef(safeGet(rawChannels, channelKey), ctx);
|
|
1614
|
+
if (!channelObj)
|
|
1615
|
+
continue;
|
|
1616
|
+
const address = (typeof channelObj.address === "string" && channelObj.address.trim()) ||
|
|
1617
|
+
channelKey;
|
|
1618
|
+
const messages = extractV3ChannelMessages(channelObj, ctx);
|
|
1619
|
+
if (messages.length === 0) {
|
|
1620
|
+
records.push(buildChannelRecord({
|
|
1621
|
+
channelKey,
|
|
1622
|
+
address,
|
|
1623
|
+
channelObj,
|
|
1624
|
+
direction: "send",
|
|
1625
|
+
defaultContentType,
|
|
1626
|
+
usedIds,
|
|
1627
|
+
ctx
|
|
1628
|
+
}));
|
|
1629
|
+
}
|
|
1630
|
+
else {
|
|
1631
|
+
for (const entry of messages) {
|
|
1632
|
+
if (records.length >= MAX_CHANNELS)
|
|
1633
|
+
break;
|
|
1634
|
+
records.push(buildChannelRecord({
|
|
1635
|
+
channelKey,
|
|
1636
|
+
address,
|
|
1637
|
+
channelObj,
|
|
1638
|
+
direction: "send",
|
|
1639
|
+
messageObj: entry.msg,
|
|
1640
|
+
messageLabel: messages.length > 1 ? entry.label : undefined,
|
|
1641
|
+
defaultContentType,
|
|
1642
|
+
usedIds,
|
|
1643
|
+
ctx
|
|
1644
|
+
}));
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
return records;
|
|
1651
|
+
}
|
|
1652
|
+
function finalScrubChannel(ch, secretValues) {
|
|
1653
|
+
const scrubbedHeaders = {};
|
|
1654
|
+
for (const [k, v] of Object.entries(ch.headers)) {
|
|
1655
|
+
if (isUnsafeKey(k) || isAsyncApiSensitiveHeader(k) || SENSITIVE_HEADER_VALUE_RE.test(v)) {
|
|
1656
|
+
recordSecretValue(secretValues, v);
|
|
1657
|
+
continue;
|
|
1658
|
+
}
|
|
1659
|
+
scrubbedHeaders[k] = scrubText(v, secretValues).value;
|
|
1660
|
+
}
|
|
1661
|
+
return {
|
|
1662
|
+
id: ch.id,
|
|
1663
|
+
channel: scrubText(ch.channel, secretValues).value,
|
|
1664
|
+
...(ch.operationId ? { operationId: scrubText(ch.operationId, secretValues).value } : {}),
|
|
1665
|
+
direction: ch.direction,
|
|
1666
|
+
method: ch.method,
|
|
1667
|
+
path: scrubText(ch.path, secretValues).value,
|
|
1668
|
+
...(ch.summary ? { summary: scrubText(ch.summary, secretValues).value } : {}),
|
|
1669
|
+
headers: scrubbedHeaders,
|
|
1670
|
+
...(ch.payloadSchema ? { payloadSchema: scrubSchemaDeep(ch.payloadSchema, secretValues) } : {}),
|
|
1671
|
+
...(ch.samplePayload !== undefined ? { samplePayload: scrubValueDeep(ch.samplePayload, secretValues).value } : {}),
|
|
1672
|
+
expectedStatus: ch.expectedStatus,
|
|
1673
|
+
...(ch.responseSchema ? { responseSchema: scrubSchemaDeep(ch.responseSchema, secretValues) } : {})
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
function parseRawDocument(rawText) {
|
|
1677
|
+
if (typeof rawText !== "string") {
|
|
1678
|
+
throw new VibecodeError("CONTRACT_INVALID", "AsyncAPI input must be a string.", {
|
|
1679
|
+
fallbackHint: "Pass a YAML or JSON AsyncAPI 2.x or 3.0 document."
|
|
1680
|
+
});
|
|
1681
|
+
}
|
|
1682
|
+
if (Buffer.byteLength(rawText, "utf8") > MAX_SOURCE_BYTES) {
|
|
1683
|
+
throw new VibecodeError("CONTRACT_INVALID", `AsyncAPI payload exceeds maximum size of ${MAX_SOURCE_BYTES} bytes.`, { fallbackHint: "Reduce the AsyncAPI document below 2 MiB or split into smaller specs." });
|
|
1684
|
+
}
|
|
1685
|
+
if (rawText.includes("\0")) {
|
|
1686
|
+
throw new VibecodeError("CONTRACT_INVALID", "AsyncAPI input contains NUL bytes.", {
|
|
1687
|
+
fallbackHint: "Provide a valid UTF-8 YAML or JSON AsyncAPI document without binary data."
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
1690
|
+
const cleaned = stripBom(rawText).trim();
|
|
1691
|
+
if (!cleaned) {
|
|
1692
|
+
throw new VibecodeError("CONTRACT_INVALID", "AsyncAPI input is empty.", {
|
|
1693
|
+
fallbackHint: "Provide a non-empty AsyncAPI 2.x or 3.0 YAML/JSON specification."
|
|
1694
|
+
});
|
|
1695
|
+
}
|
|
1696
|
+
let parsed;
|
|
1697
|
+
try {
|
|
1698
|
+
if (cleaned.startsWith("{")) {
|
|
1699
|
+
parsed = JSON.parse(cleaned);
|
|
1700
|
+
}
|
|
1701
|
+
else {
|
|
1702
|
+
parsed = parseYaml(cleaned);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
catch (err) {
|
|
1706
|
+
const scrubbedErr = scrubText(errorMessage(err), new Set()).value
|
|
1707
|
+
.replace(CONTROL_CHAR_GLOBAL_RE, " ")
|
|
1708
|
+
.replace(/"[^"\r\n]{1,200}"\s+is not valid JSON/gi, '"[REDACTED_INPUT]" is not valid JSON')
|
|
1709
|
+
.slice(0, 160);
|
|
1710
|
+
throw new VibecodeError("CONTRACT_INVALID", `Failed to parse AsyncAPI document: ${scrubbedErr}`, {
|
|
1711
|
+
fallbackHint: "Ensure the input is valid JSON or YAML conforming to AsyncAPI 2.x or 3.0."
|
|
1712
|
+
});
|
|
1713
|
+
}
|
|
1714
|
+
const sanitized = sanitizeParsedValue(parsed);
|
|
1715
|
+
if (!isObject(sanitized)) {
|
|
1716
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", "AsyncAPI document must be a JSON/YAML object.", {
|
|
1717
|
+
fallbackHint: "Provide a root object containing 'asyncapi' and 'channels'."
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1720
|
+
return sanitized;
|
|
1721
|
+
}
|
|
1722
|
+
export function isAsyncApiDoc(value) {
|
|
1723
|
+
if (!isObject(value))
|
|
1724
|
+
return false;
|
|
1725
|
+
// Explicitly exclude OpenAPI, Swagger, Insomnia, Postman, and HAR documents
|
|
1726
|
+
if (hasOwn(value, "openapi") || hasOwn(value, "swagger"))
|
|
1727
|
+
return false;
|
|
1728
|
+
if (safeGet(value, "_type") === "export")
|
|
1729
|
+
return false;
|
|
1730
|
+
const info = safeGet(value, "info");
|
|
1731
|
+
if (isObject(info) && Array.isArray(safeGet(value, "item")))
|
|
1732
|
+
return false;
|
|
1733
|
+
const log = safeGet(value, "log");
|
|
1734
|
+
if (isObject(log) && Array.isArray(safeGet(log, "entries")))
|
|
1735
|
+
return false;
|
|
1736
|
+
const rawVersion = safeGet(value, "asyncapi");
|
|
1737
|
+
if (typeof rawVersion !== "string")
|
|
1738
|
+
return false;
|
|
1739
|
+
const match = ASYNCAPI_VERSION_RE.exec(rawVersion.trim());
|
|
1740
|
+
if (!match)
|
|
1741
|
+
return false;
|
|
1742
|
+
const major = Number(match[1]);
|
|
1743
|
+
const hasChannels = isObject(safeGet(value, "channels"));
|
|
1744
|
+
const hasOperations = isObject(safeGet(value, "operations"));
|
|
1745
|
+
if (major === 2)
|
|
1746
|
+
return hasChannels;
|
|
1747
|
+
if (major === 3)
|
|
1748
|
+
return hasChannels || hasOperations;
|
|
1749
|
+
return false;
|
|
1750
|
+
}
|
|
1751
|
+
export function isAsyncApiText(rawText) {
|
|
1752
|
+
if (typeof rawText !== "string")
|
|
1753
|
+
return false;
|
|
1754
|
+
if (rawText.includes("\0"))
|
|
1755
|
+
return false;
|
|
1756
|
+
if (Buffer.byteLength(rawText, "utf8") > MAX_SOURCE_BYTES)
|
|
1757
|
+
return false;
|
|
1758
|
+
const cleaned = stripBom(rawText).trim();
|
|
1759
|
+
if (!cleaned)
|
|
1760
|
+
return false;
|
|
1761
|
+
if (cleaned.startsWith("{")) {
|
|
1762
|
+
if (!cleaned.includes("\"asyncapi\""))
|
|
1763
|
+
return false;
|
|
1764
|
+
try {
|
|
1765
|
+
const parsed = JSON.parse(cleaned);
|
|
1766
|
+
return isAsyncApiDoc(parsed);
|
|
1767
|
+
}
|
|
1768
|
+
catch {
|
|
1769
|
+
return false;
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
if (!ASYNCAPI_YAML_HEADER_RE.test(cleaned))
|
|
1773
|
+
return false;
|
|
1774
|
+
if (OPENAPI_YAML_HEADER_RE.test(cleaned) || INSOMNIA_YAML_HEADER_RE.test(cleaned))
|
|
1775
|
+
return false;
|
|
1776
|
+
try {
|
|
1777
|
+
const parsed = parseYaml(cleaned);
|
|
1778
|
+
return isAsyncApiDoc(parsed);
|
|
1779
|
+
}
|
|
1780
|
+
catch {
|
|
1781
|
+
return false;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
function parseAsyncApiInternal(rawText) {
|
|
1785
|
+
const doc = parseRawDocument(rawText);
|
|
1786
|
+
if (!isAsyncApiDoc(doc)) {
|
|
1787
|
+
const rawVersion = safeGet(doc, "asyncapi");
|
|
1788
|
+
if (typeof rawVersion === "string" && rawVersion.trim()) {
|
|
1789
|
+
const safeVer = scrubText(rawVersion.trim(), new Set()).value
|
|
1790
|
+
.replace(CONTROL_CHAR_GLOBAL_RE, " ")
|
|
1791
|
+
.slice(0, 64);
|
|
1792
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported AsyncAPI version "${safeVer}"; supported versions are AsyncAPI 2.x and 3.0.`, { fallbackHint: "Use an AsyncAPI 2.x (e.g. 2.6.0) or 3.0.0 specification." });
|
|
1793
|
+
}
|
|
1794
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", "Document is not a valid AsyncAPI 2.x or 3.0 specification.", { fallbackHint: "Include an 'asyncapi' version field (2.x or 3.0) and a 'channels' or 'operations' map." });
|
|
1795
|
+
}
|
|
1796
|
+
const version = String(safeGet(doc, "asyncapi")).trim();
|
|
1797
|
+
const major = Number(ASYNCAPI_VERSION_RE.exec(version)?.[1] ?? "2");
|
|
1798
|
+
const ctx = {
|
|
1799
|
+
doc,
|
|
1800
|
+
warnings: [],
|
|
1801
|
+
warningSet: new Set(),
|
|
1802
|
+
secretValues: new Set(),
|
|
1803
|
+
redactedSecrets: false,
|
|
1804
|
+
nodeBudget: { remaining: MAX_NODE_BUDGET }
|
|
1805
|
+
};
|
|
1806
|
+
const infoObj = resolveObjectRef(safeGet(doc, "info"), ctx);
|
|
1807
|
+
const rawTitle = infoObj && typeof infoObj.title === "string" && infoObj.title.trim() ? infoObj.title.trim() : "AsyncAPI Webhooks";
|
|
1808
|
+
const scrubbedTitle = scrubText(rawTitle.replace(CONTROL_CHAR_GLOBAL_RE, " "), ctx.secretValues);
|
|
1809
|
+
if (scrubbedTitle.redacted)
|
|
1810
|
+
ctx.redactedSecrets = true;
|
|
1811
|
+
const rawDefaultCt = safeGet(doc, "defaultContentType");
|
|
1812
|
+
const defaultContentType = typeof rawDefaultCt === "string" && rawDefaultCt.trim() ? rawDefaultCt.trim() : "application/json";
|
|
1813
|
+
const baseUrl = extractBaseUrlFromServers(doc, ctx);
|
|
1814
|
+
const records = major === 3
|
|
1815
|
+
? parseAsyncApiV3Channels(doc, defaultContentType, ctx)
|
|
1816
|
+
: parseAsyncApiV2Channels(doc, defaultContentType, ctx);
|
|
1817
|
+
if (records.length === 0) {
|
|
1818
|
+
throw new VibecodeError("CONTRACT_INVALID", "AsyncAPI specification contains no usable channels or operations.", { fallbackHint: "Define at least one channel with a publish/subscribe operation (2.x) or operations/channels entry (3.0)." });
|
|
1819
|
+
}
|
|
1820
|
+
// Final pass to guarantee any secret discovered later in the document is scrubbed everywhere
|
|
1821
|
+
const scrubbedTitleFinal = scrubText(scrubbedTitle.value, ctx.secretValues).value;
|
|
1822
|
+
const finalRecords = records.map((rec) => ({
|
|
1823
|
+
parsed: finalScrubChannel(rec.parsed, ctx.secretValues),
|
|
1824
|
+
explicitStatus: rec.explicitStatus
|
|
1825
|
+
}));
|
|
1826
|
+
const finalWarnings = ctx.warnings.map((w) => scrubText(w, ctx.secretValues).value);
|
|
1827
|
+
const spec = {
|
|
1828
|
+
version,
|
|
1829
|
+
title: scrubbedTitleFinal,
|
|
1830
|
+
...(baseUrl ? { baseUrl: scrubText(baseUrl, ctx.secretValues).value } : {}),
|
|
1831
|
+
channels: finalRecords.map((r) => r.parsed),
|
|
1832
|
+
warnings: finalWarnings
|
|
1833
|
+
};
|
|
1834
|
+
return {
|
|
1835
|
+
spec,
|
|
1836
|
+
records: finalRecords,
|
|
1837
|
+
secretValues: ctx.secretValues,
|
|
1838
|
+
redactedSecrets: ctx.redactedSecrets
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
export function parseAsyncApiSpec(rawText) {
|
|
1842
|
+
return parseAsyncApiInternal(rawText).spec;
|
|
1843
|
+
}
|
|
1844
|
+
function looksLikeFilePath(trimmed) {
|
|
1845
|
+
if (/[\r\n{}]/.test(trimmed))
|
|
1846
|
+
return false;
|
|
1847
|
+
const ext = path.extname(trimmed).toLowerCase();
|
|
1848
|
+
if (ext === ".yaml" || ext === ".yml" || ext === ".json" || ext === ".asyncapi")
|
|
1849
|
+
return true;
|
|
1850
|
+
if (!trimmed.includes(":") && !trimmed.includes("\n"))
|
|
1851
|
+
return true;
|
|
1852
|
+
// Windows drive path like C:\foo\bar.yaml
|
|
1853
|
+
if (/^[A-Za-z]:[\\/]/.test(trimmed))
|
|
1854
|
+
return true;
|
|
1855
|
+
return false;
|
|
1856
|
+
}
|
|
1857
|
+
function uniqueInvariantId(seed, used) {
|
|
1858
|
+
let id = slugify(seed, "asyncapi");
|
|
1859
|
+
if (!id.startsWith("inv-"))
|
|
1860
|
+
id = `inv-${id}`;
|
|
1861
|
+
if (!used.has(id)) {
|
|
1862
|
+
used.add(id);
|
|
1863
|
+
return id;
|
|
1864
|
+
}
|
|
1865
|
+
let n = 2;
|
|
1866
|
+
while (used.has(`${id}-${n}`))
|
|
1867
|
+
n += 1;
|
|
1868
|
+
const out = `${id}-${n}`;
|
|
1869
|
+
used.add(out);
|
|
1870
|
+
return out;
|
|
1871
|
+
}
|
|
1872
|
+
function validateInvariantsOrThrow(invariants) {
|
|
1873
|
+
const contract = {
|
|
1874
|
+
schemaVersion: "0.2.0",
|
|
1875
|
+
target: {
|
|
1876
|
+
name: "asyncapi",
|
|
1877
|
+
domains: ["api"],
|
|
1878
|
+
sources: [{ id: "src-1", kind: "asyncapi", ref: "inline", meta: {} }]
|
|
1879
|
+
},
|
|
1880
|
+
artifacts: { root: ".vibecode/artifacts", files: {} },
|
|
1881
|
+
thresholds: {
|
|
1882
|
+
hardBehavioralParity: 1,
|
|
1883
|
+
softPerceptualParity: 0.85,
|
|
1884
|
+
softGateMode: "warn",
|
|
1885
|
+
defaults: {}
|
|
1886
|
+
},
|
|
1887
|
+
invariants
|
|
1888
|
+
};
|
|
1889
|
+
const res = validateContract(contract);
|
|
1890
|
+
if (!res.ok) {
|
|
1891
|
+
const err = res.errors[0];
|
|
1892
|
+
throw new VibecodeError("BRIDGE_FORMAT_ERROR", `AsyncAPI ingestor produced invalid invariant: ${err.path} ${err.message}`, { details: res.errors });
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
export async function ingestAsyncApi(options = {}, _deps = {}) {
|
|
1896
|
+
if (typeof options.source !== "string" || !options.source.trim()) {
|
|
1897
|
+
throw new VibecodeError("TARGET_MISSING", "AsyncAPI ingestor requires --source <asyncapi.yaml|asyncapi.json|inline>.", { fallbackHint: "Pass a path to an AsyncAPI 2.x/3.0 YAML or JSON file, or inline spec text." });
|
|
1898
|
+
}
|
|
1899
|
+
const cwd = options.cwd || process.cwd();
|
|
1900
|
+
const rawSource = options.source;
|
|
1901
|
+
const trimmedSource = rawSource.trim();
|
|
1902
|
+
let rawText = "";
|
|
1903
|
+
let isFileSource = false;
|
|
1904
|
+
if (!/[\r\n]/.test(trimmedSource) && !trimmedSource.includes("\0")) {
|
|
1905
|
+
const candidatePath = path.resolve(cwd, trimmedSource);
|
|
1906
|
+
let exists = false;
|
|
1907
|
+
try {
|
|
1908
|
+
exists = fs.existsSync(candidatePath);
|
|
1909
|
+
}
|
|
1910
|
+
catch {
|
|
1911
|
+
exists = false;
|
|
1912
|
+
}
|
|
1913
|
+
if (exists) {
|
|
1914
|
+
let stat;
|
|
1915
|
+
try {
|
|
1916
|
+
stat = fs.statSync(candidatePath);
|
|
1917
|
+
}
|
|
1918
|
+
catch (err) {
|
|
1919
|
+
throw new VibecodeError("CONTRACT_INVALID", `Failed to inspect AsyncAPI source: ${errorMessage(err)}`, {
|
|
1920
|
+
fallbackHint: "Verify file permissions and path."
|
|
1921
|
+
});
|
|
1922
|
+
}
|
|
1923
|
+
if (!stat.isFile()) {
|
|
1924
|
+
const safePath = scrubText(trimmedSource, new Set()).value;
|
|
1925
|
+
throw new VibecodeError("CONTRACT_INVALID", `AsyncAPI source path is a directory or non-file: ${safePath}`, {
|
|
1926
|
+
fallbackHint: "Point --source to an AsyncAPI YAML or JSON file, not a directory."
|
|
1927
|
+
});
|
|
1928
|
+
}
|
|
1929
|
+
if (stat.size === 0) {
|
|
1930
|
+
const safePath = scrubText(trimmedSource, new Set()).value;
|
|
1931
|
+
throw new VibecodeError("CONTRACT_INVALID", `AsyncAPI source file is empty: ${safePath}`, {
|
|
1932
|
+
fallbackHint: "Provide a non-empty AsyncAPI 2.x or 3.0 specification file."
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
if (stat.size > MAX_SOURCE_BYTES) {
|
|
1936
|
+
throw new VibecodeError("CONTRACT_INVALID", `AsyncAPI source file exceeds maximum size of ${MAX_SOURCE_BYTES} bytes.`, { fallbackHint: "Reduce the AsyncAPI file size below 2 MiB." });
|
|
1937
|
+
}
|
|
1938
|
+
let buf;
|
|
1939
|
+
try {
|
|
1940
|
+
buf = fs.readFileSync(candidatePath);
|
|
1941
|
+
}
|
|
1942
|
+
catch (err) {
|
|
1943
|
+
throw new VibecodeError("CONTRACT_INVALID", `Failed to read AsyncAPI source file: ${errorMessage(err)}`, {
|
|
1944
|
+
fallbackHint: "Ensure the AsyncAPI file is readable."
|
|
1945
|
+
});
|
|
1946
|
+
}
|
|
1947
|
+
if (buf.length > MAX_SOURCE_BYTES) {
|
|
1948
|
+
throw new VibecodeError("CONTRACT_INVALID", `AsyncAPI source file exceeds maximum size of ${MAX_SOURCE_BYTES} bytes.`);
|
|
1949
|
+
}
|
|
1950
|
+
if (buf.includes(0)) {
|
|
1951
|
+
throw new VibecodeError("CONTRACT_INVALID", "AsyncAPI source file contains NUL bytes.", {
|
|
1952
|
+
fallbackHint: "Provide a UTF-8 text YAML or JSON AsyncAPI file."
|
|
1953
|
+
});
|
|
1954
|
+
}
|
|
1955
|
+
rawText = buf.toString("utf8");
|
|
1956
|
+
isFileSource = true;
|
|
1957
|
+
}
|
|
1958
|
+
else if (looksLikeFilePath(trimmedSource)) {
|
|
1959
|
+
const safePath = scrubText(trimmedSource, new Set()).value;
|
|
1960
|
+
throw new VibecodeError("TARGET_MISSING", `AsyncAPI source file not found: ${safePath}`, {
|
|
1961
|
+
fallbackHint: "Verify the file path exists or pass inline AsyncAPI YAML/JSON."
|
|
1962
|
+
});
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
if (!isFileSource) {
|
|
1966
|
+
if (Buffer.byteLength(rawSource, "utf8") > MAX_SOURCE_BYTES) {
|
|
1967
|
+
throw new VibecodeError("CONTRACT_INVALID", `Inline AsyncAPI payload exceeds maximum size of ${MAX_SOURCE_BYTES} bytes.`, { fallbackHint: "Reduce the AsyncAPI document size below 2 MiB." });
|
|
1968
|
+
}
|
|
1969
|
+
rawText = rawSource;
|
|
1970
|
+
}
|
|
1971
|
+
const parsedResult = parseAsyncApiInternal(rawText);
|
|
1972
|
+
const { spec, records, secretValues } = parsedResult;
|
|
1973
|
+
let redactedSecrets = parsedResult.redactedSecrets;
|
|
1974
|
+
const warnings = spec.warnings.map((message) => ({
|
|
1975
|
+
code: "BRIDGE_FORMAT_WARNING",
|
|
1976
|
+
message
|
|
1977
|
+
}));
|
|
1978
|
+
// Resolve and sanitize baseUrl (options.baseUrl overrides spec.baseUrl)
|
|
1979
|
+
let safeBaseUrl = spec.baseUrl || "";
|
|
1980
|
+
if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
|
|
1981
|
+
const sanitizedBase = sanitizeUrlString(options.baseUrl, secretValues, { requireHttp: true });
|
|
1982
|
+
if (sanitizedBase.redacted)
|
|
1983
|
+
redactedSecrets = true;
|
|
1984
|
+
if (sanitizedBase.valid && sanitizedBase.safeUrl) {
|
|
1985
|
+
safeBaseUrl = sanitizedBase.safeUrl;
|
|
1986
|
+
}
|
|
1987
|
+
else {
|
|
1988
|
+
warnings.push({
|
|
1989
|
+
code: "ADAPTER_DEGRADED",
|
|
1990
|
+
message: "Invalid AsyncAPI baseUrl provided; falling back to spec server URL or path-only invariants."
|
|
1991
|
+
});
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
// Sanitize global option headers
|
|
1995
|
+
const globalSafeHeaders = {};
|
|
1996
|
+
if (isObject(options.headers)) {
|
|
1997
|
+
const headerCtx = {
|
|
1998
|
+
doc: {},
|
|
1999
|
+
warnings: [],
|
|
2000
|
+
warningSet: new Set(),
|
|
2001
|
+
secretValues,
|
|
2002
|
+
redactedSecrets: false,
|
|
2003
|
+
nodeBudget: { remaining: 0 }
|
|
2004
|
+
};
|
|
2005
|
+
for (const [rawKey, rawVal] of Object.entries(options.headers)) {
|
|
2006
|
+
if (rawVal === undefined || rawVal === null)
|
|
2007
|
+
continue;
|
|
2008
|
+
const clean = sanitizeHeaderEntry(rawKey, String(rawVal), headerCtx);
|
|
2009
|
+
if (clean) {
|
|
2010
|
+
setHeaderCaseInsensitive(globalSafeHeaders, clean.name, clean.value);
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
if (headerCtx.redactedSecrets)
|
|
2014
|
+
redactedSecrets = true;
|
|
2015
|
+
for (const msg of headerCtx.warnings) {
|
|
2016
|
+
warnings.push({ code: "BRIDGE_FORMAT_WARNING", message: scrubText(msg, secretValues).value });
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
const usedIds = new Set();
|
|
2020
|
+
const invariants = [];
|
|
2021
|
+
for (const record of records) {
|
|
2022
|
+
const ch = record.parsed;
|
|
2023
|
+
const mergedHeaders = redactHeaders(mergeHeaders(ch.headers, globalSafeHeaders), "strip");
|
|
2024
|
+
deleteHeaderCaseInsensitive(mergedHeaders, "host");
|
|
2025
|
+
const finalHeaders = {};
|
|
2026
|
+
for (const [hk, hv] of Object.entries(mergedHeaders)) {
|
|
2027
|
+
if (isUnsafeKey(hk) || isAsyncApiSensitiveHeader(hk) || SENSITIVE_HEADER_VALUE_RE.test(hv)) {
|
|
2028
|
+
redactedSecrets = true;
|
|
2029
|
+
recordSecretValue(secretValues, hv);
|
|
2030
|
+
continue;
|
|
2031
|
+
}
|
|
2032
|
+
const scrubbedVal = scrubText(hv.replace(CONTROL_CHAR_GLOBAL_RE, "").trim(), secretValues);
|
|
2033
|
+
if (scrubbedVal.redacted)
|
|
2034
|
+
redactedSecrets = true;
|
|
2035
|
+
finalHeaders[hk] = scrubbedVal.value;
|
|
2036
|
+
}
|
|
2037
|
+
if (ch.samplePayload !== undefined && !hasHeaderCaseInsensitive(finalHeaders, "content-type")) {
|
|
2038
|
+
finalHeaders["content-type"] = "application/json";
|
|
2039
|
+
}
|
|
2040
|
+
const bodyValue = ch.samplePayload !== undefined ? scrubValueDeep(ch.samplePayload, secretValues).value : undefined;
|
|
2041
|
+
const responseSchemaValue = ch.responseSchema
|
|
2042
|
+
? scrubSchemaDeep(ch.responseSchema, secretValues)
|
|
2043
|
+
: undefined;
|
|
2044
|
+
const input = {
|
|
2045
|
+
method: ch.method,
|
|
2046
|
+
path: scrubText(ch.path, secretValues).value,
|
|
2047
|
+
...(Object.keys(finalHeaders).length > 0 ? { headers: finalHeaders } : {}),
|
|
2048
|
+
...(bodyValue !== undefined ? { body: bodyValue } : {})
|
|
2049
|
+
};
|
|
2050
|
+
const expected = {
|
|
2051
|
+
status: record.explicitStatus !== undefined ? record.explicitStatus : [200, 202],
|
|
2052
|
+
...(responseSchemaValue ? { jsonSchema: responseSchemaValue } : {})
|
|
2053
|
+
};
|
|
2054
|
+
const label = ch.operationId || ch.channel;
|
|
2055
|
+
const summarySuffix = ch.summary ? ` — ${ch.summary}` : "";
|
|
2056
|
+
const description = scrubText(`AsyncAPI ${ch.direction} ${label} (${ch.method} ${ch.path})${summarySuffix}`, secretValues).value;
|
|
2057
|
+
const tags = [
|
|
2058
|
+
"api",
|
|
2059
|
+
"asyncapi",
|
|
2060
|
+
"webhook",
|
|
2061
|
+
ch.direction,
|
|
2062
|
+
ch.method.toLowerCase()
|
|
2063
|
+
];
|
|
2064
|
+
invariants.push({
|
|
2065
|
+
id: uniqueInvariantId(`inv-asyncapi-${ch.id}`, usedIds),
|
|
2066
|
+
domain: "api",
|
|
2067
|
+
type: "http",
|
|
2068
|
+
severity: "hard",
|
|
2069
|
+
description,
|
|
2070
|
+
tags,
|
|
2071
|
+
sourceId: "src-1",
|
|
2072
|
+
input,
|
|
2073
|
+
expected,
|
|
2074
|
+
tolerance: {}
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
validateInvariantsOrThrow(invariants);
|
|
2078
|
+
const safeRef = isFileSource
|
|
2079
|
+
? scrubText(trimmedSource, secretValues).value
|
|
2080
|
+
: safeBaseUrl || "inline";
|
|
2081
|
+
const finalWarnings = warnings.map((w) => ({
|
|
2082
|
+
...w,
|
|
2083
|
+
message: scrubText(w.message, secretValues).value
|
|
2084
|
+
}));
|
|
2085
|
+
return {
|
|
2086
|
+
domain: "api",
|
|
2087
|
+
sources: [
|
|
2088
|
+
{
|
|
2089
|
+
id: "src-1",
|
|
2090
|
+
kind: "asyncapi",
|
|
2091
|
+
ref: safeRef,
|
|
2092
|
+
meta: {
|
|
2093
|
+
asyncapiVersion: spec.version,
|
|
2094
|
+
title: scrubText(spec.title, secretValues).value,
|
|
2095
|
+
...(safeBaseUrl ? { baseUrl: scrubText(safeBaseUrl, secretValues).value } : {}),
|
|
2096
|
+
channelCount: spec.channels.length,
|
|
2097
|
+
...(redactedSecrets ? { redactedSecrets: true } : {})
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
],
|
|
2101
|
+
artifacts: { root: ".vibecode/artifacts", files: {} },
|
|
2102
|
+
invariants,
|
|
2103
|
+
warnings: finalWarnings
|
|
2104
|
+
};
|
|
2105
|
+
}
|