typeclaw 0.45.1 → 0.46.0

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 (142) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -1
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +151 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +198 -0
  11. package/src/agent/plugin-tools.ts +379 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1050 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +143 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +27 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/index.ts +2 -1
  32. package/src/bundled-plugins/backup/runner.ts +2 -1
  33. package/src/bundled-plugins/doc-render/render.ts +93 -12
  34. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  35. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  36. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  37. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  38. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  39. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  40. package/src/bundled-plugins/memory/README.md +23 -11
  41. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  42. package/src/bundled-plugins/memory/citations.ts +22 -9
  43. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  44. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  45. package/src/bundled-plugins/memory/index.ts +0 -4
  46. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  47. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  48. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  49. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  50. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  51. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  52. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  53. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  54. package/src/bundled-plugins/reviewer/index.ts +2 -2
  55. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  56. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  57. package/src/bundled-plugins/scout/scout.ts +8 -0
  58. package/src/bundled-plugins/security/index.ts +4 -4
  59. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  60. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  61. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  62. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  63. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  64. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  65. package/src/channels/adapters/discord-bot.ts +66 -6
  66. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  67. package/src/channels/adapters/discord-id.ts +4 -0
  68. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  69. package/src/channels/adapters/discord.ts +57 -7
  70. package/src/channels/adapters/github/auth-app.ts +41 -12
  71. package/src/channels/adapters/github/index.ts +23 -11
  72. package/src/channels/adapters/github/review-submitter.ts +302 -0
  73. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  74. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  75. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  76. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  77. package/src/channels/adapters/slack-bot.ts +19 -8
  78. package/src/channels/adapters/slack-classify.ts +21 -2
  79. package/src/channels/adapters/slack.ts +59 -7
  80. package/src/channels/adapters/telegram-bot.ts +18 -5
  81. package/src/channels/adapters/webex-bot.ts +8 -3
  82. package/src/channels/adapters/webex.ts +8 -3
  83. package/src/channels/fetch-attachment.ts +43 -0
  84. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  85. package/src/channels/github-token-bridge.ts +10 -3
  86. package/src/channels/manager.ts +9 -0
  87. package/src/channels/router.ts +248 -6
  88. package/src/channels/types.ts +28 -1
  89. package/src/cli/channel.ts +1 -1
  90. package/src/cli/init.ts +1 -1
  91. package/src/cli/model.ts +57 -7
  92. package/src/compose/stop.ts +17 -5
  93. package/src/config/config.ts +6 -6
  94. package/src/config/models-mutation.ts +13 -1
  95. package/src/config/providers.ts +176 -0
  96. package/src/container/start.ts +49 -10
  97. package/src/doctor/checks.ts +3 -1
  98. package/src/doctor/commit.ts +2 -1
  99. package/src/doctor/file-ownership.ts +52 -0
  100. package/src/dreams/git.ts +2 -1
  101. package/src/git/hookless.ts +5 -0
  102. package/src/git/reconcile-ignored.ts +18 -5
  103. package/src/git/secret-history.ts +371 -0
  104. package/src/git/system-commit.ts +12 -6
  105. package/src/init/dockerfile.ts +86 -5
  106. package/src/init/index.ts +17 -5
  107. package/src/init/models-dev.ts +4 -0
  108. package/src/init/validate-api-key.ts +2 -0
  109. package/src/mcp/tools.ts +16 -3
  110. package/src/permissions/builtins.ts +3 -1
  111. package/src/plugin/context.ts +2 -0
  112. package/src/plugin/index.ts +1 -0
  113. package/src/plugin/manager.ts +4 -0
  114. package/src/plugin/types.ts +21 -0
  115. package/src/run/index.ts +40 -0
  116. package/src/run/llm-fetch-observer.ts +41 -4
  117. package/src/sandbox/build.ts +37 -15
  118. package/src/sandbox/canonical-secrets.ts +18 -0
  119. package/src/sandbox/env-exposure.ts +80 -0
  120. package/src/sandbox/errors.ts +13 -6
  121. package/src/sandbox/hidden-paths.ts +102 -44
  122. package/src/sandbox/index.ts +22 -4
  123. package/src/sandbox/package-install.ts +3 -27
  124. package/src/sandbox/policy.ts +11 -25
  125. package/src/sandbox/privileged-runtime.ts +255 -0
  126. package/src/sandbox/session-tmp.ts +8 -2
  127. package/src/sandbox/writable-zones.ts +204 -140
  128. package/src/secrets/index.ts +8 -0
  129. package/src/secrets/refresh-provider-oauth.ts +128 -0
  130. package/src/server/command-runner.ts +48 -4
  131. package/src/server/index.ts +4 -0
  132. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  133. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  134. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  135. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  136. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  137. package/src/skills/typeclaw-config/SKILL.md +5 -5
  138. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  139. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  140. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  141. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  142. package/typeclaw.schema.json +20 -0
