boatramp 0.4.24

boatramp — self-hosted, streaming-first static site publishing (server + CLI in one binary)
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
//! Shared helpers for the HTTP-client subcommands (sync, deployments, rollback).

use boatramp_core::time::now_unix;
use std::collections::BTreeMap;
use std::sync::Arc;

use boatramp_core::config::SiteConfig;
use boatramp_core::cose::{self, LocalSigner, PopClaims};
use boatramp_core::deploy::{DeploymentList, Manifest};
use boatramp_core::domain_verify::DomainVerification;
use serde::{Deserialize, Serialize};

use crate::config::ProjectConfig;

/// A failure talking to the boatramp control-plane API.
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
    /// No server URL was configured (pass `--server` or set `publish.server`).
    #[error("no server configured; pass --server or set publish.server")]
    NoServer,
    /// No site was configured (pass `--site` or set `publish.site`).
    #[error("no site configured; pass --site or set publish.site")]
    NoSite,
    /// An HTTP request to the control plane failed.
    #[error("control-plane request: {0}")]
    Http(#[from] reqwest::Error),
    /// Reading a local artifact (kernel/rootfs/blob) file failed.
    #[error(transparent)]
    Io(#[from] std::io::Error),
    /// The control plane refused the request (`409`), carrying its own explanatory
    /// message — surfaced verbatim rather than as a generic HTTP status error.
    #[error("{0}")]
    Refused(String),
}

/// `client` module result: a control-plane API call; `Err` is [`ClientError`].
type Result<T> = std::result::Result<T, ClientError>;

/// Resolve the API token from `BOATRAMP_TOKEN` or `publish.token`.
pub fn token(config: &ProjectConfig) -> Option<String> {
    std::env::var("BOATRAMP_TOKEN")
        .ok()
        .filter(|token| !token.is_empty())
        .or_else(|| config.publish.token.clone())
}

/// Build an HTTP client that sends `Authorization: Bearer <token>` when present,
/// and — when a **holder key** and canonical origin are configured — signs a fresh
/// per-request proof-of-possession (DPoP) into the `Boatramp-PoP` header.
///
/// PoP signing turns on when all of `token`, `BOATRAMP_TOKEN_HOLDER_KEY`
/// (`"<alg>:<hex>"`, the private half of the token's `cnf`), and
/// `BOATRAMP_POP_ORIGIN` (the server's canonical origin, matching its
/// `[serve] pop_origin`) are present; otherwise the client is a plain bearer client
/// (unchanged). This is a *single* seam — every request through the returned
/// [`ApiClient`] is signed, with no per-call-site change.
///
/// When `BOATRAMP_SERVER_PUBKEY` is set (the raw-public-key SPKI hex that
/// `boatramp serve --tls rpk` prints), the client **pins** the control plane to
/// that RFC 7250 identity — so the operator reaches an `--tls rpk` server over an
/// encrypted, authenticated channel with no ACME/tunnel/proxy, on day zero. A
/// malformed pin is ignored (falls back to normal WebPKI TLS) rather than
/// silently disabling verification.
pub fn http_client(token: Option<&str>) -> ApiClient {
    let holder = std::env::var("BOATRAMP_TOKEN_HOLDER_KEY")
        .ok()
        .filter(|v| !v.is_empty());
    let origin = std::env::var("BOATRAMP_POP_ORIGIN")
        .ok()
        .filter(|v| !v.is_empty());
    let server_pubkey = std::env::var("BOATRAMP_SERVER_PUBKEY")
        .ok()
        .filter(|v| !v.is_empty());
    build_client(
        token,
        holder.as_deref(),
        origin.as_deref(),
        server_pubkey.as_deref(),
    )
}

/// The explicit-parameter builder behind [`http_client`] (which reads the same
/// values from the environment). PoP signing is enabled only when `token`,
/// `holder_key`, and `origin` are all `Some` (and the holder key parses).
pub fn build_client(
    token: Option<&str>,
    holder_key: Option<&str>,
    origin: Option<&str>,
    server_pubkey: Option<&str>,
) -> ApiClient {
    let mut builder = reqwest::Client::builder();
    if let Some(token) = token {
        if let Ok(value) = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}")) {
            let mut headers = reqwest::header::HeaderMap::new();
            headers.insert(reqwest::header::AUTHORIZATION, value);
            builder = builder.default_headers(headers);
        }
    }
    if let Some(hex) = server_pubkey {
        // The pinned rustls config's type is only inferred (never named), so the
        // CLI needs no direct `rustls` dep — `use_preconfigured_tls` takes `Any`.
        // The single logical control-plane peer is id `0`.
        if let Ok(spki) = boatramp_rpktls::parse_public_key(hex.trim()) {
            let trust = boatramp_rpktls::TrustSet::from_map(std::collections::BTreeMap::from([(
                0u64, spki,
            )]));
            if let Ok(config) = boatramp_rpktls::client_config_server_auth(trust, 0) {
                builder = builder.use_preconfigured_tls(config);
            }
        }
    }
    let inner = builder.build().unwrap_or_default();
    // Enable PoP signing only with a token + a parseable holder key + an origin.
    let pop = match (token, holder_key, origin) {
        (Some(token), Some(holder), Some(origin)) => LocalSigner::from_private_hex(holder.trim())
            .ok()
            .map(|holder| {
                Arc::new(PopSigner {
                    holder,
                    token: token.to_string(),
                    origin: origin.to_string(),
                })
            }),
        _ => None,
    };
    ApiClient { inner, pop }
}

/// A control-plane HTTP client that transparently attaches a per-request
/// proof-of-possession when a holder key is configured (see [`http_client`]). It
/// mirrors the slice of `reqwest`'s builder surface the CLI uses (`get`/`post`/
/// `put`/`delete` → `json`/`query`/`body`/`send`); `send()` returns a plain
/// [`reqwest::Response`], so response handling and error types are unchanged.
#[derive(Clone)]
pub struct ApiClient {
    inner: reqwest::Client,
    pop: Option<Arc<PopSigner>>,
}

