minicode-ai 0.9.26

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 (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
package/src/lib/net.ts ADDED
@@ -0,0 +1,70 @@
1
+ // Penjaga jaringan bersama: validasi host anti-SSRF + DNS pinning.
2
+ // Dipakai web_fetch (tool), web_search, dan transport HTTP MCP — server MCP
3
+ // remote yang menunjuk ke metadata endpoint adalah jalur SSRF yang identik,
4
+ // jadi semuanya memakai satu penjaga yang sama.
5
+ import { lookup } from "node:dns/promises"
6
+
7
+ // Host validasi untuk anti-SSRF. Catatan: WHATWG URL sudah menormalisasi host
8
+ // IPv4 non-dotted (hex 0x7f000001 / desimal 2130706433) menjadi dotted-decimal,
9
+ // jadi cukup cek bentuk dotted di sini — bypass encoding tertutup oleh parser.
10
+ function isPrivateIPv4(host: string): boolean {
11
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host)
12
+ if (!m) return false
13
+ const a = Number(m[1])
14
+ const b = Number(m[2])
15
+ if (a === 127 || a === 10 || a === 0) return true // loopback / priv10 / this-network
16
+ if (a === 192 && b === 168) return true
17
+ if (a === 172 && b >= 16 && b <= 31) return true
18
+ if (a === 169 && b === 254) return true // link-local (cloud metadata IMDS)
19
+ if (a === 100 && b >= 64 && b <= 127) return true // CGNAT 100.64/10
20
+ return false
21
+ }
22
+
23
+ export function isPrivateHost(host: string): boolean {
24
+ const h = host.toLowerCase().replace(/^\[|\]$/g, "")
25
+ if (!h) return true
26
+ if (h === "localhost" || h.endsWith(".localhost")) return true
27
+ if (h.endsWith(".internal") || h.endsWith(".local")) return true
28
+ if (h === "::1" || h === "::") return true
29
+ if (h.startsWith("::ffff:")) return isPrivateIPv4(h.slice(7)) // IPv4-mapped IPv6
30
+ if (/^f[cd][0-9a-f]{2}:/.test(h)) return true // fc00::/7 unique-local
31
+ if (/^fe[89ab][0-9a-f]{0,1}:/.test(h)) return true // fe80::/10 link-local
32
+ return isPrivateIPv4(h)
33
+ }
34
+
35
+ // DNS pinning untuk tutup DNS rebinding: resolve hostname → cek IP private
36
+ // default timeout 400ms fail-open (web_fetch butuh availability); mode strict
37
+ // fail-close untuk embedding/MCP (P1.4) agar DNS timeout tidak jadi SSRF bypass.
38
+ const dnsCache = new Map<string, { addrs: string[]; at: number }>()
39
+ export async function isPrivateHostWithDns(
40
+ hostname: string,
41
+ opts: { strict?: boolean; timeoutMs?: number; noCache?: boolean } = {},
42
+ ): Promise<boolean> {
43
+ if (isPrivateHost(hostname)) return true
44
+ if (/^[\d.]+$/.test(hostname) || hostname.includes(":")) return false
45
+ const timeoutMs = opts.timeoutMs ?? (opts.strict ? 1000 : 400)
46
+ if (!opts.noCache) {
47
+ const cached = dnsCache.get(hostname)
48
+ if (cached && Date.now() - cached.at < 30_000) {
49
+ for (const a of cached.addrs) if (isPrivateHost(a) || isPrivateIPv4(a)) return true
50
+ return false
51
+ }
52
+ }
53
+ try {
54
+ const addrs = (await Promise.race([
55
+ lookup(hostname, { all: true } as never).then((r) => {
56
+ if (Array.isArray(r)) return (r as { address: string }[]).map((x) => x.address)
57
+ return [(r as { address: string }).address]
58
+ }),
59
+ new Promise<never>((_, rej) => setTimeout(() => rej(new Error("dns timeout")), timeoutMs)),
60
+ ])) as string[]
61
+ if (!opts.noCache) dnsCache.set(hostname, { addrs, at: Date.now() })
62
+ for (const a of addrs) if (isPrivateHost(a) || isPrivateIPv4(a)) return true
63
+ } catch {
64
+ // lookup gagal/timeout → strict fail-close (embedding/MCP), default fail-open
65
+ // agar web_fetch tidak block availability bila DNS lambat
66
+ if (!opts.noCache) dnsCache.set(hostname, { addrs: [], at: Date.now() })
67
+ if (opts.strict) return true
68
+ }
69
+ return false
70
+ }
@@ -0,0 +1,138 @@
1
+ import { constants } from "node:fs"
2
+ import type { FileHandle } from "node:fs/promises"
3
+ import { open, realpath } from "node:fs/promises"
4
+ import { basename, dirname, isAbsolute, resolve } from "node:path"
5
+ import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
6
+
7
+ // O_NOFOLLOW mencegah open mengikuti symlink (TOCTOU swap).
8
+ // Di Windows nilai tidak didefinisikan — fallback ke 0 dan pakai dev+ino check.
9
+ const O_NOFOLLOW: number = (constants as unknown as { O_NOFOLLOW?: number }).O_NOFOLLOW ?? 0x20000
10
+ const O_RDONLY = constants.O_RDONLY
11
+
12
+ /**
13
+ * Verifikasi path untuk tool PENULIS (write/edit/patch/delete/move): butuh
14
+ * path real sebagai target tulis (atomicWriteText/rename/trash), jadi cek
15
+ * logis + target nyata dilakukan di sini, toleran ENOENT (file baru — induk
16
+ * yang diverifikasi). Pembaca (read_file/read_image) tidak lewat sini: mereka
17
+ * open via safeOpenRead yang memverifikasi pada titik open.
18
+ *
19
+ * Tanpa state global — realpath segar tiap panggil (wajib untuk TOCTOU).
20
+ * Pesan error mempertahankan substring lama ("path/outside workspace",
21
+ * "blocked sensitive file", "symlink points outside workspace") agar test
22
+ * regex tetap hijau.
23
+ */
24
+ export async function resolveSafePath(
25
+ p: string,
26
+ root: string,
27
+ ): Promise<{ abs: string; real: string }> {
28
+ if (isPathOutsideRoot(p, root)) throw new Error(`path outside workspace: ${p}`)
29
+ if (isSensitive(p)) throw new Error(`blocked sensitive file: ${p}`)
30
+ const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
31
+ const realRoot = await realpath(root).catch(() => root)
32
+ const realDir = await realpath(dirname(abs)).catch(() => dirname(abs))
33
+ const fileReal = await realpath(abs).catch(() => null)
34
+ const real = fileReal ?? resolve(realDir, basename(abs))
35
+ if (isPathOutsideRoot(real, realRoot)) throw new Error(`symlink points outside workspace: ${p}`)
36
+ if (isSensitive(real)) throw new Error(`blocked sensitive file: ${p}`)
37
+ return { abs, real }
38
+ }
39
+
40
+ /**
41
+ * Buka file dengan O_NOFOLLOW pada path yang SUDAH terverifikasi di dalam root.
42
+ *
43
+ * Urutan: realpath(abs) → tolak bila di luar root → open(preReal, O_NOFOLLOW).
44
+ * Membuka hasil resolusi (bukan abs asli) berarti symlink internal tetap bisa
45
+ * dibaca (targetnya yang dibuka langsung), sementara swap jadi symlink lain
46
+ * sebelum open gagal tutup (ELOOP) — tidak ada konten luar yang terbaca.
47
+ *
48
+ * POSIX-only: di Windows konstanta O_NOFOLLOW tidak didefinisikan (Node) dan
49
+ * flag diabaikan libuv, sehingga proteksi = pre-check realpath saja (window
50
+ * race sama seperti pola lama). Catatan jujur: klaim "0 lolos" hanya sah di
51
+ * POSIX — lihat test/tool-toctou.test.ts (skip bila symlink EPERM).
52
+ */
53
+ export async function safeOpenRead(
54
+ abs: string,
55
+ root: string,
56
+ ): Promise<{ handle: FileHandle; realPath: string }> {
57
+ const realRoot = await realpath(root).catch(() => root)
58
+ // Pre-check cepat (fail-fast tanpa open)
59
+ const preReal = await realpath(abs).catch(() => abs)
60
+ if (isPathOutsideRoot(preReal, realRoot))
61
+ throw new Error(`symlink points outside workspace: ${abs}`)
62
+ // Sensitif pada target nyata — symlink bernama jinak bisa menunjuk .env;
63
+ // di sini agar semua pembaca via open (read_file/read_image/stat) mewarisinya.
64
+ if (isSensitive(preReal)) throw new Error(`blocked sensitive file: ${abs}`)
65
+
66
+ // Buka path terverifikasi — bukan abs (yang bisa di-swap setelah realpath).
67
+ let handle: FileHandle
68
+ try {
69
+ handle = await open(preReal, O_RDONLY | O_NOFOLLOW)
70
+ } catch (e) {
71
+ const code = (e as NodeJS.ErrnoException).code
72
+ if (code === "ELOOP") throw new Error(`symlink swapped during open (O_NOFOLLOW): ${abs}`)
73
+ // EINVAL: O_NOFOLLOW tidak didukung → buka biasa (Windows: pre-check saja)
74
+ if (code === "EINVAL" && O_NOFOLLOW !== 0) {
75
+ handle = await open(preReal, O_RDONLY)
76
+ } else throw e
77
+ }
78
+ // Hardlink ke luar workspace tak terlihat oleh realpath (semua nama setara)
79
+ // — baca via hardlink = baca konten luar. fstat pada handle yang SUDAH
80
+ // terbuka: tepat untuk file ini, bebas race dengan swap nama. File normal
81
+ // nlink=1; tolak sisanya dengan pesan yang bisa ditindaklanjuti.
82
+ const st = await handle.stat().catch(() => null)
83
+ // Hardlink check hanya untuk file regular: direktori punya nlink >= 2
84
+ // (`.` dan `..`) dan bukan target hardlink — biarkan tool yang menolak
85
+ // direktori dengan pesan yang user-friendly.
86
+ if (st && !st.isDirectory() && st.nlink > 1) {
87
+ await handle.close().catch(() => {})
88
+ throw new Error(`refusing to read file with multiple hardlinks (nlink=${st.nlink}): ${abs}`)
89
+ }
90
+ return { handle, realPath: preReal }
91
+ }
92
+
93
+ export async function safeReadFile(abs: string, root: string): Promise<string> {
94
+ const { handle } = await safeOpenRead(abs, root)
95
+ try {
96
+ return await handle.readFile("utf8")
97
+ } finally {
98
+ await handle.close().catch(() => {})
99
+ }
100
+ }
101
+
102
+ export async function safeStat(abs: string, root: string) {
103
+ const { handle } = await safeOpenRead(abs, root)
104
+ try {
105
+ return await handle.stat()
106
+ } finally {
107
+ await handle.close().catch(() => {})
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Untuk write: pastikan parent dir tidak symlink keluar workspace,
113
+ * lalu tulis via atomicWriteText yang sudah pakai O_EXCL.
114
+ * Tambahan: O_NOFOLLOW untuk file target bila sudah ada (cegah overwrite
115
+ * symlink yang menunjuk keluar). Di Windows fallback ke realpath check.
116
+ *
117
+ * LIVE di tool penulis overwrite (write_file/edit/apply_patch, audit
118
+ * 2026-09-16 L11): verifikasi target nyata + parent-dir pada titik tulis.
119
+ * Symlink INTERNAL sengaja TIDAK ditolak di sini — kontrak tool file adalah
120
+ * "symlink internal tetap bisa diedit, targetnya yang dicek" (dijaga
121
+ * test/live-toctou.test.ts). Escape/sensitif sudah ditutup resolveSafePath
122
+ * via isPathOutsideRoot(real) + isSensitive(real), dan cek realpath di
123
+ * bawah menjaga parent-dir yang di-swap jadi symlink keluar.
124
+ */
125
+ export async function assertSafeWriteTarget(abs: string, root: string): Promise<string> {
126
+ const realRoot = await realpath(root).catch(() => root)
127
+ const dir = dirname(abs)
128
+ const realDir = await realpath(dir).catch(() => dir)
129
+ if (isPathOutsideRoot(realDir, realRoot)) throw new Error(`parent outside workspace: ${abs}`)
130
+ const fileReal = await realpath(abs).catch(() => null)
131
+ // basename (bukan split "/"): path Windows memakai backslash — split "/"
132
+ // mengembalikan seluruh path absolut sehingga resolve() mengabaikan realDir
133
+ // dan verifikasi parent symlink gugur diam-diam di Windows.
134
+ const realAbs = fileReal ?? resolve(realDir, basename(abs))
135
+ if (fileReal && isPathOutsideRoot(realAbs, realRoot))
136
+ throw new Error(`symlink points outside workspace: ${abs}`)
137
+ return realAbs
138
+ }
@@ -0,0 +1,23 @@
1
+ // SATU-SATUNYA sanitizer identitas sesi (F-17).
2
+ //
3
+ // Tiga subsistem (checkpoint dir, shadow-git ref, journal file) dulu punya
4
+ // pemetaan sendiri-sendiri: `...` → `-` vs `x`, leading-dot di-strip vs tidak
5
+ // (checkpoint bisa membuat direktori HIDDEN `.foo`), default `default` vs `x`.
6
+ // Akibatnya satu session id dipetakan ke tiga nama berbeda antar subsistem,
7
+ // dan `pruneSessionRefs`/pembersih bisa salah sasaran untuk id adversarial
8
+ // (`--session` dikendalikan user).
9
+ //
10
+ // Aturan gabungan (paling ketat dari ketiganya): aman untuk path file, ref
11
+ // git, dan nama berkas di semua OS. Id normal (alnum, `-`, `_`, titik tunggal
12
+ // di tengah) dipetakan IDENTIK dengan ketiga fungsi lama — migrasi hanya
13
+ // mengubah id adversarial yang memang sudah rusak (direktori hidden / ref
14
+ // ilegal). Kolisi `a/b` ↔ `a-b` tetap ada di SEMUA varian (tanpa escaping tak
15
+ // terhindarkan) — didokumentasikan, bukan diperbaiki di sini.
16
+ export function sanitizeSessionPart(s: string): string {
17
+ const cleaned = s
18
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
19
+ .replace(/\.\.+/g, "-")
20
+ .replace(/^[.-]+|[.-]+$/g, "")
21
+ .slice(0, 60)
22
+ return cleaned || "x"
23
+ }
@@ -0,0 +1,38 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import { mkdir, readdir, rename, rm, stat } from "node:fs/promises"
3
+ import { basename, join } from "node:path"
4
+
5
+ // Soft-delete bersama untuk delete_file & move_file (backup overwrite).
6
+ // Lokasi di <root>/.minicode/.trash — otomatis gitignored (.minicode/) dan
7
+ // di-skip glob/grep (dot-dir), jadi tidak mengotori workspace. Cap 100 file
8
+ // terbaru; best-effort, jangan gagalkan tool bila prune gagal.
9
+ const TRASH_MAX_FILES = 100
10
+
11
+ export function trashDir(root: string): string {
12
+ return join(root, ".minicode", ".trash")
13
+ }
14
+
15
+ export async function trashFile(root: string, abs: string): Promise<string> {
16
+ const dir = trashDir(root)
17
+ await mkdir(dir, { recursive: true, mode: 0o700 }).catch(() => {})
18
+ const dest = join(dir, `${randomUUID().slice(0, 8)}-${basename(abs)}`)
19
+ await rename(abs, dest)
20
+ await pruneTrash(dir).catch(() => {})
21
+ return dest
22
+ }
23
+
24
+ async function pruneTrash(dir: string): Promise<void> {
25
+ const entries = await readdir(dir).catch(() => [] as string[])
26
+ if (entries.length <= TRASH_MAX_FILES) return
27
+ const withTime: { e: string; m: number }[] = []
28
+ for (const e of entries) {
29
+ try {
30
+ const st = await stat(join(dir, e))
31
+ withTime.push({ e, m: st.mtimeMs })
32
+ } catch {}
33
+ }
34
+ withTime.sort((a, b) => a.m - b.m)
35
+ for (const v of withTime.slice(0, withTime.length - TRASH_MAX_FILES)) {
36
+ await rm(join(dir, v.e), { force: true }).catch(() => {})
37
+ }
38
+ }
@@ -0,0 +1,81 @@
1
+ import { accessSync, constants, statSync } from "node:fs"
2
+ import { delimiter, isAbsolute, join } from "node:path"
3
+
4
+ // Resolusi executable TERPERCAYA (audit #10 P0).
5
+ //
6
+ // Masalah: `spawn("git", …, { cwd: workspace })` di Windows memakai urutan
7
+ // pencarian CreateProcess yang mencari DIREKTORI CWD lebih dulu daripada PATH.
8
+ // Repo yang dibuka cukup menaruh `git.bat`/`git.cmd`/`git.exe` → operasi git
9
+ // otomatis minicode (mis. `git ls-files` saat membangun system prompt setiap
10
+ // sesi) menjalankan kode repo TANPA persetujuan. Mengubah PATH child TIDAK
11
+ // menolong (cwd tetap menang), jadi resolusi harus absolut.
12
+ //
13
+ // Solusi: cari nama di entri PATH yang VALID (absolut, bukan ""/"."), memakai
14
+ // PATHEXT di Windows, TANPA pernah melihat cwd. Bila tak ketemu → kembalikan
15
+ // nama telanjang (perilaku lama) supaya kegagalan tetap fail-open seperti
16
+ // semula, tetapi kasus umum (git terpasang di PATH) jadi aman dari hijack.
17
+
18
+ const isWin = process.platform === "win32"
19
+
20
+ function validPathEntries(): string[] {
21
+ const raw = process.env.PATH ?? process.env.Path ?? ""
22
+ const out: string[] = []
23
+ for (const entry of raw.split(delimiter)) {
24
+ if (!entry) continue // "" = direktori kerja (bahaya)
25
+ if (!isAbsolute(entry)) continue // relatif = tak dapat dipercaya
26
+ out.push(entry)
27
+ }
28
+ return out
29
+ }
30
+
31
+ function isExecutableFile(p: string): boolean {
32
+ try {
33
+ const st = statSync(p)
34
+ if (!st.isFile()) return false
35
+ if (isWin) return true
36
+ accessSync(p, constants.X_OK)
37
+ return true
38
+ } catch {
39
+ return false
40
+ }
41
+ }
42
+
43
+ const cache = new Map<string, string>()
44
+
45
+ /**
46
+ * Kembalikan path absolut terpercaya untuk `name`, atau `name` itu sendiri
47
+ * bila tak ditemukan (fail-open, sama seperti perilaku spawn bawaan).
48
+ * Hasil di-cache per proses.
49
+ */
50
+ export function resolveTrustedExecutable(name: string): string {
51
+ const cached = cache.get(name)
52
+ if (cached) return cached
53
+ const resolved = resolveUncached(name)
54
+ cache.set(name, resolved)
55
+ return resolved
56
+ }
57
+
58
+ function resolveUncached(name: string): string {
59
+ // Nama yang sudah absolut atau memuat pemisah path (mis. "./scripts/x",
60
+ // "tools\\run.exe") adalah pilihan eksplisit pemanggil — jangan diubah.
61
+ if (isAbsolute(name)) return name
62
+ if (name.includes("/") || name.includes("\\")) return name
63
+ const exts = isWin
64
+ ? (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
65
+ .split(";")
66
+ .map((e) => e.trim())
67
+ .filter(Boolean)
68
+ : [""]
69
+ for (const dir of validPathEntries()) {
70
+ if (isWin) {
71
+ for (const ext of exts) {
72
+ const candidate = join(dir, name.endsWith(ext.toLowerCase()) ? name : name + ext)
73
+ if (isExecutableFile(candidate)) return candidate
74
+ }
75
+ } else {
76
+ const candidate = join(dir, name)
77
+ if (isExecutableFile(candidate)) return candidate
78
+ }
79
+ }
80
+ return name
81
+ }