@@ -1,44 +1,65 @@
1
- import { lstat, mkdir, writeFile } from 'node:fs/promises'
2
- import { join } from 'node:path'
1
+ import { lstat, mkdir, opendir, writeFile } from 'node:fs/promises'
2
+ import { join, sep } from 'node:path'
3
3
 
4
4
  import type { SessionOrigin } from '@/agent/session-origin'
5
5
  import { CORE_PERMISSIONS } from '@/permissions/builtins'
6
6
  import type { PermissionService } from '@/permissions/permissions'
7
7
 
8
+ import { CANONICAL_AGENT_SECRET_DIRS, CANONICAL_AGENT_SECRET_FILES } from './canonical-secrets'
9
+ import { SandboxMaskTargetError } from './errors'
10
+
8
11
  export type HiddenPaths = {
9
12
  dirs: string[]
10
13
  files: string[]
11
14
  }
12
15
 
13
16
  const PRIVATE_DIRS = ['workspace', 'memory', 'sessions'] as const
14
- const SECRET_FILES = ['.env', 'secrets.json'] as const
17
+ const MAX_CANONICAL_SECRET_SCAN_ENTRIES = 4096
15
18
 
16
- // The agent's private working surface and credential files are masked from
17
- // sandboxed bash unless the resolved role carries the matching fs.see.* grant.
19
+ // The ordinary private working surface is role-scoped, but canonical credential
20
+ // files and runtime-owned credential directories are always masked.
18
21
  // `permissions.has` resolves the role from the live origin and fails safe to
19
22
  // guest (empty permissions) for an unclear/undefined origin, so a missing
20
23
  // grant — whether from a low tier or an unresolvable author — hides the path.
21
24
  //
22
- // The security.bypass.* fallback keeps custom roles (which may never name the
23
- // fs.see.* strings) working by capability: a role trusted enough to bypass
24
- // medium-severity guards is treated as trusted for filesystem visibility, and
25
- // bypass.low maps to the private-surface tier. fs.see.* always wins when
26
- // present; the fallback only fires when it is absent.
25
+ // The security.bypass.* fallback keeps custom roles (which may never name
26
+ // fs.see.private) working by capability. fs.see.secrets remains useful for
27
+ // runtime-owned credential injection, but it deliberately cannot make raw
28
+ // .env, secrets.json, or historical auth.json bytes available to an LLM.
29
+ // Privileged diagnostics must
30
+ // use host-side commands that report presence/status without returning values.
27
31
  export function resolveHiddenPaths(
28
32
  permissions: PermissionService,
29
33
  origin: SessionOrigin | undefined,
30
34
  agentDir: string,
31
35
  ): HiddenPaths {
32
- const seesPrivate =
33
- permissions.has(origin, CORE_PERMISSIONS.fsSeePrivate) ||
34
- permissions.has(origin, 'security.bypass.low') ||
35
- permissions.has(origin, 'security.bypass.medium')
36
+ const seesPrivate = canSeePrivateSurface(permissions, origin)
37
+ const dirs = [
38
+ ...CANONICAL_AGENT_SECRET_DIRS.map((dir) => join(agentDir, dir)),
39
+ ...(seesPrivate ? [] : PRIVATE_DIRS.map((dir) => join(agentDir, dir))),
40
+ ]
41
+ const files = CANONICAL_AGENT_SECRET_FILES.map((f) => join(agentDir, f))
42
+ return { dirs, files }
43
+ }
44
+
45
+ // Before canonical secret masking became unconditional, roles carrying both
46
+ // visibility capabilities ran bash unsandboxed and therefore had full write
47
+ // access to the agent root. They now enter bwrap so canonical credential paths
48
+ // can be masked, but must retain ordinary root-write capability. The policy
49
+ // overlays the secret masks after the RW root bind, so this does not restore raw
50
+ // credential access.
51
+ export function canWriteAgentRootInSandbox(permissions: PermissionService, origin: SessionOrigin | undefined): boolean {
36
52
  const seesSecrets =
37
53
  permissions.has(origin, CORE_PERMISSIONS.fsSeeSecrets) || permissions.has(origin, 'security.bypass.medium')
54
+ return canSeePrivateSurface(permissions, origin) && seesSecrets
55
+ }
38
56
 
39
- const dirs = seesPrivate ? [] : PRIVATE_DIRS.map((d) => join(agentDir, d))
40
- const files = seesSecrets ? [] : SECRET_FILES.map((f) => join(agentDir, f))
41
- return { dirs, files }
57
+ function canSeePrivateSurface(permissions: PermissionService, origin: SessionOrigin | undefined): boolean {
58
+ return (
59
+ permissions.has(origin, CORE_PERMISSIONS.fsSeePrivate) ||
60
+ permissions.has(origin, 'security.bypass.low') ||
61
+ permissions.has(origin, 'security.bypass.medium')
62
+ )
42
63
  }
43
64
 
44
65
  // SECURITY / bwrap contract: the mask ops REQUIRE a pre-existing target.
