MCPcopy Create free account
hub / github.com/AnukarOP/claude-code-leaked / hasMalformedTokens

Function hasMalformedTokens

source code/utils/bash/shellQuote.ts:119–178  ·  view source on GitHub ↗
(
  command: string,
  parsed: ParseEntry[],
)

Source from the content-addressed store, hash-verified

117 * shell-quote's correct parsing of ambiguous input can be exploited.
118 */
119export function hasMalformedTokens(
120 command: string,
121 parsed: ParseEntry[],
122): boolean {
123 // Check for unterminated quotes in the original command. shell-quote drops
124 // an unmatched quote without leaving any trace in the tokens, so this must
125 // inspect the raw string. Walk with bash semantics: backslash escapes the
126 // next char outside single-quotes; no escapes inside single-quotes.
127 let inSingle = false
128 let inDouble = false
129 let doubleCount = 0
130 let singleCount = 0
131 for (let i = 0; i < command.length; i++) {
132 const c = command[i]
133 if (c === '\\' && !inSingle) {
134 i++
135 continue
136 }
137 if (c === '"' && !inSingle) {
138 doubleCount++
139 inDouble = !inDouble
140 } else if (c === "'" && !inDouble) {
141 singleCount++
142 inSingle = !inSingle
143 }
144 }
145 if (doubleCount % 2 !== 0 || singleCount % 2 !== 0) return true
146
147 for (const entry of parsed) {
148 if (typeof entry !== 'string') continue
149
150 // Check for unbalanced curly braces
151 const openBraces = (entry.match(/{/g) || []).length
152 const closeBraces = (entry.match(/}/g) || []).length
153 if (openBraces !== closeBraces) return true
154
155 // Check for unbalanced parentheses
156 const openParens = (entry.match(/\(/g) || []).length
157 const closeParens = (entry.match(/\)/g) || []).length
158 if (openParens !== closeParens) return true
159
160 // Check for unbalanced square brackets
161 const openBrackets = (entry.match(/\[/g) || []).length
162 const closeBrackets = (entry.match(/\]/g) || []).length
163 if (openBrackets !== closeBrackets) return true
164
165 // Check for unbalanced double quotes
166 // Count quotes that aren't escaped (preceded by backslash)
167 // A token with an odd number of unescaped quotes is malformed
168 // eslint-disable-next-line custom-rules/no-lookbehind-regex -- gated by hasCommandSeparator check at caller, runs on short per-token strings
169 const doubleQuotes = entry.match(/(?<!\\)"/g) || []
170 if (doubleQuotes.length % 2 !== 0) return true
171
172 // Check for unbalanced single quotes
173 // eslint-disable-next-line custom-rules/no-lookbehind-regex -- same as above
174 const singleQuotes = entry.match(/(?<!\\)'/g) || []
175 if (singleQuotes.length % 2 !== 0) return true
176 }

Callers 2

rearrangePipeCommandFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected