zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
//! `zakuro://` deep links (ADR ZC-0020, zc#509): parse a link, verify the
//! hub-signed action token it carries, and describe what it would change.
//!
//! The closed set of links:
//!
//! | Link | Token |
//! |---|---|
//! | `zakuro://open?view=<screen>` | none: opens a screen, changes nothing |
//! | `zakuro://auth/callback?code=&state=` | none: PKCE, the verifier stays with whoever started the sign-in |
//! | `zakuro://squad/join?t=<jwt>` | hub-signed |
//! | `zakuro://env/launch?t=<jwt>` | hub-signed |
//! | `zakuro://env/connect?t=<jwt>` | hub-signed |
//! | `zakuro://share/budget?t=<jwt>` | hub-signed |
//!
//! A token is a compact JWS (`header.payload.signature`, base64url) signed
//! with EdDSA (Ed25519) by the hub's dedicated *action* key, never the
//! voucher key (ZC-0006). The claims are the ones zak-marketplace's
//! `services/action_tokens.py` mints: `act`, `args`, `sub` (the account's
//! `zakuro_user_id`), optional `node` (this node's key fingerprint), `iat`,
//! `exp` (at most 10 minutes), `jti`, `kid`, `iss`.
//!
//! The keys a token may verify against are the active `ZAKURO_ENV`
//! profile's action trust roots ([`profile_roots`]),
//! or, when set, `ZAKURO_ACTION_PUBKEYS` (comma-separated base64 32-byte
//! Ed25519 public keys) in their place, the same way `ZAKURO_API_URL`
//! overrides the profile's hub. No key at all means every signed link is
//! refused: fail closed, never "accept unsigned".
//!
//! Verification is pure ([`verify`], [`check_binding`]); single use is the
//! caller's ([`Seen`]): the agent keeps the used ids until they expire.

use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::Path;

pub const SCHEME_PREFIX: &str = "zakuro://";
/// ADR ZC-0020: "exp: at most 10 minutes".
pub const MAX_TTL_SECS: i64 = 600;
/// Clock skew tolerated on `exp` and on the 10-minute ceiling, the same as the
/// signed peer requests (`broker::node_identity`).
pub const LEEWAY_SECS: i64 = 30;
/// Replaces the profile's action trust roots (comma-separated base64 keys).
pub const ENV_ACTION_PUBKEYS: &str = "ZAKURO_ACTION_PUBKEYS";
/// Longest link accepted. The hub caps a token at 8 KiB (`RedeemRequest`).
pub const MAX_LINK_LEN: usize = 8192 + 64;

/// The screens `zakuro://open?view=` may name: the app's sidebar, plus the
/// first-run screens. Anything else is refused rather than guessed at.
pub const VIEWS: &[&str] = &[
    "contribution",
    "nodes",
    "jobs",
    "environments",
    "squads",
    "budget",
    "wallet",
    "settings",
    "setup",
];

/// The six actions of ADR ZC-0020 §2.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Act {
    AuthCallback,
    SquadJoin,
    EnvLaunch,
    EnvConnect,
    ShareBudget,
    Open,
}

impl Act {
    pub const ALL: [Act; 6] = [
        Act::AuthCallback,
        Act::SquadJoin,
        Act::EnvLaunch,
        Act::EnvConnect,
        Act::ShareBudget,
        Act::Open,
    ];

    /// The link path, which is also the token's `act` claim.
    pub fn path(self) -> &'static str {
        match self {
            Act::AuthCallback => "auth/callback",
            Act::SquadJoin => "squad/join",
            Act::EnvLaunch => "env/launch",
            Act::EnvConnect => "env/connect",
            Act::ShareBudget => "share/budget",
            Act::Open => "open",
        }
    }

    pub fn parse(path: &str) -> Option<Act> {
        Act::ALL.into_iter().find(|a| a.path() == path)
    }

    /// Whether the link must carry a hub-signed token (every state change).
    pub fn signed(self) -> bool {
        !matches!(self, Act::AuthCallback | Act::Open)
    }
}

/// A parsed link, before any verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Link {
    Open { view: String },
    AuthCallback { code: String, state: String },
    Signed { act: Act, token: String },
}

impl Link {
    pub fn act(&self) -> Act {
        match self {
            Link::Open { .. } => Act::Open,
            Link::AuthCallback { .. } => Act::AuthCallback,
            Link::Signed { act, .. } => *act,
        }
    }
}

/// Everything that can refuse a link. Each maps to the agent API's error
/// envelope (`status`, `code`) so the app and the CLI say the same thing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkError {
    /// Not a `zakuro://` link, an action outside the closed set, or a missing
    /// or malformed parameter.
    Invalid(String),
    /// The token is not a three-part JWS, or its signature part is empty, or
    /// it names an algorithm other than EdDSA (`none` included).
    Unsigned,
    /// No trusted key has the token's `kid`.
    UnknownKey,
    /// The signature does not verify against the key named by `kid`.
    BadSignature,
    /// This zc has no action key for the active profile.
    NoTrustRoot(String),
    /// The configured action keys do not parse.
    KeyConfig(String),
    /// `exp` has passed.
    Expired,
    /// The token claims to live longer than ten minutes.
    TooLong,
    /// The claims are malformed, or `act` differs from the link's action.
    BadClaims(String),
    /// `sub` is another account.
    WrongAccount { sub: String },
    /// The agent does not know which account it is signed in as yet.
    AccountUnknown,
    /// `node` (or the args' node) is another node.
    WrongNode,
    /// The `jti` was already used.
    AlreadyUsed,
    /// The used-id file could not be read or written, so this zc cannot
    /// prove a link is unused: it refuses rather than risk a replay.
    Storage(String),
}

impl LinkError {
    pub fn status(&self) -> u16 {
        match self {
            LinkError::Invalid(_) => 400,
            LinkError::Unsigned
            | LinkError::UnknownKey
            | LinkError::BadSignature
            | LinkError::TooLong
            | LinkError::BadClaims(_)
            | LinkError::WrongNode => 403,
            LinkError::WrongAccount { .. } | LinkError::AccountUnknown => 409,
            LinkError::Expired | LinkError::AlreadyUsed => 410,
            LinkError::NoTrustRoot(_) | LinkError::KeyConfig(_) => 503,
            LinkError::Storage(_) => 500,
        }
    }

    pub fn code(&self) -> &'static str {
        match self {
            LinkError::Invalid(_) => "invalid_link",
            LinkError::Unsigned => "unsigned",
            LinkError::UnknownKey => "unknown_key",
            LinkError::BadSignature => "bad_signature",
            LinkError::NoTrustRoot(_) | LinkError::KeyConfig(_) => "no_action_key",
            LinkError::Expired => "expired",
            LinkError::TooLong => "invalid_token",
            LinkError::BadClaims(_) => "invalid_token",
            LinkError::WrongAccount { .. } => "wrong_account",
            LinkError::AccountUnknown => "account_unknown",
            LinkError::WrongNode => "wrong_node",
            LinkError::AlreadyUsed => "already_used",
            LinkError::Storage(_) => "storage",
        }
    }

    pub fn message(&self) -> String {
        match self {
            LinkError::Invalid(m) => format!("not a valid zakuro:// link: {m}"),
            LinkError::Unsigned => "this link is not signed by the hub".into(),
            LinkError::UnknownKey => {
                "this link was signed with a key this zc does not trust (another environment?)".into()
            }
            LinkError::BadSignature => "this link's signature does not verify".into(),
            LinkError::NoTrustRoot(env) => format!(
                "this zc has no hub action key for the {env} profile, so it refuses signed links; set {ENV_ACTION_PUBKEYS} to the hub's key (GET /api/broker/action/pubkey)"
            ),
            LinkError::KeyConfig(e) => format!("the hub action keys are misconfigured: {e}"),
            LinkError::Expired => "this link has expired; open it again from the hub".into(),
            LinkError::TooLong => "this link claims to stay valid for more than 10 minutes".into(),
            LinkError::BadClaims(m) => format!("this link's token is malformed: {m}"),
            LinkError::WrongAccount { .. } => {
                "this link was made for another account; sign in as that account (zc login --force) and open it again".into()
            }
            LinkError::AccountUnknown => {
                "the agent does not know which account it is signed in as yet; sign in, or wait for the hub to answer, then open the link again".into()
            }
            LinkError::WrongNode => "this link was made for another node".into(),
            LinkError::AlreadyUsed => "this link was already used".into(),
            LinkError::Storage(m) => format!("this zc cannot track used links: {m}"),
        }
    }
}

