GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(opencode,core): close audit-v13 wave J-A shell classification fin… · anomalyco/opencode@4618e51

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/opencode
    • src/tool
      • shell.ts
    • test/tool
      • shell.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/opencode/src/tool/shell.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/tool/shell.ts
+164-12Lines changed: 164 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,18 @@ const FILES = new Set([
4242
"chmod",
4343
"chown",
4444
"cat",
45+
"head",
46+
"tail",
47+
"grep",
48+
"egrep",
49+
"fgrep",
50+
"awk",
51+
"gawk",
52+
"sed",
53+
"sort",
54+
"uniq",
55+
"source",
56+
".",
4557
// Leave PowerShell aliases out for now. Common ones like cat/cp/mv/rm/mkdir
4658
// already hit the entries above, and alias normalization should happen in one
4759
// place later so we do not risk double-prompting.
@@ -171,6 +183,13 @@ function decodeAnsiC(text: string) {
171183
scan += unicode[0].length
172184
continue
173185
}
186+
const wide = /^U([0-9A-Fa-f]{1,8})/.exec(rest)
187+
if (wide) {
188+
const code = Number.parseInt(wide[1], 16)
189+
value += String.fromCodePoint(code <= 0x10ffff ? code : 0xfffd)
190+
scan += wide[0].length
191+
continue
192+
}
174193
const next = rest[0]
175194
if (next === undefined) break
176195
value += ANSI_ESCAPES[next] ?? next
@@ -338,6 +357,21 @@ function flattenBraces(text: string) {
338357
continue
339358
}
340359
found = true
360+
let prefixStart = index
361+
while (prefixStart > 0 && /[A-Za-z0-9_.\/\\~=+-]/.test(text[prefixStart - 1])) prefixStart--
362+
let suffixEnd = end + 1
363+
while (suffixEnd < text.length && /[A-Za-z0-9_.\/\\~=+-]/.test(text[suffixEnd])) suffixEnd++
364+
const prefix = text.slice(prefixStart, index)
365+
const suffix = text.slice(end + 1, suffixEnd)
366+
if (prefix.length > 0 || suffix.length > 0) {
367+
// Bash concatenates the surrounding word with every expanded option (`ca{t,}` runs
368+
// `cat`); emit each candidate word so the real command name and its arguments stay
369+
// visible instead of hiding behind a mangled split of the same word.
370+
out = out.slice(0, out.length - prefix.length) + " "
371+
for (const option of braceOptions(text, index, end)) out += prefix + option + suffix + " "
372+
index = suffixEnd
373+
continue
374+
}
341375
out += " "
342376
let depth = 0
343377
let quote: "'" | '"' | undefined
@@ -369,6 +403,41 @@ function flattenBraces(text: string) {
369403
return { text: out, found }
370404
}
371405

406+
function braceOptions(text: string, start: number, end: number) {
407+
const options: string[] = []
408+
let acc = ""
409+
let depth = 0
410+
let quote: "'" | '"' | undefined
411+
for (let index = start + 1; index < end; index++) {
412+
const char = text[index]
413+
if (char === "\\" && index + 1 < end) {
414+
acc += char + text[index + 1]
415+
index++
416+
continue
417+
}
418+
if (quote) {
419+
acc += char
420+
if (char === quote) quote = undefined
421+
continue
422+
}
423+
if (char === "'" || char === '"') {
424+
quote = char
425+
acc += char
426+
continue
427+
}
428+
if (char === "{") depth++
429+
if (char === "}") depth--
430+
if (char === "," && depth === 0) {
431+
options.push(acc)
432+
acc = ""
433+
continue
434+
}
435+
acc += char
436+
}
437+
options.push(acc)
438+
return options
439+
}
440+
372441
// Classification must see the tokens the shell actually executes. It must use the
373442
// same position-free quote/escape canonicalization the persisted-grant matcher uses
374443
// (`Wildcard.unquote`), or a command name built from quotes (`cat""`) is invisible to
@@ -484,6 +553,10 @@ type Wrapper = {
484553
valueLong: Set<string>
485554
positionals: number
486555
shellString?: string
556+
// Options that consume an input file path (`xargs -a`, `parallel --arg-file`) must be
557+
// scanned: a stored wrapper grant would otherwise absorb that read.
558+
pathChars?: string
559+
pathLong?: Set<string>
487560
}
488561

489562
const WRAPPERS: Record<string, Wrapper> = {
@@ -496,6 +569,7 @@ const WRAPPERS: Record<string, Wrapper> = {
496569
stdbuf: { valueChars: "ioe", valueLong: new Set(["--input", "--output", "--error"]), positionals: 0 },
497570
xargs: {
498571
valueChars: "InPsaEdL",
572+
pathChars: "a",
499573
valueLong: new Set([
500574
"--arg-file",
501575
"--delimiter",
@@ -507,6 +581,7 @@ const WRAPPERS: Record<string, Wrapper> = {
507581
"--process-slot-var",
508582
"--replace",
509583
]),
584+
pathLong: new Set(["--arg-file"]),
510585
positionals: 0,
511586
},
512587
watch: { valueChars: "n", valueLong: new Set(["--interval"]), positionals: 0 },
@@ -535,6 +610,23 @@ const WRAPPERS: Record<string, Wrapper> = {
535610
},
536611
doas: { valueChars: "u", valueLong: new Set(), positionals: 0 },
537612
script: { valueChars: "", valueLong: new Set(), positionals: 0, shellString: "c" },
613+
parallel: {
614+
valueChars: "ajNS",
615+
pathChars: "a",
616+
valueLong: new Set(["--jobs", "--max-args", "--max-lines", "--arg-file", "--files"]),
617+
pathLong: new Set(["--arg-file"]),
618+
positionals: 0,
619+
},
620+
busybox: { valueChars: "", valueLong: new Set(), positionals: 0 },
621+
fakeroot: { valueChars: "", valueLong: new Set(), positionals: 0 },
622+
unshare: { valueChars: "", valueLong: new Set(), positionals: 0 },
623+
"ssh-agent": { valueChars: "at", valueLong: new Set(), positionals: 0 },
624+
"dbus-run-session": { valueChars: "", valueLong: new Set(), positionals: 0 },
625+
"systemd-inhibit": {
626+
valueChars: "",
627+
valueLong: new Set(["--what", "--who", "--why"]),
628+
positionals: 0,
629+
},
538630
}
539631

540632
type Effective = {
@@ -544,17 +636,26 @@ type Effective = {
544636
evalScript?: string
545637
wrapped?: boolean
546638
unresolved?: boolean
639+
extraPaths?: string[]
547640
}
548641

549642
function commandName(text: string) {
550643
const name = Wildcard.unquote(text)
551644
return name.startsWith("\\") ? name.slice(1) : name
552645
}
553646

647+
// A path-qualified command (`/usr/bin/cat`, `.\bin\type`) runs the same binary as its
648+
// bare name; lookups must normalize so an absolute path cannot dodge the FILES scan.
649+
function bareName(text: string) {
650+
const slash = Math.max(text.lastIndexOf("/"), text.lastIndexOf("\\"))
651+
return slash === -1 ? text : text.slice(slash + 1)
652+
}
653+
554654
// Strip one wrapper's options and positional prefixes so the next token is the command
555655
// it runs. An option shape the spec does not model returns `unresolved` instead of
556656
// guessing: a wrong guess would skip the real file command and hide the read.
557657
function stripWrapperOptions(parts: Part[], spec: Wrapper) {
658+
const paths: string[] = []
558659
let index = 1
559660
while (index < parts.length) {
560661
const text = parts[index].text
@@ -569,14 +670,18 @@ function stripWrapperOptions(parts: Part[], spec: Wrapper) {
569670
continue
570671
}
571672
if (spec.valueLong.has(text)) {
673+
if (spec.pathLong?.has(text)) {
674+
const value = parts[index + 1]?.text
675+
if (value !== undefined) paths.push(unquote(value))
676+
}
572677
index += 2
573678
continue
574679
}
575680
if (spec.shellString && text === "--command") {
576681
const value = parts[index + 1]?.text
577-
return { rest: parts.slice(index + 2), shell: value === undefined ? "" : unquote(value), wrapped: true }
682+
return { rest: parts.slice(index + 2), shell: value === undefined ? "" : unquote(value), wrapped: true, paths }
578683
}
579-
return { rest: parts, wrapped: true, unresolved: true }
684+
return { rest: parts, wrapped: true, unresolved: true, paths }
580685
}
581686
const body = text.slice(1)
582687
let consumed = false
@@ -589,18 +694,24 @@ function stripWrapperOptions(parts: Part[], spec: Wrapper) {
589694
rest: parts.slice(attached ? index + 1 : index + 2),
590695
shell: value === undefined ? "" : unquote(value),
591696
wrapped: true,
697+
paths,
592698
}
593699
}
594700
if (!spec.valueChars.includes(flag)) continue
595701
consumed = true
702+
if (spec.pathChars?.includes(flag)) {
703+
const attached = body.slice(position + 1)
704+
const value = attached || parts[index + 1]?.text
705+
if (value !== undefined) paths.push(unquote(value))
706+
}
596707
index += position === body.length - 1 ? 2 : 1
597708
break
598709
}
599710
if (!consumed) index += 1
600711
}
601712
let rest = parts.slice(index)
602713
for (let skip = 0; skip < spec.positionals && rest.length > 0; skip++) rest = rest.slice(1)
603-
return { rest, wrapped: true }
714+
return { rest, wrapped: true, paths }
604715
}
605716

606717
function stripEnvOptions(parts: Part[]) {
@@ -670,12 +781,14 @@ function effective(command: Part[]): Effective {
670781
let cwdTarget: Part | undefined
671782
let evalScript: string | undefined
672783
let wrapped = false
784+
let extraPaths: string[] = []
673785
for (let depth = 0; depth < 64 && parts.length > 0; depth++) {
674-
const name = commandName(parts[0].text)
786+
const name = bareName(commandName(parts[0].text))
675787
const spec = WRAPPERS[name]
676788
if (spec) {
677789
const stripped = stripWrapperOptions(parts, spec)
678790
wrapped = true
791+
if (stripped.paths?.length) extraPaths = extraPaths.concat(stripped.paths)
679792
if (stripped.unresolved) return { name: undefined, command, wrapped, unresolved: true }
680793
if (stripped.shell !== undefined) evalScript = stripped.shell
681794
parts = stripped.rest
@@ -695,14 +808,21 @@ function effective(command: Part[]): Effective {
695808
.map((item) => Wildcard.unquote(item.text))
696809
.join(" ")
697810
.trim()
698-
return { name, command: parts, cwdTarget, evalScript: script, wrapped: true }
811+
return { name, command: parts, cwdTarget, evalScript: script, wrapped: true, extraPaths }
699812
}
700813
break
701814
}
702-
if (parts.length > 0 && WRAPPERS[commandName(parts[0].text)]) {
703-
return { name: undefined, command, wrapped, unresolved: true }
815+
if (parts.length > 0 && WRAPPERS[bareName(commandName(parts[0].text))]) {
816+
return { name: undefined, command, wrapped, unresolved: true, extraPaths }
817+
}
818+
return {
819+
name: parts.length > 0 ? bareName(commandName(parts[0].text)) : undefined,
820+
command: parts,
821+
cwdTarget,
822+
evalScript,
823+
wrapped,
824+
extraPaths,
704825
}
705-
return { name: parts.length > 0 ? commandName(parts[0].text) : undefined, command: parts, cwdTarget, evalScript, wrapped }
706826
}
707827

708828
// A dynamic argument cannot be resolved to a real path, but if it still carries a
@@ -990,7 +1110,7 @@ export const ShellTool = Tool.define(
9901110
const classify: (
9911111
command: Part[],
9921112
depth?: number,
993-
) => Effect.Effect<{ name?: string; info: Effective }, never, never> = Effect.fnUntraced(function* (
1113+
) => Effect.Effect<{ name?: string; info: Effective; conservative?: boolean }, never, never> = Effect.fnUntraced(function* (
9941114
command: Part[],
9951115
depth = 0,
9961116
) {
@@ -1007,6 +1127,10 @@ export const ShellTool = Tool.define(
10071127
)
10081128
if (info.cwdTarget && dynamic(unquote(info.cwdTarget.text), ps)) state.dynamic = true
10091129
if (info.cwdTarget) yield* addPath(yield* argPath(info.cwdTarget.text, cwd, ps, shell))
1130+
if (info.extraPaths?.length) {
1131+
for (const item of info.extraPaths) yield* addPath(yield* argPath(item, cwd, ps, shell))
1132+
}
1133+
let conservative = false
10101134
if (name && (FILES.has(name) || (shellKind === "cmd" && CMD_FILES.has(name)))) {
10111135
for (const arg of pathArgs(info.command, ps, shellKind === "cmd")) {
10121136
yield* addPath(yield* argPath(arg, cwd, ps, shell))
@@ -1018,6 +1142,22 @@ export const ShellTool = Tool.define(
10181142
for (const item of info.command.slice(1)) {
10191143
yield* addPath(yield* argPath(item.text, cwd, ps, shell))
10201144
}
1145+
} else if (
1146+
name &&
1147+
!info.wrapped &&
1148+
info.command.slice(1).some((item) => {
1149+
if (item.text.startsWith("-")) return false
1150+
const inner = bareName(commandName(item.text))
1151+
return FILES.has(inner) || (shellKind === "cmd" && CMD_FILES.has(inner))
1152+
})
1153+
) {
1154+
// An unmodelled exec wrapper (`parallel cat x`) runs the file command named in
1155+
// its arguments; scan every token and suppress `always` so the wrapper name
1156+
// cannot absorb a future read.
1157+
for (const item of info.command.slice(1)) {
1158+
yield* addPath(yield* argPath(item.text, cwd, ps, shell))
1159+
}
1160+
conservative = true
10211161
}
10221162
if (info.evalScript && depth < 8) {
10231163
const exit = yield* parse(info.evalScript, ps).pipe(Effect.exit)
@@ -1035,14 +1175,23 @@ export const ShellTool = Tool.define(
10351175
scan.dirs.add(path.parse(cwd).root)
10361176
}
10371177
}
1038-
return { name, info }
1178+
return { name, info, conservative }
10391179
})
10401180

10411181
const entries = commands(root).map((node) => {
10421182
const command = parts(node)
10431183
return { node, command, tokens: command.map((item) => item.text) }
10441184
})
10451185

1186+
// Redirection targets (`cat < /etc/hostname`, `cmd > /tmp/out`) are dropped from
1187+
// the token list, so a stored grant could absorb that read or write; scan each
1188+
// target path through the same resolution as other arguments.
1189+
for (const redirect of root.descendantsOfType("file_redirect")) {
1190+
if (!redirect) continue
1191+
const destination = redirect.childForFieldName("destination")
1192+
if (destination) yield* addPath(yield* argPath(destination.text, cwd, ps, shell))
1193+
}
1194+
10461195
// A non-empty command the parser could not turn into a `command` node (a bare
10471196
// brace list, any future parse blind spot) must not run unprompted. Anchor the
10481197
// scan at the filesystem root and prompt; `always` stays empty.
@@ -1055,7 +1204,7 @@ export const ShellTool = Tool.define(
10551204
// Classify every command before deciding the always-grant, so a dynamic `cd`
10561205
// anywhere in the invocation (including through a wrapper or `eval`) suppresses
10571206
// it for all of them, not just commands that happen to parse after it.
1058-
const resolved: { name?: string; info: Effective }[] = []
1207+
const resolved: { name?: string; info: Effective; conservative?: boolean }[] = []
10591208
for (const entry of entries) resolved.push(yield* classify(entry.command))
10601209

10611210
for (let index = 0; index < entries.length; index++) {
@@ -1074,7 +1223,10 @@ export const ShellTool = Tool.define(
10741223
dynamic:
10751224
entry.command.some((item) => dynamic(item.text, ps)) ||
10761225
result.info.wrapped === true ||
1077-
result.info.unresolved === true,
1226+
result.info.unresolved === true ||
1227+
result.conservative === true ||
1228+
(result.info.extraPaths?.length ?? 0) > 0 ||
1229+
/[\\/]/.test(entry.tokens[0] ?? ""),
10781230
})
10791231
}
10801232

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.