winx-code-agent 0.2.349

Remote-first Rust MCP runtime with Streamable HTTP, durable PTYs, and guarded agent tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Typed configuration and secret-loading helpers.

use std::path::{Path, PathBuf};

use serde::Deserialize;
use sha2::{Digest, Sha256};

use crate::errors::{Result, WinxError};
use crate::tool_policy::{ToolPolicy, ToolProfile};

/// Minimum accepted HTTP bearer-token length in bytes.
pub const MIN_HTTP_TOKEN_BYTES: usize = 32;

/// How remote `Initialize(first_call)` requests select a durable shell session.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, clap::ValueEnum)]
pub enum HttpSessionAffinity {
    /// Reuse one session per authenticated principal and canonical workspace.
    /// This is the safe default for stateless clients whose generated thread IDs
    /// are not stable across reconnects or conversations.
    #[default]
    Workspace,
    /// Reuse one session per principal, conversation identity, and canonical
    /// workspace. `Mcp-Session-Id` is preferred; modern stateless clients fall
    /// back to their supplied first-call `thread_id`, then to workspace affinity.
    /// This separates parallel conversations without giving up workspace context.
    Conversation,
    /// Trust the external `thread_id` as the session key. This preserves parallel
    /// shells in one workspace, but callers must supply a stable ID and clean up
    /// abandoned sessions themselves.
    Thread,
}

/// Parse common human-friendly boolean spellings.
pub fn parse_bool(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" | "" => Some(false),
        _ => None,
    }
}

/// Read a boolean environment variable with one consistent spelling policy.
pub fn env_flag(name: &str) -> bool {
    std::env::var(name).ok().as_deref().and_then(parse_bool).unwrap_or(false)
}

/// Read and trim a non-empty environment variable.
pub fn env_text(name: &str) -> Option<String> {
    std::env::var(name).ok().map(|value| value.trim().to_string()).filter(|value| !value.is_empty())
}

/// Authenticated HTTP principal. Only a SHA-256 token digest is retained.
#[derive(Clone)]
pub struct HttpPrincipal {
    name: String,
    id: String,
    token_digest: [u8; 32],
    tool_policy: ToolPolicy,
}

