typeclaw 0.46.0 → 0.46.1

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 (52) 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 +396 -136
  7. package/src/agent/tools/webfetch/fetch.ts +22 -2
  8. package/src/agent/tools-without-local-file-operands.ts +9 -6
  9. package/src/bundled-plugins/backup/README.md +23 -10
  10. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  11. package/src/bundled-plugins/backup/index.ts +83 -43
  12. package/src/bundled-plugins/backup/runner.ts +83 -0
  13. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  14. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  15. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  16. package/src/bundled-plugins/github-cli-auth/index.ts +110 -31
  17. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  18. package/src/bundled-plugins/memory/README.md +9 -0
  19. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  20. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  21. package/src/bundled-plugins/researcher/write-report.ts +3 -3
  22. package/src/bundled-plugins/security/policies/private-surface-read.ts +610 -50
  23. package/src/bundled-plugins/security/policies/ssrf.ts +119 -34
  24. package/src/channels/adapters/github/inbound.ts +11 -0
  25. package/src/channels/adapters/github/index.ts +48 -54
  26. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  27. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  28. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  29. package/src/channels/adapters/slack-bot.ts +7 -2
  30. package/src/channels/adapters/slack-format.ts +245 -0
  31. package/src/channels/github-token-bridge.ts +2 -3
  32. package/src/container/docker-app.ts +42 -13
  33. package/src/container/start.ts +13 -0
  34. package/src/cron/bridge.ts +9 -2
  35. package/src/doctor/checks.ts +5 -2
  36. package/src/git/bound-gc-config.ts +82 -0
  37. package/src/hostd/spawn.ts +133 -47
  38. package/src/init/dockerfile.ts +13 -0
  39. package/src/inspect/replay.ts +21 -9
  40. package/src/inspect/session-list.ts +71 -33
  41. package/src/mcp/tools.ts +1 -0
  42. package/src/network/internal-destinations.ts +267 -0
  43. package/src/plugin/types.ts +3 -2
  44. package/src/sandbox/env-exposure.ts +18 -15
  45. package/src/sandbox/policy.ts +5 -3
  46. package/src/sandbox/privileged-runtime.ts +1 -0
  47. package/src/skills/typeclaw-config/SKILL.md +22 -6
  48. package/src/skills/typeclaw-permissions/SKILL.md +22 -9
  49. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  50. package/src/usage/scan.ts +11 -2
  51. package/typeclaw.schema.json +5 -0
  52. package/src/git/secret-history.ts +0 -371
@@ -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 }
@@ -6,12 +6,12 @@ export const GRAPHQL_AUTH_NUDGE_TAG = 'github-cli-auth:graphqlRepoHint'
6
6
 
7
7
  const NUDGE_TEXT =
8
8
  `\n\n[${GRAPHQL_AUTH_NUDGE_TAG}] That looked like a GitHub auth failure on a ` +
9
- '`gh api graphql` call. Under a multi-owner GitHub App there is no single ' +
10
- '`GH_TOKEN`, and graphql carries its repo inside the query — not an inspectable ' +
11
- 'path — so TypeClaw cannot tell which installation token to mint. Re-run with an ' +
12
- 'explicit repo, e.g. `gh api graphql -R owner/repo -f query=...`. `gh api` does ' +
13
- 'not accept `-R/--repo`; TypeClaw consumes it as the mint hint and strips it ' +
14
- 'before running the command with the right token injected.'
9
+ '`gh api graphql` call. GitHub App credentials are not ambient process tokens, ' +
10
+ 'and graphql carries its repo inside the query — not an inspectable path — so ' +
11
+ 'TypeClaw needs a repo hint before it can mint a repo-scoped installation token. ' +
12
+ 'Re-run with an explicit repo, e.g. `gh api graphql -R owner/repo -f query=...`. ' +
13
+ '`gh api` does not accept `-R/--repo`; TypeClaw consumes it as the mint hint and ' +
14
+ 'strips it before running the command with the right token injected.'
15
15
 