impl ApiClient {
    /// Start a request with the given method + URL.
    fn request<U: reqwest::IntoUrl>(&self, method: reqwest::Method, url: U) -> ApiRequestBuilder {
        ApiRequestBuilder {
            inner: self.inner.request(method, url),
            client: self.inner.clone(),
            pop: self.pop.clone(),
        }
    }

    /// A `GET` request builder.
    pub fn get<U: reqwest::IntoUrl>(&self, url: U) -> ApiRequestBuilder {
        self.request(reqwest::Method::GET, url)
    }
    /// A `POST` request builder.
    pub fn post<U: reqwest::IntoUrl>(&self, url: U) -> ApiRequestBuilder {
        self.request(reqwest::Method::POST, url)
    }
    /// A `PUT` request builder.
    pub fn put<U: reqwest::IntoUrl>(&self, url: U) -> ApiRequestBuilder {
        self.request(reqwest::Method::PUT, url)
    }
    /// A `DELETE` request builder.
    pub fn delete<U: reqwest::IntoUrl>(&self, url: U) -> ApiRequestBuilder {
        self.request(reqwest::Method::DELETE, url)
    }
}

/// A request builder wrapping [`reqwest::RequestBuilder`], signing a PoP proof at
/// [`send`](Self::send) time when the [`ApiClient`] carries a holder key.
pub struct ApiRequestBuilder {
    inner: reqwest::RequestBuilder,
    client: reqwest::Client,
    pop: Option<Arc<PopSigner>>,
}

impl ApiRequestBuilder {
    /// Set a JSON body (mirrors [`reqwest::RequestBuilder::json`]).
    pub fn json<T: Serialize + ?Sized>(mut self, json: &T) -> Self {
        self.inner = self.inner.json(json);
        self
    }
    /// Set a raw body (mirrors [`reqwest::RequestBuilder::body`]).
    pub fn body<T: Into<reqwest::Body>>(mut self, body: T) -> Self {
        self.inner = self.inner.body(body);
        self
    }
    /// Append URL query parameters (mirrors [`reqwest::RequestBuilder::query`]).
    pub fn query<T: Serialize + ?Sized>(mut self, query: &T) -> Self {
        self.inner = self.inner.query(query);
        self
    }
    /// Set a request header (a malformed name/value is dropped by `reqwest`).
    pub fn header(mut self, key: &str, value: &str) -> Self {
        self.inner = self.inner.header(key, value);
        self
    }
    /// Build, (optionally) PoP-sign, and send the request. Returns the same
    /// [`reqwest::Response`]/[`reqwest::Error`] as a plain `reqwest` send.
    pub async fn send(self) -> reqwest::Result<reqwest::Response> {
        let mut request = self.inner.build()?;
        if let Some(pop) = &self.pop {
            pop.sign(&mut request).await;
        }
        self.client.execute(request).await
    }
}

/// Holds the token's holder (`cnf`) private key + the bound origin, and signs a
/// fresh [`PopClaims`] proof per request into the `Boatramp-PoP` header.
struct PopSigner {
    holder: LocalSigner,
    token: String,
    origin: String,
}

impl PopSigner {
    /// Attach a per-request PoP proof to `request` (best-effort: on any signing
    /// failure the request is sent unsigned, and the server rejects it — never a
    /// silent bypass, since the proof is *required* server-side for a `cnf` token).
    async fn sign(&self, request: &mut reqwest::Request) {
        // Bind the body hash only for a buffered body within the shared bound —
        // identical to the server's rule, so both agree on present-or-absent.
        let bh = request
            .body()
            .and_then(reqwest::Body::as_bytes)
            .filter(|b| !b.is_empty() && b.len() <= cose::POP_MAX_BODY_HASH_BYTES)
            .map(cose::pop_sha256_hex);
        let claims = PopClaims {
            htm: request.method().as_str().to_string(),
            htp: cose::canon_pop_path(request.url().path()),
            aud: self.origin.clone(),
            ath: cose::pop_sha256_hex(self.token.as_bytes()),
            bh,
        };
        let Ok(proof) = cose::mint_pop(&claims, &self.holder, now_unix()).await else {
            return;
        };
        if let Ok(value) = reqwest::header::HeaderValue::from_str(&proof) {
            request.headers_mut().insert(
                reqwest::header::HeaderName::from_static("boatramp-pop"),
                value,
            );
        }
    }
}

/// Resolve the target project: `[publish].project` in config (which `main` has already
/// overlaid with `--project` / `BOATRAMP_PROJECT`), else the `default` project.
pub fn resolve_project(config: &ProjectConfig) -> String {
    config
        .publish
        .project
        .clone()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| boatramp_core::project::DEFAULT_PROJECT.to_string())
}

/// The URL path segment for a resource collection under a project: the bare
/// `collection` for the reserved `default` project (byte-identical legacy
/// `/api/<collection>/…`), else `projects/<proj>/<collection>`. The single source of
/// the project-scoping rule, shared by [`ControlPlane`] and the imperative commands
/// (`sync` / `compute` / `function`) so `--project` routes the same everywhere.
pub fn project_seg(project: &str, collection: &str) -> String {
    if project == boatramp_core::project::DEFAULT_PROJECT {
        collection.to_string()
    } else {
        format!("projects/{project}/{collection}")
    }
}

/// Resolve the server base URL from a flag, falling back to config.
pub fn resolve_server(server: Option<String>, config: &ProjectConfig) -> Result<String> {
    let server = server
        .or_else(|| config.publish.server.clone())
        .ok_or(ClientError::NoServer)?;
    Ok(server.trim_end_matches('/').to_string())
}

