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.
- package/CHANGELOG.md +935 -0
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/cli/args.ts +195 -0
- package/cli/auto-update.ts +108 -0
- package/cli/commands/auth.ts +166 -0
- package/cli/commands/config.ts +382 -0
- package/cli/commands/doctor.ts +128 -0
- package/cli/commands/exec.ts +179 -0
- package/cli/commands/mcp.ts +35 -0
- package/cli/commands/memory.ts +107 -0
- package/cli/commands/pricing.ts +100 -0
- package/cli/commands/providers.ts +162 -0
- package/cli/commands/sessions.ts +128 -0
- package/cli/commands/skills.ts +61 -0
- package/cli/commands/stats.ts +82 -0
- package/cli/commands.ts +317 -0
- package/cli/index.ts +539 -0
- package/cli/model-manager.ts +112 -0
- package/cli/provider-manager.ts +111 -0
- package/cli/repl.ts +734 -0
- package/cli/router.ts +124 -0
- package/cli/setup.ts +780 -0
- package/cli/wizard.ts +21 -0
- package/docs/ARCHITECTURE.html +1222 -0
- package/docs/README.md +109 -0
- package/docs/architecture.md +44 -0
- package/docs/changelog.md +3 -0
- package/package.json +91 -0
- package/src/agents/pool.ts +43 -0
- package/src/app/mentions.ts +50 -0
- package/src/app/provider-layer.ts +118 -0
- package/src/app/rag-layer.ts +105 -0
- package/src/app/session.ts +154 -0
- package/src/app/tool-layer.ts +56 -0
- package/src/config.ts +372 -0
- package/src/constants.ts +119 -0
- package/src/hooks/run.ts +89 -0
- package/src/lib/atomic-write.ts +88 -0
- package/src/lib/db-path.ts +36 -0
- package/src/lib/git-hardening.ts +91 -0
- package/src/lib/ignore.ts +58 -0
- package/src/lib/keystore.ts +202 -0
- package/src/lib/net.ts +70 -0
- package/src/lib/safe-open.ts +138 -0
- package/src/lib/session-id.ts +23 -0
- package/src/lib/trash.ts +38 -0
- package/src/lib/trusted-exec.ts +81 -0
- package/src/lsp/client.ts +395 -0
- package/src/mcp/client.ts +400 -0
- package/src/mcp/http-transport.ts +344 -0
- package/src/mcp/server.ts +538 -0
- package/src/mcp/transport.ts +150 -0
- package/src/memory/files.ts +159 -0
- package/src/memory/vector.ts +775 -0
- package/src/policy/allowlist.ts +67 -0
- package/src/policy/bash-guard.ts +465 -0
- package/src/policy/compaction.ts +271 -0
- package/src/policy/context.ts +161 -0
- package/src/policy/executor.ts +199 -0
- package/src/policy/jail.ts +127 -0
- package/src/policy/permission.ts +517 -0
- package/src/policy/pricing.ts +336 -0
- package/src/policy/ratelimit.ts +54 -0
- package/src/policy/sandbox-policy.ts +157 -0
- package/src/policy/scrub.ts +138 -0
- package/src/policy/update-check.ts +200 -0
- package/src/policy/usage.ts +292 -0
- package/src/policy/verifier.ts +181 -0
- package/src/providers/anthropic.ts +401 -0
- package/src/providers/auth-store.ts +139 -0
- package/src/providers/build.ts +136 -0
- package/src/providers/detect.ts +126 -0
- package/src/providers/effort.ts +165 -0
- package/src/providers/guards.ts +107 -0
- package/src/providers/oauth.ts +326 -0
- package/src/providers/presets.ts +122 -0
- package/src/providers/provision.ts +298 -0
- package/src/providers/responses.ts +371 -0
- package/src/providers/router.ts +247 -0
- package/src/repo/repomap.ts +470 -0
- package/src/sandbox/docker.ts +129 -0
- package/src/sandbox/os.ts +193 -0
- package/src/session/checkpoint.ts +543 -0
- package/src/session/journal.ts +1347 -0
- package/src/session/persistence.ts +446 -0
- package/src/session/shadow-git.ts +351 -0
- package/src/session/turn-marker.ts +118 -0
- package/src/skills/loader.ts +117 -0
- package/src/telemetry/trace.ts +283 -0
- package/src/tools/ask_user.ts +54 -0
- package/src/tools/bash.ts +400 -0
- package/src/tools/code_run.ts +96 -0
- package/src/tools/delete_file.ts +31 -0
- package/src/tools/edit.ts +204 -0
- package/src/tools/git.ts +301 -0
- package/src/tools/glob.ts +90 -0
- package/src/tools/grep.ts +281 -0
- package/src/tools/hashline.ts +66 -0
- package/src/tools/index.ts +103 -0
- package/src/tools/lsp.ts +346 -0
- package/src/tools/mcp_call.ts +163 -0
- package/src/tools/memory.ts +144 -0
- package/src/tools/move_file.ts +47 -0
- package/src/tools/patch.ts +86 -0
- package/src/tools/read_file.ts +130 -0
- package/src/tools/read_image.ts +80 -0
- package/src/tools/submit_result.ts +49 -0
- package/src/tools/task.ts +346 -0
- package/src/tools/todo.ts +201 -0
- package/src/tools/web_fetch.ts +161 -0
- package/src/tools/web_search.ts +156 -0
- package/src/tools/write_file.ts +42 -0
- package/src/ui/approval/prompt.ts +76 -0
- package/src/ui/assistant/simple.ts +568 -0
- package/src/ui/assistant/turn-status.ts +303 -0
- package/src/ui/contract.ts +55 -0
- package/src/ui/footer.ts +105 -0
- package/src/ui/input/input.ts +805 -0
- package/src/ui/input/prompt-engine.ts +606 -0
- package/src/ui/render/collapse.ts +84 -0
- package/src/ui/render/detail.ts +24 -0
- package/src/ui/render/diff.ts +181 -0
- package/src/ui/render/errors.ts +239 -0
- package/src/ui/render/format.ts +54 -0
- package/src/ui/render/highlight.ts +294 -0
- package/src/ui/render/markdown.ts +120 -0
- package/src/ui/render/money.ts +12 -0
- package/src/ui/render/reasoning.ts +20 -0
- package/src/ui/render/sanitize.ts +80 -0
- package/src/ui/render/table.ts +88 -0
- package/src/ui/render/theme.ts +339 -0
- package/src/ui/render/width.ts +256 -0
- package/src/ui/render/wrap.ts +120 -0
- package/src/ui/runtime/bus-debug.ts +83 -0
- package/src/ui/runtime/chrome.ts +301 -0
- package/src/ui/runtime/spinner.ts +77 -0
- package/src/ui/runtime/statusline.ts +227 -0
- package/src/ui/screens/model-manager.ts +434 -0
- package/src/ui/screens/overlay.ts +61 -0
- package/src/ui/screens/picker.ts +307 -0
- package/src/ui/screens/provider-manager.ts +450 -0
- package/src/ui/screens/wizard.ts +132 -0
- package/vendor/minicore/VENDOR.md +29 -0
- package/vendor/minicore/package.json +21 -0
- package/vendor/minicore/src/core/budget.ts +26 -0
- package/vendor/minicore/src/core/compact.ts +76 -0
- package/vendor/minicore/src/core/errors.ts +60 -0
- package/vendor/minicore/src/core/events.ts +74 -0
- package/vendor/minicore/src/core/executor.ts +139 -0
- package/vendor/minicore/src/core/history.ts +32 -0
- package/vendor/minicore/src/core/index.ts +42 -0
- package/vendor/minicore/src/core/loop.ts +344 -0
- package/vendor/minicore/src/core/permission.ts +24 -0
- package/vendor/minicore/src/core/provider.ts +39 -0
- package/vendor/minicore/src/core/recovery.ts +34 -0
- package/vendor/minicore/src/core/session.ts +327 -0
- package/vendor/minicore/src/core/snapshot.ts +142 -0
- package/vendor/minicore/src/core/tokens.ts +111 -0
- package/vendor/minicore/src/core/tool.ts +118 -0
- package/vendor/minicore/src/core/types.ts +50 -0
- package/vendor/minicore/src/providers/openai-compat.ts +366 -0
package/src/constants.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** Centralized magic numbers — full English naming. Single source for limits. */
|
|
2
|
+
export const LIMITS = {
|
|
3
|
+
/** File size limits */
|
|
4
|
+
READ_FILE_MAX_BYTES: 2_000_000,
|
|
5
|
+
WRITE_FILE_MAX_CHARS: 5_000_000,
|
|
6
|
+
/** read_file paging — file besar dibaca per rentang baris, bukan sekaligus */
|
|
7
|
+
READ_FILE_DEFAULT_LINE_LIMIT: 2_000,
|
|
8
|
+
READ_FILE_MAX_LINE_LIMIT: 5_000,
|
|
9
|
+
READ_FILE_MAX_LINE_CHARS: 2_000,
|
|
10
|
+
/** Tool output truncation */
|
|
11
|
+
BASH_OUTPUT_MAX_CHARS: 20_000,
|
|
12
|
+
BASH_DEFAULT_TIMEOUT_MS: 30_000,
|
|
13
|
+
/** bash background: proses hidup melewati batas turn, dipanggil via bash_output */
|
|
14
|
+
BASH_BACKGROUND_MAX_JOBS: 8,
|
|
15
|
+
BASH_BACKGROUND_MAX_LIFETIME_MS: 3_600_000,
|
|
16
|
+
DOCKER_OUTPUT_MAX_CHARS: 100_000,
|
|
17
|
+
MCP_OUTPUT_MAX_CHARS: 100_000,
|
|
18
|
+
MCP_REQUEST_TIMEOUT_MS: 30_000,
|
|
19
|
+
TASK_SUB_AGENT_MAX_TOKENS: 2_000,
|
|
20
|
+
/** Context & memory */
|
|
21
|
+
SYSTEM_PROMPT_MAX_CHARS: 8_000,
|
|
22
|
+
MEMORY_FILE_MAX_CHARS: 4_000,
|
|
23
|
+
MEMORY_FILE_MAX_BYTES: 200_000,
|
|
24
|
+
MEMORY_TRUNCATE_KEEP_BYTES: 150_000,
|
|
25
|
+
AGENTS_MD_MAX_CHARS: 3_000,
|
|
26
|
+
COMPACTION_SUMMARY_MAX_CHARS: 1_500,
|
|
27
|
+
COMPACTION_LLM_TIMEOUT_MS: 10_000,
|
|
28
|
+
EMBEDDING_TIMEOUT_MS: 3_500,
|
|
29
|
+
/** Budget TOTAL semua attempt embedding (3 header × 2 URL sekuensial):
|
|
30
|
+
* tanpa ini endpoint lambat-menjawab menahan RAG setup ~21 dtk (6×3,5 dtk
|
|
31
|
+
* + DNS per attempt) dengan spinner "Menyiapkan sesi…" yang diam = macet.
|
|
32
|
+
* Lewat budget = fallback keyword, bukan hang. */
|
|
33
|
+
EMBEDDING_TOTAL_TIMEOUT_MS: 10_000,
|
|
34
|
+
VECTOR_SEARCH_LIMIT: 500,
|
|
35
|
+
VECTOR_RECENT_LIMIT: 300,
|
|
36
|
+
VECTOR_KEYWORD_LIMIT: 200,
|
|
37
|
+
MEMORY_MIN_SCORE_HYBRID: 0.2,
|
|
38
|
+
MEMORY_MIN_SCORE_KEYWORD: 0.25,
|
|
39
|
+
/** P13 P1 — TTL hierarkis per kategori (hari): fakta awet, ringkasan
|
|
40
|
+
* sedang, snippet cepat basi. Menggantikan MEMORY_TTL_DAYS flat 90. */
|
|
41
|
+
MEMORY_TTL_FACT_DAYS: 180,
|
|
42
|
+
MEMORY_TTL_SUMMARY_DAYS: 90,
|
|
43
|
+
MEMORY_TTL_SNIPPET_DAYS: 14,
|
|
44
|
+
MEMORY_MAX_ROWS: 5000,
|
|
45
|
+
/** P2 MMR: bobot relevansi vs diversitas + ambang dedup near-duplikat */
|
|
46
|
+
MEMORY_MMR_LAMBDA: 0.7,
|
|
47
|
+
MEMORY_MMR_CANDIDATES: 50,
|
|
48
|
+
MEMORY_DEDUP_COSINE: 0.92,
|
|
49
|
+
/** P2 chunking: entri panjang dipecah per baris ini dengan overlap */
|
|
50
|
+
MEMORY_CHUNK_CHARS: 2000,
|
|
51
|
+
MEMORY_CHUNK_OVERLAP: 200,
|
|
52
|
+
WORKSPACE_SNAPSHOT_LIMIT: 200,
|
|
53
|
+
CHECKPOINT_MAX_COUNT: 20,
|
|
54
|
+
/** Checkpoint shadow-git: operasi git punya deadline sendiri agar turn tak
|
|
55
|
+
* tergantung repo raksasa; batch path menghindari batas command-line Windows. */
|
|
56
|
+
SHADOW_GIT_TIMEOUT_MS: 20_000,
|
|
57
|
+
SHADOW_GIT_PATH_BATCH: 200,
|
|
58
|
+
/** Tool git (status/diff/log/commit). Longgar karena `git_commit` menjalankan
|
|
59
|
+
* beberapa operasi berurutan dan mesin sibuk membuat spawn git lambat. */
|
|
60
|
+
GIT_TIMEOUT_MS: 20_000,
|
|
61
|
+
/** F-15: cap output git saat streaming (git_diff/log di repo raksasa). */
|
|
62
|
+
GIT_OUTPUT_MAX_CHARS: 500_000,
|
|
63
|
+
/** Executor & sub-agents — tuned for 4-core laptop (6/1) vs 8/2 server */
|
|
64
|
+
DEFAULT_MAX_STEPS: 50,
|
|
65
|
+
EXECUTOR_CONCURRENCY: 6,
|
|
66
|
+
EXECUTOR_WRITE_CONCURRENCY: 1,
|
|
67
|
+
SUB_AGENT_POOL_SIZE: 3,
|
|
68
|
+
SUB_AGENT_BUDGET_EXPLORE: 5,
|
|
69
|
+
SUB_AGENT_BUDGET_PLAN: 15,
|
|
70
|
+
SUB_AGENT_TIMEOUT_MS: 120_000,
|
|
71
|
+
/** Network / providers */
|
|
72
|
+
RETRY_AFTER_MAX_MS: 30_000,
|
|
73
|
+
/** F-11: timeout per request provider (server hung = turn hung tanpa ini).
|
|
74
|
+
* Longgar (5 mnt) karena reasoning stream sah bisa bermenit-menit; timeout
|
|
75
|
+
* turn (default 10–15 mnt) tetap backstop terluar. */
|
|
76
|
+
PROVIDER_REQUEST_TIMEOUT_MS: 300_000,
|
|
77
|
+
/** F-16: cap akumulasi teks per stream (anti-OOM); hanya memotong kasus
|
|
78
|
+
* patologis (~250rb token teks dalam satu turn). */
|
|
79
|
+
PROVIDER_TEXT_MAX_CHARS: 1_000_000,
|
|
80
|
+
/** Investigasi Phase 5: cap reasoning stream (terbukti TANPA cap = akumulasi
|
|
81
|
+
* tak terbatas — satu-satunya jalur loop `reasoning +=` tanpa batas). */
|
|
82
|
+
PROVIDER_REASON_MAX_CHARS: 2_000_000,
|
|
83
|
+
DOCKER_TIMEOUT_MS: 30_000,
|
|
84
|
+
DETECT_MODELS_TIMEOUT_MS: 4_000,
|
|
85
|
+
DETECT_GLOBAL_TIMEOUT_MS: 6_000,
|
|
86
|
+
DETECT_ATTEMPT_TIMEOUT_MS: 2_500,
|
|
87
|
+
MCP_HANDSHAKE_TIMEOUT_MS: 3_000,
|
|
88
|
+
/** OAuth device flow: request pendek, tapi poll bisa berlangsung menit. */
|
|
89
|
+
OAUTH_REQUEST_TIMEOUT_MS: 15_000,
|
|
90
|
+
/** Pricing dari models.dev — cache agar tidak menembak jaringan tiap run. */
|
|
91
|
+
PRICING_FETCH_TIMEOUT_MS: 5_000,
|
|
92
|
+
PRICING_CACHE_TTL_MS: 86_400_000,
|
|
93
|
+
LSP_DIAGNOSTICS_TIMEOUT_MS: 5_000,
|
|
94
|
+
LSP_INIT_TIMEOUT_MS: 15_000,
|
|
95
|
+
VERIFY_DEFAULT_TIMEOUT_MS: 30_000,
|
|
96
|
+
WEB_FETCH_BODY_HARD_CAP_CHARS: 2_000_000,
|
|
97
|
+
WEB_FETCH_MAX_REDIRECTS: 5,
|
|
98
|
+
/** Glob/grep */
|
|
99
|
+
SEARCH_DEFAULT_LIMIT: 100,
|
|
100
|
+
SEARCH_MAX_LIMIT: 500,
|
|
101
|
+
/** grep: ripgrep dipakai bila ada di PATH; fallback walker JS */
|
|
102
|
+
GREP_RIPGREP_TIMEOUT_MS: 15_000,
|
|
103
|
+
GREP_MATCH_MAX_CHARS: 300,
|
|
104
|
+
GREP_FILE_MAX_BYTES: 1_000_000,
|
|
105
|
+
/** todo list per sesi */
|
|
106
|
+
TODO_MAX_ITEMS: 50,
|
|
107
|
+
TODO_CONTENT_MAX_CHARS: 200,
|
|
108
|
+
/** SQLite */
|
|
109
|
+
SQLITE_BUSY_TIMEOUT_MS: 3_000,
|
|
110
|
+
SQLITE_WAL_SIZE_LIMIT_BYTES: 33_554_432,
|
|
111
|
+
SQLITE_WAL_AUTOCHECKPOINT_PAGES: 1_000,
|
|
112
|
+
/** Telemetry */
|
|
113
|
+
TRACE_MAX_LINES: 1_000,
|
|
114
|
+
/** Repo-map */
|
|
115
|
+
REPOMAP_MAX_FILES: 60,
|
|
116
|
+
REPOMAP_MAX_FILE_BYTES: 100_000,
|
|
117
|
+
REPOMAP_MAX_CHARS: 2_500,
|
|
118
|
+
REPOMAP_MAX_SYMBOLS_PER_FILE: 40,
|
|
119
|
+
} as const
|
package/src/hooks/run.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { spawn } from "node:child_process"
|
|
2
|
+
import { existsSync, readdirSync } from "node:fs"
|
|
3
|
+
import { homedir } from "node:os"
|
|
4
|
+
import { join, resolve } from "node:path"
|
|
5
|
+
import { sanitizeSpawnEnv } from "../policy/scrub.ts"
|
|
6
|
+
|
|
7
|
+
export interface RunHookCtx {
|
|
8
|
+
phase: "pre" | "post"
|
|
9
|
+
prompt?: string
|
|
10
|
+
cwd?: string
|
|
11
|
+
result?: unknown
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Guard mode untuk hooks (audit #10 P1): hooks berjalan di luar permission
|
|
16
|
+
* system — di mode tanpa-eksekusi (plan/readonly) hook TETAP mengeksekusi
|
|
17
|
+
* tanpa gate bila tidak dijaga, melanggar kontrak read-only. Diekspor agar
|
|
18
|
+
* composition root + test memakai predikat yang sama.
|
|
19
|
+
*/
|
|
20
|
+
export function shouldRunHooks(permissionMode: string): boolean {
|
|
21
|
+
return permissionMode !== "plan" && permissionMode !== "readonly"
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// 6.4 — hooks global opt-in: ~/.minicode/hooks/{pre,post}*.js dan
|
|
25
|
+
// .minicode/hooks/{pre,post}*.js. Berjalan sebagai node script terpisah
|
|
26
|
+
// dengan konteks di env MINICODE_HOOK_CTX (JSON). Opt-in via MINICODE_HOOKS=1
|
|
27
|
+
// supaya tidak mengubah perilaku default (aman, tanpa efek samping).
|
|
28
|
+
export function findRunHooks(cwd?: string): { pre: string[]; post: string[] } {
|
|
29
|
+
const dirs: string[] = [join(homedir(), ".minicode", "hooks")]
|
|
30
|
+
if (cwd) dirs.push(resolve(cwd, ".minicode", "hooks"))
|
|
31
|
+
const out = { pre: [] as string[], post: [] as string[] }
|
|
32
|
+
for (const dir of dirs) {
|
|
33
|
+
if (!existsSync(dir)) continue
|
|
34
|
+
for (const f of readdirSync(dir)) {
|
|
35
|
+
if (!f.endsWith(".js")) continue
|
|
36
|
+
if (f.includes("pre")) out.pre.push(join(dir, f))
|
|
37
|
+
else if (f.includes("post")) out.post.push(join(dir, f))
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return out
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function runRunHooks(
|
|
44
|
+
phase: "pre" | "post",
|
|
45
|
+
ctx: RunHookCtx,
|
|
46
|
+
signal?: AbortSignal,
|
|
47
|
+
): Promise<void> {
|
|
48
|
+
if (process.env.MINICODE_HOOKS !== "1") return
|
|
49
|
+
// Hook = arbitrary Node.js di luar permission system (berjalan di SEMUA
|
|
50
|
+
// mode bila opt-in) — karenanya: tanpa secret di env (baca dari berkas bila
|
|
51
|
+
// perlu), dan hormati pembatalan sesi (lewati sisa hook bila aborted).
|
|
52
|
+
// MINICODE_HOOK_CTX sendiri memuat prompt user apa adanya — prompt yang
|
|
53
|
+
// ditempeli kredensial akan terlihat hook; itu inheren dari desain.
|
|
54
|
+
if (signal?.aborted) return
|
|
55
|
+
const hooks = findRunHooks(ctx.cwd)
|
|
56
|
+
for (const file of hooks[phase]) {
|
|
57
|
+
if (signal?.aborted) return
|
|
58
|
+
// Audit #10 P2 observability: hook adalah eksekusi di luar permission
|
|
59
|
+
// system — operator wajib bisa melihat APA yang jalan (nama berkas saja;
|
|
60
|
+
// output hook tetap dibuang, isi tak pernah di-log).
|
|
61
|
+
try {
|
|
62
|
+
process.stderr.write(`[hooks] ${phase}: ${file.split(/[\\/]/).pop()}\n`)
|
|
63
|
+
} catch {}
|
|
64
|
+
await new Promise<void>((res) => {
|
|
65
|
+
const p = spawn(process.execPath, [file], {
|
|
66
|
+
env: sanitizeSpawnEnv(process.env, { MINICODE_HOOK_CTX: JSON.stringify(ctx) }),
|
|
67
|
+
stdio: "ignore",
|
|
68
|
+
})
|
|
69
|
+
const timer = setTimeout(() => {
|
|
70
|
+
try {
|
|
71
|
+
p.kill("SIGTERM")
|
|
72
|
+
setTimeout(() => {
|
|
73
|
+
try {
|
|
74
|
+
p.kill("SIGKILL")
|
|
75
|
+
} catch {}
|
|
76
|
+
}, 1000)
|
|
77
|
+
} catch {}
|
|
78
|
+
}, 5000)
|
|
79
|
+
p.on("error", () => {
|
|
80
|
+
clearTimeout(timer)
|
|
81
|
+
res()
|
|
82
|
+
})
|
|
83
|
+
p.on("exit", () => {
|
|
84
|
+
clearTimeout(timer)
|
|
85
|
+
res()
|
|
86
|
+
})
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto"
|
|
2
|
+
import { chmod, type FileHandle, mkdir, open, rename, unlink } from "node:fs/promises"
|
|
3
|
+
import { dirname } from "node:path"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Tulis file secara atomic + tahan hijack:
|
|
7
|
+
* - nama tmp memakai randomUUID → tidak dapat diprediksi attacker
|
|
8
|
+
* - flag "wx" (O_EXCL) gagal bila tmp sudah ada (mis. symlink pre-create)
|
|
9
|
+
* - mode 0o600 best-effort sebelum rename (Windows: no-op, aman diabaikan)
|
|
10
|
+
* - rename(tmp→target) atomic per POSIX; di Windows libuv memakai
|
|
11
|
+
* MOVEFILE_REPLACE_EXISTING sehingga menimpa target lama.
|
|
12
|
+
*/
|
|
13
|
+
export async function atomicWriteText(path: string, data: string): Promise<void> {
|
|
14
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 }).catch(() => {})
|
|
15
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
16
|
+
const entropy = 16
|
|
17
|
+
const tmp = `${path}.tmp.${process.pid}.${randomUUID().slice(0, entropy)}`
|
|
18
|
+
let fh: FileHandle | undefined
|
|
19
|
+
try {
|
|
20
|
+
fh = await open(tmp, "wx", 0o600)
|
|
21
|
+
} catch (e) {
|
|
22
|
+
if ((e as NodeJS.ErrnoException).code === "EEXIST" && attempt === 0) continue
|
|
23
|
+
throw e
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
// Bun Windows: `FileHandle.writeFile` kadang nge-hit kWriteMonkeyPatchDefense
|
|
27
|
+
// bila `node:fs/promises` ke-import bareng `bun:sqlite` di top-level.
|
|
28
|
+
// Fallback ke `Bun.write` (tidak pakai FileHandle) bila kena itu.
|
|
29
|
+
try {
|
|
30
|
+
await fh.writeFile(data, "utf8")
|
|
31
|
+
} catch (e) {
|
|
32
|
+
const msg = String((e as Error)?.message ?? "")
|
|
33
|
+
if (msg.includes("kWriteMonkeyPatchDefense") || msg.includes("kWrite")) {
|
|
34
|
+
await fh.close().catch(() => {})
|
|
35
|
+
fh = undefined as unknown as FileHandle
|
|
36
|
+
await Bun.write(tmp, data)
|
|
37
|
+
// re-open untuk sync/chmod path yang sama — atau skip bila Bun.write sudah flush
|
|
38
|
+
try {
|
|
39
|
+
await chmod(tmp, 0o600).catch(() => {})
|
|
40
|
+
} catch {}
|
|
41
|
+
let lastErr2: unknown
|
|
42
|
+
for (let r = 0; r < 8; r++) {
|
|
43
|
+
try {
|
|
44
|
+
await rename(tmp, path)
|
|
45
|
+
lastErr2 = undefined
|
|
46
|
+
break
|
|
47
|
+
} catch (ee) {
|
|
48
|
+
const code = (ee as NodeJS.ErrnoException).code
|
|
49
|
+
if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
|
|
50
|
+
lastErr2 = ee
|
|
51
|
+
await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
|
|
52
|
+
} else throw ee
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (lastErr2) throw lastErr2
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
throw e
|
|
59
|
+
}
|
|
60
|
+
await fh.sync().catch(() => {})
|
|
61
|
+
await chmod(tmp, 0o600).catch(() => {})
|
|
62
|
+
// Windows: rename menimpa target yang baru saja ditulis penulis lain
|
|
63
|
+
// bisa EPERM/EBUSY/EACCES sesaat (lock AV / replace window) → backoff.
|
|
64
|
+
let lastErr: unknown
|
|
65
|
+
for (let r = 0; r < 8; r++) {
|
|
66
|
+
try {
|
|
67
|
+
await rename(tmp, path)
|
|
68
|
+
lastErr = undefined
|
|
69
|
+
break
|
|
70
|
+
} catch (e) {
|
|
71
|
+
const code = (e as NodeJS.ErrnoException).code
|
|
72
|
+
if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
|
|
73
|
+
lastErr = e
|
|
74
|
+
await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
|
|
75
|
+
} else throw e
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (lastErr) throw lastErr
|
|
79
|
+
return
|
|
80
|
+
} catch (e) {
|
|
81
|
+
await unlink(tmp).catch(() => {})
|
|
82
|
+
throw e
|
|
83
|
+
} finally {
|
|
84
|
+
await fh.close().catch(() => {})
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
throw new Error(`atomic write failed after retries: ${path}`)
|
|
88
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { existsSync, mkdirSync } from "node:fs"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import { join, resolve } from "node:path"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Satu sumber lokasi DB lokal/global (dipakai sessions.db & vector.db):
|
|
7
|
+
* - bila <cwd>/.minicode/<filename> sudah ada → pakai itu
|
|
8
|
+
* - bila direktori <cwd>/.minicode ada (DB belum dibuat) → pakai lokal
|
|
9
|
+
* - selain itu → global ~/.minicode/<filename>
|
|
10
|
+
*
|
|
11
|
+
* Home diambil dari MINICODE_HOME bila diset (test hermetic + XDG-ish),
|
|
12
|
+
* karena os.homedir() di POSIX mengabaikan $HOME (libuv pakai passwd) —
|
|
13
|
+
* tanpa ini test penggabungan global tak bisa hermetic di Linux.
|
|
14
|
+
*/
|
|
15
|
+
export function homeDir(): string {
|
|
16
|
+
return process.env.MINICODE_HOME || homedir()
|
|
17
|
+
}
|
|
18
|
+
export function resolveDbPath(filename: string, cwd?: string): string {
|
|
19
|
+
if (filename.includes("/") || filename.includes("\\") || filename.includes(".."))
|
|
20
|
+
throw new Error(`invalid filename: ${filename}`)
|
|
21
|
+
const baseCwd = cwd ?? process.cwd()
|
|
22
|
+
const local = resolve(baseCwd, ".minicode", filename)
|
|
23
|
+
const localDir = resolve(baseCwd, ".minicode")
|
|
24
|
+
if (existsSync(local)) return local
|
|
25
|
+
if (existsSync(localDir)) {
|
|
26
|
+
try {
|
|
27
|
+
mkdirSync(localDir, { recursive: true, mode: 0o700 })
|
|
28
|
+
} catch {}
|
|
29
|
+
return local
|
|
30
|
+
}
|
|
31
|
+
const global = join(homeDir(), ".minicode", filename)
|
|
32
|
+
try {
|
|
33
|
+
mkdirSync(join(global, ".."), { recursive: true, mode: 0o700 })
|
|
34
|
+
} catch {}
|
|
35
|
+
return global
|
|
36
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process"
|
|
2
|
+
import { resolveTrustedExecutable } from "./trusted-exec.ts"
|
|
3
|
+
|
|
4
|
+
// Hardening argv untuk SEMUA pemanggilan git minicode (audit #10 P0).
|
|
5
|
+
//
|
|
6
|
+
// Model ancaman: direktori repo yang dibuka bisa membawa `.git/config`
|
|
7
|
+
// (hooksPath, fsmonitor, pager, filter/diff drivers) + `.git/hooks/*` +
|
|
8
|
+
// `.gitattributes`. Tanpa netralisasi, operasi git rutin (bahkan read-only
|
|
9
|
+
// seperti `status`/`diff`) mengeksekusi perintah repo: clean/smudge filters,
|
|
10
|
+
// textconv/diff.external, fsmonitor, hooks commit, pager.
|
|
11
|
+
//
|
|
12
|
+
// Aturan pemakaian:
|
|
13
|
+
// - GIT_SAFE_BASE di semua pemanggilan (tanpa kecuali).
|
|
14
|
+
// - GIT_NO_DIFF_DRIVERS di diff/log yang menampilkan konten.
|
|
15
|
+
// - gitFilterNeutralizers HANYA untuk plumbing internal (shadow
|
|
16
|
+
// snapshot/restore) yang wajib byte-exact + tanpa eksekusi — JANGAN untuk
|
|
17
|
+
// index user (LFS/semantik clean milik user, lihat git.ts). Pengecualian:
|
|
18
|
+
// protokol `filter.<d>.process` diutamakan git di atas clean/smudge, jadi
|
|
19
|
+
// neutralizer selalu mematikannya (nilai kosong = fallback ke clean/smudge)
|
|
20
|
+
// di SEMUA jalur plumbing; jalur user-index hanya diperingatkan, bukan diubah.
|
|
21
|
+
|
|
22
|
+
/** Netralisasi universal: tanpa hooks, tanpa fsmonitor, tanpa pager. */
|
|
23
|
+
export const GIT_SAFE_BASE: readonly string[] = [
|
|
24
|
+
"--no-pager",
|
|
25
|
+
"-c",
|
|
26
|
+
"core.hooksPath=/nonexistent-minicode-nohooks",
|
|
27
|
+
"-c",
|
|
28
|
+
"core.fsmonitor=",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
/** Netralisasi driver konten untuk diff/log (tanpa eksekusi repo). */
|
|
32
|
+
export const GIT_NO_DIFF_DRIVERS: readonly string[] = ["--no-ext-diff", "--no-textconv"]
|
|
33
|
+
|
|
34
|
+
const DRIVER_RE = /^filter\.([A-Za-z0-9_.-]+)\.(?:clean|smudge|process)\b/
|
|
35
|
+
|
|
36
|
+
export interface FilterDriver {
|
|
37
|
+
name: string
|
|
38
|
+
/** Driver memakai protokol process (long-running) — diutamakan git di atas
|
|
39
|
+
* clean/smudge, sehingga override clean/smudge saja TIDAK cukup. */
|
|
40
|
+
hasProcess: boolean
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Daftar driver filter yang TERKONFIGURASI di repo (discovery read-only via
|
|
45
|
+
* `git config`, tanpa hook/filter/pager). Dipakai neutralizer plumbing DAN
|
|
46
|
+
* peringatan jalur user-index (git_commit) agar eksekusi filter repo tidak
|
|
47
|
+
* pernah diam-diam.
|
|
48
|
+
*/
|
|
49
|
+
export async function discoverFilterDrivers(cwd: string): Promise<FilterDriver[]> {
|
|
50
|
+
try {
|
|
51
|
+
const r = spawnSync(
|
|
52
|
+
resolveTrustedExecutable("git"),
|
|
53
|
+
["config", "--get-regexp", "^filter\\..*\\.(clean|smudge|process)$"],
|
|
54
|
+
{ cwd, encoding: "utf8", timeout: 10_000 },
|
|
55
|
+
)
|
|
56
|
+
if (r.status !== 0 || !r.stdout) return []
|
|
57
|
+
const drivers = new Map<string, FilterDriver>()
|
|
58
|
+
for (const line of r.stdout.split("\n")) {
|
|
59
|
+
const m = DRIVER_RE.exec(line.trim())
|
|
60
|
+
if (!m?.[1]) continue
|
|
61
|
+
const d = drivers.get(m[1]) ?? { name: m[1], hasProcess: false }
|
|
62
|
+
if (line.includes(".process")) d.hasProcess = true
|
|
63
|
+
drivers.set(m[1], d)
|
|
64
|
+
}
|
|
65
|
+
return [...drivers.values()].sort((a, b) => (a.name < b.name ? -1 : 1))
|
|
66
|
+
} catch {
|
|
67
|
+
return []
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Bangun override `-c filter.<d>.clean=cat -c filter.<d>.smudge=cat` untuk
|
|
73
|
+
* semua driver clean/smudge yang TERKONFIGURASI. `cat` = identitas byte
|
|
74
|
+
* (snapshot/restore tetap konsisten) tanpa mengeksekusi perintah repo.
|
|
75
|
+
* Discovery via `git config` (plumbing baca murni: tanpa hook/filter/pager).
|
|
76
|
+
*/
|
|
77
|
+
export async function gitFilterNeutralizers(cwd: string): Promise<string[]> {
|
|
78
|
+
const drivers = await discoverFilterDrivers(cwd)
|
|
79
|
+
const out: string[] = []
|
|
80
|
+
for (const d of drivers) {
|
|
81
|
+
out.push("-c", `filter.${d.name}.clean=cat`, "-c", `filter.${d.name}.smudge=cat`)
|
|
82
|
+
// Protokol process DIUTAMAKAN git di atas clean/smudge: tanpa override
|
|
83
|
+
// ini, `git add` tetap mengeksekusi filter process repo meski clean=cat
|
|
84
|
+
// (terbukti via probe diagnostik: marker process jalan, clean tidak).
|
|
85
|
+
// Nilai kosong diperlakukan sebagai unset → fallback ke clean/smudge
|
|
86
|
+
// (cat di jalur plumbing; milik pengguna di jalur user-index) — tanpa
|
|
87
|
+
// noise error dan tanpa merusak driver clean/smudge yang sah (LFS).
|
|
88
|
+
if (d.hasProcess) out.push("-c", `filter.${d.name}.process=`)
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { resolve } from "node:path"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Subset jujur .gitignore — nama persis, `*.ext`, prefix `dir/`.
|
|
6
|
+
* Tanpa negasi `!` (didokumentasikan sebagai batas). Dipakai glob/grep
|
|
7
|
+
* agar tidak memuntahkan `node_modules`/`dist` yang tak relevan meski
|
|
8
|
+
* walker sudah skip hard-coded.
|
|
9
|
+
* Pure kecuali load di helper; matcher bisa diuji tanpa FS.
|
|
10
|
+
*/
|
|
11
|
+
export function compileIgnoreMatchers(patterns: string[]): ((rel: string) => boolean)[] {
|
|
12
|
+
const matchers: ((rel: string) => boolean)[] = []
|
|
13
|
+
for (const raw of patterns) {
|
|
14
|
+
const pat = raw.trim()
|
|
15
|
+
if (!pat || pat.startsWith("#") || pat.startsWith("!")) continue
|
|
16
|
+
const isDir = pat.endsWith("/")
|
|
17
|
+
const core = isDir ? pat.slice(0, -1) : pat
|
|
18
|
+
const hasSlash = core.includes("/")
|
|
19
|
+
const normalized = core.replace(/^\//, "")
|
|
20
|
+
// Build regex via glob simple: * -> [^/]*, ** -> .* (pakai placeholder agar ** tidak rusak oleh * berikutnya)
|
|
21
|
+
const escapeGlob = (s: string) =>
|
|
22
|
+
s
|
|
23
|
+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
24
|
+
.replace(/\*\*/g, "§§")
|
|
25
|
+
.replace(/\*/g, "[^/]*")
|
|
26
|
+
.replace(/§§/g, ".*")
|
|
27
|
+
.replace(/\?/g, ".")
|
|
28
|
+
if (hasSlash) {
|
|
29
|
+
// path pattern: cocok terhadap rel path (anchored)
|
|
30
|
+
const re = new RegExp(`^${escapeGlob(normalized)}${isDir ? "(?:/.*)?" : ""}$`)
|
|
31
|
+
matchers.push((rel) => re.test(rel))
|
|
32
|
+
} else {
|
|
33
|
+
// basename pattern: cocok bagian mana pun
|
|
34
|
+
const re = new RegExp(`^${escapeGlob(normalized)}$`)
|
|
35
|
+
matchers.push((rel) => {
|
|
36
|
+
const parts = rel.split("/")
|
|
37
|
+
if (isDir) return parts.includes(normalized) || re.test(parts[parts.length - 1] ?? "")
|
|
38
|
+
return parts.some((seg) => re.test(seg))
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return matchers
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function isIgnored(rel: string, matchers: ((rel: string) => boolean)[]): boolean {
|
|
46
|
+
for (const m of matchers) if (m(rel)) return true
|
|
47
|
+
return false
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function loadIgnoreMatchers(root: string): Promise<((rel: string) => boolean)[]> {
|
|
51
|
+
try {
|
|
52
|
+
const txt = await readFile(resolve(root, ".gitignore"), "utf8")
|
|
53
|
+
const lines = txt.split("\n")
|
|
54
|
+
return compileIgnoreMatchers(lines)
|
|
55
|
+
} catch {
|
|
56
|
+
return []
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process"
|
|
2
|
+
import { chmod, mkdir, readFile } from "node:fs/promises"
|
|
3
|
+
import { homedir } from "node:os"
|
|
4
|
+
import { join } from "node:path"
|
|
5
|
+
import { atomicWriteText } from "./atomic-write.ts"
|
|
6
|
+
|
|
7
|
+
// Penyimpanan rahasia berlapis (tanpa dependensi):
|
|
8
|
+
// - Windows: DPAPI user-scope via powershell bawaan (hanya user ini yang
|
|
9
|
+
// bisa dekripsi, bahkan bila berkas dibaca pihak lain).
|
|
10
|
+
// - Selain itu: berkas chmod 600 (status quo — didokumentasikan, bukan
|
|
11
|
+
// diklaim setara keyring).
|
|
12
|
+
//
|
|
13
|
+
// Desain: envelope — yang disimpan di disk SELALU `{enc, alg}`; `alg`
|
|
14
|
+
// `"dpapi"` berarti base64 blob DPAPI, `"plain"` berarti teks biasa.
|
|
15
|
+
// Fallback ke plain OTOMATIS bila backend OS tak tersedia (bukan error),
|
|
16
|
+
// supaya CLI tetap jalan di CI/container. Tak pernah melempar.
|
|
17
|
+
|
|
18
|
+
export type SecretRunner = (
|
|
19
|
+
cmd: string,
|
|
20
|
+
args: string[],
|
|
21
|
+
input?: string,
|
|
22
|
+
) => { status: number | null; stdout: string }
|
|
23
|
+
|
|
24
|
+
let runnerOverride: SecretRunner | null = null
|
|
25
|
+
|
|
26
|
+
/** Seam uji: ganti eksekutor powershell. */
|
|
27
|
+
export function __setKeystoreRunnerForTest(r: SecretRunner | null): void {
|
|
28
|
+
runnerOverride = r
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const secretCache = new Map<string, string | null>()
|
|
32
|
+
|
|
33
|
+
/** Reset cache + runner (test saja). */
|
|
34
|
+
export function __resetKeystoreForTest(): void {
|
|
35
|
+
secretCache.clear()
|
|
36
|
+
runnerOverride = null
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function defaultRunner(
|
|
40
|
+
cmd: string,
|
|
41
|
+
args: string[],
|
|
42
|
+
input?: string,
|
|
43
|
+
): { status: number | null; stdout: string } {
|
|
44
|
+
try {
|
|
45
|
+
const r = spawnSync(cmd, args, {
|
|
46
|
+
input,
|
|
47
|
+
encoding: "utf8",
|
|
48
|
+
timeout: 15000,
|
|
49
|
+
shell: process.platform === "win32",
|
|
50
|
+
windowsHide: true,
|
|
51
|
+
})
|
|
52
|
+
return { status: typeof r.status === "number" ? r.status : null, stdout: r.stdout ?? "" }
|
|
53
|
+
} catch {
|
|
54
|
+
return { status: null, stdout: "" }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function storePath(): string {
|
|
59
|
+
const home = process.env.MINICODE_HOME || homedir()
|
|
60
|
+
return join(home, ".minicode", "secrets.json")
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface SecretStore {
|
|
64
|
+
version: 1
|
|
65
|
+
entries: Record<string, { enc: string; alg: "dpapi" | "plain" }>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function loadStore(): Promise<SecretStore> {
|
|
69
|
+
try {
|
|
70
|
+
const raw = await readFile(storePath(), "utf8")
|
|
71
|
+
const parsed = JSON.parse(raw) as Partial<SecretStore>
|
|
72
|
+
if (
|
|
73
|
+
parsed &&
|
|
74
|
+
typeof parsed === "object" &&
|
|
75
|
+
parsed.entries &&
|
|
76
|
+
typeof parsed.entries === "object"
|
|
77
|
+
)
|
|
78
|
+
return { version: 1, entries: parsed.entries as SecretStore["entries"] }
|
|
79
|
+
} catch {}
|
|
80
|
+
return { version: 1, entries: {} }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function saveStore(store: SecretStore): Promise<void> {
|
|
84
|
+
try {
|
|
85
|
+
await mkdir(join(storePath(), ".."), { recursive: true, mode: 0o700 }).catch(() => {})
|
|
86
|
+
await atomicWriteText(storePath(), JSON.stringify(store))
|
|
87
|
+
await chmod(storePath(), 0o600).catch(() => {})
|
|
88
|
+
} catch {}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// DPAPI user-scope roundtrip via powershell bawaan (5.1 maupun 7.x).
|
|
92
|
+
// stdin: teks biasa (protect) / base64 blob (unprotect); stdout: hasilnya.
|
|
93
|
+
// Scope CurrentUser = hanya user Windows ini yang bisa membuka.
|
|
94
|
+
// `Add-Type System.Security` WAJIB eksplisit: assembly ProtectedData tidak
|
|
95
|
+
// di-load default oleh powershell (terbukti gagal tanpanya di Win 10/11).
|
|
96
|
+
const DPAPI_PRELUDE = "Add-Type -AssemblyName System.Security; "
|
|
97
|
+
const DPAPI_PROTECT = [
|
|
98
|
+
"-NoProfile",
|
|
99
|
+
"-NonInteractive",
|
|
100
|
+
"-Command",
|
|
101
|
+
DPAPI_PRELUDE +
|
|
102
|
+
"$t = [Console]::In.ReadToEnd(); " +
|
|
103
|
+
"$b = [Text.Encoding]::UTF8.GetBytes($t); " +
|
|
104
|
+
"$p = [Security.Cryptography.ProtectedData]::Protect($b, $null, 'CurrentUser'); " +
|
|
105
|
+
"[Convert]::ToBase64String($p)",
|
|
106
|
+
].join(" ")
|
|
107
|
+
|
|
108
|
+
const DPAPI_UNPROTECT = [
|
|
109
|
+
"-NoProfile",
|
|
110
|
+
"-NonInteractive",
|
|
111
|
+
"-Command",
|
|
112
|
+
DPAPI_PRELUDE +
|
|
113
|
+
"$t = [Console]::In.ReadToEnd(); " +
|
|
114
|
+
"$p = [Convert]::FromBase64String($t.Trim()); " +
|
|
115
|
+
"$b = [Security.Cryptography.ProtectedData]::Unprotect($p, $null, 'CurrentUser'); " +
|
|
116
|
+
"[Text.Encoding]::UTF8.GetString($b)",
|
|
117
|
+
].join(" ")
|
|
118
|
+
|
|
119
|
+
function dpapiAvailable(): boolean {
|
|
120
|
+
if (process.env.MINICODE_KEYSTORE_DISABLE === "1") return false
|
|
121
|
+
if (process.platform !== "win32" && !process.env.MINICODE_KEYSTORE_FORCE_DPAPI) return false
|
|
122
|
+
return true
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function dpapiProtect(plaintext: string): string | null {
|
|
126
|
+
const run = runnerOverride ?? defaultRunner
|
|
127
|
+
const exe = process.platform === "win32" ? "powershell" : "pwsh"
|
|
128
|
+
const r = run(exe, DPAPI_PROTECT.split(" ").filter(Boolean), plaintext)
|
|
129
|
+
if (r.status !== 0) return null
|
|
130
|
+
const out = r.stdout.trim()
|
|
131
|
+
return out ? out : null
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function dpapiUnprotect(blob: string): string | null {
|
|
135
|
+
const run = runnerOverride ?? defaultRunner
|
|
136
|
+
const shell = process.platform === "win32" ? "powershell" : "pwsh"
|
|
137
|
+
const r = run(shell, DPAPI_UNPROTECT.split(" ").filter(Boolean), blob)
|
|
138
|
+
if (r.status !== 0) return null
|
|
139
|
+
// powershell mengakhiri output dengan newline — hanya itu yang dibuang,
|
|
140
|
+
// isi secret utuh (bisa mengandung newline di tengah).
|
|
141
|
+
return r.stdout.replace(/\r?\n$/, "")
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Simpan rahasia. Return backend yang dipakai ("dpapi"|"plain"), null bila gagal total. */
|
|
145
|
+
export async function setSecret(key: string, value: string): Promise<"dpapi" | "plain" | null> {
|
|
146
|
+
if (!key || !value) return null
|
|
147
|
+
const store = await loadStore()
|
|
148
|
+
// Platform ber-DPAPI tapi proteksi GAGAL = jangan turun diam-diam ke
|
|
149
|
+
// plaintext (user mengira secret-nya terproteksi OS). Tanpa backend
|
|
150
|
+
// (non-Windows) = plain jujur berlabel.
|
|
151
|
+
if (dpapiAvailable()) {
|
|
152
|
+
const blob = dpapiProtect(value)
|
|
153
|
+
if (!blob) return null
|
|
154
|
+
store.entries[key] = { enc: blob, alg: "dpapi" }
|
|
155
|
+
await saveStore(store)
|
|
156
|
+
secretCache.set(key, value)
|
|
157
|
+
return "dpapi"
|
|
158
|
+
}
|
|
159
|
+
store.entries[key] = { enc: value, alg: "plain" }
|
|
160
|
+
await saveStore(store)
|
|
161
|
+
secretCache.set(key, value)
|
|
162
|
+
return "plain"
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Baca rahasia. null = tak ada / tak bisa dibuka. Tak pernah melempar. */
|
|
166
|
+
export async function getSecret(key: string): Promise<string | null> {
|
|
167
|
+
if (!key) return null
|
|
168
|
+
if (secretCache.has(key)) return secretCache.get(key) ?? null
|
|
169
|
+
let value: string | null = null
|
|
170
|
+
try {
|
|
171
|
+
const store = await loadStore()
|
|
172
|
+
const entry = store.entries[key]
|
|
173
|
+
if (entry) {
|
|
174
|
+
if (entry.alg === "dpapi") {
|
|
175
|
+
if (dpapiAvailable()) value = dpapiUnprotect(entry.enc)
|
|
176
|
+
} else {
|
|
177
|
+
value = entry.enc
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
} catch {
|
|
181
|
+
value = null
|
|
182
|
+
}
|
|
183
|
+
secretCache.set(key, value)
|
|
184
|
+
return value
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Hapus rahasia. Selalu "sukses" semu (idempoten, tak melempar). */
|
|
188
|
+
export async function deleteSecret(key: string): Promise<void> {
|
|
189
|
+
secretCache.delete(key)
|
|
190
|
+
try {
|
|
191
|
+
const store = await loadStore()
|
|
192
|
+
if (store.entries[key]) {
|
|
193
|
+
delete store.entries[key]
|
|
194
|
+
await saveStore(store)
|
|
195
|
+
}
|
|
196
|
+
} catch {}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Backend aktif untuk pesan/diagnostik (bukan rahasia). */
|
|
200
|
+
export function keystoreBackend(): "dpapi" | "plain-file" {
|
|
201
|
+
return dpapiAvailable() ? "dpapi" : "plain-file"
|
|
202
|
+
}
|