impl std::fmt::Display for LinkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message())
    }
}

fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// `application/x-www-form-urlencoded` decoding of one query component.
fn percent_decode(s: &str) -> Result<String, LinkError> {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'%' => {
                let hi = bytes.get(i + 1).copied().and_then(hex_val);
                let lo = bytes.get(i + 2).copied().and_then(hex_val);
                match (hi, lo) {
                    (Some(h), Some(l)) => out.push(h * 16 + l),
                    _ => return Err(LinkError::Invalid("bad percent-escape".into())),
                }
                i += 3;
            }
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b => {
                out.push(b);
                i += 1;
            }
        }
    }
    String::from_utf8(out).map_err(|_| LinkError::Invalid("query is not UTF-8".into()))
}

/// Parse a link. Only the closed set of ADR ZC-0020 §2 is accepted, each with
/// exactly the parameter it needs; a repeated parameter is refused rather
/// than resolved one way or the other.
pub fn parse_link(raw: &str) -> Result<Link, LinkError> {
    let raw = raw.trim();
    if raw.len() > MAX_LINK_LEN {
        return Err(LinkError::Invalid("too long".into()));
    }
    let rest = raw
        .get(..SCHEME_PREFIX.len())
        .filter(|p| p.eq_ignore_ascii_case(SCHEME_PREFIX))
        .map(|_| &raw[SCHEME_PREFIX.len()..])
        .ok_or_else(|| LinkError::Invalid("the scheme must be zakuro://".into()))?;
    let rest = rest.split('#').next().unwrap_or("");
    let (path, query) = match rest.split_once('?') {
        Some((p, q)) => (p, q),
        None => (rest, ""),
    };
    let path = path.trim_end_matches('/');
    let act =
        Act::parse(path).ok_or_else(|| LinkError::Invalid(format!("unknown action '{path}'")))?;

    let mut params: BTreeMap<String, String> = BTreeMap::new();
    for pair in query.split('&').filter(|p| !p.is_empty()) {
        let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
        let k = percent_decode(k)?;
        let v = percent_decode(v)?;
        if params.insert(k.clone(), v).is_some() {
            return Err(LinkError::Invalid(format!("'{k}' is given twice")));
        }
    }
    let take = |params: &mut BTreeMap<String, String>, k: &str| -> Result<String, LinkError> {
        params
            .remove(k)
            .filter(|v| !v.trim().is_empty())
            .ok_or_else(|| LinkError::Invalid(format!("'{k}' is missing")))
    };
    let link = match act {
        Act::Open => {
            let view = take(&mut params, "view")?;
            if !VIEWS.contains(&view.as_str()) {
                return Err(LinkError::Invalid(format!("unknown view '{view}'")));
            }
            Link::Open { view }
        }
        Act::AuthCallback => Link::AuthCallback {
            code: take(&mut params, "code")?,
            state: take(&mut params, "state")?,
        },
        act => Link::Signed {
            act,
            token: take(&mut params, "t")?,
        },
    };
    if let Some(k) = params.keys().next() {
        return Err(LinkError::Invalid(format!("unexpected parameter '{k}'")));
    }
    Ok(link)
}

/// One action public key, with its `kid`: the first 8 bytes of SHA-256 of
/// the raw key, lowercase hex (what the hub's `key_id` computes).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrustedKey {
    pub kid: String,
    pub raw: [u8; 32],
}

pub fn key_id(raw: &[u8]) -> String {
    let d = ring::digest::digest(&ring::digest::SHA256, raw);
    hex::encode(&d.as_ref()[..8])
}

impl TrustedKey {
    /// A base64 (standard or URL-safe, padded or not) 32-byte Ed25519 key.
    pub fn from_b64(s: &str) -> Result<TrustedKey, String> {
        let s = s.trim();
        let raw = base64::engine::general_purpose::STANDARD
            .decode(s)
            .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(s))
            .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(s))
            .or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s))
            .map_err(|_| format!("'{s}' is not base64"))?;
        let raw: [u8; 32] = raw
            .try_into()
            .map_err(|_| format!("'{s}' is not a 32-byte Ed25519 public key"))?;
        Ok(TrustedKey {
            kid: key_id(&raw),
            raw,
        })
    }
}

/// The keys signed links verify against: `override_var`
/// (`ZAKURO_ACTION_PUBKEYS`) when set and non-blank, else the profile's
/// roots. A malformed key is an error, not skipped: a typo must not silently
/// turn into "no key".
pub fn trusted_keys(
    profile_roots: &[&str],
    override_var: Option<String>,
) -> Result<Vec<TrustedKey>, String> {
    let from_var = override_var.filter(|v| !v.trim().is_empty());
    let items: Vec<String> = match &from_var {
        Some(v) => v.split(',').map(str::to_string).collect(),
        None => profile_roots.iter().map(|s| s.to_string()).collect(),
    };
    items
        .iter()
        .filter(|s| !s.trim().is_empty())
        .map(|s| {
            TrustedKey::from_b64(s).map_err(|e| match from_var {
                Some(_) => format!("{ENV_ACTION_PUBKEYS}: {e}"),
                None => format!("profile action trust root: {e}"),
            })
        })
        .collect()
}

/// stg.hub's action key (kid `bde74a18996820b2`).
pub const STAGING_ACTION_PUBKEY: &str = "dOhGMGFe0iJu4g6KvZKsG8MwK/W0i8WX4l3tXbsmL04=";

/// Each `ZAKURO_ENV` profile's action trust roots (ADR ZC-0020 §3): base64
/// 32-byte Ed25519 public keys, current first, then any previous key still
/// inside a token lifetime. Unlike the update and image roots in
/// [`crate::profile`], empty is enforced: every signed link is refused.
///
/// Staging's key (kid `bde74a18996820b2`) was provisioned on 2026-11-04 as
/// the `action-key` Secret behind stg.hub's `ZAKURO_ACTION_PRIVKEY`; its
/// `GET /api/broker/action/pubkey` answers this kid. Prod has not provisioned
/// one yet, so prod still refuses every signed link. The lab's key is derived
/// per lab from its voucher key, so zlab stages it through
/// `ZAKURO_ACTION_PUBKEYS`. Rotating a key: add the new one first, keep the
/// old one for one token lifetime (10 minutes) after the hub switches. Kept here rather than as a `Profile`
/// field so the trust roots of one feature live with its verifier; the
/// profile still selects which set applies.
pub fn profile_roots(env: crate::profile::Env) -> &'static [&'static str] {
    use crate::profile::Env;
    match env {
        Env::Lab => &[],
        Env::Staging => &[STAGING_ACTION_PUBKEY],
        Env::Prod => &[],
    }
}

/// [`trusted_keys`] for the active profile and the process environment.
pub fn active_keys() -> Result<Vec<TrustedKey>, String> {
    trusted_keys(
        profile_roots(crate::profile::active().env),
        std::env::var(ENV_ACTION_PUBKEYS).ok(),
    )
}

