Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190import { parse } from 'sh-syntax';
export type BashIneligibleReason = | 'empty' | 'too-large' | 'too-many-ast-nodes' | 'too-deep' | 'parse-failure' | 'unsupported-syntax' | 'expansion' | 'redirection' | 'background' | 'environment-prefix' | 'declaration' | 'unknown-node';
export interface BashCommandSignature { executable: string; flags: string[]; signature: string; display: string;}
export type BashCommandAnalysis = | { eligible: true; signatures: BashCommandSignature[] } | { eligible: false; reason: BashIneligibleReason; detail?: string };
const MAX_COMMAND_BYTES = 64 * 1024;const MAX_NODES = 4096;const MAX_DEPTH = 32;const WILDCARD = '*';
type Token = | { kind: 'word'; value: string } | { kind: 'separator'; value: ';' | '&&' | '||' | '|' };
function ineligible(reason: BashIneligibleReason, detail?: string): BashCommandAnalysis { return { eligible: false, reason, ...(detail ? { detail } : {}) };}
function exceedsNestingLimit(source: string): boolean { let depth = 0; let quote = ''; for (let i = 0; i < source.length; i++) { const char = source[i]; if (char === '\\') { i++; continue; } if (quote) { if (char === quote) quote = ''; continue; } if (char === "'" || char === '"') { quote = char; continue; } if (char === '(' || char === '{') depth++; if (char === ')' || char === '}') depth = Math.max(0, depth - 1); if (depth > MAX_DEPTH) return true; } return false;}
/** Split shell separators while retaining only literal words. This is deliberately not an evaluator. */function tokenize(source: string): Token[] | BashCommandAnalysis { const tokens: Token[] = []; let value = ''; let quote = ''; const push = () => { if (value) tokens.push({ kind: 'word', value }); value = ''; }; const separator = (operator: ';' | '&&' | '||' | '|') => { push(); tokens.push({ kind: 'separator', value: operator }); }; const newline = () => { push(); if (tokens.length === 0 || tokens.at(-1)?.kind === 'separator') return; tokens.push({ kind: 'separator', value: ';' }); }; for (let i = 0; i < source.length; i++) { const c = source[i]; if (c === undefined) return ineligible('parse-failure', 'unexpected end'); if (quote) { if (c === quote) { quote = ''; continue; } if ((c === '$' || c === '`') && quote === '"') return ineligible('expansion'); if (c === '\\' && quote === '"' && source[i + 1] === '"') { value += '"'; i++; continue; } value += c; continue; } if (c === "'" || c === '"') { quote = c; continue; } if (c === '\\') { const escaped = source[++i]; if (escaped === undefined) return ineligible('parse-failure', 'trailing escape'); if (escaped !== '\n' && escaped !== '\r') value += escaped; continue; } if (c === '\n' || c === '\r') { if (c === '\r' && source[i + 1] === '\n') i++; newline(); continue; } if (/\s/.test(c)) { push(); continue; } if (c === ';' || c === '&' || c === '|') { const next = source[i + 1]; if (c === '&' && next === '&') { separator('&&'); i++; } else if (c === '|' && next === '|') { separator('||'); i++; } else if (c === '|' || c === ';') separator(c); else return ineligible('background'); continue; } if (c === '<' || c === '>') return ineligible('redirection'); if (c === '$' || c === '`' || c === '*' || c === '?' || c === '[') return ineligible('expansion'); if (c === '(' || c === ')' || c === '{' || c === '}') return ineligible('unsupported-syntax'); value += c; } if (quote) return ineligible('parse-failure', 'unterminated quote'); push(); return tokens;}
function rejectWord(token: Extract<Token, { kind: 'word' }>): BashCommandAnalysis | undefined { if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token.value)) return ineligible('environment-prefix'); if (token.value.startsWith('#') || token.value === '!') return ineligible('unsupported-syntax'); return undefined;}
function simpleSignature(words: Extract<Token, { kind: 'word' }>[]): BashCommandSignature | BashCommandAnalysis { if (!words.length) return ineligible('empty'); for (const word of words) { const rejected = rejectWord(word); if (rejected) return rejected; } const executable = words[0]?.value; if (!executable) return ineligible('empty'); if (!executable || ['function', 'if', 'then', 'case', 'for', 'while', 'until', 'select', 'export', 'local', 'readonly', 'declare', 'typeset'].includes(executable)) return ineligible('declaration'); const flags = new Set<string>(); const normalized: string[] = [executable]; let options = true; for (let i = 1; i < words.length; i++) { const word = words[i]?.value; if (word === undefined) return ineligible('unknown-node'); if (options && word === '--') { options = false; normalized.push('--'); continue; } if (options && /^--[^=]+=.*/.test(word)) { const name = word.slice(0, word.indexOf('=')); flags.add(name); normalized.push(`${name}=${WILDCARD}`); continue; } if (options && /^--[A-Za-z0-9][A-Za-z0-9_-]*$/.test(word)) { flags.add(word); normalized.push(word); continue; } if (options && /^-[A-Za-z?][A-Za-z0-9?]*$/.test(word)) { // Compact short options are ambiguous: retain them as entered, but still expose its exact name. flags.add(word); normalized.push(word); continue; } normalized.push(WILDCARD); } const signature = normalized.join(' '); return { executable, flags: [...flags].sort(), signature, display: signature };}
function analyzeTokens(tokens: Token[]): BashCommandAnalysis { const signatures: BashCommandSignature[] = []; let words: Extract<Token, { kind: 'word' }>[] = []; let nodes = 0; for (const token of tokens) { nodes++; if (nodes > MAX_NODES) return ineligible('too-many-ast-nodes'); if (token.kind === 'separator') { const result = simpleSignature(words); if ('eligible' in result) return result; signatures.push(result); words = []; continue; } words.push(token); } if (words.length > 0) { const result = simpleSignature(words); if ('eligible' in result) return result; signatures.push(result); } if (signatures.length === 0) return ineligible('empty'); const signatureKey = (item: BashCommandSignature) => JSON.stringify([item.executable, item.flags]); const unique = [...new Map(signatures.map((item) => [signatureKey(item), item])).values()] .sort((a, b) => signatureKey(a).localeCompare(signatureKey(b))); return { eligible: true, signatures: unique };}
/** Analyze a Bash command without executing or expanding it. */export async function analyzeBashCommand(command: string): Promise<BashCommandAnalysis> { if (!command.trim()) return ineligible('empty'); if (new TextEncoder().encode(command).byteLength > MAX_COMMAND_BYTES) return ineligible('too-large'); if (exceedsNestingLimit(command)) return ineligible('too-deep'); try { await parse(command, { recoverErrors: 0 }); } catch (error) { return ineligible('parse-failure', error instanceof Error ? error.message : String(error)); } const tokens = tokenize(command); if (!Array.isArray(tokens)) return tokens; return analyzeTokens(tokens);}
export const analyzeBashCommandScope = analyzeBashCommand;