16
16
  // The shell strips quotes/escapes, so we match the raw `gh ... graphql` substring
17
17
  // rather than parse — the nudge is advisory, so a loose match is acceptable and a
@@ -40,9 +40,9 @@ const AUTH_FAILURE_SIGNATURES = [
40
40
  export function checkGraphqlAuthNudge(options: { tool: string; result: ToolResult }): void {
41
41
  if (options.tool !== 'bash') return
42
42
 
43
- // Only meaningful when no usable token is seeded — the multi-owner App case.
44
- // A seeded global token (single-owner App, classic/fine-grained PAT) means
45
- // graphql already authenticates, so the advice would be wrong.
43
+ // Only meaningful when no usable process token exists. An operator token or a
44
+ // runtime-seeded PAT means graphql already authenticates, so the advice would
45
+ // be wrong.
46
46
  const tokenClass = classifyGhToken(process.env.GH_TOKEN)
47
47
  if (tokenClass !== 'none') return
48
48
 
@@ -4,6 +4,7 @@ import {
4
4
  configureReviewVerdictCoordinator,
5
5
  createSharedReviewVerdictGuard,
6
6
  } from '@/channels/github-review-verdict-coordinator'
7
+ import { hasEnvKey } from '@/init/env-file'
7
8
  import { CORE_PERMISSIONS } from '@/permissions/builtins'
8
9
  import { definePlugin } from '@/plugin'
9
10
 
@@ -14,6 +15,7 @@ import {
14
15
  effectiveGhTokensForAuthenticatedUserEndpoint,
15
16
  usesGhApiGraphqlEndpoint,
16
17
  } from './gh-command'
18
+ import { ensureGitAskPassHelper, resolveSandboxGitAskPassPath } from './git-askpass'
17
19
  import { analyzeGitCommand, defaultGitResolvers, resolveGhDefaultRepoFromCwd } from './git-command'
18
20
  import { checkGraphqlAuthNudge } from './graphql-auth-nudge'
19
21
  import { commitReviewIfSucceeded, noteReviewCommand } from './review-recorder'
@@ -52,17 +54,38 @@ export default definePlugin({
52
54
  : undefined
53
55
  }
54
56
 
55
- // The PAT is in the container env but stripped by --clearenv for this role,
56
- // and a PAT is not re-mintable per repo, so there is no token to inject. Tell
57
- // the AGENT (model-visible block) instead of letting git/gh fail ambiguously
58
- // — the silent variant of this is exactly what caused a multi-day debugging
59
- // hunt. App auth is the supported path for low-trust roles.
57
+ // The token `gh` will actually resolve INSIDE the low-trust sandbox. Only
58
+ // `.env`-declared names survive `--clearenv` (`hasEnvKey` reads the same
59
+ // `readEnvFile(agentDir)` parse the sandbox's `resolveExposableEnvNames` uses,
60
+ // so this is congruent with what the sandbox inherits), and gh's precedence is
61
+ // GH_TOKEN > GITHUB_TOKEN. So a process-only GH_TOKEN does NOT mask an
62
+ // inheritable, operator-declared GITHUB_TOKEN: the process-only name is cleared,
63
+ // leaving the declared alias as the one gh sees. Returns the surviving PAT/App
64
+ // token (value snapshotted from process.env, which holds the declared value),
65
+ // or undefined when the operator declared no usable GitHub token in `.env`.
66
+ const sandboxInheritedGhToken = (): { envName: 'GH_TOKEN' | 'GITHUB_TOKEN'; value: string } | undefined => {
67
+ for (const envName of ['GH_TOKEN', 'GITHUB_TOKEN'] as const) {
68
+ if (!hasEnvKey(ctx.agentDir, envName)) continue
69
+ const value = process.env[envName]
70
+ if (value !== undefined && value !== '') return { envName, value }
71
+ }
72
+ return undefined
73
+ }
74
+
75
+ // A process-only PAT (runtime/App-seeded process.env, NOT declared in `.env`)
76
+ // is stripped by --clearenv for this role, and a PAT is not re-mintable per
77
+ // repo, so there is no token to inject. Tell the AGENT (model-visible block)
78
+ // instead of letting git/gh fail ambiguously — the silent variant of this is
79
+ // exactly what caused a multi-day debugging hunt. This does NOT fire for a PAT
80
+ // the operator declared in `.env`: that one is inherited into the sandbox and
81
+ // handled by the allow-path above.
60
82
  const sandboxedPatWithheldReason =
61
- 'A classic/fine-grained GitHub PAT is configured (via .env GH_TOKEN), but this command runs ' +
62
- 'in a sandboxed (low-trust) role whose environment is cleared before bash — so the PAT is ' +
63
- 'withheld here and is NOT available to git/gh. This is a deliberate guard, not missing auth: a ' +
64
- 'broad, long-lived PAT must not be reachable from a low-trust sandbox. Configure GitHub App auth ' +
65
- '(channels.github) to grant per-repo, short-lived tokens that DO work for sandboxed roles.'
83
+ 'A classic/fine-grained GitHub PAT is present in the runtime environment but was NOT declared ' +
84
+ 'in `.env`, and this command runs in a sandboxed (low-trust) role whose environment is cleared ' +
85
+ 'before bash — so the PAT is withheld here and is NOT available to git/gh. This is a deliberate ' +
86
+ 'guard, not missing auth: a broad, long-lived runtime PAT must not be reachable from a low-trust ' +
87
+ 'sandbox. Configure GitHub App auth (channels.github) for per-repo, short-lived tokens that work ' +
88
+ 'for sandboxed roles, or declare the PAT in `.env` to deliberately expose it to model bash.'
66
89
 
67
90
  let warnedSandboxedPatWithheld = false
68
91
  const warnSandboxedPatWithheldOnce = (): void => {
@@ -250,22 +273,41 @@ export default definePlugin({
250
273
  event.args.command = decision.rewrittenCommand
251
274
  }
252
275
 
276
+ // When NO per-repo App minter is available, prefer the token the operator
277
+ // deliberately exposed via `.env`: the sandbox inherits it into bash for
278
+ // EVERY role, so the validated command just runs on it — no block, no
279
+ // overlay except GH_REPO (non-secret) for a trusted-fallback repo. This runs
280
+ // BEFORE the process-token-class branches so it is independent of gh's
281
+ // GH_TOKEN>GITHUB_TOKEN process preference: an undeclared (process-only)
282
+ // GH_TOKEN — even App-class `ghs_` — never masks a declared, inheritable
283
+ // GITHUB_TOKEN, because sandboxInheritedGhToken() only considers names that
284
+ // survive --clearenv. When a minter IS available it wins (least-privilege
285
+ // short-lived per-repo token over a broad declared PAT) via the paths below.
286
+ if (!hasAppTokenResolver() && sandboxInheritedGhToken() !== undefined) {
287
+ if (decision.kind === 'inject' && fallbackRepoUsed && fallbackRepo !== undefined) {
288
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = { GH_REPO: fallbackRepo }
289
+ }
290
+ return
291
+ }
292
+
253
293
  // PAT classes (classic = cross-owner, fine-grained) are not re-minted per
254
294
  // repo; the seeded GH_TOKEN is the only token we have. App minting, when
255
- // available, is preferred for roles without credential-use permission,
256
- // so a PAT must not suppress minting there. An entitled role receives the
257
- // PAT through the narrow overlay; raw process.env and credential files
258
- // remain unavailable inside bash. Sandboxed PAT-only:
259
- // block with guidance instead of failing silently.
295
+ // available, is preferred for ALL roles (least-privilege per-repo token over
296
+ // a broad PAT), so a PAT must not suppress minting. An entitled role with NO
297
+ // minter receives the PAT through the narrow overlay; raw process.env and
298
+ // credential files remain unavailable inside bash. Sandboxed PAT-only with no
299
+ // minter and no `.env` declaration: block with guidance instead of failing
300
+ // silently.
260
301
  // Set when a sandboxed PAT falls through to App minting: the tail's
261
302
  // shouldMintAppToken(process.env.GH_TOKEN) re-check would see the PAT and
262
303
  // bail, so this flag forces the mint that the PAT must not suppress.
263
304
  let mintForSandboxedPat = false
264
305
  if (tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat') {
265
- // Credential-entitled role: for a repo-targeting command, inject the PAT
266
- // through the runtime-owned overlay. The same literal-repo and
267
- // credential-safe argv gates apply to PATs and App tokens.
268
- if (canUsePat(event.origin)) {
306
+ // Credential-entitled role, NO App minter: inject the PAT through the
307
+ // runtime-owned overlay. Gated on `!hasAppTokenResolver()` — when a minter
308
+ // is available it wins, so a declared/entitled PAT does not beat the
309
+ // least-privilege per-repo App token; execution falls through to minting.
310
+ if (canUsePat(event.origin) && !hasAppTokenResolver()) {
269
311
  if (decision.kind === 'inject') {
270
312
  event.args[TYPECLAW_INTERNAL_BASH_ENV] = {
271
313
  [processToken?.envName ?? 'GH_TOKEN']: processToken?.value ?? '',
@@ -274,9 +316,10 @@ export default definePlugin({
274
316
  }
275
317
  return
276
318
  }
277
- // Sandboxed: the PAT is stripped by --clearenv. Prefer App minting when
278
- // available (a PAT must NOT suppress it, or the original silent-failure
279
- // bug returns); otherwise block with guidance rather than failing mute.
319
+ // Sandboxed PAT, no minter, not declared in `.env`: the sandbox clears it
320
+ // for this role, so there is no inheritable token. Block with guidance
321
+ // rather than failing mute. (A declared `.env` PAT already returned via the
322
+ // sandbox-inherited allow-path above; an available minter falls through.)
280
323
  if (!shouldMintAppToken(undefined, hasAppTokenResolver())) {
281
324
  warnSandboxedPatWithheldOnce()
282
325
  return blockAfterLease({ block: true, reason: sandboxedPatWithheldReason })
@@ -304,18 +347,54 @@ export default definePlugin({
304
347
  return
305
348
  }
306
349
 
307
- const handleGitCommand = async (params: { command: string; agentDir: string }): Promise<HookResult> => {
308
- const { command, agentDir } = params
350
+ const handleGitCommand = async (params: {
351
+ event: { args: Record<string, unknown> }
352
+ command: string
353
+ agentDir: string
354
+ }): Promise<HookResult> => {
355
+ const { event, command, agentDir } = params
309
356
  const decision = await analyzeGitCommand(command, { cwd: agentDir, resolvers: defaultGitResolvers })
310
357
  if (decision.kind === 'pass-through') return
311
358
  if (decision.kind === 'block') return { block: true, reason: decision.reason }
312
- const token = effectiveProcessToken()
313
- if (token === undefined && !hasAppTokenResolver()) return
314
- return {
315
- block: true,
316
- reason:
317
- 'Authenticated git is unavailable to model-driven bash because git can invoke repository hooks and credential helpers that inherit reusable credentials. Local git commands still work; use a first-class GitHub action or run network git host-side.',
359
+
360
+ // Only a per-repo GitHub App token is brokered to git — never a PAT (git,
361
+ // unlike gh, runs repo-local hooks/helpers, and a PAT is not repo-confined).
362
+ // With no App minter, pass through so git fails honestly.
363
+ if (!hasAppTokenResolver()) return
364
+ const result = await resolveTokenForRepo(decision.repoSlug)
365
+ if (result.kind === 'unavailable') return { block: true, reason: result.reason }
366
+
367
+ // Deliver the token via GIT_ASKPASS (env, never argv/config). The analyzer
368
+ // already constrained this to a single bare github git command, so the token
369
+ // env reaches only this git. hooksPath=/dev/null + credential.helper= stop the
370
+ // two highest-value ways a repo could capture the token; insteadOf folds
371
+ // ssh/scp remotes to https so the credential applies. This is defense-in-depth
372
+ // WITHIN one trust domain, not a wall against a hostile repo — untrusted repos
373
+ // belong in a separate agent (see docs/internals/sandbox.mdx).
374
+ // Sandboxed bash: the helper must be on a sandbox-visible path (baked /usr),
375
+ // not the unsandboxed /tmp default the tmpfs would hide.
376
+ const askpass = await ensureGitAskPassHelper(resolveSandboxGitAskPassPath())
377
+ const existing = event.args[TYPECLAW_INTERNAL_BASH_ENV]
378
+ const overlay = existing !== null && typeof existing === 'object' ? (existing as Record<string, string>) : {}
379
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = {
380
+ ...overlay,
381
+ GIT_ASKPASS: askpass,
382
+ TYPECLAW_GIT_TOKEN: result.token,
383
+ GIT_TERMINAL_PROMPT: '0',
384
+ GIT_CONFIG_COUNT: '4',
385
+ GIT_CONFIG_KEY_0: 'core.hooksPath',
386
+ GIT_CONFIG_VALUE_0: '/dev/null',
387
+ GIT_CONFIG_KEY_1: 'credential.helper',
388
+ GIT_CONFIG_VALUE_1: '',
389
+ // Both ssh remote spellings fold to https so the askpass credential applies:
390
+ // the scp short form (git@github.com:owner/repo) and the ssh:// URL form.
391
+ GIT_CONFIG_KEY_2: 'url.https://github.com/.insteadOf',
392
+ GIT_CONFIG_VALUE_2: 'git@github.com:',
393
+ GIT_CONFIG_KEY_3: 'url.https://github.com/.insteadOf',
394
+ GIT_CONFIG_VALUE_3: 'ssh://git@github.com/',
318
395
  }
396
+ if (decision.rewrittenCommand !== undefined) event.args.command = decision.rewrittenCommand
397
+ return
319
398
  }
320
399
 
321
400
  return {
@@ -331,7 +410,7 @@ export default definePlugin({
331
410
  }
332
411
 
333
412
  if (command.includes('git')) {
334
- return await handleGitCommand({ command, agentDir: ctx.agentDir })
413
+ return await handleGitCommand({ event, command, agentDir: ctx.agentDir })
335
414
  }
336
415
  return
337
416
  },
@@ -11,12 +11,10 @@ export function classifyGhToken(token: string | undefined): GhTokenClass {
11
11
  }
12
12
 
13
13
  // Whether the per-repo App minter should fire for a repo-targeting command.
14
- // App auth is detected via EITHER a seeded App-class GH_TOKEN OR a live App
15
- // token resolver — the latter is the authority because multi-owner / no-repos
16
- // App configs intentionally leave GH_TOKEN unseeded (the prefix would read
17
- // 'none'), yet the per-repo minter is still registered and able to mint. Classic
18
- // and fine-grained PATs are never re-minted: they pass through with whatever
19
- // GH_TOKEN is seeded, exactly as before.
14
+ // App auth is detected via EITHER an operator-supplied App-class GH_TOKEN OR a
15
+ // live App token resolver. The resolver is authoritative for channel App auth,
16
+ // whose credentials are never seeded into process.env. Classic and fine-grained
17
+ // PATs are never re-minted: they pass through with the effective process token.
20
18
  export function shouldMintAppToken(token: string | undefined, hasAppTokenResolver: boolean): boolean {
21
19
  const tokenClass = classifyGhToken(token)
22
20
  if (tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat') return false