/// The environment whose trust roots verify links for a node signed in to
/// `api_url`: the hub that minted the token is the one the node talks to.
/// A LaunchAgent started without `ZAKURO_ENV` resolves the profile to prod
/// even when `zc login --staging` pointed the credentials at staging, so the
/// signed-in hub wins when it is staging's or prod's. A lab or custom URL
/// falls back to the profile.
pub fn env_for_api_url(api_url: Option<&str>) -> crate::profile::Env {
    use crate::profile::Env;
    match api_url.map(|u| u.trim().trim_end_matches('/')) {
        Some(u) if u == crate::credentials::STAGING_API_URL => Env::Staging,
        Some(u) if u == crate::credentials::PROD_API_URL => Env::Prod,
        _ => crate::profile::active().env,
    }
}

/// [`trusted_keys`] for `env`, with the process environment's override.
pub fn keys_for(env: crate::profile::Env) -> Result<Vec<TrustedKey>, String> {
    trusted_keys(profile_roots(env), std::env::var(ENV_ACTION_PUBKEYS).ok())
}

/// One line for `zc doctor`: the action keys' `kid`s and where they come from.
pub fn doctor_line() -> String {
    let var = std::env::var(ENV_ACTION_PUBKEYS)
        .ok()
        .filter(|v| !v.trim().is_empty());
    let keys = match active_keys() {
        Err(e) => format!("invalid ({e})"),
        Ok(k) if k.is_empty() => "(none: signed zakuro:// links are refused)".to_string(),
        Ok(k) => format!(
            "{} ({})",
            k.iter()
                .map(|k| k.kid.as_str())
                .collect::<Vec<_>>()
                .join(", "),
            if var.is_some() {
                ENV_ACTION_PUBKEYS
            } else {
                "profile"
            }
        ),
    };
    format!("  action key: {keys}")
}

/// The verified claims of an action token.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Claims {
    pub act: String,
    #[serde(default)]
    pub args: Value,
    pub sub: String,
    #[serde(default)]
    pub node: Option<String>,
    #[serde(default)]
    pub iat: Option<i64>,
    pub exp: i64,
    pub jti: String,
    #[serde(default)]
    pub kid: Option<String>,
    #[serde(default)]
    pub iss: Option<String>,
}

#[derive(Deserialize)]
struct Header {
    #[serde(default)]
    alg: Option<String>,
    #[serde(default)]
    kid: Option<String>,
}

fn b64url(part: &str) -> Result<Vec<u8>, LinkError> {
    base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(part.trim_end_matches('='))
        .map_err(|_| LinkError::BadClaims("not base64url".into()))
}

/// Check one token's signature, `exp` and shape, for the link's `act`, at
/// `now` (unix seconds). Account, node and single use are checked by
/// [`check_binding`] and [`Seen`]: they depend on the caller's state.
pub fn verify(token: &str, act: Act, keys: &[TrustedKey], now: i64) -> Result<Claims, LinkError> {
    let parts: Vec<&str> = token.trim().split('.').collect();
    if parts.len() != 3 || parts[2].is_empty() {
        return Err(LinkError::Unsigned);
    }
    let header: Header = serde_json::from_slice(&b64url(parts[0])?)
        .map_err(|_| LinkError::BadClaims("unreadable header".into()))?;
    if header.alg.as_deref() != Some("EdDSA") {
        return Err(LinkError::Unsigned);
    }
    let kid = header.kid.unwrap_or_default();
    let key = keys
        .iter()
        .find(|k| k.kid == kid)
        .ok_or(LinkError::UnknownKey)?;
    let sig = b64url(parts[2]).map_err(|_| LinkError::BadSignature)?;
    let signed = format!("{}.{}", parts[0], parts[1]);
    ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, key.raw)
        .verify(signed.as_bytes(), &sig)
        .map_err(|_| LinkError::BadSignature)?;

    // Only now, with the signature good, is the payload worth reading.
    let claims: Claims = serde_json::from_slice(&b64url(parts[1])?)
        .map_err(|e| LinkError::BadClaims(format!("claims: {e}")))?;
    if claims.act != act.path() {
        return Err(LinkError::BadClaims(format!(
            "the token is for '{}', the link is '{}'",
            claims.act,
            act.path()
        )));
    }
    if claims.kid.as_deref().is_some_and(|k| k != kid) {
        return Err(LinkError::BadClaims(
            "kid differs between header and claims".into(),
        ));
    }
    if claims.jti.trim().is_empty() || claims.sub.trim().is_empty() {
        return Err(LinkError::BadClaims("jti and sub are required".into()));
    }
    if now >= claims.exp + LEEWAY_SECS {
        return Err(LinkError::Expired);
    }
    if claims.exp > now + MAX_TTL_SECS + LEEWAY_SECS
        || claims
            .iat
            .is_some_and(|iat| claims.exp - iat > MAX_TTL_SECS)
    {
        return Err(LinkError::TooLong);
    }
    Ok(claims)
}

/// The token is for this account and, when it names one, this node.
///
/// `account_sub` is the signed-in account's `zakuro_user_id` (`None` when not
/// known yet: refused, never assumed). `node_fp` is this node's key
/// fingerprint and `node_pubkey` its base64 public key: a `share/budget`
/// token also names the node in `args.node_pubkey`, and both must match.
pub fn check_binding(
    claims: &Claims,
    account_sub: Option<&str>,
    node_fp: &str,
    node_pubkey: &str,
) -> Result<(), LinkError> {
    match account_sub {
        None => return Err(LinkError::AccountUnknown),
        Some(sub) if sub != claims.sub => {
            return Err(LinkError::WrongAccount {
                sub: claims.sub.clone(),
            })
        }
        Some(_) => {}
    }
    if let Some(n) = claims.node.as_deref() {
        let n = crate::broker::node_identity::strip_node_arg(n);
        if n != node_fp {
            return Err(LinkError::WrongNode);
        }
    }
    if let Some(pk) = claims.args.get("node_pubkey").and_then(Value::as_str) {
        if pk.trim() != node_pubkey.trim() {
            return Err(LinkError::WrongNode);
        }
    }
    Ok(())
}

/// The used action ids, each kept until its token expires (ADR ZC-0020 §4).
/// Persisted so a restart does not reopen a used link.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Seen {
    /// jti -> exp (unix seconds).
    #[serde(default)]
    used: BTreeMap<String, i64>,
}

impl Seen {
    /// Read the used ids. A missing file is an empty set. An unreadable or
    /// corrupt one is an error (fail closed: an empty set would re-arm every
    /// used link), unless it is older than any token could live, in which
    /// case every id it held has expired and an empty set is exact.
    pub fn load(path: &Path) -> Result<Seen, LinkError> {
        Self::load_at(path, std::time::SystemTime::now())
    }

    fn load_at(path: &Path, now: std::time::SystemTime) -> Result<Seen, LinkError> {
        let bytes = match std::fs::read(path) {
            Ok(b) => b,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Seen::default()),
            Err(e) => {
                return Err(LinkError::Storage(format!(
                    "could not read {}: {e}",
                    path.display()
                )))
            }
        };
        match serde_json::from_slice(&bytes) {
            Ok(s) => Ok(s),
            Err(e) => {
                let stale = std::fs::metadata(path)
                    .and_then(|m| m.modified())
                    .ok()
                    .and_then(|m| now.duration_since(m).ok())
                    .is_some_and(|age| age.as_secs() as i64 > MAX_TTL_SECS + 2 * LEEWAY_SECS);
                if stale {
                    Ok(Seen::default())
                } else {
                    Err(LinkError::Storage(format!(
                        "{} is corrupt ({e}); it resets by itself {} minutes after its last change, or delete it once no link opened in the last 10 minutes matters",
                        path.display(),
                        (MAX_TTL_SECS + 2 * LEEWAY_SECS + 59) / 60
                    )))
                }
            }
        }
    }

    /// Add the ids `other` holds (another process may have written the
    /// file since this one read it).
    pub fn merge(&mut self, other: Seen) {
        for (jti, exp) in other.used {
            let e = self.used.entry(jti).or_insert(exp);
            *e = (*e).max(exp);
        }
    }

    pub fn save(&self, path: &Path) -> std::io::Result<()> {
        if let Some(dir) = path.parent() {
            std::fs::create_dir_all(dir)?;
        }
        let tmp = path.with_extension("tmp");
        std::fs::write(&tmp, serde_json::to_vec(self).unwrap_or_default())?;
        std::fs::rename(tmp, path)
    }

    /// Drop the ids whose tokens can no longer verify anyway.
    pub fn prune(&mut self, now: i64) {
        self.used.retain(|_, exp| now < *exp + LEEWAY_SECS);
    }

    pub fn contains(&self, jti: &str) -> bool {
        self.used.contains_key(jti)
    }

    /// Mark `jti` used. `Err(AlreadyUsed)` when it already was.
    pub fn mark(&mut self, jti: &str, exp: i64) -> Result<(), LinkError> {
        if self.used.contains_key(jti) {
            return Err(LinkError::AlreadyUsed);
        }
        self.used.insert(jti.to_string(), exp);
        Ok(())
    }

    pub fn len(&self) -> usize {
        self.used.len()
    }

    pub fn is_empty(&self) -> bool {
        self.used.is_empty()
    }
}

