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,2690 @@
|
|
|
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 { isSensitiveHeader, isSensitiveQueryParam, mergeHeaders, redactHeaders } from "./trace.js";
|
|
6
|
+
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
|
7
|
+
const MAX_CYCLIC_DEPTH = 12;
|
|
8
|
+
const MAX_SAMPLE_DEPTH = 10;
|
|
9
|
+
const MAX_PARSER_NESTING = 16;
|
|
10
|
+
const MAX_MESSAGES = 200;
|
|
11
|
+
const MAX_FIELDS_PER_MESSAGE = 200;
|
|
12
|
+
const MAX_ENUM_VALUES = 200;
|
|
13
|
+
const MAX_RPCS = 100;
|
|
14
|
+
const MAX_NODE_BUDGET = 4000;
|
|
15
|
+
const MAX_SANITIZE_DEPTH = 32;
|
|
16
|
+
const DRAFT_2020_12_SCHEMA = "https://json-schema.org/draft/2020-12/schema";
|
|
17
|
+
const VALID_HTTP_METHODS = new Set([
|
|
18
|
+
"GET",
|
|
19
|
+
"POST",
|
|
20
|
+
"PUT",
|
|
21
|
+
"PATCH",
|
|
22
|
+
"DELETE",
|
|
23
|
+
"HEAD",
|
|
24
|
+
"OPTIONS"
|
|
25
|
+
]);
|
|
26
|
+
const INT32_TYPES = new Set(["int32", "sint32", "sfixed32"]);
|
|
27
|
+
const UINT32_TYPES = new Set(["uint32", "fixed32"]);
|
|
28
|
+
const INT64_TYPES = new Set(["int64", "sint64", "sfixed64", "uint64", "fixed64"]);
|
|
29
|
+
const FLOAT_TYPES = new Set(["float", "double"]);
|
|
30
|
+
const SCALAR_TYPES = new Set([
|
|
31
|
+
"string",
|
|
32
|
+
"bytes",
|
|
33
|
+
"bool",
|
|
34
|
+
...INT32_TYPES,
|
|
35
|
+
...UINT32_TYPES,
|
|
36
|
+
...INT64_TYPES,
|
|
37
|
+
...FLOAT_TYPES
|
|
38
|
+
]);
|
|
39
|
+
const HEADER_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
40
|
+
const ANSI_ESCAPE_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
|
|
41
|
+
const BIDI_AND_BOM_RE = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g;
|
|
42
|
+
const CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f]/;
|
|
43
|
+
const CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f-\x9f]+/g;
|
|
44
|
+
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|passphrase|api[-_]?key|apikey|auth|jwt|cookie|csrf|xsrf|private[-_]?key|signing[-_]?key|credential)/i;
|
|
45
|
+
const SENSITIVE_FIELD_RE = /(?:secret|hmac|signature|signing[-_]?key|api[-_]?key|apikey|token|password|passwd|passphrase|private[-_]?key|client[-_]?secret|webhook[-_]?secret|vault[-_]?path|bearer|jwt|cookie|csrf|xsrf|session[-_]?id|authorization|proxy[-_]?authorization|credential)/i;
|
|
46
|
+
const SENSITIVE_QUERY_RE = /(?:hmac|webhook[-_]?secret|signing[-_]?key|secret|token|signature|sig|api[-_]?key|apikey|password|passwd|passphrase|auth|jwt|cookie|credential)/i;
|
|
47
|
+
const SENSITIVE_HEADER_VALUE_RE = /^\s*(?:Bearer|Basic|Token|Digest|ApiKey|HMAC|OAuth)\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|pk_live|gh[pousr])_[A-Za-z0-9_=-]{4,}|\bxox[baprs]-[A-Za-z0-9-]{8,}|\bAIza[0-9A-Za-z_-]{16,}|\bAKIA[0-9A-Z]{16}\b|\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/i;
|
|
48
|
+
const INLINE_DIGEST_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"(?:\\.|[^"\\\r\n])*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"(?:\\.|[^"\\\r\n])*"))*|[A-Za-z0-9._~+/:-]{6,}={0,2})/gi;
|
|
49
|
+
const INLINE_AUTH_VALUE_RE = /\b(Bearer|Basic|Token|Digest|ApiKey|HMAC|OAuth)\s+([^\s"'`<>,;]+)/gi;
|
|
50
|
+
const INLINE_COOKIE_HEADER_RE = /\b(Cookie|Set-Cookie)\s*:\s*([^\r\n"'`]+)/gi;
|
|
51
|
+
const INLINE_HEADER_SECRET_RE = /\b(Authorization|Proxy-Authorization|X-Api-Key|X-Auth-Token|X-Access-Token|X-Session-Token|X-Webhook-Secret|X-Hub-Signature(?:-256)?|X-Signature(?:-256|-sha256|-hmac)?|X-Webhook-Signature|X-Hmac(?:-Signature|-Sha256)?)\s*:\s*(?:(?:[A-Za-z][A-Za-z0-9._-]{1,31})\s+(?:\[REDACTED\]|[^\s,;|"'`]+)|[^\r\n"'`]+)/gi;
|
|
52
|
+
const INLINE_KV_SECRET_RE = /\b([A-Za-z0-9_.-]*(?:aws[_-]?secret[_-]?access[_-]?key|aws[_-]?access[_-]?key[_-]?id|aws[_-]?session[_-]?token|stripe[_-]?secret[_-]?key|api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|id[_-]?token|auth[_-]?token|client[_-]?secret|private[_-]?key|access[_-]?key|secret[_-]?key|signing[_-]?key|encryption[_-]?key|master[_-]?key|session[_-]?id|session[_-]?secret|jwt[_-]?secret|webhook[_-]?secret|password|passwd|passphrase|secret|token|jwt|hmac|signature|credentials?|authorization|cookie|csrf[_-]?token|xsrf[_-]?token)[A-Za-z0-9_.-]*)(["']?)\s*([:=])\s*(?:"((?:\\.|[^"\\\r\n])*)"|'((?:\\.|[^'\\\r\n])*)'|([^\s,;&"'`<>]+))/gi;
|
|
53
|
+
const INLINE_TOKEN_RE = /\b(?:whsec|sk_live|sk_test|pk_live|gh[pousr])_[A-Za-z0-9_=-]{4,}|\bxox[baprs]-[A-Za-z0-9-]{8,}|\bAIza[0-9A-Za-z_-]{16,}|\bAKIA[0-9A-Z]{16}\b|\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g;
|
|
54
|
+
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;
|
|
55
|
+
const VAULT_PATH_RE = /(?:file:\/\/)?(?:[A-Za-z]:)?(?:[\\/][^\\/\s"'`<>|]*)*[\\/]?\.vibecode-vault(?:[\\/][^\\/\s"'`<>|]*)*/gi;
|
|
56
|
+
const URL_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/|(?<=^|[\s"'`(\[{=,;|])\/\/)([^/?#\s"'`<>]+)@/g;
|
|
57
|
+
const INLINE_URL_RE = /(?:[a-zA-Z][a-zA-Z0-9+.-]*:\/\/|(?<=^|[\s"'`(\[{=,;|])\/\/)(?:[^\s"'`<>)\]{}]+|\{[^{}\s"'`<>]*\}|\[[0-9a-fA-F:.]+\])+/g;
|
|
58
|
+
const ENV_SECRET_ASSIGN_RE = /\b([A-Z0-9_]*(?:SECRET|HMAC|TOKEN|API_KEY|APIKEY|PASSWORD|PASSWD|PASSPHRASE|PRIVATE_KEY|SIGNING_KEY|WEBHOOK_KEY|COOKIE|CREDENTIAL)[A-Z0-9_]*)\s*=\s*([^\s"'`,;]+)/gi;
|
|
59
|
+
// Detection patterns for rejecting sibling formats cleanly
|
|
60
|
+
const YAML_HEADER_RE = /^\s*['"]?(?:openapi|swagger|asyncapi|_type)['"]?\s*:/m;
|
|
61
|
+
const CURL_START_RE = /^(?:\s*#[^\n]*\n)*\s*(?:\$\s*)?curl(?:\s+|$)/i;
|
|
62
|
+
const HTTP_FILE_START_RE = /^(?:\s*(?:#|\/\/)[^\n]*\n)*\s*(?:###|@[A-Za-z_][A-Za-z0-9_-]*\s*=|(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(?:https?:\/\/|\/|\{\{)\S+)/i;
|
|
63
|
+
const BRUNO_BLOCK_RE = /^\s*meta\s*\{[\s\S]*?\}\s*(?:get|post|put|patch|delete|head|options|http)\s*\{/i;
|
|
64
|
+
const GRAPHQL_HEADER_RE = /^\s*(?:type\s+(?:Query|Mutation|Subscription)\b|schema\s*\{|input\s+[A-Za-z_]\w*\s*\{|interface\s+[A-Za-z_]\w*\s*\{|scalar\s+[A-Za-z_]\w*|directive\s+@)/m;
|
|
65
|
+
const PROTO_SYNTAX_RE = /(?:^|[;\n])\s*syntax\s*=\s*["']proto[23]["']\s*;/;
|
|
66
|
+
const PROTO_SERVICE_RE = /\bservice\s+[A-Za-z_][A-Za-z0-9_]*\s*\{/;
|
|
67
|
+
const PROTO_RPC_RE = /\brpc\s+[A-Za-z_][A-Za-z0-9_]*\s*\(\s*(?:stream\s+)?\.?[A-Za-z_][A-Za-z0-9_.]*\s*\)\s*returns\s*\(\s*(?:stream\s+)?\.?[A-Za-z_][A-Za-z0-9_.]*\s*\)/;
|
|
68
|
+
function hasOwn(obj, key) {
|
|
69
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
70
|
+
}
|
|
71
|
+
function isObject(value) {
|
|
72
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
73
|
+
}
|
|
74
|
+
function isUnsafeKey(key) {
|
|
75
|
+
return key === "__proto__" || key === "constructor" || key === "prototype";
|
|
76
|
+
}
|
|
77
|
+
function stripBom(raw) {
|
|
78
|
+
return raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
|
|
79
|
+
}
|
|
80
|
+
function slugify(value, fallback = "rpc") {
|
|
81
|
+
const s = value
|
|
82
|
+
.toLowerCase()
|
|
83
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
84
|
+
.replace(/^-+|-+$/g, "")
|
|
85
|
+
.slice(0, 64);
|
|
86
|
+
return s || fallback;
|
|
87
|
+
}
|
|
88
|
+
function snakeToLowerCamel(name) {
|
|
89
|
+
let out = "";
|
|
90
|
+
let capNext = false;
|
|
91
|
+
for (let i = 0; i < name.length; i += 1) {
|
|
92
|
+
const ch = name[i];
|
|
93
|
+
if (ch === "_") {
|
|
94
|
+
capNext = true;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (capNext && ch >= "a" && ch <= "z") {
|
|
98
|
+
out += ch.toUpperCase();
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
out += ch;
|
|
102
|
+
}
|
|
103
|
+
capNext = false;
|
|
104
|
+
}
|
|
105
|
+
return out || name;
|
|
106
|
+
}
|
|
107
|
+
function pushWarning(ctx, message) {
|
|
108
|
+
const clean = message.replace(CONTROL_CHAR_GLOBAL_RE, " ").trim();
|
|
109
|
+
if (!clean || ctx.warningSet.has(clean))
|
|
110
|
+
return;
|
|
111
|
+
ctx.warningSet.add(clean);
|
|
112
|
+
ctx.warnings.push(clean);
|
|
113
|
+
}
|
|
114
|
+
function isProtoSensitiveHeader(name) {
|
|
115
|
+
const lower = name.trim().toLowerCase();
|
|
116
|
+
if (!lower)
|
|
117
|
+
return false;
|
|
118
|
+
return isSensitiveHeader(lower) || SENSITIVE_HEADER_RE.test(lower);
|
|
119
|
+
}
|
|
120
|
+
function isSensitiveFieldName(name) {
|
|
121
|
+
const trimmed = name.trim();
|
|
122
|
+
if (!trimmed)
|
|
123
|
+
return false;
|
|
124
|
+
return SENSITIVE_FIELD_RE.test(trimmed);
|
|
125
|
+
}
|
|
126
|
+
function isProtoSensitiveQueryParam(name) {
|
|
127
|
+
const trimmed = name.trim();
|
|
128
|
+
if (!trimmed)
|
|
129
|
+
return false;
|
|
130
|
+
return isSensitiveQueryParam(trimmed) || SENSITIVE_QUERY_RE.test(trimmed);
|
|
131
|
+
}
|
|
132
|
+
function sanitizeDecodedControlText(raw) {
|
|
133
|
+
return String(raw)
|
|
134
|
+
.replace(ANSI_ESCAPE_RE, "")
|
|
135
|
+
.replace(BIDI_AND_BOM_RE, "")
|
|
136
|
+
.replace(CONTROL_CHAR_GLOBAL_RE, "");
|
|
137
|
+
}
|
|
138
|
+
function recordSecretValue(secretValues, raw) {
|
|
139
|
+
if (typeof raw !== "string")
|
|
140
|
+
return;
|
|
141
|
+
const trimmed = raw.trim();
|
|
142
|
+
if (!trimmed || trimmed === "[REDACTED]" || trimmed === "[REDACTED_VAULT]" || trimmed === "[REDACTED_URL]") {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (trimmed.length >= 3) {
|
|
146
|
+
secretValues.add(trimmed);
|
|
147
|
+
}
|
|
148
|
+
const schemeMatch = /^(?:Bearer|Basic|Token|Digest|ApiKey|HMAC|OAuth|[A-Za-z][A-Za-z0-9._-]{1,31})\s+(.+)$/i.exec(trimmed);
|
|
149
|
+
if (schemeMatch && schemeMatch[1].trim().length >= 3) {
|
|
150
|
+
secretValues.add(schemeMatch[1].trim());
|
|
151
|
+
}
|
|
152
|
+
const sigMatch = /^(?:hmac-)?(?:sha512|sha256|sha1)=([0-9a-fA-F]{6,})$/i.exec(trimmed);
|
|
153
|
+
if (sigMatch && sigMatch[1]) {
|
|
154
|
+
secretValues.add(sigMatch[1]);
|
|
155
|
+
}
|
|
156
|
+
if (trimmed.includes("=")) {
|
|
157
|
+
for (const part of trimmed.split(/[;,]/)) {
|
|
158
|
+
const eqIdx = part.indexOf("=");
|
|
159
|
+
if (eqIdx > 0) {
|
|
160
|
+
const val = part.slice(eqIdx + 1).trim();
|
|
161
|
+
if (val.length >= 3 && val !== "[REDACTED]") {
|
|
162
|
+
secretValues.add(val);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function recordUserInfoSecrets(secretValues, rawUserinfo) {
|
|
169
|
+
let decoded = rawUserinfo;
|
|
170
|
+
try {
|
|
171
|
+
decoded = decodeURIComponent(rawUserinfo);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
decoded = rawUserinfo;
|
|
175
|
+
}
|
|
176
|
+
for (const candidate of new Set([rawUserinfo, decoded])) {
|
|
177
|
+
const colonIdx = candidate.indexOf(":");
|
|
178
|
+
if (colonIdx >= 0) {
|
|
179
|
+
const pass = candidate.slice(colonIdx + 1);
|
|
180
|
+
recordSecretValue(secretValues, pass);
|
|
181
|
+
const lastColon = candidate.lastIndexOf(":");
|
|
182
|
+
if (lastColon > colonIdx) {
|
|
183
|
+
recordSecretValue(secretValues, candidate.slice(lastColon + 1));
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
else if (candidate.length >= 5) {
|
|
187
|
+
recordSecretValue(secretValues, candidate);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function sanitizeUrlString(rawUrl, secretValues, options = {}) {
|
|
192
|
+
let redacted = false;
|
|
193
|
+
let cleaned = sanitizeDecodedControlText(rawUrl).trim();
|
|
194
|
+
if (!cleaned) {
|
|
195
|
+
return { safeUrl: "", origin: "", pathname: "", redacted: false, valid: false };
|
|
196
|
+
}
|
|
197
|
+
cleaned = cleaned.replace(URL_AUTH_RE, (_m, prefix, userinfo) => {
|
|
198
|
+
redacted = true;
|
|
199
|
+
recordUserInfoSecrets(secretValues, userinfo);
|
|
200
|
+
return prefix;
|
|
201
|
+
});
|
|
202
|
+
if (cleaned.includes("#")) {
|
|
203
|
+
const hashIdx = cleaned.indexOf("#");
|
|
204
|
+
const fragment = cleaned.slice(hashIdx + 1);
|
|
205
|
+
if (fragment.length > 0) {
|
|
206
|
+
redacted = true;
|
|
207
|
+
recordSecretValue(secretValues, fragment);
|
|
208
|
+
}
|
|
209
|
+
cleaned = cleaned.slice(0, hashIdx);
|
|
210
|
+
}
|
|
211
|
+
const hasVaultPath = /\.vibecode-vault/i.test(cleaned);
|
|
212
|
+
if (hasVaultPath) {
|
|
213
|
+
redacted = true;
|
|
214
|
+
cleaned = cleaned.replace(VAULT_PATH_RE, (vaultHit) => {
|
|
215
|
+
const afterVault = vaultHit.split(/\.vibecode-vault[\\/]?/i)[1] ?? "";
|
|
216
|
+
for (const seg of afterVault.split(/[\\/]+/)) {
|
|
217
|
+
if (seg.length >= 3)
|
|
218
|
+
recordSecretValue(secretValues, seg);
|
|
219
|
+
}
|
|
220
|
+
return "[REDACTED]";
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
const filterRawQueryString = (rawQuery) => {
|
|
224
|
+
const keptParts = [];
|
|
225
|
+
for (const part of rawQuery.split("&")) {
|
|
226
|
+
if (!part)
|
|
227
|
+
continue;
|
|
228
|
+
const eqIdx = part.indexOf("=");
|
|
229
|
+
const rawK = eqIdx >= 0 ? part.slice(0, eqIdx) : part;
|
|
230
|
+
const rawV = eqIdx >= 0 ? part.slice(eqIdx + 1) : "";
|
|
231
|
+
let k = rawK;
|
|
232
|
+
let v = rawV;
|
|
233
|
+
try {
|
|
234
|
+
k = decodeURIComponent(rawK.replace(/\+/g, " "));
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
k = rawK;
|
|
238
|
+
}
|
|
239
|
+
try {
|
|
240
|
+
v = decodeURIComponent(rawV.replace(/\+/g, " "));
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
v = rawV;
|
|
244
|
+
}
|
|
245
|
+
if (isUnsafeKey(k))
|
|
246
|
+
continue;
|
|
247
|
+
const cleanK = k.trim();
|
|
248
|
+
const scrubbedK = scrubText(cleanK, secretValues);
|
|
249
|
+
const scrubbedV = scrubText(v, secretValues);
|
|
250
|
+
if (isProtoSensitiveQueryParam(cleanK) ||
|
|
251
|
+
SENSITIVE_HEADER_VALUE_RE.test(v) ||
|
|
252
|
+
scrubbedK.redacted ||
|
|
253
|
+
scrubbedV.redacted ||
|
|
254
|
+
scrubbedK.value !== cleanK ||
|
|
255
|
+
scrubbedV.value !== v) {
|
|
256
|
+
redacted = true;
|
|
257
|
+
recordSecretValue(secretValues, v);
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
keptParts.push(part);
|
|
261
|
+
}
|
|
262
|
+
return keptParts.join("&");
|
|
263
|
+
};
|
|
264
|
+
const isProtoRelative = cleaned.startsWith("//");
|
|
265
|
+
try {
|
|
266
|
+
const normalized = isProtoRelative
|
|
267
|
+
? `https:${cleaned}`
|
|
268
|
+
: /^[a-z][a-z0-9+.-]*:\/\//i.test(cleaned)
|
|
269
|
+
? cleaned
|
|
270
|
+
: `https://${cleaned}`;
|
|
271
|
+
const parsed = new URL(normalized);
|
|
272
|
+
if (options.requireHttp !== false && parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
273
|
+
return { safeUrl: "", origin: "", pathname: "", redacted, valid: false };
|
|
274
|
+
}
|
|
275
|
+
if (parsed.username || parsed.password) {
|
|
276
|
+
redacted = true;
|
|
277
|
+
if (parsed.password) {
|
|
278
|
+
recordSecretValue(secretValues, parsed.password);
|
|
279
|
+
}
|
|
280
|
+
else if (parsed.username) {
|
|
281
|
+
recordSecretValue(secretValues, parsed.username);
|
|
282
|
+
}
|
|
283
|
+
parsed.username = "";
|
|
284
|
+
parsed.password = "";
|
|
285
|
+
}
|
|
286
|
+
if (parsed.hash) {
|
|
287
|
+
redacted = true;
|
|
288
|
+
recordSecretValue(secretValues, parsed.hash.slice(1));
|
|
289
|
+
parsed.hash = "";
|
|
290
|
+
}
|
|
291
|
+
const safeParams = new URLSearchParams();
|
|
292
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
293
|
+
if (isUnsafeKey(k))
|
|
294
|
+
continue;
|
|
295
|
+
const scrubbedK = scrubText(k, secretValues);
|
|
296
|
+
const scrubbedV = scrubText(v, secretValues);
|
|
297
|
+
if (isProtoSensitiveQueryParam(k) ||
|
|
298
|
+
SENSITIVE_HEADER_VALUE_RE.test(v) ||
|
|
299
|
+
scrubbedK.redacted ||
|
|
300
|
+
scrubbedV.redacted ||
|
|
301
|
+
scrubbedK.value !== k ||
|
|
302
|
+
scrubbedV.value !== v) {
|
|
303
|
+
redacted = true;
|
|
304
|
+
recordSecretValue(secretValues, v);
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
safeParams.append(k, v);
|
|
308
|
+
}
|
|
309
|
+
if (hasVaultPath && options.requireHttp !== false) {
|
|
310
|
+
return { safeUrl: "", origin: "", pathname: "", redacted: true, valid: false };
|
|
311
|
+
}
|
|
312
|
+
const queryStr = safeParams.toString();
|
|
313
|
+
const basePath = parsed.pathname.replace(/\/+$/, "");
|
|
314
|
+
const protoOrigin = isProtoRelative
|
|
315
|
+
? `//${parsed.host}`
|
|
316
|
+
: parsed.host
|
|
317
|
+
? `${parsed.protocol}//${parsed.host}`
|
|
318
|
+
: parsed.origin !== "null"
|
|
319
|
+
? parsed.origin
|
|
320
|
+
: "";
|
|
321
|
+
const safeUrl = `${protoOrigin}${basePath}${queryStr ? `?${queryStr}` : ""}`;
|
|
322
|
+
return {
|
|
323
|
+
safeUrl,
|
|
324
|
+
origin: protoOrigin,
|
|
325
|
+
pathname: parsed.pathname || "/",
|
|
326
|
+
redacted,
|
|
327
|
+
valid: true
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
const qIdx = cleaned.indexOf("?");
|
|
332
|
+
const basePart = qIdx >= 0 ? cleaned.slice(0, qIdx) : cleaned;
|
|
333
|
+
const rawQuery = qIdx >= 0 ? cleaned.slice(qIdx + 1) : "";
|
|
334
|
+
const filteredQuery = rawQuery ? filterRawQueryString(rawQuery) : "";
|
|
335
|
+
if (!options.allowMalformed) {
|
|
336
|
+
return { safeUrl: "", origin: "", pathname: "", redacted, valid: false };
|
|
337
|
+
}
|
|
338
|
+
const fallbackUrl = filteredQuery ? `${basePart}?${filteredQuery}` : basePart;
|
|
339
|
+
const strippedAuthority = basePart.replace(/^(?:[a-z][a-z0-9+.-]*:)?\/\/[^/]*/i, "");
|
|
340
|
+
const fallbackPathname = strippedAuthority || "/";
|
|
341
|
+
return {
|
|
342
|
+
safeUrl: fallbackUrl,
|
|
343
|
+
origin: "",
|
|
344
|
+
pathname: fallbackPathname,
|
|
345
|
+
redacted,
|
|
346
|
+
valid: true
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function scrubText(text, secretValues) {
|
|
351
|
+
let redacted = false;
|
|
352
|
+
let out = text.replace(VAULT_PATH_RE, (match) => {
|
|
353
|
+
redacted = true;
|
|
354
|
+
const afterVault = match.split(/\.vibecode-vault[\\/]?/i)[1] ?? "";
|
|
355
|
+
for (const seg of afterVault.split(/[\\/]+/)) {
|
|
356
|
+
if (seg.length >= 3)
|
|
357
|
+
recordSecretValue(secretValues, seg);
|
|
358
|
+
}
|
|
359
|
+
return "[REDACTED]";
|
|
360
|
+
});
|
|
361
|
+
out = out.replace(INLINE_URL_RE, (rawMatch) => {
|
|
362
|
+
const res = sanitizeUrlString(rawMatch, secretValues, { requireHttp: false, allowMalformed: true });
|
|
363
|
+
if (res.redacted)
|
|
364
|
+
redacted = true;
|
|
365
|
+
return res.valid && res.redacted ? res.safeUrl : rawMatch;
|
|
366
|
+
});
|
|
367
|
+
out = out.replace(URL_AUTH_RE, (_m, prefix, userinfo) => {
|
|
368
|
+
redacted = true;
|
|
369
|
+
recordUserInfoSecrets(secretValues, userinfo);
|
|
370
|
+
return `${prefix}[REDACTED]@`;
|
|
371
|
+
});
|
|
372
|
+
out = out.replace(INLINE_DIGEST_RE, (match) => {
|
|
373
|
+
redacted = true;
|
|
374
|
+
const rest = match.replace(/^Digest\s+/i, "");
|
|
375
|
+
recordSecretValue(secretValues, rest);
|
|
376
|
+
for (const kvMatch of rest.matchAll(/([A-Za-z0-9_-]+)=("([^"]*)"|'([^']*)'|([^\s,]+))/g)) {
|
|
377
|
+
const kvVal = kvMatch[3] ?? kvMatch[4] ?? kvMatch[5] ?? "";
|
|
378
|
+
if (kvVal.length >= 4)
|
|
379
|
+
recordSecretValue(secretValues, kvVal);
|
|
380
|
+
}
|
|
381
|
+
return "Digest [REDACTED]";
|
|
382
|
+
});
|
|
383
|
+
out = out.replace(INLINE_COOKIE_HEADER_RE, (match, hdrName, val) => {
|
|
384
|
+
const trimmed = val.trim();
|
|
385
|
+
if (!trimmed || trimmed === "[REDACTED]")
|
|
386
|
+
return match;
|
|
387
|
+
redacted = true;
|
|
388
|
+
recordSecretValue(secretValues, trimmed);
|
|
389
|
+
return `${hdrName}: [REDACTED]`;
|
|
390
|
+
});
|
|
391
|
+
out = out.replace(INLINE_HEADER_SECRET_RE, (match, hdrName, val) => {
|
|
392
|
+
const rawRest = match.slice(match.indexOf(":") + 1).trim();
|
|
393
|
+
if (!rawRest || rawRest === "[REDACTED]")
|
|
394
|
+
return match;
|
|
395
|
+
redacted = true;
|
|
396
|
+
recordSecretValue(secretValues, val ?? rawRest);
|
|
397
|
+
recordSecretValue(secretValues, rawRest);
|
|
398
|
+
return `${hdrName}: [REDACTED]`;
|
|
399
|
+
});
|
|
400
|
+
out = out.replace(INLINE_AUTH_VALUE_RE, (match, scheme, val) => {
|
|
401
|
+
if (val === "[REDACTED]")
|
|
402
|
+
return match;
|
|
403
|
+
redacted = true;
|
|
404
|
+
recordSecretValue(secretValues, val);
|
|
405
|
+
return `${scheme} [REDACTED]`;
|
|
406
|
+
});
|
|
407
|
+
out = out.replace(INLINE_TOKEN_RE, (match) => {
|
|
408
|
+
redacted = true;
|
|
409
|
+
recordSecretValue(secretValues, match);
|
|
410
|
+
return "[REDACTED]";
|
|
411
|
+
});
|
|
412
|
+
out = out.replace(INLINE_HMAC_SIG_RE, (match) => {
|
|
413
|
+
redacted = true;
|
|
414
|
+
recordSecretValue(secretValues, match);
|
|
415
|
+
return "[REDACTED]";
|
|
416
|
+
});
|
|
417
|
+
out = out.replace(INLINE_KV_SECRET_RE, (full, key, q, sep, dq, sq, bare) => {
|
|
418
|
+
const val = dq ?? sq ?? bare ?? "";
|
|
419
|
+
if (!val || val === "[REDACTED]" || val === "[REDACTED_VAULT]")
|
|
420
|
+
return full;
|
|
421
|
+
redacted = true;
|
|
422
|
+
recordSecretValue(secretValues, val);
|
|
423
|
+
const unescapedVal = val.replace(/\\"/g, '"').replace(/\\'/g, "'");
|
|
424
|
+
if (unescapedVal !== val)
|
|
425
|
+
recordSecretValue(secretValues, unescapedVal);
|
|
426
|
+
if (dq !== undefined)
|
|
427
|
+
return `${key}${q}${sep}"[REDACTED]"`;
|
|
428
|
+
if (sq !== undefined)
|
|
429
|
+
return `${key}${q}${sep}'[REDACTED]'`;
|
|
430
|
+
return `${key}${q}${sep}[REDACTED]`;
|
|
431
|
+
});
|
|
432
|
+
out = out.replace(ENV_SECRET_ASSIGN_RE, (match, envName, envVal) => {
|
|
433
|
+
if (envVal === "[REDACTED]")
|
|
434
|
+
return match;
|
|
435
|
+
redacted = true;
|
|
436
|
+
recordSecretValue(secretValues, envVal);
|
|
437
|
+
return `${envName}=[REDACTED]`;
|
|
438
|
+
});
|
|
439
|
+
const sorted = [...secretValues]
|
|
440
|
+
.filter((s) => s.length >= 3 && s !== "[REDACTED]")
|
|
441
|
+
.sort((a, b) => b.length - a.length);
|
|
442
|
+
for (const secret of sorted) {
|
|
443
|
+
if (out.includes(secret)) {
|
|
444
|
+
out = out.replaceAll(secret, "[REDACTED]");
|
|
445
|
+
redacted = true;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return { value: out, redacted };
|
|
449
|
+
}
|
|
450
|
+
function scrubSchemaDeep(value, secretValues, depth = 0) {
|
|
451
|
+
if (depth >= MAX_SANITIZE_DEPTH)
|
|
452
|
+
return { value: null, redacted: false };
|
|
453
|
+
if (typeof value === "string") {
|
|
454
|
+
return scrubText(value, secretValues);
|
|
455
|
+
}
|
|
456
|
+
if (value === null || typeof value !== "object") {
|
|
457
|
+
return { value, redacted: false };
|
|
458
|
+
}
|
|
459
|
+
if (Array.isArray(value)) {
|
|
460
|
+
let redacted = false;
|
|
461
|
+
const arr = value.map((item) => {
|
|
462
|
+
const res = scrubSchemaDeep(item, secretValues, depth + 1);
|
|
463
|
+
if (res.redacted)
|
|
464
|
+
redacted = true;
|
|
465
|
+
return res.value;
|
|
466
|
+
});
|
|
467
|
+
return { value: arr, redacted };
|
|
468
|
+
}
|
|
469
|
+
const src = value;
|
|
470
|
+
const out = {};
|
|
471
|
+
let redacted = false;
|
|
472
|
+
for (const key of Object.keys(src)) {
|
|
473
|
+
if (isUnsafeKey(key))
|
|
474
|
+
continue;
|
|
475
|
+
const child = src[key];
|
|
476
|
+
// Preserve JSON Schema structural keywords without recording or redacting type/format strings.
|
|
477
|
+
if (key === "type" ||
|
|
478
|
+
key === "format" ||
|
|
479
|
+
key === "$schema" ||
|
|
480
|
+
key === "required" ||
|
|
481
|
+
(key === "additionalProperties" && typeof child === "boolean")) {
|
|
482
|
+
out[key] = child;
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
const res = scrubSchemaDeep(child, secretValues, depth + 1);
|
|
486
|
+
if (res.redacted)
|
|
487
|
+
redacted = true;
|
|
488
|
+
out[key] = res.value;
|
|
489
|
+
}
|
|
490
|
+
return { value: out, redacted };
|
|
491
|
+
}
|
|
492
|
+
function scrubValueDeep(value, secretValues, depth = 0, isSensitiveParent = false) {
|
|
493
|
+
if (depth >= MAX_SANITIZE_DEPTH)
|
|
494
|
+
return { value: null, redacted: false };
|
|
495
|
+
if (typeof value === "string") {
|
|
496
|
+
if (isSensitiveParent) {
|
|
497
|
+
if (value && value !== "[REDACTED]") {
|
|
498
|
+
recordSecretValue(secretValues, value);
|
|
499
|
+
return { value: "[REDACTED]", redacted: true };
|
|
500
|
+
}
|
|
501
|
+
return { value: "[REDACTED]", redacted: false };
|
|
502
|
+
}
|
|
503
|
+
return scrubText(value, secretValues);
|
|
504
|
+
}
|
|
505
|
+
if (value === null || typeof value !== "object") {
|
|
506
|
+
return { value, redacted: false };
|
|
507
|
+
}
|
|
508
|
+
if (Array.isArray(value)) {
|
|
509
|
+
let redacted = false;
|
|
510
|
+
const arr = value.map((item) => {
|
|
511
|
+
const res = scrubValueDeep(item, secretValues, depth + 1, isSensitiveParent);
|
|
512
|
+
if (res.redacted)
|
|
513
|
+
redacted = true;
|
|
514
|
+
return res.value;
|
|
515
|
+
});
|
|
516
|
+
return { value: arr, redacted };
|
|
517
|
+
}
|
|
518
|
+
const src = value;
|
|
519
|
+
const out = {};
|
|
520
|
+
let redacted = false;
|
|
521
|
+
for (const key of Object.keys(src)) {
|
|
522
|
+
if (isUnsafeKey(key))
|
|
523
|
+
continue;
|
|
524
|
+
const childSensitive = isSensitiveParent || isSensitiveFieldName(key);
|
|
525
|
+
const res = scrubValueDeep(src[key], secretValues, depth + 1, childSensitive);
|
|
526
|
+
if (res.redacted)
|
|
527
|
+
redacted = true;
|
|
528
|
+
out[key] = res.value;
|
|
529
|
+
}
|
|
530
|
+
return { value: out, redacted };
|
|
531
|
+
}
|
|
532
|
+
function sanitizeHeaderEntry(rawName, rawValue, secretValues, warnings) {
|
|
533
|
+
let redacted = false;
|
|
534
|
+
const nameHasControl = CONTROL_CHAR_RE.test(rawName);
|
|
535
|
+
const valHasControl = CONTROL_CHAR_RE.test(rawValue);
|
|
536
|
+
const scanSmuggledLines = (text) => {
|
|
537
|
+
const lines = text.split(/[\r\n]+/);
|
|
538
|
+
for (let i = 1; i < lines.length; i += 1) {
|
|
539
|
+
const smuggledLine = lines[i]?.trim();
|
|
540
|
+
if (!smuggledLine)
|
|
541
|
+
continue;
|
|
542
|
+
const colonIdx = smuggledLine.indexOf(":");
|
|
543
|
+
if (colonIdx > 0) {
|
|
544
|
+
const smuggledName = smuggledLine.slice(0, colonIdx).trim();
|
|
545
|
+
const smuggledVal = smuggledLine.slice(colonIdx + 1).trim();
|
|
546
|
+
if (isProtoSensitiveHeader(smuggledName) || SENSITIVE_HEADER_VALUE_RE.test(smuggledVal)) {
|
|
547
|
+
redacted = true;
|
|
548
|
+
recordSecretValue(secretValues, smuggledVal);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
const scrubbedLine = scrubText(smuggledLine, secretValues);
|
|
552
|
+
if (scrubbedLine.redacted)
|
|
553
|
+
redacted = true;
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
if (nameHasControl) {
|
|
557
|
+
scanSmuggledLines(rawName);
|
|
558
|
+
const scrubbedName = scrubText(rawName, secretValues);
|
|
559
|
+
if (scrubbedName.redacted)
|
|
560
|
+
redacted = true;
|
|
561
|
+
if (rawValue) {
|
|
562
|
+
const scrubbedVal = scrubText(rawValue, secretValues);
|
|
563
|
+
if (scrubbedVal.redacted)
|
|
564
|
+
redacted = true;
|
|
565
|
+
}
|
|
566
|
+
warnings.push("Dropped header with invalid or control characters to prevent header injection.");
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
const cleanName = rawName.trim();
|
|
570
|
+
if (!cleanName || isUnsafeKey(cleanName) || !HEADER_TOKEN_RE.test(cleanName)) {
|
|
571
|
+
if (rawValue) {
|
|
572
|
+
const checkVal = scrubText(rawValue, secretValues);
|
|
573
|
+
if (checkVal.redacted)
|
|
574
|
+
redacted = true;
|
|
575
|
+
}
|
|
576
|
+
return null;
|
|
577
|
+
}
|
|
578
|
+
const rawValueNoCtrl = rawValue.replace(CONTROL_CHAR_GLOBAL_RE, "").trim();
|
|
579
|
+
if (valHasControl) {
|
|
580
|
+
warnings.push(`Stripped control/CRLF characters from header "${cleanName}".`);
|
|
581
|
+
}
|
|
582
|
+
if (isProtoSensitiveHeader(cleanName) || SENSITIVE_HEADER_VALUE_RE.test(rawValueNoCtrl)) {
|
|
583
|
+
recordSecretValue(secretValues, rawValueNoCtrl);
|
|
584
|
+
if (valHasControl)
|
|
585
|
+
scanSmuggledLines(rawValue);
|
|
586
|
+
return null;
|
|
587
|
+
}
|
|
588
|
+
if (rawValue.includes("\r") || rawValue.includes("\n")) {
|
|
589
|
+
scanSmuggledLines(rawValue);
|
|
590
|
+
const firstLine = (rawValue.split(/[\r\n]+/)[0] ?? "").replace(CONTROL_CHAR_GLOBAL_RE, "").trim();
|
|
591
|
+
const scrubbed = scrubText(firstLine, secretValues);
|
|
592
|
+
if (scrubbed.redacted)
|
|
593
|
+
redacted = true;
|
|
594
|
+
return { name: cleanName, value: scrubbed.value, redacted };
|
|
595
|
+
}
|
|
596
|
+
const scrubbed = scrubText(rawValueNoCtrl, secretValues);
|
|
597
|
+
if (scrubbed.redacted)
|
|
598
|
+
redacted = true;
|
|
599
|
+
return { name: cleanName, value: scrubbed.value, redacted };
|
|
600
|
+
}
|
|
601
|
+
function hasHeaderCaseInsensitive(headers, name) {
|
|
602
|
+
const lower = name.toLowerCase();
|
|
603
|
+
return Object.keys(headers).some((k) => k.toLowerCase() === lower);
|
|
604
|
+
}
|
|
605
|
+
function setHeaderCaseInsensitive(headers, name, value) {
|
|
606
|
+
const lower = name.toLowerCase();
|
|
607
|
+
for (const k of Object.keys(headers)) {
|
|
608
|
+
if (k.toLowerCase() === lower && k !== name) {
|
|
609
|
+
delete headers[k];
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
headers[name] = value;
|
|
613
|
+
}
|
|
614
|
+
function deleteHeaderCaseInsensitive(headers, name) {
|
|
615
|
+
const lower = name.toLowerCase();
|
|
616
|
+
for (const k of Object.keys(headers)) {
|
|
617
|
+
if (k.toLowerCase() === lower) {
|
|
618
|
+
delete headers[k];
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
function stripProtoCommentsForDetection(text) {
|
|
623
|
+
const len = text.length;
|
|
624
|
+
let out = "";
|
|
625
|
+
let i = 0;
|
|
626
|
+
while (i < len) {
|
|
627
|
+
const ch = text[i];
|
|
628
|
+
if (ch === '"' || ch === "'") {
|
|
629
|
+
const quote = ch;
|
|
630
|
+
out += ch;
|
|
631
|
+
i += 1;
|
|
632
|
+
while (i < len) {
|
|
633
|
+
const c = text[i];
|
|
634
|
+
out += c;
|
|
635
|
+
i += 1;
|
|
636
|
+
if (c === "\\" && i < len) {
|
|
637
|
+
out += text[i];
|
|
638
|
+
i += 1;
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
if (c === quote)
|
|
642
|
+
break;
|
|
643
|
+
}
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
if (ch === "/" && text[i + 1] === "/") {
|
|
647
|
+
i += 2;
|
|
648
|
+
while (i < len && text[i] !== "\n" && text[i] !== "\r")
|
|
649
|
+
i += 1;
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
if (ch === "/" && text[i + 1] === "*") {
|
|
653
|
+
i += 2;
|
|
654
|
+
while (i < len && !(text[i] === "*" && text[i + 1] === "/"))
|
|
655
|
+
i += 1;
|
|
656
|
+
if (i < len)
|
|
657
|
+
i += 2;
|
|
658
|
+
out += " ";
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
out += ch;
|
|
662
|
+
i += 1;
|
|
663
|
+
}
|
|
664
|
+
return out;
|
|
665
|
+
}
|
|
666
|
+
export function isProtoSchemaText(rawText) {
|
|
667
|
+
if (typeof rawText !== "string")
|
|
668
|
+
return false;
|
|
669
|
+
if (rawText.includes("\0"))
|
|
670
|
+
return false;
|
|
671
|
+
if (Buffer.byteLength(rawText, "utf8") > MAX_SOURCE_BYTES)
|
|
672
|
+
return false;
|
|
673
|
+
const cleaned = stripBom(rawText).trim();
|
|
674
|
+
if (!cleaned)
|
|
675
|
+
return false;
|
|
676
|
+
// Immediately reject JSON, HTML/XML, cURL, .http, Bruno, OpenAPI/AsyncAPI/Insomnia YAML, GraphQL
|
|
677
|
+
const firstChar = cleaned[0];
|
|
678
|
+
if (firstChar === "{" || firstChar === "[" || firstChar === "<")
|
|
679
|
+
return false;
|
|
680
|
+
if (CURL_START_RE.test(cleaned))
|
|
681
|
+
return false;
|
|
682
|
+
if (HTTP_FILE_START_RE.test(cleaned))
|
|
683
|
+
return false;
|
|
684
|
+
if (YAML_HEADER_RE.test(cleaned))
|
|
685
|
+
return false;
|
|
686
|
+
if (BRUNO_BLOCK_RE.test(cleaned))
|
|
687
|
+
return false;
|
|
688
|
+
const stripped = stripProtoCommentsForDetection(cleaned).trim();
|
|
689
|
+
if (!stripped)
|
|
690
|
+
return false;
|
|
691
|
+
if (GRAPHQL_HEADER_RE.test(stripped))
|
|
692
|
+
return false;
|
|
693
|
+
if (PROTO_SYNTAX_RE.test(stripped)) {
|
|
694
|
+
return true;
|
|
695
|
+
}
|
|
696
|
+
if (PROTO_SERVICE_RE.test(stripped) && PROTO_RPC_RE.test(stripped)) {
|
|
697
|
+
return true;
|
|
698
|
+
}
|
|
699
|
+
return false;
|
|
700
|
+
}
|
|
701
|
+
function isIdentStart(code) {
|
|
702
|
+
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95;
|
|
703
|
+
}
|
|
704
|
+
function isIdentContinue(code) {
|
|
705
|
+
return isIdentStart(code) || (code >= 48 && code <= 57);
|
|
706
|
+
}
|
|
707
|
+
function isDigit(code) {
|
|
708
|
+
return code >= 48 && code <= 57;
|
|
709
|
+
}
|
|
710
|
+
function isHexDigit(code) {
|
|
711
|
+
return ((code >= 48 && code <= 57) ||
|
|
712
|
+
(code >= 65 && code <= 70) ||
|
|
713
|
+
(code >= 97 && code <= 102));
|
|
714
|
+
}
|
|
715
|
+
function tokenizeProto(rawText, ctx) {
|
|
716
|
+
const text = stripBom(rawText);
|
|
717
|
+
const tokens = [];
|
|
718
|
+
const len = text.length;
|
|
719
|
+
let i = 0;
|
|
720
|
+
let line = 1;
|
|
721
|
+
let col = 1;
|
|
722
|
+
const advanceLine = () => {
|
|
723
|
+
line += 1;
|
|
724
|
+
col = 1;
|
|
725
|
+
};
|
|
726
|
+
while (i < len) {
|
|
727
|
+
const ch = text[i];
|
|
728
|
+
const code = text.charCodeAt(i);
|
|
729
|
+
if (ch === " " || ch === "\t" || ch === "\f" || ch === "\v") {
|
|
730
|
+
i += 1;
|
|
731
|
+
col += 1;
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
if (ch === "\n") {
|
|
735
|
+
i += 1;
|
|
736
|
+
advanceLine();
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
if (ch === "\r") {
|
|
740
|
+
i += text[i + 1] === "\n" ? 2 : 1;
|
|
741
|
+
advanceLine();
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
744
|
+
// Line comment `// ...`
|
|
745
|
+
if (ch === "/" && text[i + 1] === "/") {
|
|
746
|
+
const commentStart = i + 2;
|
|
747
|
+
i += 2;
|
|
748
|
+
col += 2;
|
|
749
|
+
while (i < len && text[i] !== "\n" && text[i] !== "\r") {
|
|
750
|
+
i += 1;
|
|
751
|
+
col += 1;
|
|
752
|
+
}
|
|
753
|
+
const commentText = text.slice(commentStart, i);
|
|
754
|
+
const scanned = scrubText(commentText, ctx.secretValues);
|
|
755
|
+
if (scanned.redacted)
|
|
756
|
+
ctx.redactedSecrets = true;
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
// Block comment `/* ... */`
|
|
760
|
+
if (ch === "/" && text[i + 1] === "*") {
|
|
761
|
+
const startLine = line;
|
|
762
|
+
const startCol = col;
|
|
763
|
+
const commentStart = i + 2;
|
|
764
|
+
i += 2;
|
|
765
|
+
col += 2;
|
|
766
|
+
let closed = false;
|
|
767
|
+
while (i < len) {
|
|
768
|
+
if (text[i] === "*" && text[i + 1] === "/") {
|
|
769
|
+
const commentText = text.slice(commentStart, i);
|
|
770
|
+
const scanned = scrubText(commentText, ctx.secretValues);
|
|
771
|
+
if (scanned.redacted)
|
|
772
|
+
ctx.redactedSecrets = true;
|
|
773
|
+
i += 2;
|
|
774
|
+
col += 2;
|
|
775
|
+
closed = true;
|
|
776
|
+
break;
|
|
777
|
+
}
|
|
778
|
+
if (text[i] === "\n") {
|
|
779
|
+
i += 1;
|
|
780
|
+
advanceLine();
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
if (text[i] === "\r") {
|
|
784
|
+
i += text[i + 1] === "\n" ? 2 : 1;
|
|
785
|
+
advanceLine();
|
|
786
|
+
continue;
|
|
787
|
+
}
|
|
788
|
+
i += 1;
|
|
789
|
+
col += 1;
|
|
790
|
+
}
|
|
791
|
+
if (!closed) {
|
|
792
|
+
throw new VibecodeError("CONTRACT_INVALID", `Unterminated protobuf block comment at line ${startLine}, column ${startCol}.`, { fallbackHint: "Close every /* block comment with */." });
|
|
793
|
+
}
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
const startLine = line;
|
|
797
|
+
const startCol = col;
|
|
798
|
+
// Punctuation
|
|
799
|
+
if (ch === "{" ||
|
|
800
|
+
ch === "}" ||
|
|
801
|
+
ch === "(" ||
|
|
802
|
+
ch === ")" ||
|
|
803
|
+
ch === "[" ||
|
|
804
|
+
ch === "]" ||
|
|
805
|
+
ch === "<" ||
|
|
806
|
+
ch === ">" ||
|
|
807
|
+
ch === ";" ||
|
|
808
|
+
ch === "," ||
|
|
809
|
+
ch === "=" ||
|
|
810
|
+
ch === ":" ||
|
|
811
|
+
ch === "." ||
|
|
812
|
+
ch === "+") {
|
|
813
|
+
tokens.push({ kind: "PUNCT", value: ch, line: startLine, col: startCol });
|
|
814
|
+
i += 1;
|
|
815
|
+
col += 1;
|
|
816
|
+
continue;
|
|
817
|
+
}
|
|
818
|
+
// String literal (`"..."` or `'...'`)
|
|
819
|
+
if (ch === '"' || ch === "'") {
|
|
820
|
+
const quote = ch;
|
|
821
|
+
i += 1;
|
|
822
|
+
col += 1;
|
|
823
|
+
let val = "";
|
|
824
|
+
let closed = false;
|
|
825
|
+
while (i < len) {
|
|
826
|
+
const c = text[i];
|
|
827
|
+
if (c === "\n" || c === "\r") {
|
|
828
|
+
throw new VibecodeError("CONTRACT_INVALID", `Unterminated protobuf string literal at line ${startLine}, column ${startCol}.`, { fallbackHint: "Close string literals on the same line." });
|
|
829
|
+
}
|
|
830
|
+
if (c === quote) {
|
|
831
|
+
i += 1;
|
|
832
|
+
col += 1;
|
|
833
|
+
closed = true;
|
|
834
|
+
break;
|
|
835
|
+
}
|
|
836
|
+
if (c === "\\") {
|
|
837
|
+
i += 1;
|
|
838
|
+
col += 1;
|
|
839
|
+
if (i >= len) {
|
|
840
|
+
throw new VibecodeError("CONTRACT_INVALID", `Unterminated escape in protobuf string at line ${startLine}, column ${startCol}.`, { fallbackHint: "Complete the escape sequence before the end of input." });
|
|
841
|
+
}
|
|
842
|
+
const esc = text[i];
|
|
843
|
+
if (esc === "n") {
|
|
844
|
+
val += "\n";
|
|
845
|
+
i += 1;
|
|
846
|
+
col += 1;
|
|
847
|
+
}
|
|
848
|
+
else if (esc === "r") {
|
|
849
|
+
val += "\r";
|
|
850
|
+
i += 1;
|
|
851
|
+
col += 1;
|
|
852
|
+
}
|
|
853
|
+
else if (esc === "t") {
|
|
854
|
+
val += "\t";
|
|
855
|
+
i += 1;
|
|
856
|
+
col += 1;
|
|
857
|
+
}
|
|
858
|
+
else if (esc === "\\") {
|
|
859
|
+
val += "\\";
|
|
860
|
+
i += 1;
|
|
861
|
+
col += 1;
|
|
862
|
+
}
|
|
863
|
+
else if (esc === '"') {
|
|
864
|
+
val += '"';
|
|
865
|
+
i += 1;
|
|
866
|
+
col += 1;
|
|
867
|
+
}
|
|
868
|
+
else if (esc === "'") {
|
|
869
|
+
val += "'";
|
|
870
|
+
i += 1;
|
|
871
|
+
col += 1;
|
|
872
|
+
}
|
|
873
|
+
else if (esc === "b") {
|
|
874
|
+
val += "\b";
|
|
875
|
+
i += 1;
|
|
876
|
+
col += 1;
|
|
877
|
+
}
|
|
878
|
+
else if (esc === "f") {
|
|
879
|
+
val += "\f";
|
|
880
|
+
i += 1;
|
|
881
|
+
col += 1;
|
|
882
|
+
}
|
|
883
|
+
else if (esc === "x" || esc === "X") {
|
|
884
|
+
const hex = text.slice(i + 1, i + 3);
|
|
885
|
+
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
|
886
|
+
val += String.fromCharCode(parseInt(hex, 16));
|
|
887
|
+
i += 3;
|
|
888
|
+
col += 3;
|
|
889
|
+
}
|
|
890
|
+
else {
|
|
891
|
+
val += esc;
|
|
892
|
+
i += 1;
|
|
893
|
+
col += 1;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
else if (esc === "u") {
|
|
897
|
+
const hex = text.slice(i + 1, i + 5);
|
|
898
|
+
if (/^[0-9a-fA-F]{4}$/.test(hex)) {
|
|
899
|
+
val += String.fromCharCode(parseInt(hex, 16));
|
|
900
|
+
i += 5;
|
|
901
|
+
col += 5;
|
|
902
|
+
}
|
|
903
|
+
else {
|
|
904
|
+
val += esc;
|
|
905
|
+
i += 1;
|
|
906
|
+
col += 1;
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
else {
|
|
910
|
+
val += esc;
|
|
911
|
+
i += 1;
|
|
912
|
+
col += 1;
|
|
913
|
+
}
|
|
914
|
+
continue;
|
|
915
|
+
}
|
|
916
|
+
val += c;
|
|
917
|
+
i += 1;
|
|
918
|
+
col += 1;
|
|
919
|
+
}
|
|
920
|
+
if (!closed) {
|
|
921
|
+
throw new VibecodeError("CONTRACT_INVALID", `Unterminated protobuf string literal at line ${startLine}, column ${startCol}.`, { fallbackHint: "Ensure all string literals are closed." });
|
|
922
|
+
}
|
|
923
|
+
tokens.push({ kind: "STRING", value: val, line: startLine, col: startCol });
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
// Identifier
|
|
927
|
+
if (isIdentStart(code)) {
|
|
928
|
+
const start = i;
|
|
929
|
+
i += 1;
|
|
930
|
+
col += 1;
|
|
931
|
+
while (i < len && isIdentContinue(text.charCodeAt(i))) {
|
|
932
|
+
i += 1;
|
|
933
|
+
col += 1;
|
|
934
|
+
}
|
|
935
|
+
tokens.push({ kind: "IDENT", value: text.slice(start, i), line: startLine, col: startCol });
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
// Numeric literal (int, hex, float, negative)
|
|
939
|
+
if (ch === "-" || isDigit(code)) {
|
|
940
|
+
const start = i;
|
|
941
|
+
let isFloat = false;
|
|
942
|
+
if (ch === "-") {
|
|
943
|
+
i += 1;
|
|
944
|
+
col += 1;
|
|
945
|
+
if (i >= len || !isDigit(text.charCodeAt(i))) {
|
|
946
|
+
throw new VibecodeError("CONTRACT_INVALID", `Unexpected '-' at line ${startLine}, column ${startCol}.`, { fallbackHint: "Ensure numeric literals are well-formed." });
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
if (text[i] === "0" && (text[i + 1] === "x" || text[i + 1] === "X")) {
|
|
950
|
+
i += 2;
|
|
951
|
+
col += 2;
|
|
952
|
+
const hexStart = i;
|
|
953
|
+
while (i < len && isHexDigit(text.charCodeAt(i))) {
|
|
954
|
+
i += 1;
|
|
955
|
+
col += 1;
|
|
956
|
+
}
|
|
957
|
+
if (i === hexStart) {
|
|
958
|
+
throw new VibecodeError("CONTRACT_INVALID", `Malformed hexadecimal literal at line ${startLine}, column ${startCol}.`, { fallbackHint: "Hexadecimal literals must include at least one hex digit after 0x." });
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
else {
|
|
962
|
+
while (i < len && isDigit(text.charCodeAt(i))) {
|
|
963
|
+
i += 1;
|
|
964
|
+
col += 1;
|
|
965
|
+
}
|
|
966
|
+
if (i < len && text[i] === "." && i + 1 < len && isDigit(text.charCodeAt(i + 1))) {
|
|
967
|
+
isFloat = true;
|
|
968
|
+
i += 1;
|
|
969
|
+
col += 1;
|
|
970
|
+
while (i < len && isDigit(text.charCodeAt(i))) {
|
|
971
|
+
i += 1;
|
|
972
|
+
col += 1;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
if (i < len && (text[i] === "e" || text[i] === "E")) {
|
|
976
|
+
isFloat = true;
|
|
977
|
+
i += 1;
|
|
978
|
+
col += 1;
|
|
979
|
+
if (i < len && (text[i] === "+" || text[i] === "-")) {
|
|
980
|
+
i += 1;
|
|
981
|
+
col += 1;
|
|
982
|
+
}
|
|
983
|
+
while (i < len && isDigit(text.charCodeAt(i))) {
|
|
984
|
+
i += 1;
|
|
985
|
+
col += 1;
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
tokens.push({
|
|
990
|
+
kind: isFloat ? "FLOAT" : "INT",
|
|
991
|
+
value: text.slice(start, i),
|
|
992
|
+
line: startLine,
|
|
993
|
+
col: startCol
|
|
994
|
+
});
|
|
995
|
+
continue;
|
|
996
|
+
}
|
|
997
|
+
throw new VibecodeError("CONTRACT_INVALID", `Unexpected character ${JSON.stringify(ch)} in protobuf schema at line ${startLine}, column ${startCol}.`, { fallbackHint: "Provide a valid proto2 or proto3 .proto schema file." });
|
|
998
|
+
}
|
|
999
|
+
tokens.push({ kind: "EOF", value: "", line, col });
|
|
1000
|
+
return tokens;
|
|
1001
|
+
}
|
|
1002
|
+
function normalizeHttpPathTemplate(rawTemplate, requestMsg, ctx) {
|
|
1003
|
+
const boundFields = new Set();
|
|
1004
|
+
let working = sanitizeDecodedControlText(rawTemplate).trim();
|
|
1005
|
+
if (!working)
|
|
1006
|
+
return { path: "/", boundFields };
|
|
1007
|
+
if (/^(?:[a-z][a-z0-9+.-]*:\/\/|\/\/)/i.test(working)) {
|
|
1008
|
+
const sanitized = sanitizeUrlString(working, ctx.secretValues, { requireHttp: false, allowMalformed: true });
|
|
1009
|
+
if (sanitized.redacted)
|
|
1010
|
+
ctx.redactedSecrets = true;
|
|
1011
|
+
working = sanitized.valid ? sanitized.pathname : "/";
|
|
1012
|
+
}
|
|
1013
|
+
else {
|
|
1014
|
+
const hashIdx = working.indexOf("#");
|
|
1015
|
+
if (hashIdx >= 0) {
|
|
1016
|
+
const frag = working.slice(hashIdx + 1);
|
|
1017
|
+
if (frag) {
|
|
1018
|
+
ctx.redactedSecrets = true;
|
|
1019
|
+
recordSecretValue(ctx.secretValues, frag);
|
|
1020
|
+
}
|
|
1021
|
+
working = working.slice(0, hashIdx);
|
|
1022
|
+
}
|
|
1023
|
+
const queryIdx = working.indexOf("?");
|
|
1024
|
+
if (queryIdx >= 0) {
|
|
1025
|
+
const rawQuery = working.slice(queryIdx + 1);
|
|
1026
|
+
const params = new URLSearchParams(rawQuery);
|
|
1027
|
+
for (const [k, v] of params.entries()) {
|
|
1028
|
+
const sk = scrubText(k, ctx.secretValues);
|
|
1029
|
+
const sv = scrubText(v, ctx.secretValues);
|
|
1030
|
+
if (isProtoSensitiveQueryParam(k) || SENSITIVE_HEADER_VALUE_RE.test(v) || sk.redacted || sv.redacted) {
|
|
1031
|
+
ctx.redactedSecrets = true;
|
|
1032
|
+
recordSecretValue(ctx.secretValues, v);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
working = working.slice(0, queryIdx);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
const resolveFieldSampleSegment = (fieldPath) => {
|
|
1039
|
+
if (!requestMsg)
|
|
1040
|
+
return "sample";
|
|
1041
|
+
const segments = fieldPath.split(".").filter(Boolean);
|
|
1042
|
+
let currentMsg = requestMsg;
|
|
1043
|
+
let foundField;
|
|
1044
|
+
for (let idx = 0; idx < segments.length; idx += 1) {
|
|
1045
|
+
if (!currentMsg) {
|
|
1046
|
+
foundField = undefined;
|
|
1047
|
+
break;
|
|
1048
|
+
}
|
|
1049
|
+
const seg = segments[idx];
|
|
1050
|
+
const match = currentMsg.fields.find((f) => f.name === seg || f.jsonName === seg);
|
|
1051
|
+
if (!match) {
|
|
1052
|
+
foundField = undefined;
|
|
1053
|
+
break;
|
|
1054
|
+
}
|
|
1055
|
+
foundField = match;
|
|
1056
|
+
if (idx < segments.length - 1) {
|
|
1057
|
+
currentMsg = resolveMessageType(match.type, currentMsg.fullName, ctx);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
if (!foundField)
|
|
1061
|
+
return "sample";
|
|
1062
|
+
if (isSensitiveFieldName(foundField.name) || isSensitiveFieldName(foundField.jsonName)) {
|
|
1063
|
+
return "sample";
|
|
1064
|
+
}
|
|
1065
|
+
if (INT32_TYPES.has(foundField.type) || UINT32_TYPES.has(foundField.type) || INT64_TYPES.has(foundField.type)) {
|
|
1066
|
+
return "1";
|
|
1067
|
+
}
|
|
1068
|
+
if (FLOAT_TYPES.has(foundField.type))
|
|
1069
|
+
return "1.5";
|
|
1070
|
+
if (foundField.type === "bool")
|
|
1071
|
+
return "true";
|
|
1072
|
+
const enumVals = resolveEnumType(foundField.type, requestMsg.fullName, ctx);
|
|
1073
|
+
if (enumVals && enumVals.length > 0) {
|
|
1074
|
+
const preferred = enumVals.find((v) => !v.endsWith("_UNSPECIFIED")) ?? enumVals[0];
|
|
1075
|
+
return encodeURIComponent(preferred);
|
|
1076
|
+
}
|
|
1077
|
+
return "sample";
|
|
1078
|
+
};
|
|
1079
|
+
working = working.replace(/\{([^{}]+)\}/g, (_m, inner) => {
|
|
1080
|
+
const trimmedInner = inner.trim();
|
|
1081
|
+
const eqIdx = trimmedInner.indexOf("=");
|
|
1082
|
+
if (eqIdx >= 0) {
|
|
1083
|
+
const fieldPath = trimmedInner.slice(0, eqIdx).trim();
|
|
1084
|
+
const pattern = trimmedInner.slice(eqIdx + 1).trim();
|
|
1085
|
+
if (fieldPath) {
|
|
1086
|
+
const topField = fieldPath.split(".")[0];
|
|
1087
|
+
if (topField) {
|
|
1088
|
+
boundFields.add(topField);
|
|
1089
|
+
boundFields.add(snakeToLowerCamel(topField));
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
const replaced = pattern.replace(/\*\*|\*/g, "sample");
|
|
1093
|
+
return replaced || "sample";
|
|
1094
|
+
}
|
|
1095
|
+
if (trimmedInner) {
|
|
1096
|
+
const topField = trimmedInner.split(".")[0];
|
|
1097
|
+
if (topField) {
|
|
1098
|
+
boundFields.add(topField);
|
|
1099
|
+
boundFields.add(snakeToLowerCamel(topField));
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
return resolveFieldSampleSegment(trimmedInner);
|
|
1103
|
+
});
|
|
1104
|
+
const scrubbed = scrubText(working, ctx.secretValues);
|
|
1105
|
+
if (scrubbed.redacted)
|
|
1106
|
+
ctx.redactedSecrets = true;
|
|
1107
|
+
working = scrubbed.value;
|
|
1108
|
+
const rawSegments = working
|
|
1109
|
+
.split("/")
|
|
1110
|
+
.filter((s) => s.length > 0 && s !== "." && s !== "..")
|
|
1111
|
+
.map((s) => s.replace(/\s+/g, "%20"));
|
|
1112
|
+
if (rawSegments.length === 0)
|
|
1113
|
+
return { path: "/", boundFields };
|
|
1114
|
+
return { path: `/${rawSegments.join("/")}`, boundFields };
|
|
1115
|
+
}
|
|
1116
|
+
function scopeCandidates(typeName, currentScope, packageName) {
|
|
1117
|
+
const trimmed = typeName.trim();
|
|
1118
|
+
if (!trimmed)
|
|
1119
|
+
return [];
|
|
1120
|
+
if (trimmed.startsWith(".")) {
|
|
1121
|
+
return [trimmed.slice(1)];
|
|
1122
|
+
}
|
|
1123
|
+
const candidates = [];
|
|
1124
|
+
const seen = new Set();
|
|
1125
|
+
const add = (cand) => {
|
|
1126
|
+
if (cand && !seen.has(cand)) {
|
|
1127
|
+
seen.add(cand);
|
|
1128
|
+
candidates.push(cand);
|
|
1129
|
+
}
|
|
1130
|
+
};
|
|
1131
|
+
if (currentScope) {
|
|
1132
|
+
const parts = currentScope.split(".").filter(Boolean);
|
|
1133
|
+
for (let i = parts.length; i >= 1; i -= 1) {
|
|
1134
|
+
add(`${parts.slice(0, i).join(".")}.${trimmed}`);
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
if (packageName) {
|
|
1138
|
+
const pkgParts = packageName.split(".").filter(Boolean);
|
|
1139
|
+
for (let i = pkgParts.length; i >= 1; i -= 1) {
|
|
1140
|
+
add(`${pkgParts.slice(0, i).join(".")}.${trimmed}`);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
add(trimmed);
|
|
1144
|
+
return candidates;
|
|
1145
|
+
}
|
|
1146
|
+
function resolveMessageType(typeName, currentScope, ctx) {
|
|
1147
|
+
for (const cand of scopeCandidates(typeName, currentScope, ctx.packageName)) {
|
|
1148
|
+
const found = ctx.messagesByFullName.get(cand);
|
|
1149
|
+
if (found)
|
|
1150
|
+
return found;
|
|
1151
|
+
}
|
|
1152
|
+
return undefined;
|
|
1153
|
+
}
|
|
1154
|
+
function resolveEnumType(typeName, currentScope, ctx) {
|
|
1155
|
+
for (const cand of scopeCandidates(typeName, currentScope, ctx.packageName)) {
|
|
1156
|
+
const found = ctx.enumsByFullName.get(cand);
|
|
1157
|
+
if (found)
|
|
1158
|
+
return found;
|
|
1159
|
+
}
|
|
1160
|
+
return undefined;
|
|
1161
|
+
}
|
|
1162
|
+
function wellKnownTypeSchema(typeName) {
|
|
1163
|
+
const clean = typeName.startsWith(".") ? typeName.slice(1) : typeName;
|
|
1164
|
+
switch (clean) {
|
|
1165
|
+
case "google.protobuf.Empty":
|
|
1166
|
+
case "google.protobuf.Struct":
|
|
1167
|
+
case "google.protobuf.Any":
|
|
1168
|
+
return { type: "object" };
|
|
1169
|
+
case "google.protobuf.Timestamp":
|
|
1170
|
+
return { type: "string", format: "date-time" };
|
|
1171
|
+
case "google.protobuf.Duration":
|
|
1172
|
+
case "google.protobuf.FieldMask":
|
|
1173
|
+
case "google.protobuf.StringValue":
|
|
1174
|
+
case "google.protobuf.BytesValue":
|
|
1175
|
+
return { type: "string" };
|
|
1176
|
+
case "google.protobuf.BoolValue":
|
|
1177
|
+
return { type: "boolean" };
|
|
1178
|
+
case "google.protobuf.Int32Value":
|
|
1179
|
+
return { type: "integer" };
|
|
1180
|
+
case "google.protobuf.UInt32Value":
|
|
1181
|
+
return { type: "integer", minimum: 0 };
|
|
1182
|
+
case "google.protobuf.Int64Value":
|
|
1183
|
+
case "google.protobuf.UInt64Value":
|
|
1184
|
+
return { type: ["string", "integer"] };
|
|
1185
|
+
case "google.protobuf.FloatValue":
|
|
1186
|
+
case "google.protobuf.DoubleValue":
|
|
1187
|
+
return { type: "number" };
|
|
1188
|
+
case "google.protobuf.ListValue":
|
|
1189
|
+
return { type: "array" };
|
|
1190
|
+
case "google.protobuf.Value":
|
|
1191
|
+
return {};
|
|
1192
|
+
default:
|
|
1193
|
+
return undefined;
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
function wellKnownTypeSample(typeName) {
|
|
1197
|
+
const clean = typeName.startsWith(".") ? typeName.slice(1) : typeName;
|
|
1198
|
+
switch (clean) {
|
|
1199
|
+
case "google.protobuf.Empty":
|
|
1200
|
+
case "google.protobuf.Struct":
|
|
1201
|
+
case "google.protobuf.Any":
|
|
1202
|
+
return {};
|
|
1203
|
+
case "google.protobuf.Timestamp":
|
|
1204
|
+
return "2026-01-01T00:00:00Z";
|
|
1205
|
+
case "google.protobuf.Duration":
|
|
1206
|
+
return "1s";
|
|
1207
|
+
case "google.protobuf.FieldMask":
|
|
1208
|
+
return "id";
|
|
1209
|
+
case "google.protobuf.StringValue":
|
|
1210
|
+
return "sample";
|
|
1211
|
+
case "google.protobuf.BytesValue":
|
|
1212
|
+
return "c2FtcGxl";
|
|
1213
|
+
case "google.protobuf.BoolValue":
|
|
1214
|
+
return true;
|
|
1215
|
+
case "google.protobuf.Int32Value":
|
|
1216
|
+
case "google.protobuf.UInt32Value":
|
|
1217
|
+
return 1;
|
|
1218
|
+
case "google.protobuf.Int64Value":
|
|
1219
|
+
case "google.protobuf.UInt64Value":
|
|
1220
|
+
return "1";
|
|
1221
|
+
case "google.protobuf.FloatValue":
|
|
1222
|
+
case "google.protobuf.DoubleValue":
|
|
1223
|
+
return 1.5;
|
|
1224
|
+
case "google.protobuf.ListValue":
|
|
1225
|
+
return [];
|
|
1226
|
+
case "google.protobuf.Value":
|
|
1227
|
+
return "sample";
|
|
1228
|
+
default:
|
|
1229
|
+
return undefined;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
function scalarTypeSchema(typeName) {
|
|
1233
|
+
if (typeName === "string" || typeName === "bytes")
|
|
1234
|
+
return { type: "string" };
|
|
1235
|
+
if (typeName === "bool")
|
|
1236
|
+
return { type: "boolean" };
|
|
1237
|
+
if (INT32_TYPES.has(typeName))
|
|
1238
|
+
return { type: "integer" };
|
|
1239
|
+
if (UINT32_TYPES.has(typeName))
|
|
1240
|
+
return { type: "integer", minimum: 0 };
|
|
1241
|
+
if (INT64_TYPES.has(typeName))
|
|
1242
|
+
return { type: ["string", "integer"] };
|
|
1243
|
+
if (FLOAT_TYPES.has(typeName))
|
|
1244
|
+
return { type: "number" };
|
|
1245
|
+
return undefined;
|
|
1246
|
+
}
|
|
1247
|
+
function scalarTypeSample(typeName, defaultVal, sensitive) {
|
|
1248
|
+
if (typeName === "string") {
|
|
1249
|
+
if (sensitive)
|
|
1250
|
+
return "[REDACTED]";
|
|
1251
|
+
return defaultVal !== undefined ? defaultVal : "sample";
|
|
1252
|
+
}
|
|
1253
|
+
if (typeName === "bytes") {
|
|
1254
|
+
return sensitive ? "[REDACTED]" : "c2FtcGxl";
|
|
1255
|
+
}
|
|
1256
|
+
if (typeName === "bool") {
|
|
1257
|
+
if (defaultVal === "false")
|
|
1258
|
+
return false;
|
|
1259
|
+
return true;
|
|
1260
|
+
}
|
|
1261
|
+
if (INT32_TYPES.has(typeName) || UINT32_TYPES.has(typeName)) {
|
|
1262
|
+
if (defaultVal !== undefined) {
|
|
1263
|
+
const parsed = Number(defaultVal);
|
|
1264
|
+
if (Number.isInteger(parsed))
|
|
1265
|
+
return parsed;
|
|
1266
|
+
}
|
|
1267
|
+
return 1;
|
|
1268
|
+
}
|
|
1269
|
+
if (INT64_TYPES.has(typeName)) {
|
|
1270
|
+
if (defaultVal !== undefined && /^-?\d+$/.test(defaultVal)) {
|
|
1271
|
+
return defaultVal;
|
|
1272
|
+
}
|
|
1273
|
+
return "1";
|
|
1274
|
+
}
|
|
1275
|
+
if (FLOAT_TYPES.has(typeName)) {
|
|
1276
|
+
if (defaultVal !== undefined) {
|
|
1277
|
+
const parsed = Number(defaultVal);
|
|
1278
|
+
if (Number.isFinite(parsed))
|
|
1279
|
+
return parsed;
|
|
1280
|
+
}
|
|
1281
|
+
return 1.5;
|
|
1282
|
+
}
|
|
1283
|
+
return "sample";
|
|
1284
|
+
}
|
|
1285
|
+
function compileTypeSchemaInternal(typeName, currentScope, ctx, ancestors, depth) {
|
|
1286
|
+
if (ctx.nodeBudget.remaining <= 0) {
|
|
1287
|
+
pushWarning(ctx, "Schema node expansion budget reached; truncated remaining nested schema.");
|
|
1288
|
+
return {};
|
|
1289
|
+
}
|
|
1290
|
+
ctx.nodeBudget.remaining -= 1;
|
|
1291
|
+
const scalar = scalarTypeSchema(typeName);
|
|
1292
|
+
if (scalar)
|
|
1293
|
+
return scalar;
|
|
1294
|
+
const enumValues = resolveEnumType(typeName, currentScope, ctx);
|
|
1295
|
+
if (enumValues) {
|
|
1296
|
+
return enumValues.length > 0 ? { type: "string", enum: enumValues.slice() } : { type: "string" };
|
|
1297
|
+
}
|
|
1298
|
+
const wkt = wellKnownTypeSchema(typeName);
|
|
1299
|
+
if (wkt)
|
|
1300
|
+
return { ...wkt };
|
|
1301
|
+
const msg = resolveMessageType(typeName, currentScope, ctx);
|
|
1302
|
+
if (!msg) {
|
|
1303
|
+
pushWarning(ctx, `Unresolved protobuf type "${scrubText(typeName, ctx.secretValues).value}"; falling back to generic object schema.`);
|
|
1304
|
+
return { type: "object" };
|
|
1305
|
+
}
|
|
1306
|
+
if (depth >= MAX_CYCLIC_DEPTH) {
|
|
1307
|
+
pushWarning(ctx, `Max message nesting depth (${MAX_CYCLIC_DEPTH}) reached at "${msg.fullName}"; bounded schema expansion.`);
|
|
1308
|
+
return { type: "object" };
|
|
1309
|
+
}
|
|
1310
|
+
if (ancestors.has(msg.fullName)) {
|
|
1311
|
+
pushWarning(ctx, `Cyclic message reference detected at "${msg.fullName}"; bounded schema expansion.`);
|
|
1312
|
+
return { type: "object" };
|
|
1313
|
+
}
|
|
1314
|
+
return compileMessageSchemaInternal(msg, ctx, ancestors, depth, false);
|
|
1315
|
+
}
|
|
1316
|
+
function compileMessageSchemaInternal(msg, ctx, ancestors, depth, isRoot, excludedFields) {
|
|
1317
|
+
if (depth >= MAX_CYCLIC_DEPTH) {
|
|
1318
|
+
pushWarning(ctx, `Max message nesting depth (${MAX_CYCLIC_DEPTH}) reached at "${msg.fullName}"; bounded schema expansion.`);
|
|
1319
|
+
return { type: "object" };
|
|
1320
|
+
}
|
|
1321
|
+
const nextAncestors = new Set(ancestors);
|
|
1322
|
+
nextAncestors.add(msg.fullName);
|
|
1323
|
+
const properties = {};
|
|
1324
|
+
const required = [];
|
|
1325
|
+
for (const field of msg.fields) {
|
|
1326
|
+
if (isUnsafeKey(field.jsonName) || isUnsafeKey(field.name))
|
|
1327
|
+
continue;
|
|
1328
|
+
if (excludedFields && (excludedFields.has(field.name) || excludedFields.has(field.jsonName))) {
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
let fieldSchema;
|
|
1332
|
+
let isCyclicField = false;
|
|
1333
|
+
if (field.mapKeyType && field.mapValueType) {
|
|
1334
|
+
const valTarget = resolveMessageType(field.mapValueType, msg.fullName, ctx);
|
|
1335
|
+
if (valTarget && nextAncestors.has(valTarget.fullName)) {
|
|
1336
|
+
isCyclicField = true;
|
|
1337
|
+
}
|
|
1338
|
+
const valSchema = compileTypeSchemaInternal(field.mapValueType, msg.fullName, ctx, nextAncestors, depth + 1);
|
|
1339
|
+
fieldSchema = {
|
|
1340
|
+
type: "object",
|
|
1341
|
+
additionalProperties: valSchema
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
else {
|
|
1345
|
+
const targetMsg = resolveMessageType(field.type, msg.fullName, ctx);
|
|
1346
|
+
if (targetMsg && nextAncestors.has(targetMsg.fullName)) {
|
|
1347
|
+
isCyclicField = true;
|
|
1348
|
+
}
|
|
1349
|
+
const baseSchema = compileTypeSchemaInternal(field.type, msg.fullName, ctx, nextAncestors, depth + 1);
|
|
1350
|
+
fieldSchema = field.repeated ? { type: "array", items: baseSchema } : baseSchema;
|
|
1351
|
+
}
|
|
1352
|
+
properties[field.jsonName] = fieldSchema;
|
|
1353
|
+
const shouldRequire = !isCyclicField &&
|
|
1354
|
+
!field.optional &&
|
|
1355
|
+
!field.oneofGroup &&
|
|
1356
|
+
(ctx.syntax === "proto3" ? true : !field.repeated && !field.mapKeyType);
|
|
1357
|
+
if (shouldRequire) {
|
|
1358
|
+
required.push(field.jsonName);
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
const schema = {
|
|
1362
|
+
...(isRoot ? { $schema: DRAFT_2020_12_SCHEMA } : {}),
|
|
1363
|
+
type: "object",
|
|
1364
|
+
...(Object.keys(properties).length > 0 ? { properties } : {}),
|
|
1365
|
+
...(required.length > 0 ? { required } : {})
|
|
1366
|
+
};
|
|
1367
|
+
return schema;
|
|
1368
|
+
}
|
|
1369
|
+
function compileRootTypeSchema(typeName, currentScope, ctx, excludedFields) {
|
|
1370
|
+
const wkt = wellKnownTypeSchema(typeName);
|
|
1371
|
+
if (wkt) {
|
|
1372
|
+
return { $schema: DRAFT_2020_12_SCHEMA, ...wkt };
|
|
1373
|
+
}
|
|
1374
|
+
const msg = resolveMessageType(typeName, currentScope, ctx);
|
|
1375
|
+
if (msg) {
|
|
1376
|
+
return compileMessageSchemaInternal(msg, ctx, new Set(), 0, true, excludedFields);
|
|
1377
|
+
}
|
|
1378
|
+
const inner = compileTypeSchemaInternal(typeName, currentScope, ctx, new Set(), 0);
|
|
1379
|
+
return { $schema: DRAFT_2020_12_SCHEMA, ...inner };
|
|
1380
|
+
}
|
|
1381
|
+
function synthesizeTypeSampleInternal(typeName, currentScope, ctx, ancestors, depth, defaultVal, sensitive) {
|
|
1382
|
+
if (ctx.nodeBudget.remaining <= 0 || depth >= MAX_SAMPLE_DEPTH) {
|
|
1383
|
+
return undefined;
|
|
1384
|
+
}
|
|
1385
|
+
ctx.nodeBudget.remaining -= 1;
|
|
1386
|
+
if (SCALAR_TYPES.has(typeName)) {
|
|
1387
|
+
return scalarTypeSample(typeName, defaultVal, sensitive);
|
|
1388
|
+
}
|
|
1389
|
+
const enumValues = resolveEnumType(typeName, currentScope, ctx);
|
|
1390
|
+
if (enumValues) {
|
|
1391
|
+
if (enumValues.length === 0)
|
|
1392
|
+
return "UNSPECIFIED";
|
|
1393
|
+
if (defaultVal && enumValues.includes(defaultVal))
|
|
1394
|
+
return defaultVal;
|
|
1395
|
+
return enumValues.find((v) => !v.endsWith("_UNSPECIFIED")) ?? enumValues[0];
|
|
1396
|
+
}
|
|
1397
|
+
const wktSample = wellKnownTypeSample(typeName);
|
|
1398
|
+
if (wktSample !== undefined)
|
|
1399
|
+
return wktSample;
|
|
1400
|
+
const msg = resolveMessageType(typeName, currentScope, ctx);
|
|
1401
|
+
if (!msg)
|
|
1402
|
+
return {};
|
|
1403
|
+
if (ancestors.has(msg.fullName)) {
|
|
1404
|
+
return undefined;
|
|
1405
|
+
}
|
|
1406
|
+
return synthesizeMessageSampleInternal(msg, ctx, ancestors, depth);
|
|
1407
|
+
}
|
|
1408
|
+
function synthesizeMessageSampleInternal(msg, ctx, ancestors, depth, excludedFields) {
|
|
1409
|
+
if (depth >= MAX_SAMPLE_DEPTH)
|
|
1410
|
+
return {};
|
|
1411
|
+
const nextAncestors = new Set(ancestors);
|
|
1412
|
+
nextAncestors.add(msg.fullName);
|
|
1413
|
+
const out = {};
|
|
1414
|
+
const emittedOneofs = new Set();
|
|
1415
|
+
for (const field of msg.fields) {
|
|
1416
|
+
if (isUnsafeKey(field.jsonName) || isUnsafeKey(field.name))
|
|
1417
|
+
continue;
|
|
1418
|
+
if (excludedFields && (excludedFields.has(field.name) || excludedFields.has(field.jsonName))) {
|
|
1419
|
+
continue;
|
|
1420
|
+
}
|
|
1421
|
+
if (field.oneofGroup) {
|
|
1422
|
+
if (emittedOneofs.has(field.oneofGroup))
|
|
1423
|
+
continue;
|
|
1424
|
+
emittedOneofs.add(field.oneofGroup);
|
|
1425
|
+
}
|
|
1426
|
+
const fieldMetaKey = `${msg.fullName}.${field.name}`;
|
|
1427
|
+
const rawDefault = ctx.fieldDefaults.get(fieldMetaKey)?.defaultValue;
|
|
1428
|
+
const sensitive = isSensitiveFieldName(field.name) || isSensitiveFieldName(field.jsonName);
|
|
1429
|
+
if (field.mapKeyType && field.mapValueType) {
|
|
1430
|
+
const valTarget = resolveMessageType(field.mapValueType, msg.fullName, ctx);
|
|
1431
|
+
if (valTarget && nextAncestors.has(valTarget.fullName)) {
|
|
1432
|
+
out[field.jsonName] = {};
|
|
1433
|
+
}
|
|
1434
|
+
else {
|
|
1435
|
+
const keySample = field.mapKeyType === "bool"
|
|
1436
|
+
? "true"
|
|
1437
|
+
: INT32_TYPES.has(field.mapKeyType) || UINT32_TYPES.has(field.mapKeyType) || INT64_TYPES.has(field.mapKeyType)
|
|
1438
|
+
? "1"
|
|
1439
|
+
: "sampleKey";
|
|
1440
|
+
const valSample = synthesizeTypeSampleInternal(field.mapValueType, msg.fullName, ctx, nextAncestors, depth + 1, undefined, sensitive);
|
|
1441
|
+
out[field.jsonName] = valSample !== undefined ? { [keySample]: valSample } : {};
|
|
1442
|
+
}
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1445
|
+
const targetMsg = resolveMessageType(field.type, msg.fullName, ctx);
|
|
1446
|
+
if (targetMsg && nextAncestors.has(targetMsg.fullName)) {
|
|
1447
|
+
if (field.repeated) {
|
|
1448
|
+
out[field.jsonName] = [];
|
|
1449
|
+
}
|
|
1450
|
+
continue;
|
|
1451
|
+
}
|
|
1452
|
+
const sampleVal = synthesizeTypeSampleInternal(field.type, msg.fullName, ctx, nextAncestors, depth + 1, rawDefault, sensitive);
|
|
1453
|
+
if (field.repeated) {
|
|
1454
|
+
out[field.jsonName] = sampleVal !== undefined ? [sampleVal] : [];
|
|
1455
|
+
}
|
|
1456
|
+
else if (sampleVal !== undefined) {
|
|
1457
|
+
out[field.jsonName] = sampleVal;
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
return out;
|
|
1461
|
+
}
|
|
1462
|
+
function extractHttpRulesFromOption(optValue, ctx, allowAdditional = true) {
|
|
1463
|
+
if (!isObject(optValue))
|
|
1464
|
+
return [];
|
|
1465
|
+
const obj = optValue;
|
|
1466
|
+
const rules = [];
|
|
1467
|
+
const bodyRaw = hasOwn(obj, "body") && typeof obj.body === "string"
|
|
1468
|
+
? sanitizeDecodedControlText(obj.body).trim()
|
|
1469
|
+
: undefined;
|
|
1470
|
+
const methodKeys = [
|
|
1471
|
+
["get", "GET"],
|
|
1472
|
+
["post", "POST"],
|
|
1473
|
+
["put", "PUT"],
|
|
1474
|
+
["patch", "PATCH"],
|
|
1475
|
+
["delete", "DELETE"]
|
|
1476
|
+
];
|
|
1477
|
+
let primary;
|
|
1478
|
+
for (const [k, httpMethod] of methodKeys) {
|
|
1479
|
+
if (hasOwn(obj, k) && typeof obj[k] === "string") {
|
|
1480
|
+
primary = {
|
|
1481
|
+
method: httpMethod,
|
|
1482
|
+
pathTemplate: obj[k],
|
|
1483
|
+
...(bodyRaw ? { bodyField: bodyRaw } : {})
|
|
1484
|
+
};
|
|
1485
|
+
break;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
if (!primary && hasOwn(obj, "custom") && isObject(obj.custom)) {
|
|
1489
|
+
const customObj = obj.custom;
|
|
1490
|
+
const rawKind = hasOwn(customObj, "kind") && typeof customObj.kind === "string" ? customObj.kind.trim().toUpperCase() : "";
|
|
1491
|
+
const rawPath = hasOwn(customObj, "path") && typeof customObj.path === "string" ? customObj.path : "";
|
|
1492
|
+
if (rawKind && VALID_HTTP_METHODS.has(rawKind) && rawPath) {
|
|
1493
|
+
primary = {
|
|
1494
|
+
method: rawKind,
|
|
1495
|
+
pathTemplate: rawPath,
|
|
1496
|
+
...(bodyRaw ? { bodyField: bodyRaw } : {})
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
else if (rawKind || rawPath) {
|
|
1500
|
+
pushWarning(ctx, `Ignored invalid google.api.http custom binding (kind="${rawKind || "?"}").`);
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
if (primary) {
|
|
1504
|
+
rules.push(primary);
|
|
1505
|
+
}
|
|
1506
|
+
if (hasOwn(obj, "additional_bindings")) {
|
|
1507
|
+
if (!allowAdditional) {
|
|
1508
|
+
pushWarning(ctx, "Ignored nested google.api.http additional_bindings (forbidden by protobuf HTTP transcoding spec).");
|
|
1509
|
+
}
|
|
1510
|
+
else {
|
|
1511
|
+
const rawBindings = obj.additional_bindings;
|
|
1512
|
+
const list = Array.isArray(rawBindings) ? rawBindings : [rawBindings];
|
|
1513
|
+
for (const item of list) {
|
|
1514
|
+
rules.push(...extractHttpRulesFromOption(item, ctx, false));
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
return rules;
|
|
1519
|
+
}
|
|
1520
|
+
function parseProtoInternal(rawText) {
|
|
1521
|
+
if (typeof rawText !== "string") {
|
|
1522
|
+
throw new VibecodeError("CONTRACT_INVALID", "Protobuf input must be a string.", {
|
|
1523
|
+
fallbackHint: "Provide a valid proto2 or proto3 .proto schema."
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
if (rawText.includes("\0")) {
|
|
1527
|
+
throw new VibecodeError("CONTRACT_INVALID", "Protobuf specification contains NUL bytes.", {
|
|
1528
|
+
fallbackHint: "Provide a valid UTF-8 text .proto file."
|
|
1529
|
+
});
|
|
1530
|
+
}
|
|
1531
|
+
if (Buffer.byteLength(rawText, "utf8") > MAX_SOURCE_BYTES) {
|
|
1532
|
+
throw new VibecodeError("CONTRACT_INVALID", `Protobuf specification exceeds maximum size of ${MAX_SOURCE_BYTES} bytes.`, { fallbackHint: "Reduce the .proto file size below 2 MiB." });
|
|
1533
|
+
}
|
|
1534
|
+
const strippedRaw = stripBom(rawText).trim();
|
|
1535
|
+
if (!strippedRaw) {
|
|
1536
|
+
throw new VibecodeError("CONTRACT_INVALID", "Protobuf specification is empty.", {
|
|
1537
|
+
fallbackHint: "Provide a non-empty proto2 or proto3 schema with at least one service RPC."
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
const ctx = {
|
|
1541
|
+
syntax: "proto2",
|
|
1542
|
+
messagesByFullName: new Map(),
|
|
1543
|
+
enumsByFullName: new Map(),
|
|
1544
|
+
fieldDefaults: new Map(),
|
|
1545
|
+
messageCount: 0,
|
|
1546
|
+
warnings: [],
|
|
1547
|
+
warningSet: new Set(),
|
|
1548
|
+
secretValues: new Set(),
|
|
1549
|
+
redactedSecrets: false,
|
|
1550
|
+
nodeBudget: { remaining: MAX_NODE_BUDGET }
|
|
1551
|
+
};
|
|
1552
|
+
const tokens = tokenizeProto(rawText, ctx);
|
|
1553
|
+
let pos = 0;
|
|
1554
|
+
const peek = (offset = 0) => tokens[Math.min(pos + offset, tokens.length - 1)];
|
|
1555
|
+
const next = () => {
|
|
1556
|
+
const tok = peek();
|
|
1557
|
+
if (pos < tokens.length - 1)
|
|
1558
|
+
pos += 1;
|
|
1559
|
+
return tok;
|
|
1560
|
+
};
|
|
1561
|
+
const fail = (message, tok = peek()) => {
|
|
1562
|
+
const safeMsgRaw = scrubText(sanitizeDecodedControlText(message).replace(/\s+/g, " ").trim(), ctx.secretValues).value;
|
|
1563
|
+
const safeMsg = safeMsgRaw.length > 220 ? `${safeMsgRaw.slice(0, 217)}...` : safeMsgRaw;
|
|
1564
|
+
throw new VibecodeError("CONTRACT_INVALID", `Protobuf syntax error at line ${tok.line}, column ${tok.col}: ${safeMsg}`, { fallbackHint: "Verify the input is a valid proto2 or proto3 .proto schema." });
|
|
1565
|
+
};
|
|
1566
|
+
const parseProtoFieldNumber = (numTok, fieldLabel) => {
|
|
1567
|
+
if (numTok.kind !== "INT") {
|
|
1568
|
+
fail(`expected field number for '${fieldLabel}'`, numTok);
|
|
1569
|
+
}
|
|
1570
|
+
const parsedNum = Number(numTok.value);
|
|
1571
|
+
if (!Number.isSafeInteger(parsedNum) ||
|
|
1572
|
+
parsedNum < 1 ||
|
|
1573
|
+
parsedNum > 536870911 ||
|
|
1574
|
+
(parsedNum >= 19000 && parsedNum <= 19999)) {
|
|
1575
|
+
fail(`invalid protobuf field number '${numTok.value}' for '${fieldLabel}'`, numTok);
|
|
1576
|
+
}
|
|
1577
|
+
return parsedNum;
|
|
1578
|
+
};
|
|
1579
|
+
const matchPunct = (val) => {
|
|
1580
|
+
const tok = peek();
|
|
1581
|
+
if (tok.kind === "PUNCT" && tok.value === val) {
|
|
1582
|
+
next();
|
|
1583
|
+
return true;
|
|
1584
|
+
}
|
|
1585
|
+
return false;
|
|
1586
|
+
};
|
|
1587
|
+
const expectPunct = (val) => {
|
|
1588
|
+
if (!matchPunct(val)) {
|
|
1589
|
+
const tok = peek();
|
|
1590
|
+
fail(`expected '${val}', got ${tok.kind === "EOF" ? "EOF" : `'${tok.value}'`}`, tok);
|
|
1591
|
+
}
|
|
1592
|
+
};
|
|
1593
|
+
const expectIdent = (context = "identifier") => {
|
|
1594
|
+
const tok = peek();
|
|
1595
|
+
if (tok.kind !== "IDENT") {
|
|
1596
|
+
fail(`expected ${context}, got ${tok.kind === "EOF" ? "EOF" : `'${tok.value}'`}`, tok);
|
|
1597
|
+
}
|
|
1598
|
+
next();
|
|
1599
|
+
return tok.value;
|
|
1600
|
+
};
|
|
1601
|
+
const parseConcatString = () => {
|
|
1602
|
+
const first = peek();
|
|
1603
|
+
if (first.kind !== "STRING") {
|
|
1604
|
+
fail(`expected string literal, got ${first.kind === "EOF" ? "EOF" : `'${first.value}'`}`, first);
|
|
1605
|
+
}
|
|
1606
|
+
let combined = next().value;
|
|
1607
|
+
while (peek().kind === "STRING") {
|
|
1608
|
+
combined += next().value;
|
|
1609
|
+
}
|
|
1610
|
+
return combined;
|
|
1611
|
+
};
|
|
1612
|
+
const parseQualifiedName = () => {
|
|
1613
|
+
let leadingDot = "";
|
|
1614
|
+
if (matchPunct("."))
|
|
1615
|
+
leadingDot = ".";
|
|
1616
|
+
let name = expectIdent("qualified name");
|
|
1617
|
+
while (matchPunct(".")) {
|
|
1618
|
+
name += `.${expectIdent("identifier after '.'")}`;
|
|
1619
|
+
}
|
|
1620
|
+
return `${leadingDot}${name}`;
|
|
1621
|
+
};
|
|
1622
|
+
const parseOptionName = () => {
|
|
1623
|
+
const parts = [];
|
|
1624
|
+
const readPart = () => {
|
|
1625
|
+
if (matchPunct("(")) {
|
|
1626
|
+
const inner = parseQualifiedName();
|
|
1627
|
+
expectPunct(")");
|
|
1628
|
+
return `(${inner})`;
|
|
1629
|
+
}
|
|
1630
|
+
return expectIdent("option name");
|
|
1631
|
+
};
|
|
1632
|
+
parts.push(readPart());
|
|
1633
|
+
while (matchPunct(".")) {
|
|
1634
|
+
parts.push(readPart());
|
|
1635
|
+
}
|
|
1636
|
+
return parts.join(".");
|
|
1637
|
+
};
|
|
1638
|
+
const parseOptionMessageLiteral = (depth) => {
|
|
1639
|
+
if (depth > MAX_PARSER_NESTING) {
|
|
1640
|
+
fail("option nesting depth exceeded");
|
|
1641
|
+
}
|
|
1642
|
+
expectPunct("{");
|
|
1643
|
+
const obj = {};
|
|
1644
|
+
while (!(peek().kind === "PUNCT" && peek().value === "}")) {
|
|
1645
|
+
if (peek().kind === "EOF")
|
|
1646
|
+
fail("unterminated option message literal");
|
|
1647
|
+
if (matchPunct(",") || matchPunct(";"))
|
|
1648
|
+
continue;
|
|
1649
|
+
let key;
|
|
1650
|
+
if (matchPunct("[")) {
|
|
1651
|
+
key = parseQualifiedName();
|
|
1652
|
+
expectPunct("]");
|
|
1653
|
+
}
|
|
1654
|
+
else {
|
|
1655
|
+
key = expectIdent("option field name");
|
|
1656
|
+
}
|
|
1657
|
+
let val;
|
|
1658
|
+
if (matchPunct(":")) {
|
|
1659
|
+
val = parseOptionValue(depth + 1);
|
|
1660
|
+
}
|
|
1661
|
+
else if (peek().kind === "PUNCT" && peek().value === "{") {
|
|
1662
|
+
val = parseOptionMessageLiteral(depth + 1);
|
|
1663
|
+
}
|
|
1664
|
+
else {
|
|
1665
|
+
fail(`expected ':' or '{' after option field '${key}'`);
|
|
1666
|
+
val = "";
|
|
1667
|
+
}
|
|
1668
|
+
matchPunct(",");
|
|
1669
|
+
matchPunct(";");
|
|
1670
|
+
if (isUnsafeKey(key)) {
|
|
1671
|
+
pushWarning(ctx, `Filtered unsafe option key "${key}".`);
|
|
1672
|
+
continue;
|
|
1673
|
+
}
|
|
1674
|
+
if (hasOwn(obj, key)) {
|
|
1675
|
+
const existing = obj[key];
|
|
1676
|
+
if (Array.isArray(existing)) {
|
|
1677
|
+
existing.push(val);
|
|
1678
|
+
}
|
|
1679
|
+
else {
|
|
1680
|
+
obj[key] = [existing, val];
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
else {
|
|
1684
|
+
obj[key] = val;
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
expectPunct("}");
|
|
1688
|
+
return obj;
|
|
1689
|
+
};
|
|
1690
|
+
const parseOptionValue = (depth = 0) => {
|
|
1691
|
+
if (depth > MAX_PARSER_NESTING) {
|
|
1692
|
+
fail("option value nesting depth exceeded");
|
|
1693
|
+
}
|
|
1694
|
+
const tok = peek();
|
|
1695
|
+
if (tok.kind === "STRING") {
|
|
1696
|
+
return parseConcatString();
|
|
1697
|
+
}
|
|
1698
|
+
if (tok.kind === "INT" || tok.kind === "FLOAT") {
|
|
1699
|
+
next();
|
|
1700
|
+
const num = Number(tok.value);
|
|
1701
|
+
return Number.isFinite(num) ? num : tok.value;
|
|
1702
|
+
}
|
|
1703
|
+
if (tok.kind === "PUNCT" && tok.value === "+") {
|
|
1704
|
+
next();
|
|
1705
|
+
const numTok = peek();
|
|
1706
|
+
if (numTok.kind === "INT" || numTok.kind === "FLOAT") {
|
|
1707
|
+
next();
|
|
1708
|
+
const num = Number(numTok.value);
|
|
1709
|
+
return Number.isFinite(num) ? num : numTok.value;
|
|
1710
|
+
}
|
|
1711
|
+
fail("expected number after '+'");
|
|
1712
|
+
}
|
|
1713
|
+
if (tok.kind === "PUNCT" && tok.value === "{") {
|
|
1714
|
+
return parseOptionMessageLiteral(depth + 1);
|
|
1715
|
+
}
|
|
1716
|
+
if (tok.kind === "PUNCT" && tok.value === "[") {
|
|
1717
|
+
next();
|
|
1718
|
+
const arr = [];
|
|
1719
|
+
while (!(peek().kind === "PUNCT" && peek().value === "]")) {
|
|
1720
|
+
if (peek().kind === "EOF")
|
|
1721
|
+
fail("unterminated option list");
|
|
1722
|
+
arr.push(parseOptionValue(depth + 1));
|
|
1723
|
+
matchPunct(",");
|
|
1724
|
+
}
|
|
1725
|
+
expectPunct("]");
|
|
1726
|
+
return arr;
|
|
1727
|
+
}
|
|
1728
|
+
if (tok.kind === "IDENT") {
|
|
1729
|
+
next();
|
|
1730
|
+
if (tok.value === "true")
|
|
1731
|
+
return true;
|
|
1732
|
+
if (tok.value === "false")
|
|
1733
|
+
return false;
|
|
1734
|
+
return tok.value;
|
|
1735
|
+
}
|
|
1736
|
+
return fail(`expected option value, got ${tok.kind === "EOF" ? "EOF" : `'${tok.value}'`}`, tok);
|
|
1737
|
+
};
|
|
1738
|
+
const handlePossibleBaseUrlOption = (optName, optVal) => {
|
|
1739
|
+
const cleanName = optName.replace(/[()]/g, "").toLowerCase();
|
|
1740
|
+
if (typeof optVal === "string" &&
|
|
1741
|
+
(cleanName === "google.api.default_host" ||
|
|
1742
|
+
cleanName.endsWith(".default_host") ||
|
|
1743
|
+
cleanName === "default_host" ||
|
|
1744
|
+
cleanName === "base_url" ||
|
|
1745
|
+
cleanName.endsWith(".base_url"))) {
|
|
1746
|
+
const sanitized = sanitizeUrlString(optVal, ctx.secretValues, { requireHttp: true });
|
|
1747
|
+
if (sanitized.redacted)
|
|
1748
|
+
ctx.redactedSecrets = true;
|
|
1749
|
+
if (sanitized.valid && sanitized.safeUrl && !ctx.baseUrl) {
|
|
1750
|
+
ctx.baseUrl = sanitized.safeUrl;
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
};
|
|
1754
|
+
const parseOptionStatement = () => {
|
|
1755
|
+
expectIdent("option");
|
|
1756
|
+
const name = parseOptionName();
|
|
1757
|
+
expectPunct("=");
|
|
1758
|
+
const value = parseOptionValue(0);
|
|
1759
|
+
expectPunct(";");
|
|
1760
|
+
return { name, value };
|
|
1761
|
+
};
|
|
1762
|
+
const skipReservedOrExtensions = () => {
|
|
1763
|
+
next(); // 'reserved' or 'extensions'
|
|
1764
|
+
while (peek().kind !== "EOF") {
|
|
1765
|
+
if (matchPunct(";"))
|
|
1766
|
+
return;
|
|
1767
|
+
next();
|
|
1768
|
+
}
|
|
1769
|
+
fail("unterminated reserved/extensions statement");
|
|
1770
|
+
};
|
|
1771
|
+
const parseFieldOptions = () => {
|
|
1772
|
+
const opts = {};
|
|
1773
|
+
if (!matchPunct("["))
|
|
1774
|
+
return opts;
|
|
1775
|
+
while (!(peek().kind === "PUNCT" && peek().value === "]")) {
|
|
1776
|
+
if (peek().kind === "EOF")
|
|
1777
|
+
fail("unterminated field options");
|
|
1778
|
+
const name = parseOptionName();
|
|
1779
|
+
expectPunct("=");
|
|
1780
|
+
const value = parseOptionValue(0);
|
|
1781
|
+
if (!isUnsafeKey(name)) {
|
|
1782
|
+
opts[name] = value;
|
|
1783
|
+
}
|
|
1784
|
+
if (!matchPunct(","))
|
|
1785
|
+
break;
|
|
1786
|
+
}
|
|
1787
|
+
expectPunct("]");
|
|
1788
|
+
return opts;
|
|
1789
|
+
};
|
|
1790
|
+
const parseEnumBody = (enumName, fullName) => {
|
|
1791
|
+
expectPunct("{");
|
|
1792
|
+
const values = [];
|
|
1793
|
+
const seen = new Set();
|
|
1794
|
+
while (!(peek().kind === "PUNCT" && peek().value === "}")) {
|
|
1795
|
+
if (peek().kind === "EOF")
|
|
1796
|
+
fail(`unterminated enum '${enumName}'`);
|
|
1797
|
+
if (matchPunct(";"))
|
|
1798
|
+
continue;
|
|
1799
|
+
if (peek().kind === "IDENT" && peek().value === "option" && (peek(1).value === "(" || peek(2).value === "=" || peek(2).value === ".")) {
|
|
1800
|
+
parseOptionStatement();
|
|
1801
|
+
continue;
|
|
1802
|
+
}
|
|
1803
|
+
if (peek().kind === "IDENT" && peek().value === "reserved" && (peek(1).kind === "INT" || peek(1).kind === "STRING")) {
|
|
1804
|
+
skipReservedOrExtensions();
|
|
1805
|
+
continue;
|
|
1806
|
+
}
|
|
1807
|
+
const valName = expectIdent("enum value name");
|
|
1808
|
+
expectPunct("=");
|
|
1809
|
+
const numTok = peek();
|
|
1810
|
+
if (numTok.kind !== "INT") {
|
|
1811
|
+
fail(`expected enum integer value for '${valName}'`, numTok);
|
|
1812
|
+
}
|
|
1813
|
+
next();
|
|
1814
|
+
parseFieldOptions();
|
|
1815
|
+
expectPunct(";");
|
|
1816
|
+
if (isUnsafeKey(valName)) {
|
|
1817
|
+
pushWarning(ctx, `Filtered unsafe enum value "${valName}" in "${fullName}".`);
|
|
1818
|
+
continue;
|
|
1819
|
+
}
|
|
1820
|
+
if (!seen.has(valName)) {
|
|
1821
|
+
if (values.length >= MAX_ENUM_VALUES) {
|
|
1822
|
+
pushWarning(ctx, `Enum "${fullName}" truncated at ${MAX_ENUM_VALUES} values.`);
|
|
1823
|
+
}
|
|
1824
|
+
else {
|
|
1825
|
+
seen.add(valName);
|
|
1826
|
+
values.push(valName);
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
expectPunct("}");
|
|
1831
|
+
return values;
|
|
1832
|
+
};
|
|
1833
|
+
const skipBalancedBlock = (openChar, closeChar) => {
|
|
1834
|
+
expectPunct(openChar);
|
|
1835
|
+
let depth = 1;
|
|
1836
|
+
while (depth > 0) {
|
|
1837
|
+
const tok = peek();
|
|
1838
|
+
if (tok.kind === "EOF")
|
|
1839
|
+
fail(`unterminated '${openChar}...${closeChar}' block`);
|
|
1840
|
+
next();
|
|
1841
|
+
if (tok.kind === "PUNCT" && tok.value === openChar)
|
|
1842
|
+
depth += 1;
|
|
1843
|
+
else if (tok.kind === "PUNCT" && tok.value === closeChar)
|
|
1844
|
+
depth -= 1;
|
|
1845
|
+
}
|
|
1846
|
+
};
|
|
1847
|
+
const parseMessageBody = (msgName, fullName, depth) => {
|
|
1848
|
+
if (depth > MAX_PARSER_NESTING) {
|
|
1849
|
+
fail(`message nesting depth (${MAX_PARSER_NESTING}) exceeded at '${fullName}'`);
|
|
1850
|
+
}
|
|
1851
|
+
expectPunct("{");
|
|
1852
|
+
const fields = [];
|
|
1853
|
+
const nestedMessages = {};
|
|
1854
|
+
const nestedEnums = {};
|
|
1855
|
+
const recordField = (field, opts) => {
|
|
1856
|
+
if (isUnsafeKey(field.name) || isUnsafeKey(field.jsonName)) {
|
|
1857
|
+
pushWarning(ctx, `Filtered unsafe field name "${field.name}" in message "${fullName}".`);
|
|
1858
|
+
return;
|
|
1859
|
+
}
|
|
1860
|
+
if (fields.length >= MAX_FIELDS_PER_MESSAGE) {
|
|
1861
|
+
pushWarning(ctx, `Message "${fullName}" truncated at ${MAX_FIELDS_PER_MESSAGE} fields.`);
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
if (hasOwn(opts, "json_name") && typeof opts.json_name === "string") {
|
|
1865
|
+
const customJson = opts.json_name.replace(CONTROL_CHAR_GLOBAL_RE, "").trim();
|
|
1866
|
+
if (customJson && !isUnsafeKey(customJson)) {
|
|
1867
|
+
field.jsonName = customJson;
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
if (hasOwn(opts, "default")) {
|
|
1871
|
+
const rawDef = opts.default;
|
|
1872
|
+
const defStr = typeof rawDef === "string" ? sanitizeDecodedControlText(rawDef) : String(rawDef);
|
|
1873
|
+
const sensitiveField = isSensitiveFieldName(field.name) || isSensitiveFieldName(field.jsonName);
|
|
1874
|
+
if (sensitiveField || SENSITIVE_HEADER_VALUE_RE.test(defStr)) {
|
|
1875
|
+
ctx.redactedSecrets = true;
|
|
1876
|
+
recordSecretValue(ctx.secretValues, defStr);
|
|
1877
|
+
}
|
|
1878
|
+
else {
|
|
1879
|
+
const scrubbed = scrubText(defStr, ctx.secretValues);
|
|
1880
|
+
if (scrubbed.redacted)
|
|
1881
|
+
ctx.redactedSecrets = true;
|
|
1882
|
+
ctx.fieldDefaults.set(`${fullName}.${field.name}`, { defaultValue: scrubbed.value });
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
fields.push(field);
|
|
1886
|
+
};
|
|
1887
|
+
const parseSingleField = (repeated, optional, oneofGroup) => {
|
|
1888
|
+
// Handle proto2 `group` field if present
|
|
1889
|
+
if (peek().kind === "IDENT" &&
|
|
1890
|
+
peek().value === "group" &&
|
|
1891
|
+
peek(1).kind === "IDENT" &&
|
|
1892
|
+
peek(2).value === "=") {
|
|
1893
|
+
next();
|
|
1894
|
+
expectIdent("group name");
|
|
1895
|
+
expectPunct("=");
|
|
1896
|
+
parseProtoFieldNumber(next(), "group");
|
|
1897
|
+
parseFieldOptions();
|
|
1898
|
+
skipBalancedBlock("{", "}");
|
|
1899
|
+
return;
|
|
1900
|
+
}
|
|
1901
|
+
const rawType = parseQualifiedName();
|
|
1902
|
+
const fieldName = expectIdent("field name");
|
|
1903
|
+
expectPunct("=");
|
|
1904
|
+
const numTok = peek();
|
|
1905
|
+
const fieldNumber = parseProtoFieldNumber(numTok, fieldName);
|
|
1906
|
+
next();
|
|
1907
|
+
const opts = parseFieldOptions();
|
|
1908
|
+
expectPunct(";");
|
|
1909
|
+
const normalizedType = rawType.startsWith(".") ? rawType.slice(1) : rawType;
|
|
1910
|
+
const field = {
|
|
1911
|
+
name: fieldName,
|
|
1912
|
+
jsonName: snakeToLowerCamel(fieldName),
|
|
1913
|
+
number: fieldNumber,
|
|
1914
|
+
type: normalizedType,
|
|
1915
|
+
repeated,
|
|
1916
|
+
optional,
|
|
1917
|
+
...(oneofGroup ? { oneofGroup } : {})
|
|
1918
|
+
};
|
|
1919
|
+
recordField(field, opts);
|
|
1920
|
+
};
|
|
1921
|
+
while (!(peek().kind === "PUNCT" && peek().value === "}")) {
|
|
1922
|
+
if (peek().kind === "EOF")
|
|
1923
|
+
fail(`unterminated message '${msgName}'`);
|
|
1924
|
+
if (matchPunct(";"))
|
|
1925
|
+
continue;
|
|
1926
|
+
const t0 = peek(0);
|
|
1927
|
+
const t1 = peek(1);
|
|
1928
|
+
const t2 = peek(2);
|
|
1929
|
+
// Nested message
|
|
1930
|
+
if (t0.kind === "IDENT" && t0.value === "message" && t1.kind === "IDENT" && t2.value === "{") {
|
|
1931
|
+
next();
|
|
1932
|
+
const nestedName = expectIdent("nested message name");
|
|
1933
|
+
const nestedFull = `${fullName}.${nestedName}`;
|
|
1934
|
+
if (ctx.messageCount >= MAX_MESSAGES) {
|
|
1935
|
+
pushWarning(ctx, `Message limit (${MAX_MESSAGES}) reached; skipped "${nestedFull}".`);
|
|
1936
|
+
skipBalancedBlock("{", "}");
|
|
1937
|
+
continue;
|
|
1938
|
+
}
|
|
1939
|
+
ctx.messageCount += 1;
|
|
1940
|
+
const nestedMsg = parseMessageBody(nestedName, nestedFull, depth + 1);
|
|
1941
|
+
if (isUnsafeKey(nestedName)) {
|
|
1942
|
+
pushWarning(ctx, `Filtered unsafe nested message "${nestedName}".`);
|
|
1943
|
+
}
|
|
1944
|
+
else {
|
|
1945
|
+
nestedMessages[nestedName] = nestedMsg;
|
|
1946
|
+
ctx.messagesByFullName.set(nestedFull, nestedMsg);
|
|
1947
|
+
}
|
|
1948
|
+
continue;
|
|
1949
|
+
}
|
|
1950
|
+
// Nested enum
|
|
1951
|
+
if (t0.kind === "IDENT" && t0.value === "enum" && t1.kind === "IDENT" && t2.value === "{") {
|
|
1952
|
+
next();
|
|
1953
|
+
const nestedEnumName = expectIdent("nested enum name");
|
|
1954
|
+
const nestedEnumFull = `${fullName}.${nestedEnumName}`;
|
|
1955
|
+
const vals = parseEnumBody(nestedEnumName, nestedEnumFull);
|
|
1956
|
+
if (isUnsafeKey(nestedEnumName)) {
|
|
1957
|
+
pushWarning(ctx, `Filtered unsafe nested enum "${nestedEnumName}".`);
|
|
1958
|
+
}
|
|
1959
|
+
else {
|
|
1960
|
+
nestedEnums[nestedEnumName] = vals;
|
|
1961
|
+
ctx.enumsByFullName.set(nestedEnumFull, vals);
|
|
1962
|
+
}
|
|
1963
|
+
continue;
|
|
1964
|
+
}
|
|
1965
|
+
// oneof block
|
|
1966
|
+
if (t0.kind === "IDENT" && t0.value === "oneof" && t1.kind === "IDENT" && t2.value === "{") {
|
|
1967
|
+
next();
|
|
1968
|
+
const groupName = expectIdent("oneof name");
|
|
1969
|
+
const safeGroup = isUnsafeKey(groupName) ? undefined : groupName;
|
|
1970
|
+
if (!safeGroup) {
|
|
1971
|
+
pushWarning(ctx, `Filtered unsafe oneof group "${groupName}" in "${fullName}".`);
|
|
1972
|
+
}
|
|
1973
|
+
expectPunct("{");
|
|
1974
|
+
while (!(peek().kind === "PUNCT" && peek().value === "}")) {
|
|
1975
|
+
if (peek().kind === "EOF")
|
|
1976
|
+
fail(`unterminated oneof '${groupName}'`);
|
|
1977
|
+
if (matchPunct(";"))
|
|
1978
|
+
continue;
|
|
1979
|
+
if (peek().kind === "IDENT" &&
|
|
1980
|
+
peek().value === "option" &&
|
|
1981
|
+
(peek(1).value === "(" || peek(2).value === "=" || peek(2).value === ".")) {
|
|
1982
|
+
parseOptionStatement();
|
|
1983
|
+
continue;
|
|
1984
|
+
}
|
|
1985
|
+
if (safeGroup) {
|
|
1986
|
+
parseSingleField(false, true, safeGroup);
|
|
1987
|
+
}
|
|
1988
|
+
else {
|
|
1989
|
+
// Skip fields inside unsafe oneof group
|
|
1990
|
+
parseQualifiedName();
|
|
1991
|
+
expectIdent("field name");
|
|
1992
|
+
expectPunct("=");
|
|
1993
|
+
next();
|
|
1994
|
+
parseFieldOptions();
|
|
1995
|
+
expectPunct(";");
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
expectPunct("}");
|
|
1999
|
+
continue;
|
|
2000
|
+
}
|
|
2001
|
+
// map<K, V> field
|
|
2002
|
+
if (t0.kind === "IDENT" && t0.value === "map" && t1.kind === "PUNCT" && t1.value === "<") {
|
|
2003
|
+
next();
|
|
2004
|
+
expectPunct("<");
|
|
2005
|
+
const keyType = expectIdent("map key type");
|
|
2006
|
+
expectPunct(",");
|
|
2007
|
+
const rawValType = parseQualifiedName();
|
|
2008
|
+
expectPunct(">");
|
|
2009
|
+
const valType = rawValType.startsWith(".") ? rawValType.slice(1) : rawValType;
|
|
2010
|
+
const fieldName = expectIdent("map field name");
|
|
2011
|
+
expectPunct("=");
|
|
2012
|
+
const numTok = peek();
|
|
2013
|
+
const fieldNumber = parseProtoFieldNumber(numTok, `map ${fieldName}`);
|
|
2014
|
+
next();
|
|
2015
|
+
const opts = parseFieldOptions();
|
|
2016
|
+
expectPunct(";");
|
|
2017
|
+
const field = {
|
|
2018
|
+
name: fieldName,
|
|
2019
|
+
jsonName: snakeToLowerCamel(fieldName),
|
|
2020
|
+
number: fieldNumber,
|
|
2021
|
+
type: `map<${keyType}, ${valType}>`,
|
|
2022
|
+
repeated: false,
|
|
2023
|
+
optional: false,
|
|
2024
|
+
mapKeyType: keyType,
|
|
2025
|
+
mapValueType: valType
|
|
2026
|
+
};
|
|
2027
|
+
recordField(field, opts);
|
|
2028
|
+
continue;
|
|
2029
|
+
}
|
|
2030
|
+
// option statement inside message
|
|
2031
|
+
if (t0.kind === "IDENT" &&
|
|
2032
|
+
t0.value === "option" &&
|
|
2033
|
+
(t1.value === "(" || t2.value === "=" || t2.value === ".")) {
|
|
2034
|
+
parseOptionStatement();
|
|
2035
|
+
continue;
|
|
2036
|
+
}
|
|
2037
|
+
// reserved / extensions
|
|
2038
|
+
if (t0.kind === "IDENT" && t0.value === "reserved" && (t1.kind === "INT" || t1.kind === "STRING")) {
|
|
2039
|
+
skipReservedOrExtensions();
|
|
2040
|
+
continue;
|
|
2041
|
+
}
|
|
2042
|
+
if (t0.kind === "IDENT" && t0.value === "extensions" && t1.kind === "INT") {
|
|
2043
|
+
skipReservedOrExtensions();
|
|
2044
|
+
continue;
|
|
2045
|
+
}
|
|
2046
|
+
// extend block inside message
|
|
2047
|
+
if (t0.kind === "IDENT" && t0.value === "extend" && (t1.kind === "IDENT" || t1.value === ".")) {
|
|
2048
|
+
next();
|
|
2049
|
+
parseQualifiedName();
|
|
2050
|
+
skipBalancedBlock("{", "}");
|
|
2051
|
+
continue;
|
|
2052
|
+
}
|
|
2053
|
+
// Field with label (repeated | optional | required)
|
|
2054
|
+
if (t0.kind === "IDENT" &&
|
|
2055
|
+
(t0.value === "repeated" || t0.value === "optional" || t0.value === "required") &&
|
|
2056
|
+
t1.value !== "=") {
|
|
2057
|
+
const label = next().value;
|
|
2058
|
+
parseSingleField(label === "repeated", label === "optional", undefined);
|
|
2059
|
+
continue;
|
|
2060
|
+
}
|
|
2061
|
+
// Unlabeled field
|
|
2062
|
+
parseSingleField(false, false, undefined);
|
|
2063
|
+
}
|
|
2064
|
+
expectPunct("}");
|
|
2065
|
+
return {
|
|
2066
|
+
name: msgName,
|
|
2067
|
+
fullName,
|
|
2068
|
+
fields,
|
|
2069
|
+
nestedMessages,
|
|
2070
|
+
nestedEnums
|
|
2071
|
+
};
|
|
2072
|
+
};
|
|
2073
|
+
const topMessages = {};
|
|
2074
|
+
const topEnums = {};
|
|
2075
|
+
const rawRpcs = [];
|
|
2076
|
+
const parseServiceBody = (serviceName) => {
|
|
2077
|
+
expectPunct("{");
|
|
2078
|
+
const fullService = ctx.packageName ? `${ctx.packageName}.${serviceName}` : serviceName;
|
|
2079
|
+
while (!(peek().kind === "PUNCT" && peek().value === "}")) {
|
|
2080
|
+
if (peek().kind === "EOF")
|
|
2081
|
+
fail(`unterminated service '${serviceName}'`);
|
|
2082
|
+
if (matchPunct(";"))
|
|
2083
|
+
continue;
|
|
2084
|
+
if (peek().kind === "IDENT" && peek().value === "option") {
|
|
2085
|
+
const opt = parseOptionStatement();
|
|
2086
|
+
handlePossibleBaseUrlOption(opt.name, opt.value);
|
|
2087
|
+
continue;
|
|
2088
|
+
}
|
|
2089
|
+
if (peek().kind === "IDENT" && peek().value === "rpc") {
|
|
2090
|
+
next();
|
|
2091
|
+
const rpcName = expectIdent("rpc method name");
|
|
2092
|
+
expectPunct("(");
|
|
2093
|
+
let clientStreaming = false;
|
|
2094
|
+
if (peek().kind === "IDENT" && peek().value === "stream" && peek(1).value !== ")") {
|
|
2095
|
+
next();
|
|
2096
|
+
clientStreaming = true;
|
|
2097
|
+
}
|
|
2098
|
+
const rawReqType = parseQualifiedName();
|
|
2099
|
+
expectPunct(")");
|
|
2100
|
+
const returnsKw = expectIdent("'returns'");
|
|
2101
|
+
if (returnsKw !== "returns") {
|
|
2102
|
+
fail(`expected 'returns' in rpc '${rpcName}', got '${returnsKw}'`);
|
|
2103
|
+
}
|
|
2104
|
+
expectPunct("(");
|
|
2105
|
+
let serverStreaming = false;
|
|
2106
|
+
if (peek().kind === "IDENT" && peek().value === "stream" && peek(1).value !== ")") {
|
|
2107
|
+
next();
|
|
2108
|
+
serverStreaming = true;
|
|
2109
|
+
}
|
|
2110
|
+
const rawResType = parseQualifiedName();
|
|
2111
|
+
expectPunct(")");
|
|
2112
|
+
const httpRules = [];
|
|
2113
|
+
if (matchPunct("{")) {
|
|
2114
|
+
while (!(peek().kind === "PUNCT" && peek().value === "}")) {
|
|
2115
|
+
if (peek().kind === "EOF")
|
|
2116
|
+
fail(`unterminated rpc options block for '${rpcName}'`);
|
|
2117
|
+
if (matchPunct(";"))
|
|
2118
|
+
continue;
|
|
2119
|
+
if (peek().kind === "IDENT" && peek().value === "option") {
|
|
2120
|
+
const opt = parseOptionStatement();
|
|
2121
|
+
const cleanOptName = opt.name.replace(/[()]/g, "");
|
|
2122
|
+
if (cleanOptName === "google.api.http" || cleanOptName.endsWith(".google.api.http")) {
|
|
2123
|
+
httpRules.push(...extractHttpRulesFromOption(opt.value, ctx, true));
|
|
2124
|
+
}
|
|
2125
|
+
else {
|
|
2126
|
+
handlePossibleBaseUrlOption(opt.name, opt.value);
|
|
2127
|
+
}
|
|
2128
|
+
continue;
|
|
2129
|
+
}
|
|
2130
|
+
fail(`unexpected token '${peek().value}' inside rpc '${rpcName}' block`);
|
|
2131
|
+
}
|
|
2132
|
+
expectPunct("}");
|
|
2133
|
+
matchPunct(";");
|
|
2134
|
+
}
|
|
2135
|
+
else {
|
|
2136
|
+
expectPunct(";");
|
|
2137
|
+
}
|
|
2138
|
+
if (isUnsafeKey(serviceName) || isUnsafeKey(rpcName)) {
|
|
2139
|
+
pushWarning(ctx, `Filtered unsafe RPC declaration "${serviceName}.${rpcName}".`);
|
|
2140
|
+
continue;
|
|
2141
|
+
}
|
|
2142
|
+
if (rawRpcs.length >= MAX_RPCS) {
|
|
2143
|
+
pushWarning(ctx, `RPC limit (${MAX_RPCS}) reached; skipped remaining RPC declarations.`);
|
|
2144
|
+
continue;
|
|
2145
|
+
}
|
|
2146
|
+
rawRpcs.push({
|
|
2147
|
+
service: serviceName,
|
|
2148
|
+
fullService,
|
|
2149
|
+
name: rpcName,
|
|
2150
|
+
requestType: rawReqType.startsWith(".") ? rawReqType.slice(1) : rawReqType,
|
|
2151
|
+
responseType: rawResType.startsWith(".") ? rawResType.slice(1) : rawResType,
|
|
2152
|
+
clientStreaming,
|
|
2153
|
+
serverStreaming,
|
|
2154
|
+
httpRules
|
|
2155
|
+
});
|
|
2156
|
+
continue;
|
|
2157
|
+
}
|
|
2158
|
+
fail(`unexpected token '${peek().value}' in service '${serviceName}'`);
|
|
2159
|
+
}
|
|
2160
|
+
expectPunct("}");
|
|
2161
|
+
};
|
|
2162
|
+
// Top-level parse loop
|
|
2163
|
+
while (peek().kind !== "EOF") {
|
|
2164
|
+
if (matchPunct(";"))
|
|
2165
|
+
continue;
|
|
2166
|
+
const tok = peek();
|
|
2167
|
+
if (tok.kind !== "IDENT") {
|
|
2168
|
+
fail(`unexpected top-level token '${tok.value}'`, tok);
|
|
2169
|
+
}
|
|
2170
|
+
if (tok.value === "syntax") {
|
|
2171
|
+
next();
|
|
2172
|
+
expectPunct("=");
|
|
2173
|
+
const syntaxVal = parseConcatString().trim();
|
|
2174
|
+
expectPunct(";");
|
|
2175
|
+
if (syntaxVal !== "proto2" && syntaxVal !== "proto3") {
|
|
2176
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported protobuf syntax "${scrubText(syntaxVal, ctx.secretValues).value}"; expected "proto2" or "proto3".`, { fallbackHint: 'Use syntax = "proto2"; or syntax = "proto3";.' });
|
|
2177
|
+
}
|
|
2178
|
+
ctx.syntax = syntaxVal;
|
|
2179
|
+
continue;
|
|
2180
|
+
}
|
|
2181
|
+
if (tok.value === "package") {
|
|
2182
|
+
next();
|
|
2183
|
+
const rawPkg = parseQualifiedName();
|
|
2184
|
+
expectPunct(";");
|
|
2185
|
+
const segments = rawPkg.split(".").filter((seg) => seg && !isUnsafeKey(seg));
|
|
2186
|
+
if (segments.length !== rawPkg.split(".").filter(Boolean).length) {
|
|
2187
|
+
pushWarning(ctx, "Filtered unsafe segment from protobuf package declaration.");
|
|
2188
|
+
}
|
|
2189
|
+
if (segments.length > 0) {
|
|
2190
|
+
ctx.packageName = segments.join(".");
|
|
2191
|
+
}
|
|
2192
|
+
continue;
|
|
2193
|
+
}
|
|
2194
|
+
if (tok.value === "import") {
|
|
2195
|
+
next();
|
|
2196
|
+
if (peek().kind === "IDENT" && (peek().value === "weak" || peek().value === "public")) {
|
|
2197
|
+
next();
|
|
2198
|
+
}
|
|
2199
|
+
const importPath = parseConcatString();
|
|
2200
|
+
expectPunct(";");
|
|
2201
|
+
const scrubbedImport = scrubText(importPath.replace(CONTROL_CHAR_GLOBAL_RE, ""), ctx.secretValues);
|
|
2202
|
+
if (scrubbedImport.redacted)
|
|
2203
|
+
ctx.redactedSecrets = true;
|
|
2204
|
+
pushWarning(ctx, `Ignored external proto import "${scrubbedImport.value}" (external filesystem imports are never read).`);
|
|
2205
|
+
continue;
|
|
2206
|
+
}
|
|
2207
|
+
if (tok.value === "option") {
|
|
2208
|
+
const opt = parseOptionStatement();
|
|
2209
|
+
handlePossibleBaseUrlOption(opt.name, opt.value);
|
|
2210
|
+
continue;
|
|
2211
|
+
}
|
|
2212
|
+
if (tok.value === "message") {
|
|
2213
|
+
next();
|
|
2214
|
+
const msgName = expectIdent("message name");
|
|
2215
|
+
const fullName = ctx.packageName ? `${ctx.packageName}.${msgName}` : msgName;
|
|
2216
|
+
if (ctx.messageCount >= MAX_MESSAGES) {
|
|
2217
|
+
pushWarning(ctx, `Message limit (${MAX_MESSAGES}) reached; skipped "${fullName}".`);
|
|
2218
|
+
skipBalancedBlock("{", "}");
|
|
2219
|
+
continue;
|
|
2220
|
+
}
|
|
2221
|
+
ctx.messageCount += 1;
|
|
2222
|
+
const msg = parseMessageBody(msgName, fullName, 0);
|
|
2223
|
+
if (isUnsafeKey(msgName)) {
|
|
2224
|
+
pushWarning(ctx, `Filtered unsafe message "${msgName}".`);
|
|
2225
|
+
}
|
|
2226
|
+
else {
|
|
2227
|
+
topMessages[msgName] = msg;
|
|
2228
|
+
ctx.messagesByFullName.set(fullName, msg);
|
|
2229
|
+
if (ctx.packageName) {
|
|
2230
|
+
// Also index by simple name if not already taken
|
|
2231
|
+
if (!ctx.messagesByFullName.has(msgName)) {
|
|
2232
|
+
ctx.messagesByFullName.set(msgName, msg);
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
continue;
|
|
2237
|
+
}
|
|
2238
|
+
if (tok.value === "enum") {
|
|
2239
|
+
next();
|
|
2240
|
+
const enumName = expectIdent("enum name");
|
|
2241
|
+
const fullName = ctx.packageName ? `${ctx.packageName}.${enumName}` : enumName;
|
|
2242
|
+
const values = parseEnumBody(enumName, fullName);
|
|
2243
|
+
if (isUnsafeKey(enumName)) {
|
|
2244
|
+
pushWarning(ctx, `Filtered unsafe enum "${enumName}".`);
|
|
2245
|
+
}
|
|
2246
|
+
else {
|
|
2247
|
+
topEnums[enumName] = values;
|
|
2248
|
+
ctx.enumsByFullName.set(fullName, values);
|
|
2249
|
+
if (ctx.packageName && !ctx.enumsByFullName.has(enumName)) {
|
|
2250
|
+
ctx.enumsByFullName.set(enumName, values);
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
continue;
|
|
2254
|
+
}
|
|
2255
|
+
if (tok.value === "service") {
|
|
2256
|
+
next();
|
|
2257
|
+
const serviceName = expectIdent("service name");
|
|
2258
|
+
parseServiceBody(serviceName);
|
|
2259
|
+
continue;
|
|
2260
|
+
}
|
|
2261
|
+
if (tok.value === "extend") {
|
|
2262
|
+
next();
|
|
2263
|
+
parseQualifiedName();
|
|
2264
|
+
skipBalancedBlock("{", "}");
|
|
2265
|
+
continue;
|
|
2266
|
+
}
|
|
2267
|
+
fail(`unexpected top-level declaration '${tok.value}'`, tok);
|
|
2268
|
+
}
|
|
2269
|
+
if (rawRpcs.length === 0) {
|
|
2270
|
+
throw new VibecodeError("CONTRACT_INVALID", "Protobuf specification contains no service RPC definitions.", { fallbackHint: "Define at least one 'service { rpc Method(Req) returns (Res); }' block." });
|
|
2271
|
+
}
|
|
2272
|
+
// Compile parsed RPCs into HTTP/ConnectRPC metadata, schemas, and samples
|
|
2273
|
+
const usedRpcIds = new Set();
|
|
2274
|
+
const nextRpcId = (seed) => {
|
|
2275
|
+
const base = slugify(seed, "rpc");
|
|
2276
|
+
if (!usedRpcIds.has(base)) {
|
|
2277
|
+
usedRpcIds.add(base);
|
|
2278
|
+
return base;
|
|
2279
|
+
}
|
|
2280
|
+
let idx = 2;
|
|
2281
|
+
while (usedRpcIds.has(`${base}-${idx}`))
|
|
2282
|
+
idx += 1;
|
|
2283
|
+
const candidate = `${base}-${idx}`;
|
|
2284
|
+
usedRpcIds.add(candidate);
|
|
2285
|
+
return candidate;
|
|
2286
|
+
};
|
|
2287
|
+
const rpcs = [];
|
|
2288
|
+
const defaultScope = ctx.packageName || "";
|
|
2289
|
+
for (const decl of rawRpcs) {
|
|
2290
|
+
if (decl.clientStreaming || decl.serverStreaming) {
|
|
2291
|
+
const streamKind = decl.clientStreaming && decl.serverStreaming
|
|
2292
|
+
? "bidirectional"
|
|
2293
|
+
: decl.clientStreaming
|
|
2294
|
+
? "client"
|
|
2295
|
+
: "server";
|
|
2296
|
+
pushWarning(ctx, `RPC "${decl.fullService}/${decl.name}" uses ${streamKind} streaming and is skipped during HTTP invariant compilation.`);
|
|
2297
|
+
}
|
|
2298
|
+
const reqMsg = resolveMessageType(decl.requestType, defaultScope, ctx);
|
|
2299
|
+
const responseSchema = compileRootTypeSchema(decl.responseType, defaultScope, ctx);
|
|
2300
|
+
const bindings = decl.httpRules.length > 0 ? decl.httpRules.map((rule) => ({ rule })) : [{}];
|
|
2301
|
+
for (let bIdx = 0; bIdx < bindings.length; bIdx += 1) {
|
|
2302
|
+
if (rpcs.length >= MAX_RPCS) {
|
|
2303
|
+
pushWarning(ctx, `RPC limit (${MAX_RPCS}) reached; truncated additional HTTP bindings.`);
|
|
2304
|
+
break;
|
|
2305
|
+
}
|
|
2306
|
+
const binding = bindings[bIdx];
|
|
2307
|
+
let method = "POST";
|
|
2308
|
+
let httpPath = `/${decl.fullService}/${decl.name}`;
|
|
2309
|
+
let bodyField;
|
|
2310
|
+
let requestSchema;
|
|
2311
|
+
let samplePayload;
|
|
2312
|
+
if (binding.rule) {
|
|
2313
|
+
method = binding.rule.method;
|
|
2314
|
+
const normalized = normalizeHttpPathTemplate(binding.rule.pathTemplate, reqMsg, ctx);
|
|
2315
|
+
httpPath = normalized.path;
|
|
2316
|
+
bodyField = binding.rule.bodyField;
|
|
2317
|
+
if (bodyField) {
|
|
2318
|
+
if (method === "GET" || method === "HEAD") {
|
|
2319
|
+
pushWarning(ctx, `RPC "${decl.fullService}/${decl.name}" specifies google.api.http body on ${method}; ignoring request body for HTTP compatibility.`);
|
|
2320
|
+
requestSchema = compileRootTypeSchema(decl.requestType, defaultScope, ctx);
|
|
2321
|
+
samplePayload = undefined;
|
|
2322
|
+
}
|
|
2323
|
+
else if (bodyField === "*") {
|
|
2324
|
+
requestSchema = compileRootTypeSchema(decl.requestType, defaultScope, ctx, normalized.boundFields);
|
|
2325
|
+
samplePayload = reqMsg
|
|
2326
|
+
? synthesizeMessageSampleInternal(reqMsg, ctx, new Set(), 0, normalized.boundFields)
|
|
2327
|
+
: wellKnownTypeSample(decl.requestType) ?? {};
|
|
2328
|
+
}
|
|
2329
|
+
else {
|
|
2330
|
+
const matchedField = reqMsg?.fields.find((f) => f.name === bodyField || f.jsonName === bodyField);
|
|
2331
|
+
if (matchedField) {
|
|
2332
|
+
requestSchema = compileRootTypeSchema(matchedField.type, reqMsg?.fullName || defaultScope, ctx);
|
|
2333
|
+
const sensitive = isSensitiveFieldName(matchedField.name) || isSensitiveFieldName(matchedField.jsonName);
|
|
2334
|
+
samplePayload = synthesizeTypeSampleInternal(matchedField.type, reqMsg?.fullName || defaultScope, ctx, new Set(), 0, ctx.fieldDefaults.get(`${reqMsg?.fullName}.${matchedField.name}`)?.defaultValue, sensitive);
|
|
2335
|
+
if (samplePayload === undefined)
|
|
2336
|
+
samplePayload = {};
|
|
2337
|
+
}
|
|
2338
|
+
else {
|
|
2339
|
+
pushWarning(ctx, `RPC "${decl.fullService}/${decl.name}" google.api.http body field "${scrubText(bodyField, ctx.secretValues).value}" not found on "${decl.requestType}".`);
|
|
2340
|
+
requestSchema = compileRootTypeSchema(decl.requestType, defaultScope, ctx);
|
|
2341
|
+
samplePayload = {};
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
else {
|
|
2346
|
+
// No `body` specified on google.api.http: no JSON request body
|
|
2347
|
+
requestSchema = compileRootTypeSchema(decl.requestType, defaultScope, ctx);
|
|
2348
|
+
samplePayload = undefined;
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
else {
|
|
2352
|
+
// Default ConnectRPC / gRPC-JSON POST /<pkg>.<Service>/<Method>
|
|
2353
|
+
requestSchema = compileRootTypeSchema(decl.requestType, defaultScope, ctx);
|
|
2354
|
+
samplePayload = reqMsg
|
|
2355
|
+
? synthesizeMessageSampleInternal(reqMsg, ctx, new Set(), 0)
|
|
2356
|
+
: wellKnownTypeSample(decl.requestType) ?? {};
|
|
2357
|
+
}
|
|
2358
|
+
const scrubbedSample = samplePayload !== undefined ? scrubValueDeep(samplePayload, ctx.secretValues) : undefined;
|
|
2359
|
+
if (scrubbedSample?.redacted)
|
|
2360
|
+
ctx.redactedSecrets = true;
|
|
2361
|
+
const reqSchemaRes = requestSchema ? scrubSchemaDeep(requestSchema, ctx.secretValues) : undefined;
|
|
2362
|
+
if (reqSchemaRes?.redacted)
|
|
2363
|
+
ctx.redactedSecrets = true;
|
|
2364
|
+
const scrubbedReqSchema = reqSchemaRes ? reqSchemaRes.value : undefined;
|
|
2365
|
+
const resSchemaRes = scrubSchemaDeep(responseSchema, ctx.secretValues);
|
|
2366
|
+
if (resSchemaRes.redacted)
|
|
2367
|
+
ctx.redactedSecrets = true;
|
|
2368
|
+
const scrubbedResSchema = resSchemaRes.value;
|
|
2369
|
+
const idSeed = bIdx === 0 ? `${decl.service}-${decl.name}` : `${decl.service}-${decl.name}-binding-${bIdx + 1}`;
|
|
2370
|
+
rpcs.push({
|
|
2371
|
+
id: nextRpcId(idSeed),
|
|
2372
|
+
service: decl.service,
|
|
2373
|
+
fullService: decl.fullService,
|
|
2374
|
+
name: decl.name,
|
|
2375
|
+
requestType: decl.requestType,
|
|
2376
|
+
responseType: decl.responseType,
|
|
2377
|
+
clientStreaming: decl.clientStreaming,
|
|
2378
|
+
serverStreaming: decl.serverStreaming,
|
|
2379
|
+
method,
|
|
2380
|
+
path: scrubText(httpPath, ctx.secretValues).value,
|
|
2381
|
+
...(bodyField ? { bodyField: scrubText(sanitizeDecodedControlText(bodyField), ctx.secretValues).value } : {}),
|
|
2382
|
+
...(scrubbedReqSchema ? { requestSchema: scrubbedReqSchema } : {}),
|
|
2383
|
+
...(scrubbedSample !== undefined ? { samplePayload: scrubbedSample.value } : {}),
|
|
2384
|
+
responseSchema: scrubbedResSchema
|
|
2385
|
+
});
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
// Final pass to guarantee any secret discovered anywhere is scrubbed across warnings, baseUrl, and RPCs
|
|
2389
|
+
const finalWarnings = ctx.warnings.map((w) => scrubText(w, ctx.secretValues).value);
|
|
2390
|
+
const finalBaseUrl = ctx.baseUrl ? scrubText(ctx.baseUrl, ctx.secretValues).value : undefined;
|
|
2391
|
+
const finalRpcs = rpcs.map((rpc) => ({
|
|
2392
|
+
...rpc,
|
|
2393
|
+
path: scrubText(rpc.path, ctx.secretValues).value,
|
|
2394
|
+
...(rpc.bodyField
|
|
2395
|
+
? { bodyField: scrubText(sanitizeDecodedControlText(rpc.bodyField), ctx.secretValues).value }
|
|
2396
|
+
: {}),
|
|
2397
|
+
...(rpc.samplePayload !== undefined
|
|
2398
|
+
? { samplePayload: scrubValueDeep(rpc.samplePayload, ctx.secretValues).value }
|
|
2399
|
+
: {}),
|
|
2400
|
+
...(rpc.requestSchema
|
|
2401
|
+
? { requestSchema: scrubSchemaDeep(rpc.requestSchema, ctx.secretValues).value }
|
|
2402
|
+
: {}),
|
|
2403
|
+
...(rpc.responseSchema
|
|
2404
|
+
? { responseSchema: scrubSchemaDeep(rpc.responseSchema, ctx.secretValues).value }
|
|
2405
|
+
: {})
|
|
2406
|
+
}));
|
|
2407
|
+
const spec = {
|
|
2408
|
+
syntax: ctx.syntax,
|
|
2409
|
+
...(ctx.packageName ? { packageName: ctx.packageName } : {}),
|
|
2410
|
+
...(finalBaseUrl ? { baseUrl: finalBaseUrl } : {}),
|
|
2411
|
+
messages: topMessages,
|
|
2412
|
+
enums: topEnums,
|
|
2413
|
+
rpcs: finalRpcs,
|
|
2414
|
+
warnings: finalWarnings
|
|
2415
|
+
};
|
|
2416
|
+
return {
|
|
2417
|
+
spec,
|
|
2418
|
+
secretValues: ctx.secretValues,
|
|
2419
|
+
redactedSecrets: ctx.redactedSecrets
|
|
2420
|
+
};
|
|
2421
|
+
}
|
|
2422
|
+
export function parseProtoSpec(rawText) {
|
|
2423
|
+
return parseProtoInternal(rawText).spec;
|
|
2424
|
+
}
|
|
2425
|
+
function looksLikeFilePath(trimmed) {
|
|
2426
|
+
if (/[\r\n{};]/.test(trimmed))
|
|
2427
|
+
return false;
|
|
2428
|
+
const ext = path.extname(trimmed).toLowerCase();
|
|
2429
|
+
if (ext === ".proto")
|
|
2430
|
+
return true;
|
|
2431
|
+
if (/^[A-Za-z]:[\\/]/.test(trimmed))
|
|
2432
|
+
return true;
|
|
2433
|
+
if (!trimmed.includes(" ") && (trimmed.includes("/") || trimmed.includes("\\")))
|
|
2434
|
+
return true;
|
|
2435
|
+
if (!trimmed.includes(" ") && !trimmed.includes("="))
|
|
2436
|
+
return true;
|
|
2437
|
+
return false;
|
|
2438
|
+
}
|
|
2439
|
+
function uniqueInvariantId(seed, used) {
|
|
2440
|
+
let id = slugify(seed, "proto");
|
|
2441
|
+
if (!id.startsWith("inv-"))
|
|
2442
|
+
id = `inv-${id}`;
|
|
2443
|
+
if (!used.has(id)) {
|
|
2444
|
+
used.add(id);
|
|
2445
|
+
return id;
|
|
2446
|
+
}
|
|
2447
|
+
let n = 2;
|
|
2448
|
+
while (used.has(`${id}-${n}`))
|
|
2449
|
+
n += 1;
|
|
2450
|
+
const out = `${id}-${n}`;
|
|
2451
|
+
used.add(out);
|
|
2452
|
+
return out;
|
|
2453
|
+
}
|
|
2454
|
+
function validateInvariantsOrThrow(invariants) {
|
|
2455
|
+
const contract = {
|
|
2456
|
+
schemaVersion: "0.2.0",
|
|
2457
|
+
target: {
|
|
2458
|
+
name: "proto",
|
|
2459
|
+
domains: ["api"],
|
|
2460
|
+
sources: [{ id: "src-1", kind: "proto", ref: "inline", meta: {} }]
|
|
2461
|
+
},
|
|
2462
|
+
artifacts: { root: ".vibecode/artifacts", files: {} },
|
|
2463
|
+
thresholds: {
|
|
2464
|
+
hardBehavioralParity: 1,
|
|
2465
|
+
softPerceptualParity: 0.85,
|
|
2466
|
+
softGateMode: "warn",
|
|
2467
|
+
defaults: {}
|
|
2468
|
+
},
|
|
2469
|
+
invariants
|
|
2470
|
+
};
|
|
2471
|
+
const res = validateContract(contract);
|
|
2472
|
+
if (!res.ok) {
|
|
2473
|
+
const err = res.errors[0];
|
|
2474
|
+
throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Proto ingestor produced invalid invariant: ${err.path} ${err.message}`, { details: res.errors });
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
export async function ingestProto(options = {}, _deps = {}) {
|
|
2478
|
+
if (typeof options.source !== "string" || !options.source.trim()) {
|
|
2479
|
+
throw new VibecodeError("TARGET_MISSING", "Protobuf ingestor requires --source <schema.proto|inline>.", { fallbackHint: "Pass a path to a .proto file or inline proto2/proto3 schema text." });
|
|
2480
|
+
}
|
|
2481
|
+
const cwd = options.cwd || process.cwd();
|
|
2482
|
+
const rawSource = options.source;
|
|
2483
|
+
const trimmedSource = rawSource.trim();
|
|
2484
|
+
let rawText = "";
|
|
2485
|
+
let isFileSource = false;
|
|
2486
|
+
if (!/[\r\n]/.test(trimmedSource) && !trimmedSource.includes("\0")) {
|
|
2487
|
+
const candidatePath = path.resolve(cwd, trimmedSource);
|
|
2488
|
+
let exists = false;
|
|
2489
|
+
try {
|
|
2490
|
+
exists = fs.existsSync(candidatePath);
|
|
2491
|
+
}
|
|
2492
|
+
catch {
|
|
2493
|
+
exists = false;
|
|
2494
|
+
}
|
|
2495
|
+
if (exists) {
|
|
2496
|
+
let stat;
|
|
2497
|
+
try {
|
|
2498
|
+
stat = fs.statSync(candidatePath);
|
|
2499
|
+
}
|
|
2500
|
+
catch (err) {
|
|
2501
|
+
throw new VibecodeError("CONTRACT_INVALID", `Failed to inspect protobuf source: ${errorMessage(err)}`, {
|
|
2502
|
+
fallbackHint: "Verify file permissions and path."
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
if (!stat.isFile()) {
|
|
2506
|
+
const safePath = scrubText(trimmedSource, new Set()).value;
|
|
2507
|
+
throw new VibecodeError("CONTRACT_INVALID", `Protobuf source path is a directory or non-file: ${safePath}`, {
|
|
2508
|
+
fallbackHint: "Point --source to a .proto file, not a directory."
|
|
2509
|
+
});
|
|
2510
|
+
}
|
|
2511
|
+
if (stat.size === 0) {
|
|
2512
|
+
const safePath = scrubText(trimmedSource, new Set()).value;
|
|
2513
|
+
throw new VibecodeError("CONTRACT_INVALID", `Protobuf source file is empty: ${safePath}`, {
|
|
2514
|
+
fallbackHint: "Provide a non-empty proto2 or proto3 schema file."
|
|
2515
|
+
});
|
|
2516
|
+
}
|
|
2517
|
+
if (stat.size > MAX_SOURCE_BYTES) {
|
|
2518
|
+
throw new VibecodeError("CONTRACT_INVALID", `Protobuf source file exceeds maximum size of ${MAX_SOURCE_BYTES} bytes.`, { fallbackHint: "Reduce the .proto file size below 2 MiB." });
|
|
2519
|
+
}
|
|
2520
|
+
let buf;
|
|
2521
|
+
try {
|
|
2522
|
+
buf = fs.readFileSync(candidatePath);
|
|
2523
|
+
}
|
|
2524
|
+
catch (err) {
|
|
2525
|
+
throw new VibecodeError("CONTRACT_INVALID", `Failed to read protobuf source file: ${errorMessage(err)}`, {
|
|
2526
|
+
fallbackHint: "Ensure the .proto file is readable."
|
|
2527
|
+
});
|
|
2528
|
+
}
|
|
2529
|
+
if (buf.length > MAX_SOURCE_BYTES) {
|
|
2530
|
+
throw new VibecodeError("CONTRACT_INVALID", `Protobuf source file exceeds maximum size of ${MAX_SOURCE_BYTES} bytes.`, { fallbackHint: "Reduce the .proto file size below 2 MiB." });
|
|
2531
|
+
}
|
|
2532
|
+
if (buf.includes(0)) {
|
|
2533
|
+
throw new VibecodeError("CONTRACT_INVALID", "Protobuf source file contains NUL bytes.", {
|
|
2534
|
+
fallbackHint: "Provide a UTF-8 text .proto file."
|
|
2535
|
+
});
|
|
2536
|
+
}
|
|
2537
|
+
rawText = buf.toString("utf8");
|
|
2538
|
+
isFileSource = true;
|
|
2539
|
+
}
|
|
2540
|
+
else if (looksLikeFilePath(trimmedSource)) {
|
|
2541
|
+
const safePath = scrubText(trimmedSource, new Set()).value;
|
|
2542
|
+
throw new VibecodeError("TARGET_MISSING", `Protobuf source file not found: ${safePath}`, {
|
|
2543
|
+
fallbackHint: "Verify the .proto file path exists or pass inline protobuf schema text."
|
|
2544
|
+
});
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
if (!isFileSource) {
|
|
2548
|
+
if (Buffer.byteLength(rawSource, "utf8") > MAX_SOURCE_BYTES) {
|
|
2549
|
+
throw new VibecodeError("CONTRACT_INVALID", `Inline protobuf payload exceeds maximum size of ${MAX_SOURCE_BYTES} bytes.`, { fallbackHint: "Reduce the protobuf schema size below 2 MiB." });
|
|
2550
|
+
}
|
|
2551
|
+
rawText = rawSource;
|
|
2552
|
+
}
|
|
2553
|
+
const parsedResult = parseProtoInternal(rawText);
|
|
2554
|
+
const { spec, secretValues } = parsedResult;
|
|
2555
|
+
let redactedSecrets = parsedResult.redactedSecrets;
|
|
2556
|
+
const warnings = spec.warnings.map((message) => ({
|
|
2557
|
+
code: "BRIDGE_FORMAT_WARNING",
|
|
2558
|
+
message
|
|
2559
|
+
}));
|
|
2560
|
+
const unaryRpcs = spec.rpcs.filter((rpc) => !rpc.clientStreaming && !rpc.serverStreaming);
|
|
2561
|
+
const skippedStreamingCount = spec.rpcs.length - unaryRpcs.length;
|
|
2562
|
+
if (unaryRpcs.length === 0) {
|
|
2563
|
+
throw new VibecodeError("CONTRACT_INVALID", "Protobuf specification contains only streaming RPCs; no unary HTTP invariants can be compiled.", {
|
|
2564
|
+
fallbackHint: "Define at least one unary RPC (without 'stream' on request or response) for HTTP/gRPC-JSON verification."
|
|
2565
|
+
});
|
|
2566
|
+
}
|
|
2567
|
+
// Resolve and sanitize baseUrl (options.baseUrl overrides spec.baseUrl)
|
|
2568
|
+
let safeBaseUrl = spec.baseUrl || "";
|
|
2569
|
+
if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
|
|
2570
|
+
const sanitizedBase = sanitizeUrlString(options.baseUrl, secretValues, { requireHttp: true });
|
|
2571
|
+
if (sanitizedBase.redacted)
|
|
2572
|
+
redactedSecrets = true;
|
|
2573
|
+
if (sanitizedBase.valid && sanitizedBase.safeUrl) {
|
|
2574
|
+
safeBaseUrl = sanitizedBase.safeUrl;
|
|
2575
|
+
}
|
|
2576
|
+
else {
|
|
2577
|
+
warnings.push({
|
|
2578
|
+
code: "ADAPTER_DEGRADED",
|
|
2579
|
+
message: "Invalid protobuf baseUrl provided; falling back to spec default_host or path-only invariants."
|
|
2580
|
+
});
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
// Sanitize global option headers
|
|
2584
|
+
const globalSafeHeaders = {};
|
|
2585
|
+
if (isObject(options.headers)) {
|
|
2586
|
+
const headerWarnings = [];
|
|
2587
|
+
for (const [rawKey, rawVal] of Object.entries(options.headers)) {
|
|
2588
|
+
if (rawVal === undefined || rawVal === null)
|
|
2589
|
+
continue;
|
|
2590
|
+
const beforeSecrets = secretValues.size;
|
|
2591
|
+
const clean = sanitizeHeaderEntry(rawKey, String(rawVal), secretValues, headerWarnings);
|
|
2592
|
+
if (secretValues.size > beforeSecrets)
|
|
2593
|
+
redactedSecrets = true;
|
|
2594
|
+
if (clean) {
|
|
2595
|
+
if (clean.redacted)
|
|
2596
|
+
redactedSecrets = true;
|
|
2597
|
+
setHeaderCaseInsensitive(globalSafeHeaders, clean.name, clean.value);
|
|
2598
|
+
}
|
|
2599
|
+
else {
|
|
2600
|
+
const cleanName = rawKey.split(/[\r\n]/)[0]?.replace(CONTROL_CHAR_GLOBAL_RE, "").trim() ?? "";
|
|
2601
|
+
if (isProtoSensitiveHeader(cleanName) || SENSITIVE_HEADER_VALUE_RE.test(String(rawVal))) {
|
|
2602
|
+
redactedSecrets = true;
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
for (const msg of headerWarnings) {
|
|
2607
|
+
warnings.push({ code: "BRIDGE_FORMAT_WARNING", message: scrubText(msg, secretValues).value });
|
|
2608
|
+
}
|
|
2609
|
+
}
|
|
2610
|
+
const usedIds = new Set();
|
|
2611
|
+
const invariants = [];
|
|
2612
|
+
for (const rpc of unaryRpcs) {
|
|
2613
|
+
const mergedHeaders = redactHeaders(mergeHeaders({}, globalSafeHeaders), "strip");
|
|
2614
|
+
deleteHeaderCaseInsensitive(mergedHeaders, "host");
|
|
2615
|
+
const finalHeaders = {};
|
|
2616
|
+
for (const [hk, hv] of Object.entries(mergedHeaders)) {
|
|
2617
|
+
if (isUnsafeKey(hk) || isProtoSensitiveHeader(hk) || SENSITIVE_HEADER_VALUE_RE.test(hv)) {
|
|
2618
|
+
redactedSecrets = true;
|
|
2619
|
+
recordSecretValue(secretValues, hv);
|
|
2620
|
+
continue;
|
|
2621
|
+
}
|
|
2622
|
+
const scrubbedVal = scrubText(hv.replace(CONTROL_CHAR_GLOBAL_RE, "").trim(), secretValues);
|
|
2623
|
+
if (scrubbedVal.redacted)
|
|
2624
|
+
redactedSecrets = true;
|
|
2625
|
+
finalHeaders[hk] = scrubbedVal.value;
|
|
2626
|
+
}
|
|
2627
|
+
const bodyValue = rpc.samplePayload !== undefined ? scrubValueDeep(rpc.samplePayload, secretValues).value : undefined;
|
|
2628
|
+
if (bodyValue !== undefined && !hasHeaderCaseInsensitive(finalHeaders, "content-type")) {
|
|
2629
|
+
finalHeaders["content-type"] = "application/json";
|
|
2630
|
+
}
|
|
2631
|
+
const resSchemaRes = rpc.responseSchema
|
|
2632
|
+
? scrubSchemaDeep(rpc.responseSchema, secretValues)
|
|
2633
|
+
: undefined;
|
|
2634
|
+
if (resSchemaRes?.redacted)
|
|
2635
|
+
redactedSecrets = true;
|
|
2636
|
+
const responseSchemaValue = resSchemaRes ? resSchemaRes.value : undefined;
|
|
2637
|
+
const safePath = scrubText(rpc.path, secretValues).value;
|
|
2638
|
+
const input = {
|
|
2639
|
+
method: rpc.method,
|
|
2640
|
+
path: safePath,
|
|
2641
|
+
...(Object.keys(finalHeaders).length > 0 ? { headers: finalHeaders } : {}),
|
|
2642
|
+
...(bodyValue !== undefined ? { body: bodyValue } : {})
|
|
2643
|
+
};
|
|
2644
|
+
const expected = {
|
|
2645
|
+
status: 200,
|
|
2646
|
+
...(responseSchemaValue ? { jsonSchema: responseSchemaValue } : {})
|
|
2647
|
+
};
|
|
2648
|
+
const description = scrubText(`Proto RPC ${rpc.fullService}/${rpc.name} (${rpc.method} ${safePath})`, secretValues).value;
|
|
2649
|
+
const tags = ["api", "proto", "grpc", rpc.method.toLowerCase()];
|
|
2650
|
+
invariants.push({
|
|
2651
|
+
id: uniqueInvariantId(`inv-proto-${rpc.id}`, usedIds),
|
|
2652
|
+
domain: "api",
|
|
2653
|
+
type: "http",
|
|
2654
|
+
severity: "hard",
|
|
2655
|
+
description,
|
|
2656
|
+
tags,
|
|
2657
|
+
sourceId: "src-1",
|
|
2658
|
+
input,
|
|
2659
|
+
expected,
|
|
2660
|
+
tolerance: {}
|
|
2661
|
+
});
|
|
2662
|
+
}
|
|
2663
|
+
validateInvariantsOrThrow(invariants);
|
|
2664
|
+
const safeRef = scrubText(isFileSource ? trimmedSource : safeBaseUrl || "inline", secretValues).value;
|
|
2665
|
+
const finalWarnings = warnings.map((w) => ({
|
|
2666
|
+
...w,
|
|
2667
|
+
message: scrubText(w.message, secretValues).value
|
|
2668
|
+
}));
|
|
2669
|
+
return {
|
|
2670
|
+
domain: "api",
|
|
2671
|
+
sources: [
|
|
2672
|
+
{
|
|
2673
|
+
id: "src-1",
|
|
2674
|
+
kind: "proto",
|
|
2675
|
+
ref: safeRef,
|
|
2676
|
+
meta: {
|
|
2677
|
+
syntax: spec.syntax,
|
|
2678
|
+
...(spec.packageName ? { packageName: spec.packageName } : {}),
|
|
2679
|
+
...(safeBaseUrl ? { baseUrl: scrubText(safeBaseUrl, secretValues).value } : {}),
|
|
2680
|
+
rpcCount: unaryRpcs.length,
|
|
2681
|
+
...(skippedStreamingCount > 0 ? { skippedStreamingCount } : {}),
|
|
2682
|
+
...(redactedSecrets ? { redactedSecrets: true } : {})
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
],
|
|
2686
|
+
artifacts: { root: ".vibecode/artifacts", files: {} },
|
|
2687
|
+
invariants,
|
|
2688
|
+
warnings: finalWarnings
|
|
2689
|
+
};
|
|
2690
|
+
}
|