typeclaw 0.46.0 → 0.46.2

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.
Files changed (75) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -2
  3. package/src/agent/multimodal/looker.ts +11 -1
  4. package/src/agent/network/safe-http.ts +17 -8
  5. package/src/agent/plugin-tools.ts +1 -3
  6. package/src/agent/tool-file-safety.ts +414 -145
  7. package/src/agent/tools/webfetch/fetch.ts +22 -2
  8. package/src/agent/tools/webfetch/strategies/jq.ts +1 -2
  9. package/src/agent/tools/webfetch/strategies/readability.ts +39 -16
  10. package/src/agent/tools/webfetch/strategies/selector.ts +4 -2
  11. package/src/agent/tools/webfetch/strategies/snapshot.ts +3 -2
  12. package/src/agent/tools/webfetch/tool.ts +3 -3
  13. package/src/agent/tools-without-local-file-operands.ts +9 -6
  14. package/src/bundled-plugins/backup/README.md +23 -10
  15. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  16. package/src/bundled-plugins/backup/index.ts +104 -47
  17. package/src/bundled-plugins/backup/runner.ts +102 -5
  18. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  19. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  20. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  21. package/src/bundled-plugins/github-cli-auth/index.ts +110 -31
  22. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  23. package/src/bundled-plugins/memory/README.md +9 -0
  24. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  25. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  26. package/src/bundled-plugins/memory/vector/hybrid.ts +10 -2
  27. package/src/bundled-plugins/memory/vector/store.ts +21 -9
  28. package/src/bundled-plugins/researcher/write-report.ts +3 -3
  29. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +8 -3
  30. package/src/bundled-plugins/security/policies/private-surface-read.ts +616 -50
  31. package/src/bundled-plugins/security/policies/ssrf.ts +119 -34
  32. package/src/channels/adapters/github/inbound.ts +11 -0
  33. package/src/channels/adapters/github/index.ts +48 -54
  34. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  35. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  36. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  37. package/src/channels/adapters/slack-bot.ts +7 -2
  38. package/src/channels/adapters/slack-format.ts +245 -0
  39. package/src/channels/github-token-bridge.ts +2 -3
  40. package/src/cli/inspect.ts +16 -0
  41. package/src/container/docker-app.ts +42 -13
  42. package/src/container/shared.ts +19 -6
  43. package/src/container/start.ts +13 -0
  44. package/src/cron/bridge.ts +9 -2
  45. package/src/doctor/checks.ts +5 -2
  46. package/src/git/bound-gc-config.ts +82 -0
  47. package/src/hostd/spawn.ts +133 -47
  48. package/src/init/checkpoint.ts +4 -4
  49. package/src/init/dockerfile.ts +100 -88
  50. package/src/init/gitignore.ts +5 -6
  51. package/src/init/run-bun-install.ts +16 -2
  52. package/src/init/validate-api-key.ts +1 -0
  53. package/src/inspect/item-list.ts +12 -6
  54. package/src/inspect/replay.ts +21 -9
  55. package/src/inspect/session-list.ts +71 -33
  56. package/src/mcp/tools.ts +1 -0
  57. package/src/network/internal-destinations.ts +267 -0
  58. package/src/permissions/permissions.ts +93 -2
  59. package/src/plugin/types.ts +3 -2
  60. package/src/role-claim/code.ts +9 -5
  61. package/src/run/index.ts +45 -36
  62. package/src/sandbox/canonical-secrets.ts +6 -0
  63. package/src/sandbox/env-exposure.ts +18 -15
  64. package/src/sandbox/index.ts +1 -0
  65. package/src/sandbox/policy.ts +5 -3
  66. package/src/sandbox/privileged-runtime.ts +1 -0
  67. package/src/sandbox/symlinks.ts +1 -1
  68. package/src/secrets/export-claude-credentials-file.ts +13 -22
  69. package/src/secrets/export-codex-auth-file.ts +12 -28
  70. package/src/skills/typeclaw-config/SKILL.md +22 -6
  71. package/src/skills/typeclaw-permissions/SKILL.md +22 -9
  72. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  73. package/src/usage/scan.ts +11 -2
  74. package/typeclaw.schema.json +5 -0
  75. package/src/git/secret-history.ts +0 -371
@@ -6,6 +6,31 @@ import { type AgentGit, resolveAgentGit } from '@/git/resolve-agent-git'
6
6
 
7
7
  export const COMMIT_TIMEOUT_MS = 30_000
8
8
  export const NETWORK_TIMEOUT_MS = 60_000
9
+ export const MAINTENANCE_TIMEOUT_MS = 120_000
10
+
11
+ // The two maintenance tasks are gated INDEPENDENTLY because a backup commit with
12
+ // auto-gc disabled (Fix 1) produces LOOSE OBJECTS, not packs:
13
+ // - loose-objects fires on the loose-object count (`count:` in count-objects),
14
+ // which is what actually grows every idle backup cycle. Gating this on pack
15
+ // count would let loose objects accumulate forever while packs stayed ~0.
16
+ // - incremental-repack fires on the pack count (`packs:`), consolidating the
17
+ // packs that loose-objects itself produces once they build up.
18
+ // Each task consolidates its own input, so the counts reset and both self-throttle
19
+ // — no wall-clock timer needed.
20
+ const MAINTENANCE_LOOSE_THRESHOLD = 300
21
+ const MAINTENANCE_PACK_THRESHOLD = 12
22
+
23
+ // Memory caps for the maintenance repack, matching the machine-local config Fix 1
24
+ // writes so the bound holds even on a repo that predates it. Passed as `-c` so
25
+ // they apply to this invocation regardless of the persisted config.
26
+ const BOUNDED_PACK_FLAGS = [
27
+ '-c',
28
+ 'pack.threads=1',
29
+ '-c',
30
+ 'pack.windowMemory=64m',
31
+ '-c',
32
+ 'pack.deltaCacheSize=1',
33
+ ] as const
9
34
 
