| 1 | use std::path::Path; |
| 2 | |
| 3 | use codewhale_config::CustomLspDef; |
| 4 | use codewhale_runtime::config as user_config; |
| 5 | |
| 6 | use crate::LspConfig; |
| 7 | use crate::registry::Language; |
| 8 | |
| 9 | pub const NOT_APPROVED_PREFIX: &str = "language server not approved"; |
| 10 | |
| 11 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 12 | pub struct ServerSpec { |
| 13 | pub key: String, |
| 14 | pub name: String, |
| 15 | pub command: String, |
| 16 | pub args: Vec<String>, |
| 17 | } |
| 18 | |
| 19 | impl ServerSpec { |
| 20 | #[must_use] |
| 21 | pub fn built_in(config: &LspConfig, language: Language) -> Option<Self> { |
| 22 | let (command, args) = config.resolve_command(language)?; |
| 23 | Some(Self { |
| 24 | key: language.as_key().to_owned(), |
| 25 | name: language.as_key().to_owned(), |
| 26 | command, |
| 27 | args, |
| 28 | }) |
| 29 | } |
| 30 | |
| 31 | #[must_use] |
| 32 | pub fn custom(extension: &str, def: &CustomLspDef) -> Option<Self> { |
| 33 | let extension = extension.to_ascii_lowercase(); |
| 34 | let safe = !extension.is_empty() |
| 35 | && extension.len() <= 32 |
| 36 | && extension.bytes().all(|byte| { |
| 37 | byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"_+-".contains(&byte) |
| 38 | }); |
| 39 | safe.then(|| Self { |
| 40 | key: format!("custom_{extension}"), |
| 41 | name: extension, |
| 42 | command: def.command.clone(), |
| 43 | args: def.args.clone(), |
| 44 | }) |
| 45 | } |
| 46 | |
| 47 | #[must_use] |
| 48 | pub fn digest(&self) -> String { |
| 49 | let mut canonical = format!("codewhale-lsp-approval-v1;{}:{};", self.key.len(), self.key); |
| 50 | for part in std::iter::once(&self.command).chain(&self.args) { |
| 51 | canonical.push_str(&format!("{}:{};", part.len(), part)); |
| 52 | } |
| 53 | codewhale_runtime::hashing::sha256_hex(canonical.as_bytes()) |
| 54 | } |
| 55 | |
| 56 | #[must_use] |
| 57 | pub fn command_line(&self) -> String { |
| 58 | std::iter::once(self.command.as_str()) |
| 59 | .chain(self.args.iter().map(String::as_str)) |
| 60 | .collect::<Vec<_>>() |
| 61 | .join(" ") |
| 62 | } |
| 63 | |
| 64 | fn receipt_key(&self) -> String { |
| 65 | user_config::lsp_receipt_key(&self.key) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 70 | pub enum Gate { |
| 71 | Approved, |
| 72 | FolderNotTrusted, |
| 73 | NotApproved, |
| 74 | } |
| 75 | |
| 76 | #[must_use] |
| 77 | pub fn gate(workspace: &Path, spec: &ServerSpec) -> Gate { |
| 78 | if !user_config::is_workspace_trusted(workspace) { |
| 79 | return Gate::FolderNotTrusted; |
| 80 | } |
| 81 | match user_config::project_receipt_for_workspace(workspace, &spec.receipt_key()) { |
| 82 | Some(receipt) if receipt == spec.digest() => Gate::Approved, |
| 83 | _ => Gate::NotApproved, |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | #[must_use] |
| 88 | pub fn refusal_message(spec: &ServerSpec, gate: Gate) -> String { |
| 89 | let reason = match gate { |
| 90 | Gate::Approved => return String::new(), |
| 91 | Gate::FolderNotTrusted => { |
| 92 | "this folder is not permanently trusted, so no language server may start in it" |
| 93 | } |
| 94 | Gate::NotApproved => { |
| 95 | "the person using this session has not approved it for this folder, or its configured command changed since they did" |
| 96 | } |
| 97 | }; |
| 98 | format!( |
| 99 | "{NOT_APPROVED_PREFIX}: `{}` ({}) cannot start because {reason}. Tell the user that they can allow it by running `/lsp approve {}` in the Codewhale terminal app; do not try to start it or approve it yourself.", |
| 100 | spec.command_line(), |
| 101 | spec.name, |
| 102 | spec.name, |
| 103 | ) |
| 104 | } |
| 105 | |
| 106 | #[must_use] |
| 107 | pub fn refusal_notice(spec: &ServerSpec, gate: Gate) -> String { |
| 108 | let reason = match gate { |
| 109 | Gate::Approved => return String::new(), |
| 110 | Gate::FolderNotTrusted => "this folder is not permanently trusted", |
| 111 | Gate::NotApproved => "it is not approved for this folder", |
| 112 | }; |
| 113 | format!( |
| 114 | "Language server `{}` did not start because {reason}, so its diagnostics are off. Run `/lsp approve {}` to allow it, or `/lsp status` to see all servers.", |
| 115 | spec.command_line(), |
| 116 | spec.name, |
| 117 | ) |
| 118 | } |
| 119 | |
| 120 | pub fn approve(workspace: &Path, spec: &ServerSpec) -> Result<(), String> { |
| 121 | if !user_config::is_workspace_trusted(workspace) { |
| 122 | return Err( |
| 123 | "Trust this folder permanently first: accept the trust prompt, or run `/trust on --save`. A session-only trust does not allow language servers." |
| 124 | .to_owned(), |
| 125 | ); |
| 126 | } |
| 127 | user_config::save_workspace_project_receipt(workspace, &spec.receipt_key(), &spec.digest()) |
| 128 | .map(|_| ()) |
| 129 | .map_err(|_| "Could not save the approval in your user config.".to_owned()) |
| 130 | } |
| 131 | |
| 132 | pub fn revoke(workspace: &Path, spec: &ServerSpec) -> Result<bool, String> { |
| 133 | user_config::clear_workspace_project_receipt(workspace, &spec.receipt_key()) |
| 134 | .map_err(|_| "Could not update the approval in your user config.".to_owned()) |
| 135 | } |
| 136 | |
| 137 | #[must_use] |
| 138 | pub fn configured_servers(config: &LspConfig) -> Vec<ServerSpec> { |
| 139 | let mut servers: Vec<ServerSpec> = Language::BUILT_IN |
| 140 | .iter() |
| 141 | .filter_map(|language| ServerSpec::built_in(config, *language)) |
| 142 | .collect(); |
| 143 | let mut custom: Vec<_> = config.custom.iter().collect(); |
| 144 | custom.sort_by(|left, right| left.0.cmp(right.0)); |
| 145 | servers.extend( |
| 146 | custom |
| 147 | .into_iter() |
| 148 | .filter(|(extension, _)| { |
| 149 | crate::registry::detect_language(Path::new(&format!("x.{extension}"))) |
| 150 | == Language::Other |
| 151 | }) |
| 152 | .filter_map(|(extension, def)| ServerSpec::custom(extension, def)), |
| 153 | ); |
| 154 | servers |
| 155 | } |
| 156 | |
| 157 | pub fn resolve_names(config: &LspConfig, names: &[&str]) -> Result<Vec<ServerSpec>, String> { |
| 158 | let servers = configured_servers(config); |
| 159 | let mut chosen: Vec<ServerSpec> = Vec::new(); |
| 160 | for name in names { |
| 161 | let wanted = name.trim().to_ascii_lowercase(); |
| 162 | let Some(spec) = servers.iter().find(|spec| spec.name == wanted) else { |
| 163 | let known = servers |
| 164 | .iter() |
| 165 | .map(|spec| spec.name.as_str()) |
| 166 | .collect::<Vec<_>>() |
| 167 | .join(", "); |
| 168 | return Err(format!( |
| 169 | "No configured language server is named `{name}`. Choose from: {known}." |
| 170 | )); |
| 171 | }; |
| 172 | if !chosen.contains(spec) { |
| 173 | chosen.push(spec.clone()); |
| 174 | } |
| 175 | } |
| 176 | Ok(chosen) |
| 177 | } |
| 178 | |
| 179 | #[must_use] |
| 180 | pub fn render_status(config: Option<&LspConfig>, workspace: &Path) -> String { |
| 181 | let Some(config) = config else { |
| 182 | return "Language servers are off: your config has no `[lsp]` table, so none will start. Add one (see `config.example.toml`), then approve each server with `/lsp approve <name>`.".to_owned(); |
| 183 | }; |
| 184 | if !config.enabled { |
| 185 | return "Language servers are off: `[lsp] enabled = false` in your config. Remove that line or set it to true to use them.".to_owned(); |
| 186 | } |
| 187 | let trusted = user_config::is_workspace_trusted(workspace); |
| 188 | let mut out = String::from( |
| 189 | "Language servers are configured. A server starts only in a permanently trusted folder, and only after you approve it here.\n\n", |
| 190 | ); |
| 191 | out.push_str(&format!( |
| 192 | "Folder trust: {}\n\n", |
| 193 | if trusted { |
| 194 | "saved (permanent)" |
| 195 | } else { |
| 196 | "not saved; accept the trust prompt or run `/trust on --save`" |
| 197 | } |
| 198 | )); |
| 199 | for spec in configured_servers(config) { |
| 200 | let state = match gate(workspace, &spec) { |
| 201 | Gate::Approved => "approved".to_owned(), |
| 202 | Gate::FolderNotTrusted => "blocked (folder not trusted)".to_owned(), |
| 203 | Gate::NotApproved => format!("not approved; run `/lsp approve {}`", spec.name), |
| 204 | }; |
| 205 | out.push_str(&format!( |
| 206 | " {:<12} {:<44} {state}\n", |
| 207 | spec.name, |
| 208 | spec.command_line() |
| 209 | )); |
| 210 | } |
| 211 | out.push_str("\nUse `/lsp approve <name>` to allow a server in this folder and `/lsp revoke <name>` to withdraw it."); |
| 212 | out |
| 213 | } |
| 214 | |
| 215 | #[must_use] |
| 216 | pub fn approval_explanation(specs: &[ServerSpec]) -> String { |
| 217 | let mut out = String::from( |
| 218 | "Approving a language server lets Codewhale start it in this folder whenever the model reads code or an edit finishes. It runs as you, outside the sandbox, with the folder as its root. To analyse the project it may run code the folder defines, such as build scripts, plugins, toolchain or package-manager configuration, and a later `git pull` can change what that code does. Approve only folders you trust.\n\n", |
| 219 | ); |
| 220 | for spec in specs { |
| 221 | out.push_str(&format!(" {}: {}\n", spec.name, spec.command_line())); |
| 222 | } |
| 223 | out |
| 224 | } |
| 225 |