/// Resolve the target server and build an authenticated client — the shared
/// preamble of every mutating subcommand. (Was reinvented verbatim as a private
/// `conn` in both `function` and `workflow`; it lives here so there is one.)
pub fn connect(server: Option<String>, config: &ProjectConfig) -> Result<(String, ApiClient)> {
    let server = resolve_server(server, config)?;
    let http = http_client(token(config).as_deref());
    Ok((server, http))
}

/// Resolve the (server base URL, site) target from flags, falling back to config.
pub fn resolve_target(
    server: Option<String>,
    site: Option<String>,
    config: &ProjectConfig,
) -> Result<(String, String)> {
    let server = resolve_server(server, config)?;
    let site = site
        .or_else(|| config.publish.site.clone())
        .ok_or(ClientError::NoSite)?;
    Ok((server, site))
}

// ---- control-plane requests -------------------------------------------------

/// Percent-encode a host for use as a URL path segment. Hostnames are
/// `[a-z0-9.-]` plus a leading `*.` for wildcards; only `*` needs escaping.
fn host_segment(host: &str) -> String {
    host.replace('*', "%2A")
}

/// The result of a `domain verify` check, shared with the server and console.
pub use boatramp_core::domain_verify::CheckResult;

/// The captured guest log line and logs endpoint response, shared with the
/// server and console.
pub use boatramp_core::logs::{LogEntry, LogsResponse};

/// Whether `s` is a bare content-address: a 64-char lowercase hex SHA-256, as
/// printed by [`hash_file`] / `blob put`. Distinguishes an existing blob hash
/// from a file path or URL in an artifact reference.
pub fn is_blob_hash(s: &str) -> bool {
    s.len() == 64
        && s.bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// Stream-hash a file to its `sha256` hex (the blob's content-address).
pub async fn hash_file(path: &std::path::Path) -> Result<String> {
    use sha2::{Digest, Sha256};
    use tokio::io::AsyncReadExt;
    let mut file = tokio::fs::File::open(path).await?;
    let mut hasher = Sha256::new();
    let mut buf = vec![0u8; 64 * 1024];
    loop {
        let n = file.read(&mut buf).await?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hex::encode(hasher.finalize()))
}

/// A filesystem-safe temp-name fragment derived from a URL (last path segment).
fn sanitize(url: &str) -> String {
    url.rsplit('/')
        .find(|s| !s.is_empty())
        .unwrap_or("download")
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '.' || c == '-' {
                c
            } else {
                '_'
            }
        })
        .take(64)
        .collect()
}

/// The control plane's reply to a deployment negotiation (`POST …/deployments`):
/// the new deployment id and the blob hashes it is still missing (the ones the
/// client must upload). Shared by `sync` and `apply`.
#[derive(Debug, Deserialize)]
pub struct CreateDeploymentResponse {
    /// The created deployment's id.
    pub id: String,
    /// Blob hashes the server does not yet have and needs uploaded.
    pub missing: Vec<String>,
}

/// An AND-composed dead-letter filter for the `dlq` commands (mirrors the server's wire filter).
/// Serializes `match_last_error` as `match`. All-`None` = the whole DLQ.
#[derive(Debug, Default, Serialize)]
pub struct DlqFilter {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub older_than_ms: Option<u64>,
    #[serde(rename = "match", skip_serializing_if = "Option::is_none")]
    pub match_last_error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

/// One consumer group returned by `queue groups`.
#[derive(Debug, Deserialize)]
pub struct GroupEntry {
    pub group: String,
    #[serde(default)]
    pub hwm: String,
    pub in_flight: usize,
    pub lag: usize,
}

/// One live message returned by `queue peek` (payload base64).
#[derive(Debug, Deserialize)]
pub struct QueuePeekEntry {
    pub id: String,
    pub attempts: u32,
    #[serde(default)]
    pub leased: bool,
    #[serde(default)]
    pub signed_context_present: bool,
    pub payload_b64: String,
}

/// One dead-letter as returned by the `dlq` list/show/dry-run views.
#[derive(Debug, Deserialize)]
pub struct DlqEntry {
    pub id: String,
    pub group: String,
    pub attempts: u32,
    pub last_error: Option<String>,
    #[serde(default)]
    pub signed_context_present: bool,
    /// Present only from a `show` (base64 payload).
    #[serde(default)]
    pub payload_b64: Option<String>,
}

/// An authenticated control-plane connection: an [`ApiClient`] bound to a
/// resolved server base URL. The request methods key off it, so the client and
/// server base are threaded once (at construction) instead of by hand at every
/// call site.
pub struct ControlPlane {
    http: ApiClient,
    base: String,
    project: String,
}

/// Which operator queue/DLQ surface a `queue`/`dlq` op targets: a single **site's** own
/// queues (with an optional background-`alias` scope), or the **shared project bus**
/// (`{project}/bus/{topic}`, common to every site in the project). The two differ only in
/// the endpoint path (site: `/api/<sites-seg>/<site>/_boatramp/…`; bus:
/// `/api/projects/<proj>/_boatramp/bus/…`) and that the bus has no `alias` axis — the
/// request/response shapes are identical, so every client method takes an `OpScope` and
/// the CLI picks one from a `--bus` flag.
#[derive(Debug, Clone, Copy)]
pub enum OpScope<'a> {
    /// A single site's queues, optionally under a background-alias (`{site}/{alias}`) scope.
    Site {
        /// The site name.
        site: &'a str,
        /// The background-alias scope, if any.
        alias: Option<&'a str>,
    },
    /// The shared, project-scoped bus (authorized at `Project·Read`/`Project·Admin`).
    Bus,
}