@@ -51,31 +72,78 @@ export function resolveHiddenPaths(
51
72
  // here (only sandboxed bash sees it RO), so an empty placeholder is harmless and
52
73
  // the mask binds over a real empty file, leaking nothing.
53
74
  //
54
- // ENSURE, not FILTER: package-install mode makes the jail root RW
75
+ // ENSURE, not FILTER: privileged modes make the jail root RW
55
76
  // (`writableRoot: agentDir`), so dropping an absent secret would let sandboxed
56
- // code CREATE `.env`/`secrets.json` for real (planting) or expose one created
77
+ // code CREATE a canonical credential path for real (planting) or expose one created
57
78
  // mid-session (TOCTOU). A guaranteed target keeps the mask always rendered over
58
- // it (last-op-wins), closing that hole for both jail modes. A symlink squatting
59
- // a target is refused and dropped (a bind would follow it out), and each target
60
- // is best-effort so one bad entry degrades that mask, never aborts sandboxing.
79
+ // it (last-op-wins), closing that hole for every mode. Required masks are
80
+ // fail-closed: symlinks, wrong entry kinds, hardlinked files, materialization
81
+ // failures, or a late identity change abort bash.
61
82
  export async function ensureHiddenMaskTargets(hidden: HiddenPaths): Promise<HiddenPaths> {
62
- const dirs = await ensureMaskTargets(hidden.dirs, 'dir')
63
- const files = await ensureMaskTargets(hidden.files, 'file')
83
+ const dirs = await Promise.all(hidden.dirs.map((target) => ensureRequiredDirMaskTarget(target)))
84
+ const files = await Promise.all(hidden.files.map((target) => ensureRequiredFileMaskTarget(target)))
64
85
  return { dirs, files }
65
86
  }
66
87
 
67
- async function ensureMaskTargets(targets: string[], kind: 'dir' | 'file'): Promise<string[]> {
68
- const results = await Promise.all(targets.map((target) => ensureMaskTarget(target, kind)))
69
- return targets.filter((_, i) => results[i])
88
+ export async function verifyHiddenMaskTargets(hidden: HiddenPaths): Promise<void> {
89
+ await Promise.all(hidden.dirs.map((target) => verifyRequiredMaskTarget(target, 'dir')))
90
+ await Promise.all(hidden.files.map((target) => verifyRequiredMaskTarget(target, 'file')))
70
91
  }
71
92
 
72
- async function ensureMaskTarget(target: string, kind: 'dir' | 'file'): Promise<boolean> {
73
- try {
74
- if (kind === 'dir') await mkdir(target, { recursive: true })
75
- else await ensureEmptyFile(target)
76
- return await isRealEntry(target, kind)
77
- } catch {
78
- return false
93
+ async function ensureRequiredDirMaskTarget(target: string): Promise<string> {
94
+ await mkdir(target, { recursive: true }).catch(() => {})
95
+ await verifyRequiredMaskTarget(target, 'dir')
96
+ return target
97
+ }
98
+
99
+ async function ensureRequiredFileMaskTarget(target: string): Promise<string> {
100
+ await ensureEmptyFile(target)
101
+ await verifyRequiredMaskTarget(target, 'file')
102
+ return target
103
+ }
104
+
105
+ async function verifyRequiredMaskTarget(target: string, kind: 'dir' | 'file'): Promise<void> {
106
+ const stats = await lstat(target).catch(() => {
107
+ throw new SandboxMaskTargetError(target, `could not materialize or inspect a ${kind}`)
108
+ })
109
+ if (stats.isSymbolicLink()) throw new SandboxMaskTargetError(target, 'symlinks are not maskable safely')
110
+ if (kind === 'dir' && !stats.isDirectory()) throw new SandboxMaskTargetError(target, 'target is not a directory')
111
+ if (kind === 'file' && !stats.isFile()) throw new SandboxMaskTargetError(target, 'target is not a regular file')
112
+ if (kind === 'file' && stats.nlink !== 1) throw new SandboxMaskTargetError(target, 'target has hardlink aliases')
113
+ if (kind === 'dir' && isCanonicalSecretDir(target)) await rejectHardlinksUnderCanonicalDir(target)
114
+ }
115
+
116
+ function isCanonicalSecretDir(target: string): boolean {
117
+ return CANONICAL_AGENT_SECRET_DIRS.some((dir) => target.endsWith(`${sep}${dir.split('/').join(sep)}`))
118
+ }
119
+
120
+ async function rejectHardlinksUnderCanonicalDir(root: string): Promise<void> {
121
+ const pending = [root]
122
+ let visited = 0
123
+ while (pending.length > 0) {
124
+ const current = pending.pop() as string
125
+ const dir = await opendir(current).catch(() => {
126
+ throw new SandboxMaskTargetError(root, 'canonical secret directory could not be scanned safely')
127
+ })
128
+ try {
129
+ for await (const entry of dir) {
130
+ visited += 1
131
+ if (visited > MAX_CANONICAL_SECRET_SCAN_ENTRIES) {
132
+ throw new SandboxMaskTargetError(root, 'canonical secret directory exceeds bounded hardlink scan')
133
+ }
134
+ const child = join(current, entry.name)
135
+ const stats = await lstat(child)
136
+ if (stats.isSymbolicLink()) continue
137
+ if (stats.isDirectory()) pending.push(child)
138
+ if (stats.isFile() && stats.nlink !== 1) {
139
+ throw new SandboxMaskTargetError(root, `file under canonical secret directory has hardlink aliases: ${child}`)
140
+ }
141
+ }
142
+ } finally {
143
+ try {
144
+ await dir.close()
145
+ } catch {}
146
+ }
79
147
  }
80
148
  }
81
149
 
@@ -88,13 +156,3 @@ async function ensureEmptyFile(target: string): Promise<void> {
88
156
  // else is dropped from the mask.
89
157
  }
90
158
  }
91
-
92
- async function isRealEntry(target: string, kind: 'dir' | 'file'): Promise<boolean> {
93
- try {
94
- const stats = await lstat(target)
95
- if (stats.isSymbolicLink()) return false
96
- return kind === 'dir' ? stats.isDirectory() : stats.isFile()
97
- } catch {
98
- return false
99
- }
100
- }
@@ -1,4 +1,10 @@
1
1
  export { buildSandboxedCommand, type SandboxedCommand } from './build'
2
+ export {
3
+ CANONICAL_AGENT_SECRET_DIRS,
4
+ CANONICAL_AGENT_SECRET_FILES,
5
+ CANONICAL_HOME_SECRET_DIRS,
6
+ CANONICAL_HOME_SECRET_FILES,
7
+ } from './canonical-secrets'
2
8
  export {
3
9
  buildProcBindProbeScript,
4
10
  canBindProcSafely,
@@ -13,22 +19,34 @@ export {
13
19
  _resetProcBindProbeCacheForTests,
14
20
  _resetRealProcProbeCacheForTests,
15
21
  } from './availability'
16
- export { ensureHiddenMaskTargets, resolveHiddenPaths, type HiddenPaths } from './hidden-paths'
17
22
  export {
18
- resolvePackageInstallZones,
23
+ canWriteAgentRootInSandbox,
24
+ ensureHiddenMaskTargets,
25
+ resolveHiddenPaths,
26
+ verifyHiddenMaskTargets,
27
+ type HiddenPaths,
28
+ } from './hidden-paths'
29
+ export {
19
30
  resolveProtectedZones,
20
31
  resolveWritableZones,
32
+ isGitControlPath,
21
33
  subtractMasked,
22
- type PackageInstallZones,
23
34
  type ProtectedZones,
24
35
  type WritableZones,
25
36
  } from './writable-zones'
26
37
  export { resolveSandboxSymlinks, type SandboxSymlinkSpec } from './symlinks'
27
- export { commandNeedsRealProc, isPackageInstallCommand } from './package-install'
38
+ export { commandNeedsRealProc } from './package-install'
39
+ export {
40
+ cleanupPrivilegedSandboxRuntime,
41
+ resolvePrivilegedSandboxRuntime,
42
+ verifyPrivilegedSandboxRuntime,
43
+ type PrivilegedSandboxRuntime,
44
+ } from './privileged-runtime'
28
45
  export { ensureSessionTmpDir, isUnderTmp, mapVirtualTmpPath, SESSION_TMP_ROOT, sessionTmpDir } from './session-tmp'
29
46
  export { formatCommand, shellQuote } from './quote'
30
47
  export {
31
48
  SandboxDegradedProcError,
49
+ SandboxMaskTargetError,
32
50
  SandboxPolicyError,
33
51
  SandboxProcProbeUnverifiedError,
34
52
  SandboxUnavailableError,
@@ -1,27 +1,3 @@
1
- // Recognizes the narrow command class that earns the package-install sandbox
2
- // mode (RW project root). Deliberately conservative: a single standalone local
3
- // `bun add` / `bun install` / `bun i` with NO shell metacharacters, chaining,
4
- // redirects, or substitution. Anything fancier (`bun add x && rm -rf …`,
5
- // `bun add x; curl …`, a subshell, a pipe) falls back to the default ro-root
6
- // jail so the broad RW root can never be piggybacked onto an attacker-controlled
7
- // second command. Global installs (`-g` / `--global`) are excluded — the
8
- // bun-hygiene guard already blocks them and they write outside the jail anyway.
9
- const SHELL_METACHARACTERS = /[;&|`$()<>\\\n\r{}!*?[\]"']/
10
-
11
- const GLOBAL_FLAG = /^(-g|--global)$/
12
-
13
- export function isPackageInstallCommand(command: string): boolean {
14
- if (SHELL_METACHARACTERS.test(command)) return false
15
-
16
- const words = command.trim().split(/\s+/)
17
- if (words[0] !== 'bun') return false
18
-
19
- const subcommand = words[1]
20
- if (subcommand !== 'add' && subcommand !== 'install' && subcommand !== 'i') return false
21
-
22
- return !words.some((word) => GLOBAL_FLAG.test(word))
23
- }
24
-
25
1
  // The bun subcommands whose work (or whose spawned child) reads the kernel-backed
26
2
  // /proc/self/{fd,maps} magic symlinks: package installs (add/install/i), the
27
3
  // package runners (x/create), and `run` (which can exec a package bin). Under the
@@ -41,11 +17,11 @@ const SHELL_COMMAND_SEPARATOR = /(?:&&|\|\||[;|&\n()])+/
41
17
 
42
18
  // Whether a command will exercise the real /proc, so a caller can turn the
43
19
  // degraded-mode `tmpfs` fallback into an actionable diagnostic instead of letting
44
- // Bun surface its opaque "NotDir". UNLIKE isPackageInstallCommand this is a
45
- // DIAGNOSTIC heuristic, not a privilege gate — it deliberately fires through shell
20
+ // Bun surface its opaque "NotDir". This is a DIAGNOSTIC heuristic, not a
21
+ // privilege gate — it deliberately fires through shell
46
22
  // metacharacters and chained preludes (a `cd app && bunx foo` still runs bunx) and
47
23
  // never widens the sandbox surface, so erring toward catching more only improves
48
- // the error message.
24
+ // the error message. It is not an authorization boundary.
49
25
  export function commandNeedsRealProc(command: string): boolean {
50
26
  return command.split(SHELL_COMMAND_SEPARATOR).some((segment) => segmentInvokesRealProcBun(segment.trim()))
51
27
  }
@@ -9,7 +9,7 @@ export type SandboxNetwork = 'none' | 'inherit'
9
9
  // 'proc-bind' (the runtime default): --ro-bind /proc /proc binds the container's
10
10
  // ALREADY-REAL procfs straight into the sandbox — no `unshare --mount-proc`, no
11
11
  // CAP_SYS_ADMIN. A JS package runner's child gets a real /proc/self/{fd,maps,exe}
12
- // so `bunx`/`bun add`/`bun run <pkg-bin>` stop aborting with Bun's ENOTDIR. The
12
+ // so allowed `bunx`/`bun run <pkg-bin>` calls stop aborting with Bun's ENOTDIR. The
13
13
  // agent runtime's /proc/<agent>/environ (OPENAI_API_KEY, GH_TOKEN) is NOT
14
14
  // leaked: build.ts always emits --unshare-user, so the sandboxed bash runs as
15
15
  // mapped-root in a CHILD user namespace that is not an ancestor of the agent
@@ -37,6 +37,11 @@ export type SandboxProcStrategy = 'tmpfs' | 'none' | 'real-proc' | 'proc-bind'
37
37
  export type SandboxEnvPolicy = {
38
38
  set?: Record<string, string>
39
39
  passthrough?: string[]
40
+ // Preserve these names from bwrap's parent environment without rendering
41
+ // their values in argv. The builder switches from --clearenv to explicit
42
+ // --unsetenv for every other inherited name. Reserved for command-scoped
43
+ // secrets whose parent process is protected by the child-userns boundary.
44
+ inherit?: string[]
40
45
  }
41
46
 
42
47
  export type SandboxCommandFilter = {
@@ -94,36 +99,18 @@ export type SandboxSymlinkOp = {
94
99
  dest: string
95
100
  }
96
101
 
97
- // A single RW bind of the project root, used ONLY by the package-install path
98
- // (recognized standalone `bun add`/`bun install` commands). `bun add` writes
99
- // node_modules/ AND a temp lockfile (`bun.lock.NNN.tmp`, atomically renamed)
100
- // directly under the root, so a file-level RW bind of `bun.lock` alone is
101
- // insufficient — Bun needs DIRECTORY write to create its temp file. The default
102
- // ro-root + narrow carve-out model can't express that, so this widens the root
103
- // to RW for that command class only.
102
+ // A single RW bind that preserves ordinary agent-root writes for trusted/owner
103
+ // callers. Masks and protected zones overlay it; writableRoot provides no
104
+ // package-install isolation.
104
105
  //
105
106
  // CRITICAL ordering: unlike `writable` (rendered AFTER masks), `writableRoot`
106
107
  // renders BEFORE masks so the broad RW root does not re-expose secrets. With
107
108
  // last-op-wins the chain is: ro-bind root → writableRoot (RW root) → masks
108
- // (re-hide .env/secrets.json/private dirs) → protected (re-RO node_modules/typeclaw,
109
- // packages, .agents/skills, .git/hooks, .git/config). Everything stays hidden or
110
- // EROFS except the dirs a dependency install legitimately needs to write.
109
+ // (re-hide .env/secrets.json/private dirs) → protected (.git/hooks/.git/config).
111
110
  export type SandboxWritableRootPolicy = {
112
111
  dir: string
113
112
  }
114
113
 
115
- // Paths whose CREATION must be blocked under a writable root, rendered as
116
- // `--ro-bind /dev/null <path>`. Used by the package-install path for the
117
- // semantically-guarded managed files (cron.json / typeclaw.json) when they are
118
- // ABSENT: the RW root would otherwise let a postinstall lifecycle script create
119
- // them, bypassing the write/edit-tool guards. Binding /dev/null occupies the
120
- // path with an empty read-only object (blocking creation) WITHOUT manufacturing
121
- // a real invalid file on the host FS. Renders after writableRoot, with the
122
- // protected binds, so last-op-wins keeps the path occupied.
123
- export type SandboxBlockedCreationPolicy = {
124
- files?: string[]
125
- }
126
-
127
114
  export type SandboxPolicy = {
128
115
  bwrapPath?: string
129
116
  cwd?: string
@@ -140,7 +127,6 @@ export type SandboxPolicy = {
140
127
  masks?: SandboxMaskPolicy
141
128
  writable?: SandboxWritablePolicy
142
129
  protected?: SandboxProtectedPolicy
143
- blockedCreation?: SandboxBlockedCreationPolicy
144
130
  symlinks?: SandboxSymlinkOp[]
145
131
  network?: SandboxNetwork
146
132
  env?: SandboxEnvPolicy
@@ -158,7 +144,7 @@ export type SandboxPolicy = {
158
144
  //
159
145
  // BUN_TMPDIR / BUN_INSTALL both point under /tmp because `--clearenv` strips
160
146
  // the host's TMPDIR, and bun refuses to run without a writable scratch dir it
161
- // can discover: `bunx`, `bun add`, and `bun run <pkg-bin>` abort with
147
+ // can discover: `bunx` and `bun run <pkg-bin>` abort with
162
148
  // "Unexpected accessing temporary directory. Please set $BUN_TMPDIR or
163
149
  // $BUN_INSTALL". /tmp is always writable inside the sandbox (fresh tmpfs, or
164
150
  // the per-session bind that overrides it), so both are safe targets. Without
@@ -0,0 +1,255 @@
1
+ import { chmod, lstat, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { homedir, tmpdir } from 'node:os'
3
+ import path from 'node:path'
4
+
5
+ import { SandboxPolicyError } from './errors'
6
+ import type { SandboxMount } from './policy'
7
+
8
+ const SAFE_GIT_SUBCOMMANDS = new Set([
9
+ 'add',
10
+ 'branch',
11
+ 'checkout',
12
+ 'cherry-pick',
13
+ 'commit',
14
+ 'diff',
15
+ 'log',
16
+ 'merge',
17
+ 'rebase',
18
+ 'remote',
19
+ 'reset',
20
+ 'restore',
21
+ 'rev-parse',
22
+ 'show',
23
+ 'status',
24
+ 'switch',
25
+ 'symbolic-ref',
26
+ 'tag',
27
+ 'worktree',
28
+ ])
29
+
30
+ const SHELL_ACTIVE = new Set(['|', ';', '&', '\n', '\r', '(', ')', '{', '}', '<', '>', '`', '$', '\\'])
31
+
32
+ export type PrivilegedSandboxRuntime = {
33
+ env: Record<string, string>
34
+ mounts: SandboxMount[]
35
+ }
36
+
37
+ type StandaloneCommand = { executable: string; args: string[] }
38
+ type MountedIdentity = { birthtimeNs: bigint; ctimeNs: bigint; dev: bigint; ino: bigint }
39
+ const mountedIdentities = new WeakMap<PrivilegedSandboxRuntime, Map<string, MountedIdentity>>()
40
+ const cleanupDirs = new WeakMap<PrivilegedSandboxRuntime, Set<string>>()
41
+
42
+ export async function resolvePrivilegedSandboxRuntime(options: {
43
+ agentDir: string
44
+ command: string
45
+ env?: NodeJS.ProcessEnv
46
+ homeDir?: string
47
+ }): Promise<PrivilegedSandboxRuntime> {
48
+ const runtime = emptyRuntime()
49
+ // TYPECLAW_GIT_TOKEN is set only after the auth analyzer accepts a Git command.
50
+ // Trust that decision rather than reparsing its command with a less capable
51
+ // detector (notably, the analyzer accepts quoted `git` executables).
52
+ if (options.env?.TYPECLAW_GIT_TOKEN !== undefined || containsGitInvocation(options.command)) {
53
+ runtime.env.HOME = options.agentDir
54
+ runtime.env.GIT_CONFIG_GLOBAL = '/dev/null'
55
+ runtime.env.GIT_CONFIG_NOSYSTEM = '1'
56
+ }
57
+ const parsed = parseStandaloneCommand(options.command)
58
+ if (parsed === null) return runtime
59
+
60
+ const homeDir = options.homeDir ?? homedir()
61
+ const executable = unwrapBunx(parsed)
62
+ if (executable === null) return runtime
63
+
64
+ // These CLIs can print or upload arbitrary files. Supplying their reusable
65
+ // auth profile to a model-controlled child would therefore make the CLI a
66
+ // confused deputy even when the outer shell is syntactically standalone.
67
+ if (
68
+ executable.executable === 'gws' ||
69
+ executable.executable === 'codex' ||
70
+ executable.executable === 'claude' ||
71
+ executable.executable.startsWith('agent-')
72
+ ) {
73
+ return runtime
74
+ }
75
+
76
+ if (executable.executable === 'git') {
77
+ runtime.env.GIT_CONFIG_GLOBAL = '/dev/null'
78
+ runtime.env.GIT_CONFIG_NOSYSTEM = '1'
79
+ const subcommand = gitSubcommand(executable.args)
80
+ if (subcommand === null) return runtime
81
+ rejectNamedSubcommand(subcommand, new Set(['config', 'credential', 'credential-cache', 'credential-store']))
82
+ if (!SAFE_GIT_SUBCOMMANDS.has(subcommand)) return runtime
83
+ try {
84
+ await addSanitizedGitIdentity(runtime, path.join(homeDir, '.gitconfig'))
85
+ } catch (error) {
86
+ await cleanupPrivilegedSandboxRuntime(runtime)
87
+ throw error
88
+ }
89
+ }
90
+
91
+ return runtime
92
+ }
93
+
94
+ function containsGitInvocation(command: string): boolean {
95
+ return /(^|[;&|]\s*)git(?:\s|$)/.test(command.trim())
96
+ }
97
+
98
+ export async function verifyPrivilegedSandboxRuntime(runtime: PrivilegedSandboxRuntime): Promise<void> {
99
+ const identities = mountedIdentities.get(runtime) ?? new Map()
100
+ for (const mount of runtime.mounts) {
101
+ if (mount.type !== 'ro-bind') continue
102
+ const safe = await lstat(mount.source, { bigint: true })
103
+ .then(async (stats) => {
104
+ if (stats.isSymbolicLink()) return false
105
+ const expected = identities.get(mount.source)
106
+ return (
107
+ stats.isFile() &&
108
+ stats.nlink === 1n &&
109
+ expected !== undefined &&
110
+ stats.dev === expected.dev &&
111
+ stats.ino === expected.ino &&
112
+ stats.ctimeNs === expected.ctimeNs &&
113
+ stats.birthtimeNs === expected.birthtimeNs
114
+ )
115
+ })
116
+ .catch(() => false)
117
+ if (!safe) {
118
+ throw new SandboxPolicyError(`credential profile changed after validation: ${mount.source}. Refusing to run.`)
119
+ }
120
+ }
121
+ }
122
+
123
+ export async function cleanupPrivilegedSandboxRuntime(runtime: PrivilegedSandboxRuntime): Promise<void> {
124
+ const dirs = cleanupDirs.get(runtime) ?? new Set()
125
+ const outcomes = await Promise.allSettled([...dirs].map((dir) => rm(dir, { recursive: true, force: true })))
126
+ dirs.clear()
127
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected')
128
+ if (failed?.status === 'rejected') throw failed.reason
129
+ }
130
+
131
+ function emptyRuntime(): PrivilegedSandboxRuntime {
132
+ const runtime = { env: {}, mounts: [] }
133
+ mountedIdentities.set(runtime, new Map())
134
+ cleanupDirs.set(runtime, new Set())
135
+ return runtime
136
+ }
137
+
138
+ function unwrapBunx(command: StandaloneCommand): StandaloneCommand | null {
139
+ if (command.executable !== 'bunx') return command
140
+ const args = [...command.args]
141
+ if (args[0] === '--bun') args.shift()
142
+ const executable = args.shift()
143
+ return executable === undefined ? null : { executable, args }
144
+ }
145
+
146
+ function rejectNamedSubcommand(subcommand: string, denied: ReadonlySet<string>): void {
147
+ if (denied.has(subcommand)) {
148
+ throw new SandboxPolicyError(
149
+ `credential or token management command \`${subcommand}\` is unavailable to model-driven bash; use a host-side login or redacted status command instead.`,
150
+ )
151
+ }
152
+ }
153
+
154
+ function gitSubcommand(args: readonly string[]): string | null {
155
+ for (let i = 0; i < args.length; i++) {
156
+ const arg = args[i] as string
157
+ if (arg === '-C') {
158
+ i += 1
159
+ continue
160
+ }
161
+ if (arg === '-c' || arg === '--config-env' || arg.startsWith('--config-env=')) return null
162
+ if (arg.startsWith('-')) continue
163
+ return arg
164
+ }
165
+ return null
166
+ }
167
+
168
+ async function addSanitizedGitIdentity(runtime: PrivilegedSandboxRuntime, source: string): Promise<void> {
169
+ const raw = await readFile(source, 'utf8').catch((error) => {
170
+ if (isNotFoundError(error)) return ''
171
+ throw error
172
+ })
173
+ if (raw === '') return
174
+ const values = parseGitUserIdentity(raw)
175
+ if (values.length === 0) return
176
+ const dir = await mkdtemp(path.join(tmpdir(), 'typeclaw-git-identity-'))
177
+ cleanupDirs.get(runtime)?.add(dir)
178
+ const generated = path.join(dir, 'config')
179
+ await writeFile(generated, `[user]\n${values.map(([key, value]) => `\t${key} = ${value}`).join('\n')}\n`, {
180
+ flag: 'wx',
181
+ })
182
+ await chmod(generated, 0o600)
183
+ const stats = await lstat(generated, { bigint: true })
184
+ mountedIdentities.get(runtime)?.set(generated, {
185
+ birthtimeNs: stats.birthtimeNs,
186
+ ctimeNs: stats.ctimeNs,
187
+ dev: stats.dev,
188
+ ino: stats.ino,
189
+ })
190
+ runtime.mounts.push({ type: 'ro-bind', source: generated, dest: '/tmp/.gitconfig' })
191
+ runtime.env.GIT_CONFIG_GLOBAL = '/tmp/.gitconfig'
192
+ }
193
+
194
+ function parseGitUserIdentity(raw: string): Array<['name' | 'email', string]> {
195
+ const values = new Map<'name' | 'email', string>()
196
+ let inUser = false
197
+ for (const line of raw.split(/\r?\n/)) {
198
+ const section = line.match(/^\s*\[([^\]]+)]\s*$/)
199
+ if (section !== null) {
200
+ inUser = section[1]?.trim().toLocaleLowerCase() === 'user'
201
+ continue
202
+ }
203
+ if (!inUser) continue
204
+ const entry = line.match(/^\s*(name|email)\s*=\s*(.*?)\s*$/i)
205
+ if (entry === null || entry[2] === undefined) continue
206
+ const key = entry[1]?.toLocaleLowerCase() as 'name' | 'email'
207
+ const value = entry[2].replaceAll('\r', '').replaceAll('\n', '').replaceAll('\0', '')
208
+ if (value !== '') values.set(key, value)
209
+ }
210
+ return [...values.entries()]
211
+ }
212
+
213
+ function parseStandaloneCommand(command: string): StandaloneCommand | null {
214
+ const words: string[] = []
215
+ let word = ''
216
+ let quote: "'" | '"' | null = null
217
+ let active = false
218
+ for (const ch of command.trim()) {
219
+ if (quote === "'") {
220
+ if (ch === "'") quote = null
221
+ else word += ch
222
+ continue
223
+ }
224
+ if (quote === '"') {
225
+ if (ch === '"') quote = null
226
+ else if (ch === '$' || ch === '`' || ch === '\\') return null
227
+ else word += ch
228
+ continue
229
+ }
230
+ if (ch === "'" || ch === '"') {
231
+ quote = ch
232
+ active = true
233
+ continue
234
+ }
235
+ if (SHELL_ACTIVE.has(ch)) return null
236
+ if (/\s/.test(ch)) {
237
+ if (active) {
238
+ words.push(word)
239
+ word = ''
240
+ active = false
241
+ }
242
+ continue
243
+ }
244
+ word += ch
245
+ active = true
246
+ }
247
+ if (quote !== null) return null
248
+ if (active) words.push(word)
249
+ const executable = words.shift()
250
+ return executable === undefined ? null : { executable, args: words }
251
+ }
252
+
253
+ function isNotFoundError(error: unknown): boolean {
254
+ return error instanceof Error && 'code' in error && error.code === 'ENOENT'
255
+ }
@@ -27,7 +27,7 @@ export async function ensureSessionTmpDir(sessionId: string): Promise<string> {
27
27
 
28
28
  export function isUnderTmp(agentDir: string, rawPath: string): boolean {
29
29
  const resolved = resolve(agentDir, rawPath)
30
- return resolved === '/tmp' || isInside('/tmp', resolved)
30
+ return isVirtualTmpPath(agentDir, resolved)
31
31
  }
32
32
 
33
33
  // Maps a model-facing /tmp path to its per-session backing path. Returns
@@ -37,11 +37,17 @@ export function isUnderTmp(agentDir: string, rawPath: string): boolean {
37
37
  // for the sandboxed bash that reads it back.
38
38
  export function mapVirtualTmpPath(agentDir: string, sessionId: string, rawPath: string): string | undefined {
39
39
  const resolved = resolve(agentDir, rawPath)
40
- if (resolved !== '/tmp' && !isInside('/tmp', resolved)) return undefined
40
+ if (!isVirtualTmpPath(agentDir, resolved)) return undefined
41
41
  const rel = relative('/tmp', resolved)
42
42
  return rel === '' ? sessionTmpDir(sessionId) : join(sessionTmpDir(sessionId), rel)
43
43
  }
44
44
 
45
+ function isVirtualTmpPath(agentDir: string, resolved: string): boolean {
46
+ const resolvedAgentDir = resolve(agentDir)
47
+ if (resolved === resolvedAgentDir || isInside(resolvedAgentDir, resolved)) return false
48
+ return resolved === '/tmp' || isInside('/tmp', resolved)
49
+ }
50
+
45
51
  function isInside(parent: string, child: string): boolean {
46
52
  const rel = relative(parent, child)
47
53
  return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)