rpi-cli 0.33.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
use crate::prebuilt_extensions::{body_limited, check_hash};
use percent_encoding::percent_decode_str;
use reqwest::Url;
use std::path::Path;

const CDN_ENV: &str = "RPI_CDN_BASE_URL";
const CLI_REPOSITORY: &str = "https://github.com/bigfish1913/pi-rust";
const EXTENSION_REPOSITORY: &str = "https://github.com/pi-rust/rpi-extension";
/// Extension releases published before the catalog moved to
/// `pi-rust/rpi-extension` still carry the old `repository` metadata, and their
/// archives are already mirrored under the old CDN prefix. Both entries share
/// the same handling; only the path prefixes differ. Keep this pair in sync with
/// `prebuilt_extensions::MOVED_REPOSITORIES`.
const LEGACY_EXTENSION_REPOSITORY: &str = "https://github.com/pi-rust/rpi-package";

/// Resolve and validate the optional CDN base. The CDN is only a transport;
/// manifests and all release identity fields still come from GitHub.
///
/// Precedence is explicit CLI (`--cdn`), environment (`RPI_CDN_BASE_URL`),
/// project `.rpi/settings.json` (`cdnBaseUrl`), then global `settings.json`
/// (`cdnBaseUrl`). Settings are convenience defaults; they never override an
/// explicit invocation or environment configuration.
pub(crate) fn resolve_base(cli_value: Option<&str>) -> Result<Option<Url>, String> {
    let cwd = std::env::current_dir().ok();
    resolve_base_in(cli_value, cwd.as_deref())
}

fn resolve_base_in(cli_value: Option<&str>, cwd: Option<&Path>) -> Result<Option<Url>, String> {
    let global_setting = crate::settings::load_settings()
        .ok()
        .and_then(|settings| settings.cdn_base_url);
    let project_setting = cwd
        .and_then(|path| {
            crate::settings::load_active_project_settings(path)
                .ok()
                .flatten()
        })
        .and_then(|(_, settings)| settings.cdn_base_url);
    let configured_setting = project_setting.or(global_setting);
    let value = cli_value
        .map(str::to_owned)
        .or_else(|| std::env::var(CDN_ENV).ok())
        .or(configured_setting)
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty());
    let Some(value) = value else { return Ok(None) };
    let mut url = Url::parse(&value).map_err(|_| "invalid CDN base URL".to_string())?;
    if url.scheme() != "https"
        || url.host_str().is_none()
        || !url.username().is_empty()
        || url.password().is_some()
        || url.query().is_some()
        || url.fragment().is_some()
    {
        return Err("CDN base URL must be HTTPS without credentials, query, or fragment".into());
    }
    // Rebuild the base path from safe, non-empty segments. This normalizes
    // repeated/trailing slashes while preventing a base path from escaping the
    // fixed CDN namespace below.
    let segments = url
        .path()
        .split('/')
        .filter(|segment| !segment.is_empty())
        .map(|segment| {
            percent_decode_str(segment)
                .decode_utf8()
                .map(|value| value.into_owned())
                .map_err(|_| "invalid encoded CDN base path".to_string())
        })
        .collect::<Result<Vec<_>, _>>()?;
    if segments.iter().any(|segment| {
        segment == "."
            || segment == ".."
            || segment.contains(['/', '\\'])
            || segment.chars().any(|ch| ch.is_control())
    }) {
        return Err("CDN base URL contains an unsafe path".into());
    }
    {
        let mut path = url
            .path_segments_mut()
            .map_err(|_| "invalid CDN base URL")?;
        path.clear();
        for segment in &segments {
            path.push(segment);
        }
    }
    Ok(Some(url))
}

/// CDN path prefixes to try for an official repository, in order.
///
/// A moved repository may have its archives mirrored under either prefix: the
/// objects published before the move live under the previous name, and new
/// releases can be mirrored under the new one. Both are attempted so a CDN
/// mirror that has not caught up yet is a cache miss, not an install failure.
fn repository_prefixes(repository: &str) -> Option<&'static [&'static str]> {
    match repository {
        CLI_REPOSITORY => Some(&["rpi"]),
        EXTENSION_REPOSITORY => Some(&["rpi-extension", "rpi-package"]),
        LEGACY_EXTENSION_REPOSITORY => Some(&["rpi-package", "rpi-extension"]),
        _ => None,
    }
}

fn safe_path_segment(value: &str, label: &str) -> Result<String, String> {
    let decoded = percent_decode_str(value)
        .decode_utf8()
        .map_err(|_| format!("invalid encoded {label}"))?;
    if decoded.is_empty()
        || decoded == "."
        || decoded == ".."
        || decoded.contains(['/', '\\'])
        || decoded.chars().any(|ch| ch.is_control())
        || !decoded
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'+'))
    {
        return Err(format!("{label} is not a safe URL path segment"));
    }
    Ok(decoded.into_owned())
}