impl<'a> OpScope<'a> {
    /// The site surface under an optional background-alias scope.
    pub fn site_alias(site: &'a str, alias: Option<&'a str>) -> Self {
        Self::Site { site, alias }
    }

    /// The background-alias scope carried in a POST body / GET query. Always `None` for
    /// the project bus (it is not per-deployment).
    fn alias(&self) -> Option<&'a str> {
        match self {
            Self::Site { alias, .. } => *alias,
            Self::Bus => None,
        }
    }
}

impl ControlPlane {
    /// Wrap an already-built client and resolved server base.
    pub fn new(base: String, http: ApiClient, project: String) -> Self {
        Self {
            http,
            base,
            project,
        }
    }

    /// The site-collection URL segment: `sites` for the default project (byte-identical
    /// legacy `/api/sites/...`), else `projects/<proj>/sites` for a named project.
    fn sites_seg(&self) -> String {
        project_seg(&self.project, "sites")
    }

    /// The function-collection URL segment: `functions` for the default project
    /// (byte-identical legacy `/api/functions/...`), else `projects/<proj>/functions`.
    fn functions_seg(&self) -> String {
        project_seg(&self.project, "functions")
    }

    /// The compute-collection URL segment: `compute` for the default project
    /// (byte-identical legacy `/api/compute/...`), else `projects/<proj>/compute`.
    fn compute_seg(&self) -> String {
        project_seg(&self.project, "compute")
    }

    /// The project-BUS operator path prefix: always the project-scoped
    /// `projects/<proj>/_boatramp/bus` form (there is no legacy/unscoped bus route —
    /// even the `default` project's shared bus is addressed project-scoped), so a
    /// `boatramp queue|dlq --bus` targets the right project's shared bus. The server
    /// authorizes this path at `Project·Read` (GET) / `Project·Admin` (destructive POST).
    fn bus_prefix(&self) -> String {
        format!("projects/{}/_boatramp/bus", self.project)
    }

    /// The full operator-endpoint URL for a given [`OpScope`] and operation suffix
    /// (`"dlq"`, `"queue/peek"`, …): the per-site `…/<sites-seg>/<site>/_boatramp/<op>` for
    /// [`OpScope::Site`], or the shared `…/projects/<proj>/_boatramp/bus/<op>` for
    /// [`OpScope::Bus`]. The single place the site-vs-bus path split lives.
    fn op_url(&self, scope: OpScope<'_>, op: &str) -> String {
        match scope {
            OpScope::Site { site, .. } => {
                let seg = self.sites_seg();
                format!("{}/api/{seg}/{site}/_boatramp/{op}", self.base)
            }
            OpScope::Bus => format!("{}/api/{}/{op}", self.base, self.bus_prefix()),
        }
    }