/// One line of a confirmation sheet.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Detail {
    pub label: String,
    pub value: String,
}

/// What a link would do, for the confirmation sheet (`POST /v2/handoff`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Preview {
    pub act: String,
    /// `null` for the token-less links (`open`, `auth/callback`): there is
    /// nothing for the agent to confirm, the app acts on its own sheet.
    pub jti: Option<String>,
    pub sub: Option<String>,
    pub node: Option<String>,
    pub exp: Option<i64>,
    pub title: String,
    pub summary: String,
    pub details: Vec<Detail>,
    /// The app screen the action lands on.
    pub view: String,
    /// Whether confirming runs the action in this zc. When `false`, `until`
    /// names the issue it ships in, and confirming answers 501.
    pub available: bool,
    pub until: Option<String>,
    /// `share/budget`: the proposed change, prefilled on Budget & price.
    pub prefill: Option<Value>,
    pub args: Value,
}

fn view_label(view: &str) -> &'static str {
    match view {
        "contribution" => "Contribution",
        "nodes" => "Nodes",
        "jobs" => "Jobs",
        "environments" => "Environments",
        "squads" => "Squads",
        "budget" => "Budget & price",
        "wallet" => "Wallet",
        "settings" => "Settings",
        "setup" => "Setup",
        _ => "Zakuro",
    }
}

fn arg_str(args: &Value, k: &str) -> Option<String> {
    match args.get(k)? {
        Value::String(s) if !s.trim().is_empty() => Some(s.chars().take(200).collect()),
        Value::Number(n) => Some(n.to_string()),
        _ => None,
    }
}

/// A proposal value as the sheet shows it: prices in ¥ units (ADR 0027).
fn proposal_line(k: &str, v: &Value) -> Detail {
    let label = match k {
        "price_per_hour" => "Price".to_string(),
        "cpu" | "cpu_pct" => "CPU".to_string(),
        "ram" | "ram_gb" | "memory" => "Memory".to_string(),
        "gpu" => "GPU".to_string(),
        "sharing" => "Sharing".to_string(),
        other => other.replace('_', " "),
    };
    let value = match (k, v) {
        ("price_per_hour", Value::Number(n)) => format!("¥{n}/h"),
        (_, Value::Bool(true)) => "on".into(),
        (_, Value::Bool(false)) => "off".into(),
        (_, Value::Null) => "unset".into(),
        (_, Value::String(s)) => s.chars().take(200).collect(),
        (_, other) => other.to_string(),
    };
    Detail { label, value }
}

/// The confirmation sheet for a link whose token (if any) has verified.
/// `issues` names, per unavailable action, the issue it ships in.
pub fn describe(link: &Link, claims: Option<&Claims>, issues: &Issues) -> Preview {
    let args = claims.map(|c| c.args.clone()).unwrap_or(Value::Null);
    let mut p = Preview {
        act: link.act().path().to_string(),
        jti: claims.map(|c| c.jti.clone()),
        sub: claims.map(|c| c.sub.clone()),
        node: claims.and_then(|c| c.node.clone()),
        exp: claims.map(|c| c.exp),
        title: String::new(),
        summary: String::new(),
        details: vec![],
        view: "contribution".into(),
        available: true,
        until: None,
        prefill: None,
        args: args.clone(),
    };
    let d = |label: &str, value: String| Detail {
        label: label.into(),
        value,
    };
    match link {
        Link::Open { view } => {
            p.title = format!("Open {}", view_label(view));
            p.summary = "Shows a screen of the app. Nothing on this machine changes.".into();
            p.view = view.clone();
        }
        Link::AuthCallback { .. } => {
            p.title = "Finish signing in".into();
            p.summary = "The browser handed a sign-in back to Zakuro. This zc signs in with a device code instead, which finishes on its own once you approve it in the browser.".into();
            p.view = "setup".into();
            p.available = false;
            p.until = Some(issues.auth_callback.to_string());
        }
        Link::Signed { act, .. } => {
            match act {
                Act::SquadJoin => {
                    let name = arg_str(&args, "name")
                        .or_else(|| arg_str(&args, "slug"))
                        .unwrap_or_else(|| "a squad".into());
                    p.title = format!("Join {name}");
                    p.summary = "Adds this node to the squad, which can then run jobs on it within the squad's policy.".into();
                    p.details.push(d("Squad", name));
                    if let Some(r) = arg_str(&args, "role") {
                        p.details.push(d("Your role", r));
                    }
                    p.view = "squads".into();
                    p.available = false;
                    p.until = Some(issues.squads.to_string());
                }
                Act::EnvLaunch => {
                    let template =
                        arg_str(&args, "template").unwrap_or_else(|| "an environment".into());
                    p.title = format!("Launch {template}");
                    p.summary =
                        "Starts the environment through the hub, on the placement the link names."
                            .into();
                    p.details.push(d("Template", template));
                    if let Some(pl) = arg_str(&args, "placement") {
                        p.details.push(d("Placement", pl));
                    }
                    if let Some(s) = arg_str(&args, "size") {
                        p.details.push(d("Size", s));
                    }
                    p.view = "environments".into();
                    p.available = false;
                    p.until = Some(issues.envs.to_string());
                }
                Act::EnvConnect => {
                    let name = arg_str(&args, "name")
                        .or_else(|| arg_str(&args, "deployment_id"))
                        .unwrap_or_else(|| "an environment".into());
                    p.title = format!("Connect to {name}");
                    p.summary = "Brings up this machine's scoped mesh peer for the environment, then opens it.".into();
                    p.details.push(d("Environment", name));
                    p.view = "environments".into();
                    p.available = false;
                    p.until = Some(issues.envs.to_string());
                }
                Act::ShareBudget => {
                    p.title = "Review a budget change".into();
                    p.summary = "Opens Budget & price with the change the hub proposed filled in. Nothing is saved until you save it there.".into();
                    if let Some(Value::Object(m)) = args.get("proposed") {
                        for (k, v) in m {
                            p.details.push(proposal_line(k, v));
                        }
                        p.prefill = Some(Value::Object(m.clone()));
                    }
                    if p.details.is_empty() {
                        p.details
                            .push(d("Proposed", "no change, review only".into()));
                    }
                    p.view = "budget".into();
                }
                Act::Open | Act::AuthCallback => {}
            }
        }
    }
    if let Some(c) = claims {
        if c.node.is_some() {
            p.details.push(d("Node", "this node".into()));
        }
    }
    p
}

/// Where each action that has no backend yet ships.
#[derive(Debug, Clone, Copy)]
pub struct Issues {
    pub squads: &'static str,
    pub envs: &'static str,
    pub auth_callback: &'static str,
}

