Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- **Workspace lints apply to every crate** (Claude): `devcraft-core`, `devcraft-mcp` and `devcraft-app` opt into `[workspace.lints]` with `[lints] workspace = true`. Until now only the app's own `#![deny]` attribute was enforced, so `unwrap_used`, `expect_used`, `panic`, `unimplemented` and `todo` were not checked in core and mcp (an `unwrap()` added to core passed `cargo clippy -D warnings`). A root `clippy.toml` allows unwrap, expect and panic in tests. No existing code needed a change.
- **Serve token from OS randomness** (Claude): `devcraft-mcp serve` creates `.devcraft/mobile.token` from 32 bytes of OS randomness (64 hex characters, `getrandom`) instead of the clock in nanoseconds and the process id, which anyone who could guess the first start could narrow down. Presented tokens are compared without stopping at the first differing byte. An existing token file is kept; delete it to get a new token. Tests in `serve.rs`.
- **NSSM services: list, test, start, stop, create, edit, remove** (Claude): the Services page and six tools (`devcraft_nssm_list`, `devcraft_nssm_health`, `devcraft_nssm_install`, `devcraft_nssm_edit`, `devcraft_nssm_remove`, `devcraft_nssm_control`). The list comes from one PowerShell call without administrator rights: state, start mode, account, application, parameters, folder, logs, exit action, the nssm.exe process tree and the ports those processes listen on, plus ports named in the parameters (`--port`, `--rest-port`) or the environment (`PORT=`, `SPEECH_MCP_PORT=`). Environment values whose names hold PASS, SECRET, TOKEN, KEY, CREDENTIAL, PWD or AUTH show as `***`. The test probes every listening or named port with TCP and `GET /` and reads the log tails; verdicts are healthy, degraded (application not running, named port not listening, HTTP 5xx), down or disabled. Changes run as one elevated PowerShell script each, so one UAC prompt on the desktop; values are written to the NSSM registry keys with `Set-ItemProperty` instead of `nssm set` on a command line, because Windows PowerShell 5.1 drops embedded quotes from native arguments. Start, stop and restart try `sc.exe` as the user first and elevate only on access denied; nothing kills a child process. Writes need `confirm=true`, remove needs the service name as confirm. Verified on Goliath: the list (17 services) and health tests; create, edit, remove and an elevated control were not run live, they need someone at the UAC prompt.
- **Lunch page (optional, QoL)** (Claude): today's set lunch menus from the restaurants in `{workspace}/.devcraft/lunch.json`, on the Lunch page (sidebar group QoL, off by default; Setup and the page itself turn it on) and as `devcraft_lunch`. Two kinds of source: a text page that lists the week under German weekday headings (Gasthaus Orlik: soups, dishes and prices are parsed, today's day is picked by date) and a weekly sheet published as a picture (The Golden Harp Alsergrund: the JPEG is shown, its text is not read). Fetched with curl, cached for three hours and per day; nothing is fetched while the page is off. Restaurants can be added, edited and switched off on the page. Spec: `docs/SPEC_SERVICES_AND_LUNCH.md`.
- **CLI `--args`** (Claude): `devcraft-mcp tool <name> --args key=value` (repeatable, or a JSON object) passes fields that have no flag, such as `--args name=speech-mcp`.
Expand Down
3 changes: 3 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
3 changes: 3 additions & 0 deletions crates/devcraft-app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ edition.workspace = true
license.workspace = true
authors.workspace = true

[lints]
workspace = true

[[bin]]
name = "devcraft"
path = "src/main.rs"
Expand Down
3 changes: 3 additions & 0 deletions crates/devcraft-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ edition.workspace = true
license.workspace = true
authors.workspace = true

[lints]
workspace = true

[dependencies]
serde.workspace = true
serde_json.workspace = true
Expand Down
4 changes: 4 additions & 0 deletions crates/devcraft-mcp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ edition.workspace = true
license.workspace = true
authors.workspace = true

[lints]
workspace = true

[[bin]]
name = "devcraft-mcp"
path = "src/main.rs"
Expand All @@ -15,3 +18,4 @@ serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
clap.workspace = true
getrandom = "0.4"
79 changes: 71 additions & 8 deletions crates/devcraft-mcp/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

Expand Down Expand Up @@ -68,15 +67,30 @@ fn mobile_token(root: &Path) -> Result<String, String> {
return Ok(token);
}
}
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let token = format!("{:x}{:x}", nanos, std::process::id());
let token = new_token()?;
std::fs::write(&path, &token).map_err(|e| e.to_string())?;
Ok(token)
}

/// 256 bits from the OS random source, as 64 hex characters. A token made
/// from the clock and the process id can be narrowed down by anyone who can
/// guess when the companion first ran.
fn new_token() -> Result<String, String> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).map_err(|e| format!("no OS randomness: {e}"))?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}

/// Compare a presented token with the real one without stopping at the
/// first differing byte, so response time does not reveal a matching prefix.
fn token_eq(given: &str, token: &str) -> bool {
let (a, b) = (given.as_bytes(), token.as_bytes());
if a.len() != b.len() {
return false;
}
a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

/// Tailscale IPv4 from `tailscale ip -4`, empty when Tailscale is down.
fn tailscale_ip() -> String {
let output = std::process::Command::new("tailscale")
Expand Down Expand Up @@ -111,14 +125,14 @@ fn response(status: u16, content_type: &str, body: &str) -> Vec<u8> {
fn authorized(query: &str, headers: &HashMap<String, String>, token: &str) -> bool {
for pair in query.split('&') {
if let Some(value) = pair.strip_prefix("token=") {
if value == token {
if token_eq(value, token) {
return true;
}
}
}
if let Some(auth) = headers.get("authorization") {
if let Some(bearer) = auth.strip_prefix("Bearer ") {
if bearer.trim() == token {
if token_eq(bearer.trim(), token) {
return true;
}
}
Expand Down Expand Up @@ -401,3 +415,52 @@ pub async fn run(bind: &str) -> Result<(), String> {
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn new_token_is_long_random_hex() {
let a = new_token().unwrap();
let b = new_token().unwrap();
assert_eq!(a.len(), 64);
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
assert_ne!(a, b);
}

#[test]
fn mobile_token_is_created_random_then_reused() {
let root = std::env::temp_dir().join(format!("devcraft_token_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let first = mobile_token(&root).unwrap();
let second = mobile_token(&root).unwrap();
let _ = std::fs::remove_dir_all(&root);
assert_eq!(first.len(), 64);
assert_eq!(first, second);
}

#[test]
fn token_eq_compares_the_whole_value() {
assert!(token_eq("abc123", "abc123"));
assert!(!token_eq("abc124", "abc123"));
assert!(!token_eq("abc12", "abc123"));
assert!(!token_eq("abc1234", "abc123"));
assert!(!token_eq("", "abc123"));
}

#[test]
fn authorized_needs_the_exact_token_in_query_or_bearer() {
let token = "f00d";
let none = HashMap::new();
assert!(authorized("a=1&token=f00d", &none, token));
assert!(!authorized("token=f00e", &none, token));
assert!(!authorized("token=f00", &none, token));
assert!(!authorized("", &none, token));
let mut headers = HashMap::new();
headers.insert("authorization".to_string(), "Bearer f00d".to_string());
assert!(authorized("", &headers, token));
headers.insert("authorization".to_string(), "Bearer nope".to_string());
assert!(!authorized("", &headers, token));
}
}