    /// Fetch the manifest for a specific deployment id.
    pub async fn fetch_manifest(&self, site: &str, id: &str) -> Result<Manifest> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/{seg}/{site}/deployments/{id}"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Fetch a site's deployment list (current + history).
    pub async fn fetch_deployments(&self, site: &str) -> Result<DeploymentList> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/{seg}/{site}/deployments"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Fetch a site's config (server returns defaults if unset).
    pub async fn fetch_site_config(&self, site: &str) -> Result<SiteConfig> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/{seg}/{site}/config"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Replace a site's config.
    pub async fn put_site_config(&self, site: &str, config: &SiteConfig) -> Result<()> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        client
            .put(format!("{server}/api/{seg}/{site}/config"))
            .json(config)
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Fetch the project's tenancy schema (the per-table tenant-key map). A project
    /// that declared none returns the default schema (`tenant_id`, no tables).
    pub async fn get_project_tenancy(&self) -> Result<boatramp_core::tenancy::TenancySchema> {
        let seg = project_seg(&self.project, "tenancy");
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/{seg}"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Replace the project's tenancy schema (`Project·Admin`).
    pub async fn put_project_tenancy(
        &self,
        schema: &boatramp_core::tenancy::TenancySchema,
    ) -> Result<()> {
        let seg = project_seg(&self.project, "tenancy");
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        client
            .put(format!("{server}/api/{seg}"))
            .json(schema)
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Clear the project's tenancy schema (revert to legacy `Uniform` scoping).
    pub async fn clear_project_tenancy(&self) -> Result<()> {
        let seg = project_seg(&self.project, "tenancy");
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        client
            .delete(format!("{server}/api/{seg}"))
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Start (or fetch the existing) ownership challenge for a host.
    pub async fn start_domain_verification(
        &self,
        site: &str,
        host: &str,
        method: Option<&str>,
    ) -> Result<DomainVerification> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        let mut url = format!(
            "{server}/api/{seg}/{site}/domains/{}/verification",
            host_segment(host)
        );
        if let Some(method) = method {
            url.push_str(&format!("?method={method}"));
        }
        Ok(client
            .post(url)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Run the ownership check for a host; on success the server attaches it.
    pub async fn check_domain_verification(&self, site: &str, host: &str) -> Result<CheckResult> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .post(format!(
                "{server}/api/{seg}/{site}/domains/{}/verification/check",
                host_segment(host)
            ))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Admin-only: attach a host to the site **without** an ownership proof
    /// (`domain add --unverified`). Returns the server's confirmation text. The
    /// server gates this route at `system·admin`, so a site-scoped token gets a 403.
    pub async fn attach_domain_unverified(&self, site: &str, host: &str) -> Result<String> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .post(format!(
                "{server}/api/{seg}/{site}/domains/{}/attach-unverified",
                host_segment(host)
            ))
            .send()
            .await?
            .error_for_status()?
            .text()
            .await?)
    }

    /// Drop a host's ownership challenge (when detaching the host).
    pub async fn remove_domain_verification(&self, site: &str, host: &str) -> Result<()> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        client
            .delete(format!(
                "{server}/api/{seg}/{site}/domains/{}/verification",
                host_segment(host)
            ))
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// List all ownership challenges for a site (pending and verified).
    pub async fn list_domain_verifications(&self, site: &str) -> Result<Vec<DomainVerification>> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/{seg}/{site}/domain-verifications"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Activate a deployment id for a site (the atomic switch / rollback).
    pub async fn activate(&self, site: &str, id: &str) -> Result<()> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        client
            .post(format!(
                "{server}/api/{seg}/{site}/deployments/{id}/activate"
            ))
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Negotiate a new deployment for a site (project-scoped): POST the manifest;
    /// the server stores it and replies with the blob hashes it is still missing.
    /// `query` carries deploy provenance (source/branch/author/message/tags).
    pub async fn create_deployment(
        &self,
        site: &str,
        manifest: &Manifest,
        query: &[(&str, String)],
    ) -> Result<CreateDeploymentResponse> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .post(format!("{server}/api/{seg}/{site}/deployments"))
            .query(query)
            .json(manifest)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Upload one missing blob by its content-address (streams a `File`, sends a
    /// `Memory` variant's bytes). Idempotent server-side. Mirrors the two-arm body
    /// of [`crate::sync::upload_blob`] but returns [`ClientError`] (its `File`/
    /// `Memory` open-and-send maps cleanly onto our `Io`/`Http` variants).
    pub async fn upload_blob_source(
        &self,
        hash: &str,
        source: &crate::sync::BlobSource,
    ) -> Result<()> {
        use crate::sync::BlobSource;
        let Self {
            http, base: server, ..
        } = self;
        let body = match source {
            BlobSource::File(path) => {
                let file = tokio::fs::File::open(path).await?;
                reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::new(file))
            }
            BlobSource::Memory(bytes) => reqwest::Body::from(bytes.clone()),
        };
        http.put(format!("{server}/api/blobs/{hash}"))
            .body(body)
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Deploy (create/replace) a top-level function (project-scoped): PUT the
    /// function record body (`{ component, config, lifecycle }`). Returns the
    /// server's stored record verbatim.
    pub async fn deploy_function(
        &self,
        name: &str,
        body: &serde_json::Value,
    ) -> Result<serde_json::Value> {
        let seg = self.functions_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .put(format!("{server}/api/{seg}/{name}"))
            .json(body)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Create/replace a compute workload (project-scoped): PUT the
    /// `PutComputeRequest`-shaped `body` straight to the server (it validates).
    /// Returns the server's stored record verbatim.
    pub async fn put_compute(
        &self,
        name: &str,
        body: &serde_json::Value,
    ) -> Result<serde_json::Value> {
        let seg = self.compute_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .put(format!("{server}/api/{seg}/{name}"))
            .json(body)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Point a named alias at a deployment id.
    pub async fn set_alias(&self, site: &str, name: &str, id: &str) -> Result<()> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        #[derive(Serialize)]
        struct SetAlias<'a> {
            id: &'a str,
        }
        client
            .put(format!("{server}/api/{seg}/{site}/aliases/{name}"))
            .json(&SetAlias { id })
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// List a site's named aliases (`name → deployment id`).
    pub async fn list_aliases(&self, site: &str) -> Result<BTreeMap<String, String>> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/{seg}/{site}/aliases"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Remove a named alias.
    pub async fn remove_alias(&self, site: &str, name: &str) -> Result<()> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        client
            .delete(format!("{server}/api/{seg}/{site}/aliases/{name}"))
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Fetch captured guest logs for a site: the most recent `limit` lines with
    /// `seq > after`, optionally filtered to one `stream` (`stdout`/`stderr`).
    pub async fn fetch_logs(
        &self,
        site: &str,
        limit: usize,
        after: u64,
        stream: Option<&str>,
    ) -> Result<LogsResponse> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        let mut url =
            format!("{server}/api/{seg}/{site}/_boatramp/logs?limit={limit}&after={after}");
        if let Some(stream) = stream {
            url.push_str("&stream=");
            url.push_str(stream);
        }
        Ok(client
            .get(url)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Fetch captured guest logs for a **function** (symmetric to [`fetch_logs`]): the
    /// most recent `limit` lines with `seq > after`, optionally filtered to one `stream`.
    /// Honors `--project` via `functions_seg` (`functions` for the default project, else
    /// `projects/<proj>/functions`), so a per-tenant function's logs are reachable.
    ///
    /// [`fetch_logs`]: Self::fetch_logs
    pub async fn fetch_function_logs(
        &self,
        function: &str,
        limit: usize,
        after: u64,
        stream: Option<&str>,
    ) -> Result<LogsResponse> {
        let seg = self.functions_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        let mut url =
            format!("{server}/api/{seg}/{function}/_boatramp/logs?limit={limit}&after={after}");
        if let Some(stream) = stream {
            url.push_str("&stream=");
            url.push_str(stream);
        }
        Ok(client
            .get(url)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Fetch a site's operator handler stats (raw JSON: handler invocation counters,
    /// consumer backlog/dead-letters, live stream connections).
    pub async fn fetch_handler_stats(&self, site: &str) -> Result<serde_json::Value> {
        let seg = self.sites_seg();
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/{seg}/{site}/_boatramp/handlers"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Run a dead-letter mutation (`purge` / `redrive` / `discard`) on a consumer `topic`
    /// (scope-relative; `alias` for a background-alias consumer), optionally filter-selective and/or
    /// `dry_run`. Returns the number affected plus (for a dry-run) the matching preview
    /// (`POST …/_boatramp/dlq`).
    pub async fn operate_dlq(
        &self,
        scope: OpScope<'_>,
        topic: &str,
        action: &str,
        filter: &DlqFilter,
        dry_run: bool,
    ) -> Result<(usize, Vec<DlqEntry>)> {
        let url = self.op_url(scope, "dlq");
        let client = &self.http;
        #[derive(Serialize)]
        struct Request<'a> {
            topic: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            alias: Option<&'a str>,
            action: &'a str,
            filter: &'a DlqFilter,
            dry_run: bool,
        }
        #[derive(Deserialize)]
        struct DlqResponse {
            affected: usize,
            #[serde(default)]
            matched: Vec<DlqEntry>,
        }
        let resp: DlqResponse = client
            .post(url)
            .json(&Request {
                topic,
                alias: scope.alias(),
                action,
                filter,
                dry_run,
            })
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?;
        Ok((resp.affected, resp.matched))
    }

    /// Pause or resume a topic (`POST …/_boatramp/queue/pause`, P2 flow control).
    pub async fn pause_queue(&self, scope: OpScope<'_>, topic: &str, paused: bool) -> Result<()> {
        let url = self.op_url(scope, "queue/pause");
        let client = &self.http;
        #[derive(Serialize)]
        struct Request<'a> {
            topic: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            alias: Option<&'a str>,
            paused: bool,
        }
        client
            .post(url)
            .json(&Request {
                topic,
                alias: scope.alias(),
                paused,
            })
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Set a topic's per-topic operator flow-control policy (`POST …/_boatramp/queue/policy`,
    /// v0.4.24). Each cap is optional (`None` = uncapped on that axis).
    pub async fn set_topic_policy(
        &self,
        scope: OpScope<'_>,
        topic: &str,
        max_depth: Option<usize>,
        max_rate_per_sec: Option<u32>,
        max_unflushed: Option<usize>,
    ) -> Result<()> {
        let url = self.op_url(scope, "queue/policy");
        let client = &self.http;
        #[derive(Serialize)]
        struct Request<'a> {
            topic: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            alias: Option<&'a str>,
            #[serde(skip_serializing_if = "Option::is_none")]
            max_depth: Option<usize>,
            #[serde(skip_serializing_if = "Option::is_none")]
            max_rate_per_sec: Option<u32>,
            #[serde(skip_serializing_if = "Option::is_none")]
            max_unflushed: Option<usize>,
        }
        client
            .post(url)
            .json(&Request {
                topic,
                alias: scope.alias(),
                max_depth,
                max_rate_per_sec,
                max_unflushed,
            })
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// List a topic's consumer groups (`GET …/_boatramp/queue/groups`).
    pub async fn list_groups(&self, scope: OpScope<'_>, topic: &str) -> Result<Vec<GroupEntry>> {
        let url = self.op_url(scope, "queue/groups");
        let client = &self.http;
        #[derive(Deserialize)]
        struct GroupsResponse {
            #[allow(dead_code)]
            version: u32,
            groups: Vec<GroupEntry>,
        }
        let mut req = client.get(url).query(&[("topic", topic)]);
        if let Some(alias) = scope.alias() {
            req = req.query(&[("alias", alias)]);
        }
        let resp: GroupsResponse = req.send().await?.error_for_status()?.json().await?;
        Ok(resp.groups)
    }

    /// Reset or delete a consumer group (`POST …/_boatramp/queue/group`). For `reset`, `start` is
    /// `"earliest"` or `"latest"`.
    pub async fn group_op(
        &self,
        scope: OpScope<'_>,
        topic: &str,
        group: &str,
        action: &str,
        start: Option<&str>,
    ) -> Result<()> {
        let url = self.op_url(scope, "queue/group");
        let client = &self.http;
        #[derive(Serialize)]
        struct Request<'a> {
            topic: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            alias: Option<&'a str>,
            group: &'a str,
            action: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            start: Option<&'a str>,
        }
        client
            .post(url)
            .json(&Request {
                topic,
                alias: scope.alias(),
                group,
                action,
                start,
            })
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Peek the head of a topic's LIVE work-queue without consuming (`GET …/_boatramp/queue/peek`).
    pub async fn peek_queue(
        &self,
        scope: OpScope<'_>,
        topic: &str,
        limit: Option<usize>,
    ) -> Result<Vec<QueuePeekEntry>> {
        let url = self.op_url(scope, "queue/peek");
        let client = &self.http;
        #[derive(Deserialize)]
        struct QueuePeekResponse {
            #[allow(dead_code)]
            version: u32,
            messages: Vec<QueuePeekEntry>,
        }
        let mut req = client.get(url).query(&[("topic", topic)]);
        if let Some(alias) = scope.alias() {
            req = req.query(&[("alias", alias)]);
        }
        if let Some(limit) = limit {
            req = req.query(&[("limit", limit.to_string())]);
        }
        let resp: QueuePeekResponse = req.send().await?.error_for_status()?.json().await?;
        Ok(resp.messages)
    }

    /// Replay a GROUPED topic's retained history from an offset without consuming
    /// (`GET …/_boatramp/queue/replay`, P2). Returns the messages plus the `next_after` cursor to
    /// page forward (`None` when the history is exhausted).
    pub async fn replay_queue(
        &self,
        scope: OpScope<'_>,
        topic: &str,
        after: Option<&str>,
        limit: Option<usize>,
    ) -> Result<(Vec<QueuePeekEntry>, Option<String>)> {
        let url = self.op_url(scope, "queue/replay");
        let client = &self.http;
        #[derive(Deserialize)]
        struct QueueReplayResponse {
            #[allow(dead_code)]
            version: u32,
            messages: Vec<QueuePeekEntry>,
            #[serde(default)]
            next_after: Option<String>,
        }
        let mut req = client.get(url).query(&[("topic", topic)]);
        if let Some(alias) = scope.alias() {
            req = req.query(&[("alias", alias)]);
        }
        if let Some(after) = after {
            req = req.query(&[("after", after)]);
        }
        if let Some(limit) = limit {
            req = req.query(&[("limit", limit.to_string())]);
        }
        let resp: QueueReplayResponse = req.send().await?.error_for_status()?.json().await?;
        Ok((resp.messages, resp.next_after))
    }

    /// List (or `show`) a topic's dead-letters (`GET …/_boatramp/dlq`), filter-matching. `show` with
    /// `filter.id` set returns the single dead-letter in full (with `payload_b64`); otherwise a
    /// metadata listing.
    pub async fn list_dlq(
        &self,
        scope: OpScope<'_>,
        topic: &str,
        show: bool,
        filter: &DlqFilter,
    ) -> Result<Vec<DlqEntry>> {
        let url = self.op_url(scope, "dlq");
        let client = &self.http;
        #[derive(Deserialize)]
        struct DlqListResponse {
            #[allow(dead_code)]
            version: u32,
            dead_letters: Vec<DlqEntry>,
        }
        let mut req = client.get(url).query(&[("topic", topic)]);
        if let Some(alias) = scope.alias() {
            req = req.query(&[("alias", alias)]);
        }
        if show {
            req = req.query(&[("show", "true")]);
        }
        if let Some(id) = &filter.id {
            req = req.query(&[("id", id)]);
        }
        if let Some(group) = &filter.group {
            req = req.query(&[("group", group)]);
        }
        if let Some(older) = filter.older_than_ms {
            req = req.query(&[("older_than_ms", older.to_string())]);
        }
        if let Some(m) = &filter.match_last_error {
            req = req.query(&[("match", m)]);
        }
        if let Some(limit) = filter.limit {
            req = req.query(&[("limit", limit.to_string())]);
        }
        let resp: DlqListResponse = req.send().await?.error_for_status()?.json().await?;
        Ok(resp.dead_letters)
    }

    /// Upload a file as a content-addressed blob (`PUT /api/blobs/<hash>`, streamed).
    /// Idempotent: re-uploading an existing blob is a no-op server-side.
    pub async fn upload_blob(&self, hash: &str, path: &std::path::Path) -> Result<()> {
        let Self {
            http, base: server, ..
        } = self;
        let file = tokio::fs::File::open(path).await?;
        let body = reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::new(file));
        http.put(format!("{server}/api/blobs/{hash}"))
            .body(body)
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Hash a local file and upload it as a blob; returns its content-address.
    pub async fn put_file_blob(&self, path: &std::path::Path) -> Result<String> {
        let hash = hash_file(path).await?;
        self.upload_blob(&hash, path).await?;
        Ok(hash)
    }

    /// Resolve an **artifact reference** — a `--kernel` / `--rootfs` value — to a blob
    /// hash the server can stage. Accepts three forms:
    /// - a 64-hex content-address ⇒ used as-is (assumed already uploaded);
    /// - an `http(s)://` URL ⇒ downloaded to a temp file, then hashed + uploaded;
    /// - anything else ⇒ a local file path, hashed + uploaded.
    pub async fn resolve_artifact(&self, value: &str) -> Result<String> {
        if is_blob_hash(value) {
            return Ok(value.to_string());
        }
        if value.starts_with("http://") || value.starts_with("https://") {
            use tokio::io::AsyncWriteExt;
            // Stream the URL to a temp file, then hash + upload it like a local file.
            let mut resp = self.http.get(value).send().await?.error_for_status()?;
            let tmp = std::env::temp_dir().join(format!("boatramp-artifact-{}", sanitize(value)));
            let mut out = tokio::fs::File::create(&tmp).await?;
            while let Some(chunk) = resp.chunk().await? {
                out.write_all(&chunk).await?;
            }
            out.flush().await?;
            drop(out);
            let hash = self.put_file_blob(&tmp).await?;
            let _ = tokio::fs::remove_file(&tmp).await;
            return Ok(hash);
        }
        self.put_file_blob(std::path::Path::new(value)).await
    }

    // ---- projects (0.2.0) ---------------------------------------------------

    /// List every project (`GET /api/projects`).
    pub async fn list_projects(&self) -> Result<Vec<serde_json::Value>> {
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/projects"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Create a project (`POST /api/projects`); returns the created project.
    pub async fn create_project(&self, body: &serde_json::Value) -> Result<serde_json::Value> {
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .post(format!("{server}/api/projects"))
            .json(body)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Read a project (`GET /api/projects/<name>`).
    pub async fn get_project(&self, name: &str) -> Result<serde_json::Value> {
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .get(format!("{server}/api/projects/{name}"))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Delete a project (`DELETE /api/projects/<name>`). The server refuses a
    /// non-empty project or the reserved `default`. On a `409` refusal, the server's
    /// enumerated body is returned as [`ClientError::Refused`] so the CLI can print it
    /// verbatim (with a `--force` hint) rather than the opaque generic HTTP error.
    pub async fn delete_project(&self, name: &str) -> Result<()> {
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        let resp = client
            .delete(format!("{server}/api/projects/{name}"))
            .send()
            .await?;
        if resp.status() == reqwest::StatusCode::CONFLICT {
            let body = resp.text().await.unwrap_or_default();
            return Err(ClientError::Refused(body.trim_end().to_string()));
        }
        resp.error_for_status()?;
        Ok(())
    }

    /// Fetch the **teardown plan** for a project (`DELETE /api/projects/<name>?dry_run=true`)
    /// — a preview of everything a force-delete would remove. Mutates nothing.
    pub async fn project_teardown_plan(&self, name: &str) -> Result<serde_json::Value> {
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .delete(format!("{server}/api/projects/{name}"))
            .query(&[("dry_run", "true")])
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    /// Force-delete a project (`DELETE /api/projects/<name>?force=true`): cascade the
    /// teardown of everything it owns and remove the project. Returns the executed
    /// teardown report.
    pub async fn force_delete_project(&self, name: &str) -> Result<serde_json::Value> {
        let Self {
            http: client,
            base: server,
            ..
        } = self;
        Ok(client
            .delete(format!("{server}/api/projects/{name}"))
            .query(&[("force", "true")])
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }
}

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

    #[test]
    fn blob_hash_detection_is_exact() {
        let hash = "a".repeat(64);
        assert!(is_blob_hash(&hash), "64 lowercase hex is a blob hash");
        assert!(is_blob_hash(
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        ));
        // Not hashes: wrong length, uppercase, path, URL, non-hex.
        assert!(!is_blob_hash(&"a".repeat(63)));
        assert!(!is_blob_hash(&"a".repeat(65)));
        assert!(
            !is_blob_hash(&"A".repeat(64)),
            "uppercase is treated as a path, not a hash"
        );
        assert!(!is_blob_hash("./vmlinux"));
        assert!(!is_blob_hash("https://example.com/vmlinux"));
        assert!(!is_blob_hash(&"g".repeat(64)), "g is not a hex digit");
    }

    #[test]
    fn sites_seg_is_legacy_for_default_project() {
        let cp = |project: &str| {
            ControlPlane::new(
                "https://cp.example".into(),
                build_client(None, None, None, None),
                project.into(),
            )
        };
        // Default project keeps the byte-identical legacy `sites` segment.
        assert_eq!(
            cp(boatramp_core::project::DEFAULT_PROJECT).sites_seg(),
            "sites"
        );
        // A named project scopes under `projects/<name>/sites`.
        assert_eq!(cp("acme").sites_seg(), "projects/acme/sites");
    }

    #[test]
    fn resolve_project_falls_back_to_default() {
        use crate::config::ProjectConfig;
        // No `[publish].project` → the `default` project.
        let mut config = ProjectConfig::default();
        assert_eq!(
            resolve_project(&config),
            boatramp_core::project::DEFAULT_PROJECT
        );
        // An empty string is treated as unset (still `default`).
        config.publish.project = Some(String::new());
        assert_eq!(
            resolve_project(&config),
            boatramp_core::project::DEFAULT_PROJECT
        );
        // A named project wins.
        config.publish.project = Some("acme".into());
        assert_eq!(resolve_project(&config), "acme");
    }

    #[test]
    fn sanitize_url_to_temp_fragment() {
        assert_eq!(
            sanitize("https://example.com/path/vmlinux-6.1.bin"),
            "vmlinux-6.1.bin"
        );
        assert_eq!(sanitize("https://example.com/a b?c=d"), "a_b_c_d");
        assert_eq!(sanitize("https://example.com/"), "example.com");
    }

    // ---- DPoP round-trip: the PoP-signing client vs the real `require_auth` ----

    use boatramp_core::authz::GrantedRole;
    use boatramp_core::cose::{Claims, Signer, TokenAlg};
    use boatramp_core::kv::{KvStore, MemoryKv};
    use boatramp_server::{require_auth, Auth};

    /// The server's canonical origin — the client binds it into every proof; the
    /// server compares proofs against *this*, never the request host.
    const POP_ORIGIN: &str = "https://cp.example.test";

    /// Spawn a minimal control-plane router (`GET /api/sites`) behind the real
    /// [`require_auth`] middleware carrying `auth`, on a random loopback port.
    async fn spawn_guarded(auth: Auth) -> std::net::SocketAddr {
        let app = axum::Router::new()
            .route("/api/sites", axum::routing::get(|| async { "ok" }))
            .layer(axum::middleware::from_fn_with_state(auth, require_auth));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        addr
    }

    #[tokio::test]
    async fn pop_signing_client_round_trips_against_require_auth() {
        // A holder-bound (cnf) admin token + its holder private key.
        let root = LocalSigner::generate(TokenAlg::Es256);
        let holder = LocalSigner::generate(TokenAlg::Es256);
        let now = now_unix();
        let claims = Claims {
            roles: vec![GrantedRole::global("admin")],
            kind: "role".into(),
            ttl_secs: Some(3600),
            now_unix: now,
        };
        let token = cose::mint_delegatable(&claims, &holder.public_key(), &root)
            .await
            .unwrap();
        let holder_priv = holder.private_hex();

        // A server that requires a valid PoP for this (cnf) token, bound to ORIGIN.
        let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
        let auth = Auth::with_key(root.public_key(), kv).with_pop(Some(POP_ORIGIN.into()), false);
        let addr = spawn_guarded(auth).await;
        let url = format!("http://127.0.0.1:{}/api/sites", addr.port());

        // The PoP-signing client (correct holder key + origin) is authorized.
        let signed = build_client(Some(&token), Some(&holder_priv), Some(POP_ORIGIN), None);
        let resp = signed.get(&url).send().await.unwrap();
        assert_eq!(
            resp.status(),
            reqwest::StatusCode::OK,
            "signed request → 200"
        );

        // The same token with **no** proof (plain bearer client) is rejected 401 —
        // no silent bearer downgrade for a holder-bound token.
        let plain = build_client(Some(&token), None, None, None);
        let resp = plain.get(&url).send().await.unwrap();
        assert_eq!(
            resp.status(),
            reqwest::StatusCode::UNAUTHORIZED,
            "missing proof → 401"
        );

        // A proof bound to the wrong origin (what a spoofed relay would carry) is
        // rejected — the server binds its *configured* origin, not the request.
        let wrong_origin = build_client(
            Some(&token),
            Some(&holder_priv),
            Some("https://evil.example.test"),
            None,
        );
        let resp = wrong_origin.get(&url).send().await.unwrap();
        assert_eq!(
            resp.status(),
            reqwest::StatusCode::UNAUTHORIZED,
            "wrong-origin proof → 401"
        );
    }
}