/// The issues today's zc names.
pub const ISSUES: Issues = Issues {
    squads: "zakuro-ai/zc#517",
    envs: "zakuro-ai/zc#519",
    // The hub has no PKCE authorization-code endpoint yet; `zc login` signs
    // in with a device code (M2.1), which needs no callback.
    auth_callback: "zakuro-ai/zc#497",
};

/// What verification needs from the caller's state.
pub struct Context<'a> {
    pub keys: &'a [TrustedKey],
    /// The active profile's name, for the "no action key" message.
    pub env: &'a str,
    /// The signed-in account's `zakuro_user_id`, when known.
    pub account_sub: Option<&'a str>,
    pub node_fp: &'a str,
    pub node_pubkey: &'a str,
    pub now: i64,
}

/// Every check of ADR ZC-0020 §4 for one parsed link: signature, `exp`,
/// account, node and single use. The token-less links pass as they are.
pub fn check_link(link: &Link, ctx: &Context, seen: &Seen) -> Result<Option<Claims>, LinkError> {
    let Link::Signed { act, token } = link else {
        return Ok(None);
    };
    if ctx.keys.is_empty() {
        return Err(LinkError::NoTrustRoot(ctx.env.to_string()));
    }
    let claims = verify(token, *act, ctx.keys, ctx.now)?;
    check_binding(&claims, ctx.account_sub, ctx.node_fp, ctx.node_pubkey)?;
    if seen.contains(&claims.jti) {
        return Err(LinkError::AlreadyUsed);
    }
    Ok(Some(claims))
}

/// Why `confirm` did not run an action.
#[derive(Debug, Clone, PartialEq)]
pub enum ConfirmError {
    /// No verified link with that id is waiting: open the link again.
    NotFound,
    Link(LinkError),
    /// Verified, but this zc cannot run it yet (`until` names the issue).
    NotAvailable {
        until: String,
        view: String,
    },
}

/// What a confirmed action did (`POST /v2/handoff/{jti}/confirm`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Confirmed {
    /// Always `done`.
    pub status: String,
    pub act: String,
    pub jti: String,
    /// The screen to show now.
    pub view: String,
    /// `share/budget`: the proposal to prefill.
    pub prefill: Option<Value>,
}

/// Verified links waiting for their click, and the used ids. One per agent
/// (or per CLI run when no agent is running), behind its own lock.
#[derive(Debug, Default)]
pub struct Handoffs {
    pending: BTreeMap<String, (Claims, Preview)>,
    seen: Seen,
    path: Option<std::path::PathBuf>,
}

impl Handoffs {
    /// `path` persists the used ids (`<agent dir>/handoff_seen.json`).
    /// The file is read again before every check, so ids that `zc link`
    /// (or another agent run) recorded are never missed.
    pub fn new(path: Option<std::path::PathBuf>) -> Handoffs {
        Handoffs {
            pending: BTreeMap::new(),
            seen: Seen::default(),
            path,
        }
    }

    /// Fold the ids on disk into memory.
    fn refresh(&mut self) -> Result<(), LinkError> {
        if let Some(p) = &self.path {
            let disk = Seen::load(p)?;
            self.seen.merge(disk);
        }
        Ok(())
    }

    /// Parse and verify `raw`, and describe it. A signed link is kept until
    /// it expires or is confirmed; opening it again returns the same sheet.
    pub fn open(
        &mut self,
        raw: &str,
        ctx: &Context,
        issues: &Issues,
    ) -> Result<Preview, LinkError> {
        self.pending
            .retain(|_, (c, _)| ctx.now < c.exp + LEEWAY_SECS);
        let link = parse_link(raw)?;
        if link.act().signed() {
            self.refresh()?;
        }
        self.seen.prune(ctx.now);
        let claims = check_link(&link, ctx, &self.seen)?;
        let preview = describe(&link, claims.as_ref(), issues);
        if let Some(c) = claims {
            self.pending.insert(c.jti.clone(), (c, preview.clone()));
        }
        Ok(preview)
    }