fn safe_archive_filename(value: &str) -> Result<String, String> {
    let url = Url::parse(value).map_err(|_| "invalid archive URL")?;
    let filename = url
        .path_segments()
        .ok_or("archive URL has no path")?
        .next_back()
        .ok_or("archive URL has no filename")?;
    safe_path_segment(filename, "archive filename")
}

/// Construct the CDN candidate URLs for an official repository and only from
/// the already validated GitHub release tag and archive URL filename. An empty
/// list means the repository is not mirrored through this CDN.
pub(crate) fn archive_urls(
    base: &Url,
    repository: &str,
    tag: &str,
    github_archive_url: &str,
) -> Result<Vec<Url>, String> {
    let Some(prefixes) = repository_prefixes(repository) else {
        return Ok(Vec::new());
    };
    let tag = safe_path_segment(tag, "release tag")?;
    let filename = safe_archive_filename(github_archive_url)?;
    let scoped = base
        .path_segments()
        .and_then(|mut segments| segments.rfind(|segment| !segment.is_empty()))
        .and_then(|segment| prefixes.iter().find(|prefix| **prefix == segment))
        .copied();
    // A base that already ends in a CDN namespace stays inside that one; the
    // other candidates would point outside it.
    let candidates: Vec<&'static str> = match scoped {
        Some(prefix) => vec![prefix],
        None => prefixes.to_vec(),
    };
    let mut urls = Vec::with_capacity(candidates.len());
    for prefix in candidates {
        let mut url = base.clone();
        {
            let mut path = url
                .path_segments_mut()
                .map_err(|_| "invalid CDN base URL")?;
            if scoped.is_none() {
                path.push(prefix);
            }
            path.push("releases").push(&tag).push(&filename);
        }
        urls.push(url);
    }
    Ok(urls)
}

async fn download_one(
    client: &reqwest::Client,
    url: &str,
    limit: u64,
    expected_hash: &str,
    label: &str,
) -> Result<Vec<u8>, String> {
    let response = client
        .get(url)
        .send()
        .await
        .map_err(|error| format!("{label} request failed: {error}"))?;
    if !response.status().is_success() {
        return Err(format!("{label} request returned {}", response.status()));
    }
    let bytes = body_limited(response, limit).await?;
    if bytes.len() as u64 != limit {
        return Err(format!(
            "{label} size {} does not match expected size {limit}",
            bytes.len()
        ));
    }
    check_hash(&bytes, expected_hash)?;
    Ok(bytes)
}

