Open History to see the last commit
1import type { InternalLogger } from '@tanstack/ai/adapter-internals'
2
3/**
4 * Single words that on their own signal "this is a credential".
5 * Matched after splitting a parameter name into camelCase/snake/kebab words.
6 * So `accessToken` → `['access', 'token']` → matches `token`,
7 * but `tokenizer` → `['tokenizer']` → does NOT match `token`.
8 */
9const DANGEROUS_WORDS = new Set<string>([
10 'password',
11 'passwd',
12 'pwd',
13 'passcode',
14 'secret',
15 'token',
16 'credential',
17 'credentials',
18 'authorization',
19 'jwt',
20 'bearer',
21])
22
23/**
24 * Compound patterns matched as substrings of the normalized (lowercased,
25 * separator-stripped) parameter name. Catches forms like `openai_api_key`,
26 * `x-api-key`, and `webhookSecret`.
27 */
28const COMPOUND_PATTERNS = [
29 'apikey',
30 'accesskey',
31 'authkey',
32 'privatekey',
33 'clientsecret',
34 'webhooksecret',
35] as const
36
37export interface SecretParameterInfo {
38 toolName: string
39 paramName: string
40 paramPath: Array<string>
41}
42
43export type SecretParameterHandler =
44 | 'warn'
45 | 'throw'
46 | 'ignore'
47 | ((info: SecretParameterInfo) => void)
48
49interface ToolLike {
50 name: string
51 inputSchema?: Record<string, unknown>
52}
53
54interface JsonSchemaLike {
55 type?: string
56 properties?: Record<string, JsonSchemaLike>
57 items?: JsonSchemaLike | Array<JsonSchemaLike>
58 anyOf?: Array<JsonSchemaLike>
59 oneOf?: Array<JsonSchemaLike>
60 allOf?: Array<JsonSchemaLike>
61 additionalProperties?: boolean | JsonSchemaLike
62 $ref?: string
63 $defs?: Record<string, JsonSchemaLike>
64 definitions?: Record<string, JsonSchemaLike>
65}
66
67function splitIntoWords(name: string): Array<string> {
68 return name
69 .replace(/[_\-\s]+/g, ' ')
70 .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
71 .toLowerCase()
72 .split(/\s+/)
73 .filter(Boolean)
74}
75
76function looksLikeSecret(name: string): boolean {
77 const words = splitIntoWords(name)
78 if (words.some((w) => DANGEROUS_WORDS.has(w))) return true
79 const normalized = name.replace(/[_\-\s]/g, '').toLowerCase()
80 return COMPOUND_PATTERNS.some((p) => normalized.includes(p))
81}
82
83function resolveRef(
84 ref: string,
85 root: JsonSchemaLike,
86): JsonSchemaLike | undefined {
87 const match = ref.match(/^#\/(\$defs|definitions)\/(.+)$/)
88 if (!match) return undefined
89 const bucket = match[1] as '$defs' | 'definitions'
90 const key = match[2]
91 return key === undefined ? undefined : root[bucket]?.[key]
92}
93
94function findSecretParams(
95 schema: JsonSchemaLike | undefined,
96 root: JsonSchemaLike,
97 seen: Set<object>,
98 path: Array<string>,
99 found: Array<{ path: Array<string>; name: string }>,
100): void {
101 if (!schema || typeof schema !== 'object' || seen.has(schema)) return
102 seen.add(schema)
103
104 if (schema.properties && typeof schema.properties === 'object') {
105 for (const [paramName, sub] of Object.entries(schema.properties)) {
106 if (looksLikeSecret(paramName)) {
107 found.push({ path: [...path, paramName], name: paramName })
108 }
109 findSecretParams(sub, root, seen, [...path, paramName], found)
110 }
111 }
112
113 if (Array.isArray(schema.items)) {
114 schema.items.forEach((s, i) =>
115 findSecretParams(s, root, seen, [...path, `[${i}]`], found),
116 )
117 } else if (schema.items && typeof schema.items === 'object') {
118 findSecretParams(schema.items, root, seen, [...path, '[]'], found)
119 }
120
121 if (
122 schema.additionalProperties &&
123 typeof schema.additionalProperties === 'object'
124 ) {
125 findSecretParams(schema.additionalProperties, root, seen, path, found)
126 }
127
128 for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {
129 const arr = schema[key]
130 if (Array.isArray(arr)) {
131 arr.forEach((s) => findSecretParams(s, root, seen, path, found))
132 }
133 }
134
135 if (typeof schema.$ref === 'string') {
136 const target = resolveRef(schema.$ref, root)
137 if (target) findSecretParams(target, root, seen, path, found)
138 }
139}
140
141function buildMessage(toolName: string, paramPath: Array<string>): string {
142 return (
143 `[TanStack AI Code Mode] Tool "${toolName}" has parameter "${paramPath.join('.')}" ` +
144 `that looks like a secret. Code Mode executes LLM-generated code — any ` +
145 `value passed through this parameter is accessible to generated code and ` +
146 `could be exfiltrated. Keep secrets in your server-side tool implementation ` +
147 `instead of passing them as tool parameters.`
148 )
149}
150
151/**
152 * Scan tool input schemas for parameter names that look like secrets.
153 * Emits a warning (or invokes the configured handler) for each match.
154 *
155 * Recurses into nested object properties, array items, union branches
156 * (anyOf/oneOf/allOf), additionalProperties, and `$ref` targets that
157 * resolve within the same schema's `$defs`/`definitions`.
158 *
159 * Best-effort heuristic, not a security boundary.
160 */
161export function warnIfBindingsExposeSecrets(
162 tools: Array<ToolLike>,
163 options: {
164 handler?: SecretParameterHandler
165 dedupCache?: Set<string>
166 /** Receives `'warn'` output instead of `console.warn` when provided. */
167 logger?: InternalLogger
168 } = {},
169): void {
170 const { handler = 'warn', dedupCache, logger } = options
171 if (handler === 'ignore') return
172
173 for (const tool of tools) {
174 const schema = tool.inputSchema as JsonSchemaLike | undefined
175 if (!schema) continue
176
177 const found: Array<{ path: Array<string>; name: string }> = []
178 findSecretParams(schema, schema, new Set(), [], found)
179
180 for (const entry of found) {
181 const dedupKey = `${tool.name}::${entry.path.join('.')}`
182 if (dedupCache) {
183 if (dedupCache.has(dedupKey)) continue
184 dedupCache.add(dedupKey)
185 }
186
187 const info: SecretParameterInfo = {
188 toolName: tool.name,
189 paramName: entry.name,
190 paramPath: entry.path,
191 }
192
193 if (typeof handler === 'function') {
194 handler(info)
195 } else if (handler === 'throw') {
196 throw new Error(buildMessage(tool.name, entry.path))
197 } else if (logger) {
198 logger.warn(buildMessage(tool.name, entry.path), { ...info })
199 } else {
200 console.warn(buildMessage(tool.name, entry.path))
201 }
202 }
203 }
204}