    /// Run the verified action `jti` names, once. Only a confirmed,
    /// available action marks the id used; one this zc cannot run yet stays
    /// usable, so it works once the feature ships, within its 10 minutes.
    pub fn confirm(&mut self, jti: &str, now: i64) -> Result<Confirmed, ConfirmError> {
        self.refresh().map_err(ConfirmError::Link)?;
        self.seen.prune(now);
        if self.seen.contains(jti) {
            return Err(ConfirmError::Link(LinkError::AlreadyUsed));
        }
        let Some((claims, preview)) = self.pending.get(jti).cloned() else {
            return Err(ConfirmError::NotFound);
        };
        if now >= claims.exp + LEEWAY_SECS {
            self.pending.remove(jti);
            return Err(ConfirmError::Link(LinkError::Expired));
        }
        if !preview.available {
            return Err(ConfirmError::NotAvailable {
                until: preview.until.clone().unwrap_or_default(),
                view: preview.view.clone(),
            });
        }
        self.seen
            .mark(&claims.jti, claims.exp)
            .map_err(ConfirmError::Link)?;
        if let Some(p) = &self.path {
            // A used id that is not on disk could be replayed after a
            // restart: refuse to run rather than run unrecorded.
            if let Err(e) = self.seen.save(p) {
                self.seen.used.remove(&claims.jti);
                return Err(ConfirmError::Link(LinkError::Storage(format!(
                    "could not record the used link in {}: {e}",
                    p.display()
                ))));
            }
        }
        self.pending.remove(jti);
        Ok(Confirmed {
            status: "done".into(),
            act: claims.act.clone(),
            jti: claims.jti.clone(),
            view: preview.view.clone(),
            prefill: preview.prefill.clone(),
        })
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use ring::signature::{Ed25519KeyPair, KeyPair};
    use serde_json::json;

    pub(crate) const NOW: i64 = 1_800_000_000;
    pub(crate) const NODE_FP: &str = "0123456789abcdef";
    pub(crate) const NODE_PK: &str = "q8X2n0Lr4mH6vB9sK3wT7yP1cF5gJ0dZ2aE4uR8iO6s=";

    pub(crate) struct Signer {
        pair: Ed25519KeyPair,
    }

    impl Signer {
        pub(crate) fn new(seed: u8) -> Signer {
            Signer {
                pair: Ed25519KeyPair::from_seed_unchecked(&[seed; 32]).unwrap(),
            }
        }
        pub(crate) fn key(&self) -> TrustedKey {
            let raw: [u8; 32] = self.pair.public_key().as_ref().try_into().unwrap();
            TrustedKey {
                kid: key_id(&raw),
                raw,
            }
        }
        pub(crate) fn pub_b64(&self) -> String {
            base64::engine::general_purpose::STANDARD.encode(self.pair.public_key().as_ref())
        }
        pub(crate) fn sign_with_header(&self, header: Value, claims: Value) -> String {
            let e =
                |v: &Value| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v.to_string());
            let signing = format!("{}.{}", e(&header), e(&claims));
            let sig = self.pair.sign(signing.as_bytes());
            format!(
                "{signing}.{}",
                base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig.as_ref())
            )
        }
        /// What the hub's `action_tokens.mint` produces.
        pub(crate) fn mint(&self, claims: Value) -> String {
            let kid = self.key().kid;
            self.sign_with_header(json!({"alg": "EdDSA", "typ": "JWT", "kid": kid}), claims)
        }
    }

    pub(crate) fn claims(act: &str, jti: &str) -> Value {
        json!({
            "act": act,
            "args": {"squad_id": "s1", "slug": "kyoto-vision", "name": "Kyoto Vision", "role": "member"},
            "sub": "1234567890",
            "node": NODE_FP,
            "iat": NOW - 10,
            "exp": NOW + 590,
            "jti": jti,
            "iss": "https://stg.hub.zakuro-ai.com",
        })
    }

    fn with(mut v: Value, k: &str, x: Value) -> Value {
        v[k] = x;
        v
    }

    #[test]
    fn parses_the_closed_set_and_nothing_else() {
        assert_eq!(
            parse_link("zakuro://open?view=contribution").unwrap(),
            Link::Open {
                view: "contribution".into()
            }
        );
        assert_eq!(
            parse_link("ZAKURO://open/?view=budget").unwrap().act(),
            Act::Open
        );
        assert_eq!(
            parse_link("zakuro://auth/callback?code=abc&state=x%2By").unwrap(),
            Link::AuthCallback {
                code: "abc".into(),
                state: "x+y".into()
            }
        );
        for act in ["squad/join", "env/launch", "env/connect", "share/budget"] {
            match parse_link(&format!("zakuro://{act}?t=a.b.c")).unwrap() {
                Link::Signed { act: a, token } => {
                    assert_eq!(a.path(), act);
                    assert_eq!(token, "a.b.c");
                }
                other => panic!("{other:?}"),
            }
        }
        for bad in [
            "https://hub.zakuro-ai.com/open?view=contribution",
            "zakuro://open?view=../../etc",
            "zakuro://open",
            "zakuro://squad/join",
            "zakuro://squad/join?t=",
            "zakuro://squad/join?t=a&t=b",
            "zakuro://squad/leave?t=a.b.c",
            "zakuro://share/budget?t=a.b.c&price=1",
            "zakuro://open?view=%zz",
        ] {
            let e = parse_link(bad).unwrap_err();
            assert_eq!(e.code(), "invalid_link", "{bad}");
        }
    }

    #[test]
    fn a_valid_token_verifies() {
        let s = Signer::new(7);
        let t = s.mint(claims("squad/join", "j1"));
        let c = verify(&t, Act::SquadJoin, &[s.key()], NOW).unwrap();
        assert_eq!((c.sub.as_str(), c.jti.as_str()), ("1234567890", "j1"));
        assert_eq!(c.node.as_deref(), Some(NODE_FP));
        check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK).unwrap();
        // A node claim in the zc://node-<fp> form is the same node.
        let t = s.mint(with(
            claims("squad/join", "j2"),
            "node",
            json!(format!("zc://node-{NODE_FP}")),
        ));
        let c = verify(&t, Act::SquadJoin, &[s.key()], NOW).unwrap();
        check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK).unwrap();
        // No node claim: any of the account's nodes.
        let mut v = claims("squad/join", "j3");
        v.as_object_mut().unwrap().remove("node");
        let c = verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW).unwrap();
        check_binding(&c, Some("1234567890"), "ffffffffffffffff", NODE_PK).unwrap();
    }

    #[test]
    fn an_expired_token_is_refused() {
        let s = Signer::new(7);
        let v = with(
            with(claims("squad/join", "j"), "iat", json!(NOW - 700)),
            "exp",
            json!(NOW - 100),
        );
        assert_eq!(
            verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW),
            Err(LinkError::Expired)
        );
        // Inside the leeway it still verifies; past it, not.
        let v = with(claims("squad/join", "j"), "exp", json!(NOW - 5));
        assert!(verify(&s.mint(v.clone()), Act::SquadJoin, &[s.key()], NOW).is_ok());
        assert_eq!(
            verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW + LEEWAY_SECS).unwrap_err(),
            LinkError::Expired
        );
        assert_eq!(LinkError::Expired.status(), 410);
    }

    #[test]
    fn a_token_living_longer_than_ten_minutes_is_refused() {
        let s = Signer::new(7);
        let v = with(claims("squad/join", "j"), "exp", json!(NOW + 3600));
        assert_eq!(
            verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW),
            Err(LinkError::TooLong)
        );
        let v = with(
            with(claims("squad/join", "j"), "iat", json!(NOW - 500)),
            "exp",
            json!(NOW + 200),
        );
        assert_eq!(
            verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW),
            Err(LinkError::TooLong)
        );
    }

    #[test]
    fn a_token_for_another_node_is_refused() {
        let s = Signer::new(7);
        let v = with(claims("squad/join", "j"), "node", json!("fedcba9876543210"));
        let c = verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW).unwrap();
        assert_eq!(
            check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK),
            Err(LinkError::WrongNode)
        );
        // share/budget also names the node in args.node_pubkey.
        let v = with(
            claims("share/budget", "j"),
            "args",
            json!({"node_pubkey": "Vb3kT9qL2xN7mR4wY8pC1zF6hJ0sD5gA2eU9iO3tK7c=", "proposed": {}}),
        );
        let c = verify(&s.mint(v), Act::ShareBudget, &[s.key()], NOW).unwrap();
        assert_eq!(
            check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK),
            Err(LinkError::WrongNode)
        );
        assert_eq!(LinkError::WrongNode.code(), "wrong_node");
    }

    #[test]
    fn a_token_for_another_account_or_an_unknown_account_is_refused() {
        let s = Signer::new(7);
        let c = verify(
            &s.mint(claims("squad/join", "j")),
            Act::SquadJoin,
            &[s.key()],
            NOW,
        )
        .unwrap();
        assert_eq!(
            check_binding(&c, Some("999"), NODE_FP, NODE_PK),
            Err(LinkError::WrongAccount {
                sub: "1234567890".into()
            })
        );
        assert_eq!(
            check_binding(&c, None, NODE_FP, NODE_PK),
            Err(LinkError::AccountUnknown)
        );
    }

    #[test]
    fn a_wrong_signature_is_refused() {
        let hub = Signer::new(7);
        let forger = Signer::new(8);
        // Signed by another key that claims the hub's kid.
        let kid = hub.key().kid;
        let forged = forger.sign_with_header(
            json!({"alg": "EdDSA", "kid": kid}),
            claims("squad/join", "j"),
        );
        assert_eq!(
            verify(&forged, Act::SquadJoin, &[hub.key()], NOW),
            Err(LinkError::BadSignature)
        );
        // A good token whose payload was edited after signing.
        let good = hub.mint(claims("squad/join", "j"));
        let parts: Vec<&str> = good.split('.').collect();
        let edited = with(claims("squad/join", "j"), "sub", json!("attacker"));
        let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(edited.to_string());
        let tampered = format!("{}.{}.{}", parts[0], payload, parts[2]);
        assert_eq!(
            verify(&tampered, Act::SquadJoin, &[hub.key()], NOW),
            Err(LinkError::BadSignature)
        );
        // Signed by a key this zc does not trust at all.
        assert_eq!(
            verify(
                &forger.mint(claims("squad/join", "j")),
                Act::SquadJoin,
                &[hub.key()],
                NOW
            ),
            Err(LinkError::UnknownKey)
        );
        // Nothing to verify against: no profile root and no override.
        assert_eq!(
            verify(&good, Act::SquadJoin, &[], NOW),
            Err(LinkError::UnknownKey)
        );
    }

    #[test]
    fn an_unsigned_token_is_refused() {
        let hub = Signer::new(7);
        let e = |v: Value| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v.to_string());
        let kid = hub.key().kid;
        let body = e(claims("squad/join", "j"));
        for t in [
            // alg none, empty signature (the classic JWT bypass).
            format!("{}.{body}.", e(json!({"alg": "none", "kid": kid}))),
            // EdDSA header but no signature part.
            format!("{}.{body}.", e(json!({"alg": "EdDSA", "kid": kid}))),
            format!("{}.{body}", e(json!({"alg": "EdDSA", "kid": kid}))),
            // A plausible signature under another algorithm.
            format!("{}.{body}.AAAA", e(json!({"alg": "HS256", "kid": kid}))),
            "not-a-jwt".to_string(),
        ] {
            assert_eq!(
                verify(&t, Act::SquadJoin, &[hub.key()], NOW),
                Err(LinkError::Unsigned),
                "{t}"
            );
        }
    }

    #[test]
    fn the_token_must_be_for_the_links_action() {
        let s = Signer::new(7);
        let t = s.mint(claims("share/budget", "j"));
        assert!(matches!(
            verify(&t, Act::SquadJoin, &[s.key()], NOW),
            Err(LinkError::BadClaims(_))
        ));
    }

    #[test]
    fn a_jti_is_single_use_until_it_expires() {
        let mut seen = Seen::default();
        seen.mark("j1", NOW + 100).unwrap();
        assert_eq!(seen.mark("j1", NOW + 100), Err(LinkError::AlreadyUsed));
        seen.prune(NOW + 100 + LEEWAY_SECS - 1);
        assert!(seen.contains("j1"));
        seen.prune(NOW + 100 + LEEWAY_SECS);
        assert!(!seen.contains("j1"));

        let dir = std::env::temp_dir().join(format!("zc-seen-{}", std::process::id()));
        let path = dir.join("handoff_seen.json");
        let mut s = Seen::default();
        s.mark("j2", NOW).unwrap();
        s.save(&path).unwrap();
        assert!(Seen::load(&path).unwrap().contains("j2"));
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn trust_roots_come_from_the_profile_or_the_override() {
        let s = Signer::new(7);
        let other = Signer::new(9);
        let roots = [s.pub_b64()];
        let roots: Vec<&str> = roots.iter().map(String::as_str).collect();
        assert_eq!(trusted_keys(&roots, None).unwrap(), vec![s.key()]);
        assert_eq!(
            trusted_keys(&roots, Some("  ".into())).unwrap(),
            vec![s.key()]
        );
        // The override replaces the profile's roots, and takes a list.
        let both = format!("{}, {}", other.pub_b64(), s.pub_b64());
        assert_eq!(
            trusted_keys(&roots, Some(both)).unwrap(),
            vec![other.key(), s.key()]
        );
        // The JWK `x` form (base64url, no padding) is the same key.
        let x = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(s.key().raw);
        assert_eq!(trusted_keys(&[], Some(x)).unwrap(), vec![s.key()]);
        assert!(trusted_keys(&[], Some("bm90IGEga2V5".into())).is_err());
        assert!(trusted_keys(&[], None).unwrap().is_empty());
        // Every built-in profile ships without a root today: fail closed.
        for env in [
            crate::profile::Env::Lab,
            crate::profile::Env::Staging,
            crate::profile::Env::Prod,
        ] {
            for r in profile_roots(env) {
                TrustedKey::from_b64(r).unwrap();
            }
        }
    }

    #[test]
    fn previews_say_what_will_change() {
        let s = Signer::new(7);
        let issues = ISSUES;
        let link = parse_link("zakuro://open?view=contribution").unwrap();
        let p = describe(&link, None, &issues);
        assert_eq!(
            (p.title.as_str(), p.view.as_str(), p.available),
            ("Open Contribution", "contribution", true)
        );
        assert!(p.jti.is_none());

        let c = verify(
            &s.mint(claims("squad/join", "j")),
            Act::SquadJoin,
            &[s.key()],
            NOW,
        )
        .unwrap();
        let link = Link::Signed {
            act: Act::SquadJoin,
            token: String::new(),
        };
        let p = describe(&link, Some(&c), &issues);
        assert_eq!(p.title, "Join Kyoto Vision");
        assert!(!p.available);
        assert_eq!(p.until.as_deref(), Some("zakuro-ai/zc#517"));
        assert_eq!(p.view, "squads");

        let v = with(
            claims("share/budget", "j"),
            "args",
            json!({"node_pubkey": NODE_PK, "proposed": {"price_per_hour": 120}}),
        );
        let c = verify(&s.mint(v), Act::ShareBudget, &[s.key()], NOW).unwrap();
        let link = Link::Signed {
            act: Act::ShareBudget,
            token: String::new(),
        };
        let p = describe(&link, Some(&c), &issues);
        assert!(p.available);
        assert_eq!(p.view, "budget");
        assert_eq!(p.prefill, Some(json!({"price_per_hour": 120})));
        assert_eq!(
            p.details[0],
            Detail {
                label: "Price".into(),
                value: "¥120/h".into()
            }
        );
    }

    fn ctx<'a>(keys: &'a [TrustedKey]) -> Context<'a> {
        Context {
            keys,
            env: "staging",
            account_sub: Some("1234567890"),
            node_fp: NODE_FP,
            node_pubkey: NODE_PK,
            now: NOW,
        }
    }

    #[test]
    fn handoffs_confirm_once_and_never_run_what_is_not_available() {
        let s = Signer::new(7);
        let keys = [s.key()];
        let dir = std::env::temp_dir().join(format!("zc-handoffs-{}", std::process::id()));
        let path = dir.join("handoff_seen.json");
        let mut h = Handoffs::new(Some(path.clone()));

        let v = with(
            claims("share/budget", "b1"),
            "args",
            json!({"node_pubkey": NODE_PK, "proposed": {"price_per_hour": 120}}),
        );
        let link = format!("zakuro://share/budget?t={}", s.mint(v));
        let p = h.open(&link, &ctx(&keys), &ISSUES).unwrap();
        assert_eq!(p.jti.as_deref(), Some("b1"));
        // Opening it twice before confirming shows the same sheet.
        assert_eq!(h.open(&link, &ctx(&keys), &ISSUES).unwrap(), p);
        let done = h.confirm("b1", NOW).unwrap();
        assert_eq!(
            (done.view.as_str(), done.prefill.clone()),
            ("budget", Some(json!({"price_per_hour": 120})))
        );
        assert_eq!(
            h.confirm("b1", NOW),
            Err(ConfirmError::Link(LinkError::AlreadyUsed))
        );
        assert_eq!(
            h.open(&link, &ctx(&keys), &ISSUES),
            Err(LinkError::AlreadyUsed)
        );
        // The used id survives a restart.
        let mut again = Handoffs::new(Some(path));
        assert_eq!(
            again.open(&link, &ctx(&keys), &ISSUES),
            Err(LinkError::AlreadyUsed)
        );

        // Squads are not in this zc yet: verified, shown, never run or used.
        let link = format!(
            "zakuro://squad/join?t={}",
            s.mint(claims("squad/join", "s1"))
        );
        h.open(&link, &ctx(&keys), &ISSUES).unwrap();
        assert_eq!(
            h.confirm("s1", NOW),
            Err(ConfirmError::NotAvailable {
                until: "zakuro-ai/zc#517".into(),
                view: "squads".into()
            })
        );
        assert!(h.open(&link, &ctx(&keys), &ISSUES).is_ok());

        assert_eq!(h.confirm("nope", NOW), Err(ConfirmError::NotFound));
        // Past exp, a pending link no longer runs.
        let link = format!(
            "zakuro://share/budget?t={}",
            s.mint(with(
                claims("share/budget", "b2"),
                "args",
                json!({"node_pubkey": NODE_PK})
            ))
        );
        h.open(&link, &ctx(&keys), &ISSUES).unwrap();
        assert_eq!(
            h.confirm("b2", NOW + 590 + LEEWAY_SECS),
            Err(ConfirmError::Link(LinkError::Expired))
        );

        // No action key for the profile: every signed link is refused.
        assert_eq!(
            h.open(&link, &ctx(&[]), &ISSUES),
            Err(LinkError::NoTrustRoot("staging".into()))
        );
        // Token-less links need no key.
        assert!(h
            .open("zakuro://open?view=contribution", &ctx(&[]), &ISSUES)
            .is_ok());
        let _ = std::fs::remove_dir_all(dir);
    }

    /// The agent and a `zc link` run without the agent share one file: an
    /// id one of them used is refused by the other, and neither save drops
    /// the other's ids (review of zc#541, finding 1).
    #[test]
    fn two_handoffs_on_one_file_never_lose_a_used_id() {
        let s = Signer::new(7);
        let keys = [s.key()];
        let dir = std::env::temp_dir().join(format!("zc-handoffs-two-{}", std::process::id()));
        let path = dir.join("handoff_seen.json");
        let budget = |jti: &str| {
            format!(
                "zakuro://share/budget?t={}",
                s.mint(with(
                    claims("share/budget", jti),
                    "args",
                    json!({"node_pubkey": NODE_PK})
                ))
            )
        };
        // The agent starts first, with an empty file.
        let mut agent = Handoffs::new(Some(path.clone()));
        agent.open(&budget("x"), &ctx(&keys), &ISSUES).unwrap();
        // `zc link` (agent busy) confirms "x" on its own.
        let mut cli = Handoffs::new(Some(path.clone()));
        cli.open(&budget("x"), &ctx(&keys), &ISSUES).unwrap();
        cli.confirm("x", NOW).unwrap();
        // The agent sees it on confirm and on open.
        assert_eq!(
            agent.confirm("x", NOW),
            Err(ConfirmError::Link(LinkError::AlreadyUsed))
        );
        assert_eq!(
            agent.open(&budget("x"), &ctx(&keys), &ISSUES),
            Err(LinkError::AlreadyUsed)
        );
        // The agent's next save keeps "x".
        agent.open(&budget("y"), &ctx(&keys), &ISSUES).unwrap();
        agent.confirm("y", NOW).unwrap();
        let disk = Seen::load(&path).unwrap();
        assert!(disk.contains("x") && disk.contains("y"));
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A corrupt used-id file refuses signed links instead of reading as
    /// empty, until it is older than any token could live (finding 10).
    #[test]
    fn a_corrupt_seen_file_fails_closed_until_it_is_stale() {
        let dir = std::env::temp_dir().join(format!("zc-seen-corrupt-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("handoff_seen.json");
        std::fs::write(&path, b"{\"used\": {\"j\": ").unwrap();
        let now = std::time::SystemTime::now();
        assert!(matches!(
            Seen::load_at(&path, now),
            Err(LinkError::Storage(_))
        ));
        let later =
            now + std::time::Duration::from_secs((MAX_TTL_SECS + 2 * LEEWAY_SECS + 5) as u64);
        assert_eq!(Seen::load_at(&path, later), Ok(Seen::default()));

        let s = Signer::new(7);
        let keys = [s.key()];
        let mut h = Handoffs::new(Some(path.clone()));
        let link = format!(
            "zakuro://share/budget?t={}",
            s.mint(with(
                claims("share/budget", "c1"),
                "args",
                json!({"node_pubkey": NODE_PK})
            ))
        );
        let e = h.open(&link, &ctx(&keys), &ISSUES).unwrap_err();
        assert_eq!((e.status(), e.code()), (500, "storage"));
        // Token-less links do not need the file.
        assert!(h
            .open("zakuro://open?view=contribution", &ctx(&keys), &ISSUES)
            .is_ok());
        // A missing file is an empty set.
        std::fs::remove_file(&path).unwrap();
        assert!(h.open(&link, &ctx(&keys), &ISSUES).is_ok());
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A failed write of the used-id file is a storage error, not a key
    /// problem (finding 6).
    #[test]
    fn a_failed_seen_write_is_a_storage_error() {
        let s = Signer::new(7);
        let keys = [s.key()];
        let dir = std::env::temp_dir().join(format!("zc-seen-ro-{}", std::process::id()));
        // A directory where the file should be: reads fail with "is a
        // directory" on load; use a parent that is a regular file instead.
        std::fs::create_dir_all(&dir).unwrap();
        let blocker = dir.join("agent");
        std::fs::write(&blocker, b"not a dir").unwrap();
        let mut h = Handoffs::new(Some(blocker.join("handoff_seen.json")));
        let link = format!(
            "zakuro://share/budget?t={}",
            s.mint(with(
                claims("share/budget", "w1"),
                "args",
                json!({"node_pubkey": NODE_PK})
            ))
        );
        let opened = h.open(&link, &ctx(&keys), &ISSUES);
        let err = match opened {
            Ok(_) => match h.confirm("w1", NOW) {
                Err(ConfirmError::Link(e)) => e,
                other => panic!("expected a storage error, got {other:?}"),
            },
            Err(e) => e,
        };
        assert_eq!((err.status(), err.code()), (500, "storage"));
        let _ = std::fs::remove_dir_all(dir);
    }

    /// The signed-in hub picks the trust roots, not a profile the
    /// LaunchAgent never set (a staging login under a prod default).
    #[test]
    fn the_signed_in_hub_picks_the_link_environment() {
        use crate::profile::Env;
        assert_eq!(
            env_for_api_url(Some(crate::credentials::STAGING_API_URL)),
            Env::Staging
        );
        assert_eq!(
            env_for_api_url(Some(&format!("{}/", crate::credentials::STAGING_API_URL))),
            Env::Staging
        );
        assert_eq!(
            env_for_api_url(Some(crate::credentials::PROD_API_URL)),
            Env::Prod
        );
        let fallback = crate::profile::active().env;
        assert_eq!(env_for_api_url(Some("http://10.0.0.5:8080")), fallback);
        assert_eq!(env_for_api_url(None), fallback);
    }

    #[test]
    fn staging_trusts_its_hub_key_and_prod_trusts_none() {
        use crate::profile::Env;
        let k = trusted_keys(profile_roots(Env::Staging), None).unwrap();
        assert_eq!(k.len(), 1);
        assert_eq!(k[0].kid, "bde74a18996820b2");
        assert!(trusted_keys(profile_roots(Env::Prod), None)
            .unwrap()
            .is_empty());
    }

    /// A token minted by the hub's own code (zak-marketplace
    /// `services/action_tokens.mint`, PyJWT 2.13, seed `[42; 32]`): the
    /// wire format is the hub's, not a re-implementation of it.
    const HUB_PUBKEY: &str = "GX9rI+FshTLGq8g4+s1ep4m+DHaykgM0A5v6iz02jWE=";
    const HUB_TOKEN: &str = "eyJhbGciOiJFZERTQSIsImtpZCI6ImI2MDAzMDZjZmE3NjcyM2YiLCJ0eXAiOiJKV1QifQ.eyJhY3QiOiJzaGFyZS9idWRnZXQiLCJhcmdzIjp7Im5vZGVfcHVia2V5IjoicThYMm4wTHI0bUg2dkI5c0szd1Q3eVAxY0Y1Z0owZFoyYUU0dVI4aU82cz0iLCJwcm9wb3NlZCI6eyJwcmljZV9wZXJfaG91ciI6MTIwfX0sInN1YiI6IjEyMzQ1Njc4OTAiLCJpYXQiOjE3OTk5OTk5OTAsImV4cCI6MTgwMDAwMDU5MCwianRpIjoiNWYwYzlkMWFiMmUzNGY2ZjlhN2MxZDJlM2Y0MDUxNjIiLCJraWQiOiJiNjAwMzA2Y2ZhNzY3MjNmIiwiaXNzIjoiaHR0cHM6Ly9zdGcuaHViLnpha3Vyby1haS5jb20iLCJub2RlIjoiMDEyMzQ1Njc4OWFiY2RlZiJ9.E2RFli4y7gzamjzFPHdAtdT50pjd8sDOLFT574QRPLNT7gNtqj65BqteiQ7-BCWGB3HMpOquSZY0L94modUrAQ";

    #[test]
    fn verifies_a_token_the_hub_minted() {
        let keys = trusted_keys(&[HUB_PUBKEY], None).unwrap();
        assert_eq!(keys[0].kid, "b600306cfa76723f");
        let c = verify(HUB_TOKEN, Act::ShareBudget, &keys, NOW).unwrap();
        assert_eq!(c.jti, "5f0c9d1ab2e34f6f9a7c1d2e3f405162");
        assert_eq!(c.kid.as_deref(), Some("b600306cfa76723f"));
        check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK).unwrap();
        let link = parse_link(&format!("zakuro://share/budget?t={HUB_TOKEN}")).unwrap();
        let p = describe(&link, Some(&c), &ISSUES);
        assert_eq!(p.prefill, Some(json!({"price_per_hour": 120})));
    }
}