impl std::fmt::Debug for HttpPrincipal {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HttpPrincipal")
            .field("name", &self.name)
            .field("id", &self.id)
            .field("tool_policy", &self.tool_policy)
            .field("token", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

impl HttpPrincipal {
    pub fn new(name: impl Into<String>, token: &str, allow_weak_token: bool) -> Result<Self> {
        Self::new_with_tool_policy(name, token, allow_weak_token, ToolPolicy::default())
    }

    pub fn new_with_tool_policy(
        name: impl Into<String>,
        token: &str,
        allow_weak_token: bool,
        tool_policy: ToolPolicy,
    ) -> Result<Self> {
        let name = name.into().trim().to_string();
        if name.is_empty() {
            return Err(WinxError::ConfigurationError(
                "HTTP principal name cannot be empty".to_string(),
            ));
        }
        if !name
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'))
        {
            return Err(WinxError::ConfigurationError(format!(
                "HTTP principal name {name:?} may contain only ASCII letters, digits, '_' and '-'"
            )));
        }
        validate_http_token(token, allow_weak_token)?;
        let token_digest: [u8; 32] = Sha256::digest(token.as_bytes()).into();
        let id_digest = Sha256::digest(name.as_bytes());
        let id = id_digest[..8].iter().fold(String::with_capacity(16), |mut output, byte| {
            use std::fmt::Write as _;
            let _ = write!(output, "{byte:02x}");
            output
        });
        Ok(Self { name, id, token_digest, tool_policy })
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn session_prefix(&self) -> String {
        format!("p_{}__", self.id)
    }

    pub fn task_prefix(&self) -> String {
        format!("task_{}__", self.id)
    }

    pub fn matches_token(&self, presented: &str) -> bool {
        let digest: [u8; 32] = Sha256::digest(presented.as_bytes()).into();
        constant_time_digest_eq(&self.token_digest, &digest)
    }

    pub fn tool_policy(&self) -> ToolPolicy {
        self.tool_policy
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct PrincipalFile {
    principals: Vec<PrincipalEntry>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct PrincipalEntry {
    name: String,
    token_file: Option<PathBuf>,
    token_env: Option<String>,
    #[serde(default)]
    tool_profile: ToolProfile,
    allowed_tools: Option<Vec<String>>,
}

/// Resolve either a legacy single principal or a multi-principal TOML file.
pub fn load_http_principals(
    principal_config: Option<&Path>,
    command_token: Option<String>,
    command_token_file: Option<&Path>,
    allow_weak_token: bool,
) -> Result<Vec<HttpPrincipal>> {
    load_http_principals_with_policy(
        principal_config,
        command_token,
        command_token_file,
        allow_weak_token,
        ToolPolicy::default(),
    )
}

/// Resolve HTTP principals and apply `single_principal_policy` to legacy
/// `--token`/`--token-file`/environment authentication.
pub fn load_http_principals_with_policy(
    principal_config: Option<&Path>,
    command_token: Option<String>,
    command_token_file: Option<&Path>,
    allow_weak_token: bool,
    single_principal_policy: ToolPolicy,
) -> Result<Vec<HttpPrincipal>> {
    if principal_config.is_some() && (command_token.is_some() || command_token_file.is_some()) {
        return Err(WinxError::ConfigurationError(
            "--principal-config cannot be combined with --token/--token-file".to_string(),
        ));
    }

    let principals = if let Some(path) = principal_config {
        let content = std::fs::read_to_string(path).map_err(|error| {
            WinxError::ConfigurationError(format!(
                "cannot read HTTP principal config {}: {error}",
                path.display()
            ))
        })?;
        let config: PrincipalFile = toml::from_str(&content).map_err(|error| {
            WinxError::ConfigurationError(format!(
                "invalid HTTP principal config {}: {error}",
                path.display()
            ))
        })?;
        if config.principals.is_empty() {
            return Err(WinxError::ConfigurationError(
                "HTTP principal config must contain at least one [[principals]] entry".to_string(),
            ));
        }
        config
            .principals
            .into_iter()
            .map(|entry| {
                let tool_policy =
                    ToolPolicy::resolve(entry.tool_profile, entry.allowed_tools.as_deref())?;
                let token = match (entry.token_file.as_deref(), entry.token_env.as_deref()) {
                    (Some(path), None) => load_secret_file(path)?,
                    (None, Some(name)) => std::env::var(name).map_err(|error| {
                        WinxError::ConfigurationError(format!(
                            "HTTP principal {} token_env {name:?} is unavailable: {error}",
                            entry.name
                        ))
                    })?,
                    (Some(_), Some(_)) => {
                        return Err(WinxError::ConfigurationError(format!(
                            "HTTP principal {} must set exactly one of token_file or token_env",
                            entry.name
                        )))
                    }
                    (None, None) => {
                        return Err(WinxError::ConfigurationError(format!(
                            "HTTP principal {} must set token_file or token_env",
                            entry.name
                        )))
                    }
                };
                HttpPrincipal::new_with_tool_policy(
                    entry.name,
                    token.trim(),
                    allow_weak_token,
                    tool_policy,
                )
            })
            .collect::<Result<Vec<_>>>()?
    } else {
        let token = match (command_token, command_token_file) {
            (Some(_), Some(_)) => {
                return Err(WinxError::ConfigurationError(
                    "provide only one of --token or --token-file".to_string(),
                ))
            }
            (Some(token), None) => token,
            (None, Some(path)) => load_secret_file(path)?,
            (None, None) => env_text("WINX_HTTP_TOKEN").unwrap_or_default(),
        };
        vec![HttpPrincipal::new_with_tool_policy(
            "default",
            token.trim(),
            allow_weak_token,
            single_principal_policy,
        )?]
    };

    reject_duplicate_principals(&principals)?;
    Ok(principals)
}

pub fn load_secret_file(path: &Path) -> Result<String> {
    let metadata = std::fs::symlink_metadata(path).map_err(|error| {
        WinxError::ConfigurationError(format!(
            "cannot inspect secret file {}: {error}",
            path.display()
        ))
    })?;
    if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
        return Err(WinxError::ConfigurationError(format!(
            "secret path {} must be a regular, non-symlink file",
            path.display()
        )));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        let mode = metadata.permissions().mode();
        if mode & 0o077 != 0 {
            return Err(WinxError::ConfigurationError(format!(
                "secret file {} is readable or writable by group/others; use chmod 600",
                path.display()
            )));
        }
    }
    let value = std::fs::read_to_string(path).map_err(|error| {
        WinxError::ConfigurationError(format!(
            "cannot read secret file {}: {error}",
            path.display()
        ))
    })?;
    let value = value.trim().to_string();
    if value.is_empty() {
        return Err(WinxError::ConfigurationError(format!(
            "secret file {} is empty",
            path.display()
        )));
    }
    Ok(value)
}

fn validate_http_token(token: &str, allow_weak_token: bool) -> Result<()> {
    if token.is_empty() {
        return Err(WinxError::ConfigurationError(
            "refusing to start HTTP transport without a token (RCE exposure)".to_string(),
        ));
    }
    if !allow_weak_token && token.len() < MIN_HTTP_TOKEN_BYTES {
        return Err(WinxError::ConfigurationError(format!(
            "HTTP token is too short ({} bytes); use at least {MIN_HTTP_TOKEN_BYTES} bytes or pass --allow-weak-token for local development",
            token.len()
        )));
    }
    Ok(())
}

fn reject_duplicate_principals(principals: &[HttpPrincipal]) -> Result<()> {
    for (index, principal) in principals.iter().enumerate() {
        for other in principals.iter().skip(index + 1) {
            if principal.name == other.name || principal.id == other.id {
                return Err(WinxError::ConfigurationError(format!(
                    "duplicate HTTP principal name {:?}",
                    principal.name
                )));
            }
            if constant_time_digest_eq(&principal.token_digest, &other.token_digest) {
                return Err(WinxError::ConfigurationError(format!(
                    "HTTP principals {:?} and {:?} use the same token",
                    principal.name, other.name
                )));
            }
        }
    }
    Ok(())
}

fn constant_time_digest_eq(left: &[u8; 32], right: &[u8; 32]) -> bool {
    left.iter().zip(right).fold(0_u8, |difference, (left, right)| difference | (left ^ right)) == 0
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    use super::{load_http_principals, load_secret_file, parse_bool, HttpPrincipal};

    #[test]
    fn boolean_parser_is_consistent() {
        assert_eq!(parse_bool(" TRUE "), Some(true));
        assert_eq!(parse_bool("yes"), Some(true));
        assert_eq!(parse_bool("off"), Some(false));
        assert_eq!(parse_bool("false"), Some(false));
        assert_eq!(parse_bool("maybe"), None);
    }

    #[test]
    fn principal_keeps_only_a_digest_and_matches_constant_time() {
        let token = "0123456789abcdef0123456789abcdef";
        let principal = HttpPrincipal::new("chatgpt", token, false).expect("valid principal");
        assert!(principal.matches_token(token));
        assert!(!principal.matches_token("0123456789abcdef0123456789abcdeg"));
        assert!(!format!("{principal:?}").contains(token));
    }

    #[cfg(unix)]
    #[test]
    fn secret_file_requires_user_only_permissions() {
        use std::os::unix::fs::PermissionsExt as _;

        let directory = tempfile::TempDir::new().expect("temp directory");
        let secret = directory.path().join("token");
        std::fs::write(&secret, "0123456789abcdef0123456789abcdef\n").expect("write token");
        std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o644))
            .expect("set broad permissions");
        assert!(load_secret_file(&secret).is_err());

        std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o600))
            .expect("set private permissions");
        assert_eq!(
            load_secret_file(&secret).expect("private token"),
            "0123456789abcdef0123456789abcdef"
        );
    }

    #[cfg(unix)]
    #[test]
    fn principal_toml_loads_independent_file_backed_identities() {
        use std::os::unix::fs::PermissionsExt as _;

        let directory = tempfile::TempDir::new().expect("temp directory");
        let left = directory.path().join("left-token");
        let right = directory.path().join("right-token");
        for (path, value) in [
            (&left, "left-0123456789abcdef0123456789abcdef"),
            (&right, "right-0123456789abcdef0123456789abcdef"),
        ] {
            std::fs::write(path, value).expect("write token");
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
                .expect("private token permissions");
        }
        let config = directory.path().join("principals.toml");
        std::fs::write(
            &config,
            format!(
                "[[principals]]\nname = \"left\"\ntoken_file = {left:?}\ntool_profile = \"terminal\"\n\n[[principals]]\nname = \"right\"\ntoken_file = {right:?}\nallowed_tools = [\"Initialize\", \"ReadFiles\"]\n"
            ),
        )
        .expect("write principal config");

        let principals =
            load_http_principals(Some(&config), None, None, false).expect("load principals");
        assert_eq!(principals.len(), 2);
        assert!(principals[0].matches_token("left-0123456789abcdef0123456789abcdef"));
        assert!(principals[1].matches_token("right-0123456789abcdef0123456789abcdef"));
        assert_ne!(principals[0].session_prefix(), principals[1].session_prefix());
        assert_eq!(
            principals[0].tool_policy().names().collect::<Vec<_>>(),
            vec!["Initialize", "BashCommand"]
        );
        assert_eq!(
            principals[1].tool_policy().names().collect::<Vec<_>>(),
            vec!["Initialize", "ReadFiles"]
        );
    }
}