/// Try the untrusted CDN first, then always fall back to the canonical GitHub
/// release asset on any CDN transport, status, size, or hash failure.
pub(crate) async fn download_with_fallback(
    client: &reqwest::Client,
    cdn_urls: &[Url],
    github_url: &str,
    limit: u64,
    expected_hash: &str,
    label: &str,
) -> Result<Vec<u8>, String> {
    for cdn_url in cdn_urls {
        match download_one(
            client,
            cdn_url.as_str(),
            limit,
            expected_hash,
            "CDN archive",
        )
        .await
        {
            Ok(bytes) => return Ok(bytes),
            Err(error) => {
                eprintln!("warning: CDN archive failed ({error}); trying the next source")
            }
        }
    }
    download_one(client, github_url, limit, expected_hash, label).await
}

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

    #[test]
    fn validates_and_normalizes_base_and_builds_official_paths() {
        let base = resolve_base(Some("https://assets.example.test///mirror//"))
            .unwrap()
            .unwrap();
        assert_eq!(base.as_str(), "https://assets.example.test/mirror");
        let urls = archive_urls(
            &base,
            CLI_REPOSITORY,
            "v1.2.3",
            "https://github.com/bigfish1913/pi-rust/releases/download/v1.2.3/rpi.zip",
        )
        .unwrap();
        assert_eq!(
            urls.iter().map(Url::as_str).collect::<Vec<_>>(),
            ["https://assets.example.test/mirror/rpi/releases/v1.2.3/rpi.zip"]
        );
        let scoped = resolve_base(Some("https://assets.example.test/rpi"))
            .unwrap()
            .unwrap();
        let scoped_urls = archive_urls(
            &scoped,
            CLI_REPOSITORY,
            "v1.2.3",
            "https://github.com/bigfish1913/pi-rust/releases/download/v1.2.3/rpi.zip",
        )
        .unwrap();
        assert_eq!(
            scoped_urls.iter().map(Url::as_str).collect::<Vec<_>>(),
            ["https://assets.example.test/rpi/releases/v1.2.3/rpi.zip"]
        );
    }

    #[test]
    fn project_settings_provide_the_cdn_default() {
        let project = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(project.path().join(".rpi")).unwrap();
        std::fs::write(
            project.path().join(".rpi/settings.json"),
            r#"{"cdnBaseUrl":"https://project.example.test/mirror"}"#,
        )
        .unwrap();

        let base = resolve_base_in(None, Some(project.path()))
            .unwrap()
            .unwrap();
        assert_eq!(base.as_str(), "https://project.example.test/mirror");
    }

    #[test]
    fn explicit_value_beats_project_settings() {
        let project = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(project.path().join(".rpi")).unwrap();
        std::fs::write(
            project.path().join(".rpi/settings.json"),
            r#"{"cdnBaseUrl":"https://project.example.test"}"#,
        )
        .unwrap();

        let explicit = resolve_base_in(Some("https://explicit.example.test"), Some(project.path()))
            .unwrap()
            .unwrap();
        assert_eq!(explicit.as_str(), "https://explicit.example.test/");
    }

    #[tokio::test]
    async fn invalid_cdn_archive_falls_back_to_github() {
        use crate::prebuilt_extensions::hash;
        use std::io::{Read, Write};
        let good = b"canonical archive".to_vec();
        let good_len = good.len() as u64;
        let bad = b"stale CDN archive".to_vec();
        let expected = hash(&good);
        let server_good = good.clone();
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let server = std::thread::spawn(move || {
            for body in [&bad, &server_good] {
                let (mut socket, _) = listener.accept().unwrap();
                let mut request = Vec::new();
                let mut byte = [0u8; 1];
                while !request.ends_with(b"\r\n\r\n") {
                    socket.read_exact(&mut byte).unwrap();
                    request.push(byte[0]);
                }
                write!(
                    socket,
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                )
                .unwrap();
                socket.write_all(body).unwrap();
            }
        });
        let client = reqwest::Client::builder().no_proxy().build().unwrap();
        let cdn = Url::parse(&format!("http://{address}/cdn")).unwrap();
        let github = format!("http://{address}/github");
        let result = download_with_fallback(
            &client,
            std::slice::from_ref(&cdn),
            &github,
            good_len,
            &expected,
            "archive",
        )
        .await
        .unwrap();
        assert_eq!(result, good);
        server.join().unwrap();
    }

    #[test]
    fn rejects_unsafe_bases_and_filenames_and_ignores_other_repositories() {
        for value in [
            "http://assets.example.test",
            "https://user:pass@assets.example.test",
            "https://assets.example.test/x?y=1",
            "https://assets.example.test/x%2Fy",
        ] {
            assert!(resolve_base(Some(value)).is_err(), "{value}");
        }
        let base = resolve_base(Some("https://assets.example.test"))
            .unwrap()
            .unwrap();
        assert!(archive_urls(
            &base,
            CLI_REPOSITORY,
            "v1",
            "https://github.com/a/b/releases/download/v1/a%2Fb.zip"
        )
        .is_err());
        assert!(archive_urls(
            &base,
            "https://github.com/other/repo",
            "v1",
            "https://github.com/other/repo/releases/download/v1/a.zip"
        )
        .unwrap()
        .is_empty());
    }

    #[test]
    fn tries_both_cdn_prefixes_across_a_repository_move() {
        let base = resolve_base(Some("https://assets.example.test"))
            .unwrap()
            .unwrap();
        let archive =
            "https://github.com/pi-rust/rpi-extension/releases/download/rpi-todo-v1/rpi-todo.zip";
        let current = archive_urls(&base, EXTENSION_REPOSITORY, "rpi-todo-v1", archive).unwrap();
        assert_eq!(
            current.iter().map(Url::as_str).collect::<Vec<_>>(),
            [
                "https://assets.example.test/rpi-extension/releases/rpi-todo-v1/rpi-todo.zip",
                "https://assets.example.test/rpi-package/releases/rpi-todo-v1/rpi-todo.zip",
            ]
        );
        let legacy =
            archive_urls(&base, LEGACY_EXTENSION_REPOSITORY, "rpi-todo-v1", archive).unwrap();
        assert_eq!(
            legacy.iter().map(Url::as_str).collect::<Vec<_>>(),
            [
                "https://assets.example.test/rpi-package/releases/rpi-todo-v1/rpi-todo.zip",
                "https://assets.example.test/rpi-extension/releases/rpi-todo-v1/rpi-todo.zip",
            ]
        );
        // A base already scoped to one namespace stays inside it.
        let scoped = resolve_base(Some("https://assets.example.test/rpi-package"))
            .unwrap()
            .unwrap();
        let scoped_urls =
            archive_urls(&scoped, EXTENSION_REPOSITORY, "rpi-todo-v1", archive).unwrap();
        assert_eq!(
            scoped_urls.iter().map(Url::as_str).collect::<Vec<_>>(),
            ["https://assets.example.test/rpi-package/releases/rpi-todo-v1/rpi-todo.zip"]
        );
    }
}