10
35
  const RUNTIME_OWNED_PREFIXES = ['memory/'] as const
11
36
  const FORCE_ADD_PREFIXES = ['sessions/', 'todo/'] as const
@@ -152,6 +177,64 @@ export async function runBackup(options: BackupRunnerOptions, deps: BackupRunner
152
177
  return pushWithRecovery(cwd, deps, repo, plan)
153
178
  }
154
179
 
180
+ export type MaintenanceResult =
181
+ | { ok: true; kind: 'no-repo' | 'skipped' | 'ran'; tasks?: readonly string[] }
182
+ | { ok: false; kind: 'failed'; reason: string }
183
+
184
+ // Bounded, best-effort git maintenance run on the idle backup path. With auto-gc
185
+ // disabled (Fix 1), nothing reclaims what the backup keeps adding, so this runs
186
+ // the two reclamation tasks — each gated on ITS OWN growing counter (see the
187
+ // threshold comment above): `loose-objects` when loose objects pile up (the
188
+ // steady-state effect of every commit), `incremental-repack` when packs pile up.
189
+ // incremental-repack uses the multi-pack-index, touching only SMALL packs and
190
+ // leaving the big established pack alone, so memory and time stay bounded unlike a
191
+ // full `git gc`. Both tasks run under BOUNDED_PACK_FLAGS. NEVER throws: a
192
+ // maintenance failure must not turn a good commit into a reported backup failure.
193
+ // The caller runs this after a commit, holding the same git lock the commit did.
194
+ export type MaintenanceThresholds = { loose?: number; packs?: number }
195
+
196
+ export async function runMaintenance(
197
+ cwd: string,
198
+ deps: BackupRunnerDeps,
199
+ thresholds: MaintenanceThresholds = {},
200
+ ): Promise<MaintenanceResult> {
201
+ const repo = resolveAgentGit(cwd)
202
+ if (!repo) return { ok: true, kind: 'no-repo' }
203
+
204
+ const looseThreshold = thresholds.loose ?? MAINTENANCE_LOOSE_THRESHOLD
205
+ const packThreshold = thresholds.packs ?? MAINTENANCE_PACK_THRESHOLD
206
+ const counts = await countObjects(cwd, deps, repo)
207
+ const tasks: string[] = []
208
+ if (counts.loose > looseThreshold) tasks.push('loose-objects')
209
+ if (counts.packs > packThreshold) tasks.push('incremental-repack')
210
+ if (tasks.length === 0) return { ok: true, kind: 'skipped' }
211
+
212
+ const run = await deps.gitSpawn(
213
+ [...repo.gitArgs, ...BOUNDED_PACK_FLAGS, 'maintenance', 'run', ...tasks.map((task) => `--task=${task}`)],
214
+ { cwd, timeoutMs: MAINTENANCE_TIMEOUT_MS },
215
+ )
216
+ if (run.exitCode !== 0) return { ok: false, kind: 'failed', reason: shortErr(run) }
217
+ return { ok: true, kind: 'ran', tasks }
218
+ }
219
+
220
+ // Reads the loose-object (`count:`) and pack (`packs:`) counts from
221
+ // `git count-objects -v`. Returns zeroes on any failure so a probe error just
222
+ // skips maintenance rather than aborting it.
223
+ async function countObjects(
224
+ cwd: string,
225
+ deps: BackupRunnerDeps,
226
+ repo: AgentGit,
227
+ ): Promise<{ loose: number; packs: number }> {
228
+ const result = await deps.gitSpawn([...repo.gitArgs, 'count-objects', '-v'], { cwd, timeoutMs: COMMIT_TIMEOUT_MS })
229
+ if (result.exitCode !== 0) return { loose: 0, packs: 0 }
230
+ return { loose: readCount(result.stdout, 'count'), packs: readCount(result.stdout, 'packs') }
231
+ }
232
+
233
+ function readCount(stdout: string, field: 'count' | 'packs'): number {
234
+ const match = new RegExp(String.raw`^${field}:\s*(\d+)`, 'm').exec(stdout)
235
+ return match?.[1] !== undefined ? Number.parseInt(match[1], 10) : 0
236
+ }
237
+
155
238
  // `@{upstream}` resolution failing was previously treated as "no push" — but a
156
239
  // fresh agent repo that nobody ran `git push -u` on has a configured `origin`
157
240
  // and no tracking ref, so the runner committed forever and never pushed. The
@@ -316,9 +399,9 @@ function sanitizeCommitMessage(raw: string): string {
316
399
  return rest.length > 0 ? `${subject}\n\n${rest}` : subject
317
400
  }
318
401
 
319
- export function makeDefaultGitSpawn(): GitSpawn {
402
+ export function makeDefaultGitSpawn(bunOverride?: { spawn: typeof Bun.spawn }): GitSpawn {
320
403
  return withIndexLockRetry(async (args, { cwd, timeoutMs, env }) => {
321
- const bun = (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
404
+ const bun = bunOverride ?? (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
322
405
  if (!bun) {
323
406
  return { exitCode: 127, stdout: '', stderr: 'Bun runtime not available', timedOut: false }
324
407
  }
@@ -336,9 +419,23 @@ export function makeDefaultGitSpawn(): GitSpawn {
336
419
  env: { ...process.env, ...NONINTERACTIVE_ENV, ...env },
337
420
  signal: controller.signal,
338
421
  })
339
- const exitCode = await proc.exited
340
- const stdout = await new Response(proc.stdout).text()
341
- const stderr = await new Response(proc.stderr).text()
422
+ const exitedDrain = proc.exited
423
+ const stdoutDrain = new Response(proc.stdout).text()
424
+ const stderrDrain = new Response(proc.stderr).text()
425
+ let exitCode: number
426
+ let stdout: string
427
+ let stderr: string
428
+ try {
429
+ ;[exitCode, stdout, stderr] = await Promise.all([exitedDrain, stdoutDrain, stderrDrain])
430
+ } catch (drainErr) {
431
+ // A pipe-read rejection must not escape while the git child is still
432
+ // running (the outer `finally` would clear the abort timer and leave a
433
+ // stuck child unbounded). Abort to kill it, then wait for exit and both
434
+ // drains to settle before surfacing the error.
435
+ controller.abort()
436
+ await Promise.allSettled([exitedDrain, stdoutDrain, stderrDrain])
437
+ throw drainErr
438
+ }
342
439
  const timedOut = controller.signal.aborted
343
440
  return { exitCode, stdout, stderr, timedOut }
344
441
  } catch (err) {
@@ -1,5 +1,6 @@
1
1
  import { randomBytes } from 'node:crypto'
2
- import { chmod, mkdir, rename, writeFile } from 'node:fs/promises'
2
+ import { constants } from 'node:fs'
3
+ import { access, chmod, mkdir, mkdtemp, rename, writeFile } from 'node:fs/promises'
3
4
  import { dirname, join } from 'node:path'
4
5
 
5
6
  // A GIT_ASKPASS helper git invokes for username/password prompts. The token
@@ -25,7 +26,7 @@ import { dirname, join } from 'node:path'
25
26
  // \`github.com.evil/\`, or \`x@github.com.evil/\`. Without the userinfo arm the
26
27
  // password prompt falls through to \`exit 1\` and every HTTPS clone/fetch fails
27
28
  // with "unable to read askpass response".
28
- const ASKPASS_SCRIPT = `#!/bin/sh
29
+ export const ASKPASS_SCRIPT = `#!/bin/sh
29
30
  case "$1" in
30
31
  *//github.com/*|*//github.com\\'*|*//*@github.com/*|*//*@github.com\\'*) : ;;
31
32
  *) exit 1 ;;
@@ -36,40 +37,87 @@ case "$1" in
36
37
  esac
37
38
  `
38
39
 
39
- // /usr is --ro-bind mounted into the per-tool bwrap sandbox (src/sandbox/build.ts),
40
- // so a helper here is readable by sandboxed bash; the per-session /tmp bind is not
41
- // a stable path. TYPECLAW_GIT_ASKPASS_PATH overrides it for tests/CI, which
42
- // cannot write under /usr.
43
- const DEFAULT_ASKPASS_PATH = '/usr/local/bin/typeclaw-git-askpass'
40
+ // The sandboxed-bash consumer (the github-cli-auth broker's authenticated git)
41
+ // runs INSIDE the per-tool bwrap sandbox, which `--ro-bind`s /usr but masks /tmp
42
+ // with a tmpfs (src/sandbox/build.ts). So its helper must live under /usr, baked
43
+ // into the image at build time (dockerfile.ts) — the read-only /usr is why
44
+ // ensureGitAskPassHelper early-returns when the file already exists rather than
45
+ // rewriting it. TYPECLAW_GIT_ASKPASS_PATH overrides it for tests/CI.
46
+ export const TYPECLAW_GIT_ASKPASS_PATH = '/usr/local/bin/typeclaw-git-askpass'
44
47
 
45
- function defaultPath(): string {
46
- const override = process.env.TYPECLAW_GIT_ASKPASS_PATH
47
- return override !== undefined && override !== '' ? override : DEFAULT_ASKPASS_PATH
48
+ // The base is the FIXED real `/tmp`, NOT `os.tmpdir()`: os.tmpdir() honors
49
+ // TMPDIR/TMP/TEMP, so an env pointing it at a model-writable location would let a
50
+ // sandboxed tool replace the cached helper before a later UNSANDBOXED reviewer
51
+ // checkout / backup push executes it with TYPECLAW_GIT_TOKEN in env. A random
52
+ // `mkdtemp` subdir (mode 0700) keeps the name unpredictable.
53
+ const ASKPASS_DIR_BASE = '/tmp/typeclaw-git-askpass-'
54
+
55
+ let defaultDirPromise: Promise<string> | null = null
56
+
57
+ function configuredPath(): string | undefined {
58
+ const path = process.env.TYPECLAW_GIT_ASKPASS_PATH
59
+ return path !== undefined && path !== '' ? path : undefined
60
+ }
61
+
62
+ function resolveDefaultDir(): Promise<string> {
63
+ if (defaultDirPromise === null) defaultDirPromise = mkdtemp(ASKPASS_DIR_BASE)
64
+ return defaultDirPromise.catch((err) => {
65
+ defaultDirPromise = null
66
+ throw err
67
+ })
68
+ }
69
+
70
+ // The path the SANDBOXED-bash consumer must use: the baked, sandbox-visible /usr
71
+ // helper (or the test/CI override). Unlike the unsandboxed default, this never
72
+ // falls back to /tmp, which the sandbox's tmpfs would hide from model bash.
73
+ export function resolveSandboxGitAskPassPath(): string {
74
+ return configuredPath() ?? TYPECLAW_GIT_ASKPASS_PATH
75
+ }
76
+
77
+ // The path UNSANDBOXED execFile consumers (reviewer checkout, backup push) use:
78
+ // a runtime-writable, unpredictable real-/tmp path. They don't run under bwrap, so
79
+ // /tmp masking doesn't apply, and a non-root runtime can write here.
80
+ async function defaultPath(): Promise<string> {
81
+ return configuredPath() ?? join(await resolveDefaultDir(), 'typeclaw-git-askpass')
48
82
  }
49
83
 
50
- let ensurePromise: Promise<string> | null = null
84
+ // Keyed by resolved path: a single shared promise would let the first caller's
85
+ // path win even when a later caller explicitly asks for a different one (the
86
+ // sandbox /usr path and the unsandboxed /tmp path are legitimately distinct).
87
+ const ensurePromises = new Map<string, Promise<string>>()
51
88
 
52
89
  export function resetGitAskPassHelperForTests(): void {
53
- ensurePromise = null
90
+ ensurePromises.clear()
91
+ defaultDirPromise = null
54
92
  }
55
93
 
56
- // Writes the helper once per process (idempotent, race-safe via the shared
57
- // promise) and returns its absolute path. The temp name is unpredictable and
58
- // opened with `wx` (exclusive create, fails on an existing file/symlink) so a
59
- // planted symlink cannot redirect the write; then atomically renamed so a
60
- // concurrent reader never sees a partial file.
61
- export function ensureGitAskPassHelper(path: string = defaultPath()): Promise<string> {
62
- if (ensurePromise !== null) return ensurePromise
63
- ensurePromise = (async () => {
64
- await mkdir(dirname(path), { recursive: true })
65
- const tmp = join(dirname(path), `.typeclaw-git-askpass.${randomBytes(8).toString('hex')}.tmp`)
94
+ // Returns the helper's absolute path, creating it once per path if needed. When
95
+ // an executable file already exists at the resolved path (the baked /usr helper),
96
+ // we return it WITHOUT writing — the read-only /usr would EACCES a rewrite. Only
97
+ // creates when absent: dev, the unsandboxed /tmp path, or a writable test
98
+ // override. Idempotent + race-safe via the per-path promise; the create uses an
99
+ // unpredictable temp opened `wx` (fails on an existing file/symlink) then renamed.
100
+ export async function ensureGitAskPassHelper(path?: string): Promise<string> {
101
+ const resolved = path ?? (await defaultPath())
102
+ const existing = ensurePromises.get(resolved)
103
+ if (existing !== undefined) return existing
104
+ const pending = (async () => {
105
+ try {
106
+ await access(resolved, constants.X_OK)
107
+ return resolved
108
+ } catch {
109
+ // not present (or not executable) — fall through to create it
110
+ }
111
+ await mkdir(dirname(resolved), { recursive: true })
112
+ const tmp = join(dirname(resolved), `.typeclaw-git-askpass.${randomBytes(8).toString('hex')}.tmp`)
66
113
  await writeFile(tmp, ASKPASS_SCRIPT, { mode: 0o755, flag: 'wx' })
67
114
  await chmod(tmp, 0o755)
68
- await rename(tmp, path)
69
- return path
115
+ await rename(tmp, resolved)
116
+ return resolved
70
117
  })().catch((err) => {
71
- ensurePromise = null
118
+ ensurePromises.delete(resolved)
72
119
  throw err
73
120
  })
74
- return ensurePromise
121
+ ensurePromises.set(resolved, pending)
122
+ return pending
75
123
  }
@@ -57,9 +57,9 @@ export const defaultGitResolvers: GitResolvers = {
57
57
  const REMOTE_SUBCOMMANDS = new Set(['push', 'fetch', 'pull', 'clone', 'ls-remote'])
58
58
 
59
59
  const MULTI_OWNER_REASON =
60
- 'This git command targets repos under more than one owner; a single minted ' +
61
- 'GitHub App token cannot authenticate all of them. Split it into separate ' +
62
- 'commands, one owner each.'
60
+ 'This git command targets more than one repository; a single minted GitHub App ' +
61
+ 'token is scoped to one repo and cannot authenticate all of them. Split it into ' +
62
+ 'separate commands, one repository each.'
63
63
 
64
64
  const COMPOSITION_REASON =
65
65
  'A repo-targeting `git` command receives a minted GitHub App token via ' +
@@ -82,15 +82,56 @@ const FETCH_ALL_REASON =
82
82
  'cannot be enumerated safely here — a minted token scoped to one remote could ' +
83
83
  'be sent to another. Fetch a specific remote instead.'
84
84
 
85
+ // The exec prefix a `clone && <tail>` tail is re-executed under. Every key here
86
+ // MUST mirror the overlay index.ts injects for a token-bearing git (the two
87
+ // secrets TYPECLAW_GIT_TOKEN/GIT_ASKPASS, the operator PATs GH_TOKEN/GITHUB_TOKEN
88
+ // that live in bash env, and the forced GIT_CONFIG_* + GIT_TERMINAL_PROMPT) so
89
+ // the fresh tokenless shell inherits none of them. Absolute `/usr/bin/env` and
90
+ // `/bin/bash` so a PATH-shadowed shim cannot defeat the strip; a missing binary
91
+ // exits non-zero, failing closed. Drift here is a token leak — keep in lockstep
92
+ // with index.ts's git overlay (guarded by a test in index.test.ts).
93
+ const TAIL_STRIP_PREFIX =
94
+ 'exec /usr/bin/env -u TYPECLAW_GIT_TOKEN -u GIT_ASKPASS -u GH_TOKEN -u GITHUB_TOKEN ' +
95
+ '-u GIT_TERMINAL_PROMPT -u GIT_CONFIG_COUNT -u GIT_CONFIG_KEY_0 -u GIT_CONFIG_VALUE_0 ' +
96
+ '-u GIT_CONFIG_KEY_1 -u GIT_CONFIG_VALUE_1 -u GIT_CONFIG_KEY_2 -u GIT_CONFIG_VALUE_2 ' +
97
+ '-u GIT_CONFIG_KEY_3 -u GIT_CONFIG_VALUE_3 /bin/bash -c'
98
+
85
99
  // OUTSIDE single quotes these spawn a sibling process (which would inherit the
86
100
  // askpass token) or expand shell state. `$`/backtick stay active inside double
87
101
  // quotes too, so they are screened separately. Mirrors gh-command.ts.
88
102
  const SHELL_ACTIVE_METACHARS = new Set(['|', ';', '&', '\n', '\r', '(', ')', '{', '}', '<', '>', '`', '$'])
89
103
 
104
+ // `\` (Bash escaping) and `#` (comments) are the two constructs our quote-aware
105
+ // scanners do not model. Either can make our view of top-level structure disagree
106
+ // with Bash's — so a command carrying them must never drive a token mint.
107
+ function containsEscapeBlindSyntax(command: string): boolean {
108
+ return command.includes('\\') || command.includes('#')
109
+ }
110
+
111
+ // Conservative raw-text probe for a `git` word — NOT the escape-blind tokenizer.
112
+ // Used only to choose block-vs-pass in the fail-closed gate; a miss is harmless
113
+ // (the command runs tokenless), so it never needs to be exhaustive.
114
+ function looksLikePotentialGitCommand(command: string): boolean {
115
+ return /(^|[^A-Za-z0-9_])git(?=$|[^A-Za-z0-9_-])/.test(command)
116
+ }
117
+
90
118
  export async function analyzeGitCommand(
91
119
  command: string,
92
120
  options: { cwd: string; resolvers: GitResolvers },
93
121
  ): Promise<GitCommandDecision> {
122
+ // Fail-closed lexical gate BEFORE any mint decision. The scanners below are
123
+ // quote-aware but do NOT model Bash backslash escaping or `#` comments, so
124
+ // either can make our escape-blind view of the command disagree with Bash and
125
+ // drive a token mint for a structure Bash parses differently (a `\"` that keeps
126
+ // a quote open, or a `#` that comments out an appended boundary). Any command
127
+ // carrying `\` or `#` therefore never reaches an inject decision: it blocks if
128
+ // it looks git-ish, else passes through tokenless. Never mint here.
129
+ if (containsEscapeBlindSyntax(command)) {
130
+ return looksLikePotentialGitCommand(command)
131
+ ? { kind: 'block', reason: COMPOSITION_REASON }
132
+ : { kind: 'pass-through' }
133
+ }
134
+
94
135
  // The single permitted `cd <simple-path> && git …` shortcut is rewritten to a
95
136
  // bare `git -C …` before any chain parsing, so a chain never has to reason
96
137
  // about a `cd` segment changing cwd for the gits that follow it. Multi-git
@@ -99,6 +140,9 @@ export async function analyzeGitCommand(
99
140
  if (stripped.unsafe) return { kind: 'pass-through' }
100
141
  if (stripped.cdDir !== null) return analyzeSingleCdGit(stripped, options)
101
142
 
143
+ const cloneThenInspect = analyzeCloneThenInspect(command)
144
+ if (cloneThenInspect !== null) return cloneThenInspect
145
+
102
146
  // Split the command into `&&`-joined git segments. null = not a pure
103
147
  // git-only `&&` chain (a non-git segment, a forbidden shell operator, a
104
148
  // leading env assignment, or no git at all).
@@ -119,9 +163,8 @@ export async function analyzeGitCommand(
119
163
  // authenticate, so pass through and let git run with no token.
120
164
  if (remoteSegments.length === 0) return { kind: 'pass-through' }
121
165
 
122
- // Every segment — even non-remote ones like `git status` that ride along in
123
- // the chain — must pass the redirect screen: a token lives in the shared env
124
- // the whole chain inherits, so a `-c`/env-assignment on ANY git could steer
166
+ // Every segment must pass the redirect screen: a token would live in the shared
167
+ // env the whole chain inherits, so a `-c`/env-assignment on ANY git could steer
125
168
  // auth or destination.
126
169
  for (const seg of chain) {
127
170
  if (seg.hasLeadingEnvAssignment || hasDangerousGitConfig(seg.args)) {
@@ -133,11 +176,10 @@ export async function analyzeGitCommand(
133
176
  }
134
177
  }
135
178
 
136
- const owners = new Set<string>()
137
- let representativeSlug: string | null = null
179
+ const repos = new Set<string>()
138
180
  for (const seg of remoteSegments) {
139
181
  const sub = findSubcommand(seg.args) as string
140
- const effectiveCwd = resolveCwd(options.cwd, extractDashCDir(seg.args))
182
+ const effectiveCwd = resolveEffectiveCwd(options.cwd, seg.args)
141
183
  // A resolver that throws is treated as "couldn't resolve" → pass-through, so
142
184
  // a git/subprocess failure never crashes the hook or guesses a repo.
143
185
  let slugs: string[]
@@ -146,19 +188,23 @@ export async function analyzeGitCommand(
146
188
  } catch {
147
189
  return { kind: 'pass-through' }
148
190
  }
149
- for (const slug of slugs) {
150
- owners.add(slug.split('/')[0] as string)
151
- representativeSlug ??= slug
152
- }
191
+ for (const slug of slugs) repos.add(slug)
153
192
  }
154
193
 
155
- // A GitHub remote subcommand whose target owner we could not resolve: we must
156
- // not mint a possibly-wrong-owner token, and silently passing through would
157
- // reproduce the credential-less failure. Block with an actionable reason.
158
- if (representativeSlug === null) return { kind: 'pass-through' }
159
- if (owners.size > 1) return { kind: 'block', reason: MULTI_OWNER_REASON }
194
+ // No github remote resolved (e.g. a gitlab chain): no token to mint, so pass
195
+ // through and let git run tokenless — do NOT block a legitimate non-github chain.
196
+ if (repos.size === 0) return { kind: 'pass-through' }
160
197
 
161
- return { kind: 'inject', repoSlug: representativeSlug }
198
+ // A token WILL be minted. It must ride a SINGLE bare git: the shared chain env
199
+ // means a later segment — even `git leak` where the repo aliased `leak` to a
200
+ // shell command — would read it. The only multi-segment token-bearing form is
201
+ // `cd <path> && git …`, handled by analyzeSingleCdGit (rewritten to one git -C).
202
+ if (chain.length > 1) return { kind: 'block', reason: COMPOSITION_REASON }
203
+ // One minted token is repo-scoped, so more than one distinct repo (e.g.
204
+ // `fetch --multiple origin upstream`) can't authenticate.
205
+ if (repos.size > 1) return { kind: 'block', reason: MULTI_OWNER_REASON }
206
+
207
+ return { kind: 'inject', repoSlug: [...repos][0] as string }
162
208
  }
163
209
 
164
210
  // The single-git `cd <path> && git …` shortcut. Kept separate (and single-git
@@ -180,8 +226,8 @@ async function analyzeSingleCdGit(
180
226
  if ((subcommand === 'fetch' || subcommand === 'pull') && args.includes('--all')) {
181
227
  return { kind: 'block', reason: FETCH_ALL_REASON }
182
228
  }
183
- const dashCDir = extractDashCDir(args)
184
- const effectiveCwd = resolveCwd(resolveCwd(options.cwd, stripped.cdDir), dashCDir)
229
+ const hasDashC = args.includes('-C')
230
+ const effectiveCwd = resolveEffectiveCwd(resolveCwd(options.cwd, stripped.cdDir), args)
185
231
  let slugs: string[]
186
232
  try {
187
233
  slugs = await resolveRepoSlugs(subcommand, args, effectiveCwd, options.resolvers)
@@ -189,17 +235,137 @@ async function analyzeSingleCdGit(
189
235
  return { kind: 'pass-through' }
190
236
  }
191
237
  if (slugs.length === 0) return { kind: 'pass-through' }
192
- const owners = new Set(slugs.map((s) => s.split('/')[0]))
193
- if (owners.size > 1) return { kind: 'block', reason: MULTI_OWNER_REASON }
238
+ if (new Set(slugs).size > 1) return { kind: 'block', reason: MULTI_OWNER_REASON }
194
239
  const repoSlug = slugs[0] as string
195
240
  // The rewrite cannot stack two `-C` (the git part must not already carry one)
196
241
  // and the rest must be a single bare git (no further composition).
197
- if (containsShellActiveMetachar(stripped.rest) || dashCDir !== null) {
242
+ if (containsShellActiveMetachar(stripped.rest) || hasDashC) {
198
243
  return { kind: 'block', reason: COMPOSITION_REASON }
199
244
  }
200
245
  return { kind: 'inject', repoSlug, rewrittenCommand: rewriteCdToDashC(effectiveCwd, stripped.rest) }
201
246
  }
202
247
 
248
+ // The `git clone <url> <dir> && <tail>` shape: acquire a repo, then inspect it.
249
+ // A naive `env -u TOKEN <tail>` is UNSOUND — shell substitution in the tail runs
250
+ // in the still-token-bearing parent shell before `env`, and a stripped child can
251
+ // still read the parent's env via /proc/$PPID/environ. So instead the git head
252
+ // runs first (token reaches only the clone), then `exec` REPLACES the token-
253
+ // bearing shell with `/usr/bin/env -u <keys> /bin/bash -c '<tail>'`: exec removes
254
+ // that /proc target, the unset drops every injected key, and the tail rides as an
255
+ // opaque single-quoted argument the fresh tokenless shell alone parses/expands.
256
+ // Scoped to `clone` by DELIBERATE CHOICE, not a limit of the strip boundary
257
+ // (which would neutralize the token just as well after fetch/pull). `clone` names
258
+ // the repo in argv, so minting is unambiguous, and it creates a fresh tree the
259
+ // tail inspects. fetch/pull would resolve the repo through an existing repo's cwd,
260
+ // remotes, and mutable `.git/config` (and `pull` runs repo-configured integration
261
+ // while the token is live) — extra resolution complexity and token-bearing surface
262
+ // for a workflow already expressible as `git -C <repo> fetch` then a separate
263
+ // tokenless inspect. So fetch/pull/push stay single-bare. Returns null when the
264
+ // shape does not match, so the caller falls through to the normal chain analysis.
265
+ function analyzeCloneThenInspect(command: string): GitCommandDecision | null {
266
+ // `\` and `#` are already rejected by the early gate in analyzeGitCommand, so
267
+ // splitCloneHeadAndTail's quote-aware scan is trustworthy here.
268
+ const split = splitCloneHeadAndTail(command)
269
+ if (split === null) return null
270
+ const { head, tail } = split
271
+ if (tail === '') return { kind: 'block', reason: COMPOSITION_REASON }
272
+
273
+ // A git in the tail is NOT inspection — it either wants the token (so it must
274
+ // ride the single-bare path or an explicit `git -C`) or is an exfil sibling.
275
+ // Fall through so the strict chain analysis keeps its existing block/pass rules
276
+ // for every `clone && git …` shape.
277
+ if (containsGitInvocation(tail)) return null
278
+
279
+ const parsed = parseStrictCloneHead(head)
280
+ if (parsed === null) {
281
+ // A clone of a NON-github url needs no token, so the compound is harmless —
282
+ // pass through and let git run tokenless rather than block a legitimate
283
+ // e.g. gitlab clone-then-grep. Anything else (a github clone that failed the
284
+ // strict grammar — flags, odd dir, malformed url) falls through to the strict
285
+ // chain analysis, which blocks it.
286
+ return isNonGithubCloneHead(head) ? { kind: 'pass-through' } : null
287
+ }
288
+
289
+ // Reconstruct the token-bearing head from the strict parse — an absolute git
290
+ // and separately single-quoted url + destination — so NO byte of the original
291
+ // untrusted head reaches the appended `&& exec` boundary. Absolute /usr/bin/git
292
+ // also removes alias/function/PATH ambiguity for the token-bearing command.
293
+ const canonicalHead = `/usr/bin/git clone ${posixSingleQuote(parsed.url)} ${posixSingleQuote(parsed.destination)}`
294
+
295
+ return {
296
+ kind: 'inject',
297
+ repoSlug: parsed.repoSlug,
298
+ rewrittenCommand: `${canonicalHead} && ${TAIL_STRIP_PREFIX} ${posixSingleQuote(tail)}`,
299
+ }
300
+ }
301
+
302
+ type StrictCloneHead = { repoSlug: string; url: string; destination: string }
303
+
304
+ // A DELIBERATELY tiny grammar for the token-bearing clone head:
305
+ // `git clone <https-github-url> <simple-destination>` — no flags (clone's own
306
+ // `-c`/`--config` reopens credential-helper/url-redirection analysis), no leading
307
+ // env assignment, no quoting, no metachars. The captured owner/repo and url come
308
+ // straight from this match, never the generic escape-blind tokenizer, so the
309
+ // reconstructed command cannot be perturbed by anything in the raw head. Anything
310
+ // outside the grammar returns null → the caller falls through (blocks or passes).
311
+ const STRICT_CLONE_HEAD_RE =
312
+ /^[ \t]*git[ \t]+clone[ \t]+(https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?)[ \t]+([A-Za-z0-9._/-]+)[ \t]*$/
313
+
314
+ function parseStrictCloneHead(head: string): StrictCloneHead | null {
315
+ const m = STRICT_CLONE_HEAD_RE.exec(head)
316
+ if (m === null) return null
317
+ const url = m[1] as string
318
+ const repoSlug = m[2] as string
319
+ const destination = m[3] as string
320
+ if (destination.startsWith('-')) return null
321
+ if (repoSlug.endsWith('/') || repoSlug.startsWith('/')) return null
322
+ return { repoSlug, url, destination }
323
+ }
324
+
325
+ // True when the head is `git clone … <url> …` for a url whose host is clearly not
326
+ // github.com — a clone that needs no minted token, so its compound form is safe to
327
+ // run tokenless. Conservative: only a positive non-github host match returns true;
328
+ // anything ambiguous returns false so the caller falls through (and blocks).
329
+ function isNonGithubCloneHead(head: string): boolean {
330
+ if (!/^[ \t]*git[ \t]+clone[ \t]/.test(head)) return false
331
+ const url = /(?:^|[ \t])((?:https?:\/\/|git@|ssh:\/\/)[^ \t]+)/.exec(head)?.[1]
332
+ if (url === undefined) return false
333
+ return parseGithubRepoFromGitUrl(url) === null
334
+ }
335
+
336
+ // Splits on the FIRST top-level `&&`, quote-aware. Rejects (null) when any other
337
+ // top-level operator (`;`, `|`, `||`, single `&`, newline) precedes it — those
338
+ // don't guarantee the clone finished before the tail, so the token could still be
339
+ // live in a concurrent sibling. head keeps the raw text up to the `&&`; tail is
340
+ // everything after, treated as opaque.
341
+ function splitCloneHeadAndTail(command: string): { head: string; tail: string } | null {
342
+ let quote: '"' | "'" | null = null
343
+ for (let i = 0; i < command.length; i++) {
344
+ const ch = command[i] as string
345
+ if (quote !== null) {
346
+ if (ch === quote) quote = null
347
+ continue
348
+ }
349
+ if (ch === "'" || ch === '"') {
350
+ quote = ch
351
+ continue
352
+ }
353
+ if (ch === '&' && command[i + 1] === '&') {
354
+ return { head: command.slice(0, i), tail: command.slice(i + 2).trim() }
355
+ }
356
+ if (ch === ';' || ch === '|' || ch === '&' || ch === '\n' || ch === '\r') return null
357
+ }
358
+ return null
359
+ }
360
+
361
+ // Wraps a string in single quotes with POSIX-safe escaping: each embedded single
362
+ // quote becomes '\'' (close-quote, escaped literal quote, reopen). The result is
363
+ // inert — no shell metacharacter inside can act — so the tail cannot break out of
364
+ // the `bash -c` argument.
365
+ function posixSingleQuote(value: string): string {
366
+ return `'${value.replaceAll("'", "'\\''")}'`
367
+ }
368
+
203
369
  // Global flags that can redirect git's auth or destination. `-c`/`--config-env`
204
370
  // inject arbitrary config (url.insteadOf, core.askPass, credential.*, http.*);
205
371
  // `--git-dir`/`--work-tree`/`--namespace`/`--exec-path` point git at a different
@@ -225,6 +391,25 @@ async function resolveRepoSlugs(
225
391
  cwd: string,
226
392
  resolvers: GitResolvers,
227
393
  ): Promise<string[]> {
394
+ // `fetch --multiple` contacts EVERY positional target — remotes AND raw URLs,
395
+ // mixed, and a target may even be a `remotes.<group>` that expands to several.
396
+ // Enumerate them all (not just the first URL) so the distinct-repo guard sees
397
+ // the full set. FAIL CLOSED: if ANY target can't be resolved to a github slug
398
+ // (an unknown remote, a config remote-group we can't expand, a non-github URL),
399
+ // throw so the caller passes through tokenless — never mint for a subset while
400
+ // git contacts the rest. Non-`--multiple` keeps the single-target path.
401
+ const forPush = subcommand === 'push'
402
+ if (subcommand === 'fetch' && args.includes('--multiple')) {
403
+ const slugs: string[] = []
404
+ for (const pos of positionalsAfterSubcommand('fetch', args)) {
405
+ const url = looksLikeUrl(pos) ? pos : await resolvers.resolveRemoteUrl(cwd, pos, forPush)
406
+ const slug = url === null ? null : parseGithubRepoFromGitUrl(url)
407
+ if (slug === null) throw new Error('unresolved --multiple target')
408
+ slugs.push(slug)
409
+ }
410
+ return slugs
411
+ }
412
+
228
413
  const explicitUrl = extractExplicitUrl(subcommand, args)
229
414
  if (explicitUrl !== null) {
230
415
  const slug = parseGithubRepoFromGitUrl(explicitUrl)
@@ -234,12 +419,6 @@ async function resolveRepoSlugs(
234
419
  // clone needs an explicit URL; it has no configured-remote fallback.
235
420
  if (subcommand === 'clone') return []
236
421
 
237
- // Only `push` consults the push url; fetch/pull/ls-remote use the fetch url.
238
- const forPush = subcommand === 'push'
239
-
240
- // EVERY named remote must be resolved, not just the first: `git fetch
241
- // --multiple origin upstream` touches both, and feeding only one to the
242
- // multi-owner guard would let a second-owner remote slip past and still mint.
243
422
  const remoteNames = extractRemoteNames(args)
244
423
  // The branch.pushRemote/pushDefault/origin chain is a PUSH default; applying it
245
424
  // to a bare `fetch`/`pull`/`ls-remote` could mint for the wrong (push) remote,
@@ -284,7 +463,11 @@ export async function resolveGhDefaultRepoFromCwd(cwd: string, resolvers: GitRes
284
463
 
285
464
  const HTTPS_GITHUB_RE = /^https:\/\/github\.com\/([^/\s:@]+)\/([^/\s?#]+?)(?:\.git)?\/?(?:[?#].*)?$/i
286
465
  const SCP_GITHUB_RE = /^git@github\.com:([^/\s:?#]+)\/([^/\s?#]+?)(?:\.git)?$/i
287
- const SSH_GITHUB_RE = /^ssh:\/\/git@github\.com(?::\d+)?\/([^/\s]+)\/([^/\s?#]+?)(?:\.git)?\/?(?:[?#].*)?$/i
466
+ // No explicit port: the forced insteadOf only rewrites `ssh://git@github.com/`, so
467
+ // a ported form (`ssh://git@github.com:22/…`) would keep ssh transport and bypass
468
+ // the https askpass. We therefore do NOT recognize the ported spelling as github —
469
+ // it resolves to no slug, so no token is minted and git fails honestly.
470
+ const SSH_GITHUB_RE = /^ssh:\/\/git@github\.com\/([^/\s]+)\/([^/\s?#]+?)(?:\.git)?\/?(?:[?#].*)?$/i
288
471
 
289
472
  // Parses a github.com remote URL into an `owner/name` slug. Returns null for
290
473
  // non-github.com hosts, credential-bearing https URLs (https://tok@github.com/…
@@ -392,15 +575,20 @@ function positionalsAfterSubcommand(subcommand: string, args: readonly string[])
392
575
  return out
393
576
  }
394
577
 
395
- function extractDashCDir(args: readonly string[]): string | null {
578
+ // git applies repeated `-C` CUMULATIVELY: each value is resolved relative to the
579
+ // result of the previous one, and an absolute value resets the base. So `-C
580
+ // /trusted -C child` operates in `/trusted/child`, not `child`. We fold them the
581
+ // same way from `base` so we resolve the repo of the checkout git actually uses —
582
+ // resolving only the last `-C` from cwd would mint against a different tree.
583
+ function resolveEffectiveCwd(base: string, args: readonly string[]): string {
584
+ let cwd = base
396
585
  for (let i = 0; i < args.length; i++) {
397
- const arg = args[i]
398
- if (arg === '-C') {
586
+ if (args[i] === '-C') {
399
587
  const v = args[i + 1]
400
- if (v !== undefined) return stripQuotes(v)
588
+ if (v !== undefined) cwd = resolveCwd(cwd, stripQuotes(v))
401
589
  }
402
590
  }
403
- return null
591
+ return cwd
404
592
  }
405
593
 
406
594
  type GitInvocation = { args: string[]; hasLeadingEnvAssignment: boolean }