cyberbrain 0.6.0

Cited, trust-tiered, local-first memory for AI coding agents
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
//! The hub's HTTP surface. Four routes, and three of them are read-only.
//!
//! Deliberately not the store's API: no recall, no retention, nothing that reaches into a
//! store and changes it. What a client may do here is hand over rows, hand over notes for
//! the bereiche it was granted, and say hello.
//!
//! Notes were added on 2026-09-10 and the sentence above was rewritten rather than left to
//! age into a falsehood. What has not changed: nothing here writes into anybody's store.
//! The hub holds what it was given, for the bereiche a device was granted, and rings 0 and
//! 1 are refused at three separate places — the sender, `ingest_notes`, and a CHECK on the
//! table itself.

use super::{HubStore, LicenceState, Refusal, ingest};
use axum::extract::{ConnectInfo, Form, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{Html, Redirect};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde_json::json;
use std::sync::{Arc, Mutex};

pub struct HubState {
    pub hub: Mutex<HubStore>,
    /// Who is signed in. In memory, so a restart signs everybody out.
    pub sessions: super::admin::Sessions,
    /// The port it is listening on, so the page can suggest an address for invitations.
    pub port: u16,
    /// Where the record lives, so the page can say so and find a licence beside it.
    pub record: std::path::PathBuf,
    /// Whether this surface is encrypted. Not cosmetic: it decides whether a password may
    /// be typed into it from anywhere but the machine itself, and whether the session
    /// cookie is marked `Secure`.
    pub encrypted: bool,
    /// The last thing the page did, shown once on the next render.
    pub flash: Mutex<Option<Result<String, String>>>,
}

pub fn router(state: Arc<HubState>) -> Router {
    Router::new()
        .route("/", get(page))
        .route("/claim", post(claim))
        .route("/login", get(login_page).post(login))
        .route("/logout", get(logout))
        .route("/password", post(change_password))
        .route("/licence", post(install_licence))
        .route("/devices", post(add_device))
        .route("/grants", post(add_grant))
        .route("/grants/{id}/revoke", post(revoke_grant))
        .route("/health", get(health))
        .route("/api/v1/ingest", post(post_ingest))
        .route("/api/v1/enrol", post(post_enrol))
        .route("/api/v1/notes", post(post_notes))
        .route("/api/v1/erase", post(post_erase))
        .route("/api/v1/fetch", post(post_fetch))
        .route("/conflicts", get(get_conflicts))
        .route("/conflicts/{id}", post(post_conflict))
        .route("/requests", get(get_requests).post(post_request))
        .route("/requests/{id}/approve", post(approve))
        .route("/grants/{id}/approve", post(countersign))
        .route("/purges/{id}/approve", post(countersign_purge))
        .route("/api/v1/fleet", get(get_fleet))
        .with_state(state)
}

/// Whether this request came from the machine the hub runs on.
///
/// The page shows who is on the network and can install a licence, and the hub binds an
/// address the whole network can reach. Rather than invent a sign-in for this slice, the
/// rule is that you have to be at the machine: a rule with an obvious shape, which cannot be
/// misconfigured. A networked view can come later behind the admin role that already exists.
pub(crate) fn at_the_machine(who: &std::net::SocketAddr) -> bool {
    who.ip().is_loopback()
}

const ELSEWHERE: &str = "This hub has not been set up yet. Open it on the machine it runs \
     on to set the administrator password. Devices deliver to /api/v1/ingest as usual.";

/// Why a password was refused on an unencrypted hub, and what to do instead.
///
/// It names both ways out, because the operator who reads this may not be the one who can
/// take the second: signing in at the machine works today, a certificate is a change to how
/// the hub is started.
const PLAINTEXT: &str = "This hub is not encrypted, so a password typed here would travel \
     across the network in the clear. Sign in on the machine the hub runs on, or start it \
     with --tls-cert and --tls-key and come back over https (docs/HUB.md). Devices go on \
     delivering to /api/v1/ingest either way.";

/// Whether a password may be typed into this hub from where this request came from.
///
/// Encrypted: from anywhere, which is the entire reason the page has a password. Not
/// encrypted: only from the machine itself, where nothing goes over a wire at all.
fn password_may_travel(state: &HubState, from: &std::net::SocketAddr) -> bool {
    state.encrypted || at_the_machine(from)
}

/// What a caller is allowed to see.
enum Who {
    /// Signed in, or at the machine before anybody has claimed it.
    Admin,
    /// Nobody has set a password yet and this caller is at the machine.
    MayClaim,
    /// Not signed in. Show the door.
    Stranger,
    /// Nobody has set a password and this caller is not at the machine.
    TooEarly,
}

fn who(state: &HubState, headers: &HeaderMap, from: &std::net::SocketAddr) -> Who {
    let claimed = {
        match state.hub.lock() {
            Ok(hub) => super::admin::is_claimed(&hub),
            Err(_) => true, // fail towards asking for a password
        }
    };
    if !claimed {
        // Before there is a password, being at the machine is the credential. Whoever is at
        // the console can read the record with any SQLite tool, so this grants nothing that
        // was not already theirs.
        return if at_the_machine(from) {
            Who::MayClaim
        } else {
            Who::TooEarly
        };
    }
    let cookie =
        super::admin::cookie_from(headers.get(header::COOKIE).and_then(|v| v.to_str().ok()));
    // The role decides, not the mere existence of a session. A principal signs in through
    // the same login and gets the same cookie; asking only whether the cookie was live made
    // every signed-in editor, auditor and countersigner an administrator on every page and
    // form that asks this question — including the one that hands out bereich grants.
    match cookie.and_then(|t| state.sessions.who(&t, jiff::Timestamp::now())) {
        Some(super::admin::Who::Admin) => Who::Admin,
        Some(super::admin::Who::Principal { role, .. }) if role.administers() => Who::Admin,
        _ => Who::Stranger,
    }
}

fn html(body: String) -> Response {
    Html(body).into_response()
}

/// A failed password costs this much time. Not a lockout: locking out the administrator is
/// a way to take a hub away from its own operator. Enough that guessing over a network is
/// hopeless, little enough that a typo is not a punishment.
async fn stumble() {
    tokio::time::sleep(std::time::Duration::from_millis(
        super::admin::FAILURE_DELAY_MS,
    ))
    .await;
}

async fn page(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
) -> Response {
    match who(&state, &headers, &from) {
        Who::Admin => {}
        Who::MayClaim => return html(super::page::claim_page(None)),
        Who::TooEarly => return (StatusCode::FORBIDDEN, ELSEWHERE).into_response(),
        Who::Stranger => {
            // Signed in, just not as the operator: send them to the page that is theirs
            // rather than to a login form they have already filled in.
            return match signed_in(&state, &headers) {
                Some(w) => Redirect::to(home_for(&w)).into_response(),
                None => html(super::page::login_page(None)),
            };
        }
    }
    let hub = match state.hub.lock() {
        Ok(h) => h,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("hub record unavailable: {e}"),
            )
                .into_response();
        }
    };
    // Taken, not read: a message about what just happened should not survive a refresh.
    let flash = state.flash.lock().ok().and_then(|mut f| f.take());
    let view = super::page::View::gather(
        &hub,
        &state.record,
        state.port,
        state.encrypted,
        jiff::Timestamp::now(),
        flash,
    );
    Html(super::page::render(&view)).into_response()
}

#[derive(serde::Deserialize)]
pub struct ClaimForm {
    password: String,
    again: String,
}

/// Set the first password, from the machine itself.
async fn claim(
    State(state): State<Arc<HubState>>,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
    Form(form): Form<ClaimForm>,
) -> Response {
    if !at_the_machine(&from) {
        return (StatusCode::FORBIDDEN, ELSEWHERE).into_response();
    }
    let hub = match state.hub.lock() {
        Ok(h) => h,
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    };
    // Checked again here and not only in the browser: a form is a suggestion, and the
    // second field exists so a typo does not lock somebody out of their own hub.
    if super::admin::is_claimed(&hub) {
        return html(super::page::login_page(Some(
            "This hub already has a password.",
        )));
    }
    if form.password != form.again {
        return html(super::page::claim_page(Some("The two did not match.")));
    }
    match super::admin::set_password(&hub, &form.password) {
        Ok(()) => {
            drop(hub);
            let token = state.sessions.open(jiff::Timestamp::now());
            // Straight in, rather than showing the sign-in form to somebody who has just
            // proved who they are twice.
            (
                [(
                    header::SET_COOKIE,
                    super::admin::set_cookie(&token, state.encrypted),
                )],
                Redirect::to("/"),
            )
                .into_response()
        }
        Err(e) => html(super::page::claim_page(Some(&e))),
    }
}

#[derive(serde::Deserialize)]
pub struct LoginForm {
    password: String,
}

async fn login(
    State(state): State<Arc<HubState>>,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
    Form(form): Form<LoginForm>,
) -> Response {
    // Before the password is looked at, not after: a hub that checks first and refuses
    // afterwards has already been told the password by the time it objects.
    if !password_may_travel(&state, &from) {
        return (StatusCode::FORBIDDEN, PLAINTEXT).into_response();
    }
    // Two kinds of caller arrive at the same box: the administrator with the hub password,
    // and a person with the credential `hub principal add` printed for them. Tried in that
    // order, and the refusal is the same sentence either way — saying which one nearly
    // worked would tell an unknown caller what kind of secret they are holding.
    let who = match state.hub.lock() {
        Ok(hub) => {
            if super::admin::verify(&hub, &form.password) {
                Some(super::admin::Who::Admin)
            } else {
                match hub.principal_by_token(&form.password) {
                    Ok(Some(p)) if p.is_active() => Some(super::admin::Who::Principal {
                        id: p.id.clone(),
                        name: p.name.clone(),
                        role: p.role,
                    }),
                    _ => None,
                }
            }
        }
        Err(_) => None,
    };
    let Some(who) = who else {
        stumble().await;
        return html(super::page::login_page(Some(
            "That is not the password or a credential this hub knows.",
        )));
    };
    let home = home_for(&who);
    let token = state.sessions.open_as(jiff::Timestamp::now(), who);
    (
        [(
            header::SET_COOKIE,
            super::admin::set_cookie(&token, state.encrypted),
        )],
        Redirect::to(home),
    )
        .into_response()
}

/// The sign-in page as a page.
///
/// `/login` was a POST target and nothing else, so the two redirects that send an
/// unauthenticated visitor there answered 405. A person who followed one saw a bare method
/// error from a program that had just decided, correctly, that they should sign in.
async fn login_page() -> Response {
    html(super::page::login_page(None))
}

async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
    if let Some(t) =
        super::admin::cookie_from(headers.get(header::COOKIE).and_then(|v| v.to_str().ok()))
    {
        state.sessions.close(&t);
    }
    (
        [(
            header::SET_COOKIE,
            super::admin::clear_cookie(state.encrypted),
        )],
        Redirect::to("/"),
    )
        .into_response()
}

#[derive(serde::Deserialize)]
pub struct PasswordForm {
    current: String,
    password: String,
    again: String,
}

async fn change_password(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
    Form(form): Form<PasswordForm>,
) -> Response {
    if !matches!(who(&state, &headers, &from), Who::Admin) {
        return html(super::page::login_page(None));
    }
    // The form carries the current password and the new one, so the same rule applies here
    // as at sign-in. Reachable only with a session, which over plain text can only have been
    // opened at the machine — belt and braces, and it costs one comparison.
    if !password_may_travel(&state, &from) {
        return (StatusCode::FORBIDDEN, PLAINTEXT).into_response();
    }
    let outcome = {
        let hub = match state.hub.lock() {
            Ok(h) => h,
            Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
        };
        // The current one, even though the session already proves who this is: a cookie left
        // open on a shared machine should not be enough to change the password on it.
        if !super::admin::verify(&hub, &form.current) {
            Err("The current password is not right.".to_string())
        } else if form.password != form.again {
            Err("The two new ones did not match.".to_string())
        } else {
            super::admin::set_password(&hub, &form.password)
                .map(|()| "The password has been changed.".to_string())
        }
    };
    if outcome.is_err() {
        stumble().await;
    }
    if let Ok(mut f) = state.flash.lock() {
        *f = Some(outcome);
    }
    Redirect::to("/").into_response()
}

#[derive(serde::Deserialize)]
pub struct LicenceForm {
    #[serde(default)]
    text: String,
    #[serde(default)]
    use_found: String,
}

/// Install a licence from the page: the file lying next to the record, or pasted text.
async fn install_licence(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
    Form(form): Form<LicenceForm>,
) -> Response {
    if !matches!(who(&state, &headers, &from), Who::Admin) {
        return html(super::page::login_page(None));
    }
    let outcome = {
        let hub = match state.hub.lock() {
            Ok(h) => h,
            Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
        };
        if form.use_found.is_empty() {
            install_text(&hub, &form.text)
        } else {
            let dir = state
                .record
                .parent()
                .unwrap_or(std::path::Path::new("."))
                .to_path_buf();
            match super::service::adopt_dropped_licence(&hub, &dir) {
                super::service::Dropped::Installed(m) => Ok(m),
                super::service::Dropped::Unchanged => {
                    Ok("That licence is already installed.".into())
                }
                super::service::Dropped::Problem(m) => Err(m),
                super::service::Dropped::None => Err("The file is no longer there.".into()),
            }
        }
    };
    if let Ok(mut f) = state.flash.lock() {
        *f = Some(outcome);
    }
    // Redirect rather than render, so a refresh does not install anything a second time.
    Redirect::to("/").into_response()
}

#[derive(serde::Deserialize)]
pub struct DeviceForm {
    name: String,
    #[serde(default)]
    hub_url: String,
}

/// Register a machine and write its invitation next to the record.
///
/// Written to a file rather than shown on the page: the token is in it, the file is what the
/// other machine needs, and a token read off a screen gets retyped wrongly. The page says
/// where it went; copying a file is something anybody can do.
async fn add_device(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
    Form(form): Form<DeviceForm>,
) -> Response {
    if !matches!(who(&state, &headers, &from), Who::Admin) {
        return html(super::page::login_page(None));
    }
    let outcome = {
        let hub = match state.hub.lock() {
            Ok(h) => h,
            Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
        };
        register(&hub, &state.record, form.name.trim(), form.hub_url.trim())
    };
    if let Ok(mut f) = state.flash.lock() {
        *f = Some(outcome);
    }
    Redirect::to("/").into_response()
}

fn register(
    hub: &HubStore,
    record: &std::path::Path,
    name: &str,
    hub_url: &str,
) -> Result<String, String> {
    if name.is_empty() {
        return Err("A machine needs a name.".into());
    }
    // The same seat check the command does, and for the same reason: a device that is
    // allowed to register and then refused every night looks registered and collects
    // nothing, which is the worst of both.
    let state = LicenceState::read(hub, jiff::Timestamp::now());
    match state.seats() {
        None => return Err(format!("{} No device can be registered.", state.line())),
        Some(seats) => {
            let active = hub.seats_in_use().map_err(|e| e.to_string())?;
            if active >= seats {
                return Err(format!(
                    "The licence covers {seats} seat(s) and {active} are in use. Revoke a \
                     machine that is gone, or extend the licence — its rows are kept either \
                     way."
                ));
            }
        }
    }

    let (device, token) = hub
        .add_device(name, &jiff::Timestamp::now().to_string())
        .map_err(|e| e.to_string())?;
    let invitation = json!({
        "kind": "cyberbrain.hub.invitation",
        "version": 1,
        "device": device.id,
        "name": device.name,
        "token": token,
        "hub_url": if hub_url.is_empty() { serde_json::Value::Null } else { json!(hub_url) },
        "inference_url": serde_json::Value::Null,
    });
    let text = serde_json::to_string_pretty(&invitation).map_err(|e| e.to_string())?;

    let dir = record
        .parent()
        .unwrap_or(std::path::Path::new("."))
        .join("invitations");
    std::fs::create_dir_all(&dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?;
    // Named after the device, not after the person's choice of name, so two machines called
    // "laptop" do not overwrite each other's token.
    let path = dir.join(format!("{}.json", device.id));
    std::fs::write(&path, format!("{text}\n"))
        .map_err(|e| format!("cannot write {}: {e}", path.display()))?;

    Ok(format!(
        "{name} registered. Its invitation is at {} — it carries the token, so hand it over \
         the way you would a password and delete it once that machine is set up.{}",
        path.display(),
        if hub_url.is_empty() {
            " No address was given, so the machine will still have to be told where to \
             deliver."
        } else {
            ""
        }
    ))
}

fn install_text(hub: &HubStore, text: &str) -> Result<String, String> {
    let text = text.trim();
    if text.is_empty() {
        return Err("Nothing was pasted.".into());
    }
    let signed = super::licence::parse(text).map_err(|e| e.to_string())?;
    hub.set_licence(text).map_err(|e| e.to_string())?;
    let l = signed.licence();
    Ok(format!(
        "Installed: {}, {} seat(s), until {}.",
        l.customer, l.seats, l.valid_until
    ))
}

async fn health() -> impl IntoResponse {
    Json(json!({ "role": "hub", "version": env!("CARGO_PKG_VERSION") }))
}

/// Bearer token, or nothing. Deliberately strict about the scheme rather than accepting a
/// bare token as well: two accepted spellings is two things to get wrong later.
fn bearer(headers: &HeaderMap) -> Option<String> {
    let v = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
    v.strip_prefix("Bearer ").map(|t| t.trim().to_string())
}

/// The client's version, for the fleet view. A header rather than part of the bundle: the
/// bundle is evidence and its shape is fixed, while this is operational chatter.
fn client_machine(headers: &HeaderMap) -> Option<String> {
    headers
        .get("x-cyberbrain-machine")?
        .to_str()
        .ok()
        .and_then(super::normalise_machine)
}

fn client_version(headers: &HeaderMap) -> Option<String> {
    headers
        .get("x-cyberbrain-version")?
        .to_str()
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty() && s.len() <= 64)
}

#[derive(serde::Deserialize)]
struct GrantForm {
    device: String,
    bereich: String,
    direction: String,
    reason: String,
}

/// Grant a bereich from the administrator's page. The same checks as the command, because
/// a form is not a second, more forgiving way in: an empty reason is refused here too.
async fn add_grant(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
    Form(form): Form<GrantForm>,
) -> Response {
    if !matches!(who(&state, &headers, &from), Who::Admin) {
        return html(super::page::login_page(None));
    }
    let now = jiff::Timestamp::now().to_string();
    let Ok(hub) = state.hub.lock() else {
        return (StatusCode::INTERNAL_SERVER_ERROR, PLAINTEXT).into_response();
    };
    let problem = (|| -> Result<(), String> {
        cyberbrain_core::frontmatter::validate_bereich(&form.bereich)
            .map_err(|r| format!("bereich: {r}"))?;
        if form.reason.trim().is_empty() {
            return Err("a grant needs a reason: it is what an auditor reads later".into());
        }
        let dir =
            super::sync_access::Direction::parse(&form.direction).map_err(|e| e.to_string())?;
        let id = format!("bg_{}", cyberbrain_core::NoteId::generate());
        hub.grant_bereich(
            &id,
            &form.device,
            &form.bereich,
            dir,
            form.reason.trim(),
            "hub-page",
            &now,
        )
        .map_err(|e| e.to_string())?;
        let _ = hub.record(
            "hub-page",
            "grant.added",
            json!({
                "id": id, "device": form.device, "bereich": form.bereich,
                "direction": dir.as_str(), "reason": form.reason.trim(),
            }),
            &now,
        );
        Ok(())
    })();
    match problem {
        Ok(()) => Redirect::to("/").into_response(),
        Err(e) => (StatusCode::BAD_REQUEST, e).into_response(),
    }
}

async fn revoke_grant(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Response {
    if !matches!(who(&state, &headers, &from), Who::Admin) {
        return html(super::page::login_page(None));
    }
    let now = jiff::Timestamp::now().to_string();
    if let Ok(hub) = state.hub.lock()
        && hub.revoke_grant(&id, &now).unwrap_or(false)
    {
        let _ = hub.record("hub-page", "grant.revoked", json!({ "id": id }), &now);
    }
    Redirect::to("/").into_response()
}

/// Only an editor sees this page, and only their own bereiche. Both halves of that are
/// checked here rather than in the template: a page that decides its own audience is one
/// mistake away from showing everything.
fn signed_in(state: &HubState, headers: &HeaderMap) -> Option<super::admin::Who> {
    // `admin::Who` and the `Who` in this module are different questions: this one is about
    // whose session it is, that one about the page a visitor gets.
    let token =
        super::admin::cookie_from(headers.get(header::COOKIE).and_then(|v| v.to_str().ok()))?;
    state.sessions.who(&token, jiff::Timestamp::now())
}

/// Where somebody belongs after signing in, and where `/` sends them.
///
/// Every role has one page that is theirs. Before this they all landed on `/`, which is the
/// operator's page, so an editor signed in successfully and was shown the login form again —
/// a dead end that looked exactly like a wrong password.
fn home_for(who: &super::admin::Who) -> &'static str {
    use super::access::Role;
    match who {
        super::admin::Who::Admin => "/",
        super::admin::Who::Principal { role, .. } => match role {
            Role::Admin => "/",
            Role::Editor => "/conflicts",
            Role::Auditor | Role::Countersigner => "/requests",
        },
    }
}

fn editor_of(state: &HubState, headers: &HeaderMap) -> Option<(String, String)> {
    match signed_in(state, headers)? {
        super::admin::Who::Principal {
            id,
            name,
            role: super::access::Role::Editor,
        } => Some((id, name)),
        _ => None,
    }
}

async fn get_conflicts(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
    let Some((id, name)) = editor_of(&state, &headers) else {
        return Redirect::to("/login").into_response();
    };
    let Ok(hub) = state.hub.lock() else {
        return (StatusCode::INTERNAL_SERVER_ERROR, PLAINTEXT).into_response();
    };
    match hub.conflicts_for_principal(&id) {
        Ok(list) => Html(super::page::conflicts_page(&name, &list)).into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("cannot read conflicts: {e}"),
        )
            .into_response(),
    }
}

#[derive(serde::Deserialize)]
struct TakeForm {
    take: String,
}

async fn post_conflict(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    axum::extract::Path(cid): axum::extract::Path<String>,
    Form(form): Form<TakeForm>,
) -> Response {
    let Some((pid, pname)) = editor_of(&state, &headers) else {
        return Redirect::to("/login").into_response();
    };
    let now = jiff::Timestamp::now().to_string();
    let Ok(hub) = state.hub.lock() else {
        return (StatusCode::INTERNAL_SERVER_ERROR, PLAINTEXT).into_response();
    };
    // Checked against this person's bereiche, not against the id alone. Otherwise a
    // guessed id would settle a conflict in a department somebody has nothing to do with.
    match hub.conflict_for_principal(&pid, &cid) {
        Ok(Some(_)) => {}
        _ => return Redirect::to("/conflicts").into_response(),
    }
    let take_offered = form.take == "offered";
    if hub
        .resolve_conflict(&cid, take_offered, &now)
        .unwrap_or(false)
    {
        let _ = hub.record(
            &pid,
            "conflict.resolved",
            json!({
                "id": cid,
                "by": pname,
                "took": if take_offered { "offered" } else { "held" },
            }),
            &now,
        );
    }
    Redirect::to("/conflicts").into_response()
}

/// Hand a device the notes it may read. A GET, because it changes nothing here: the hub
/// answers what it holds and the device decides what to keep.
async fn post_fetch(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    body: String,
) -> Response {
    // POST rather than GET only because this is the transport that is already gated,
    // pinned and audited. It changes nothing on the hub.
    let since = serde_json::from_str::<serde_json::Value>(&body)
        .ok()
        .and_then(|v| v.get("since").and_then(|s| s.as_str()).map(str::to_string));
    let token = bearer(&headers);
    let hub = match state.hub.lock() {
        Ok(h) => h,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("hub record unavailable: {e}") })),
            )
                .into_response();
        }
    };
    match super::fetch_notes(&hub, token.as_deref(), since.as_deref()) {
        Ok(f) => (StatusCode::OK, Json(json!(f))).into_response(),
        Err(refusal) => {
            let code = match &refusal {
                Refusal::NotAuthorised(_) => StatusCode::UNAUTHORIZED,
                _ => StatusCode::BAD_REQUEST,
            };
            (code, Json(json!({ "error": refusal.to_string() }))).into_response()
        }
    }
}

/// Erase one note. Not behind the same setting as delivery: withdrawing content must work
/// even where sharing has since been switched off.
async fn post_erase(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    body: String,
) -> Response {
    let token = bearer(&headers);
    let now = jiff::Timestamp::now().to_string();
    let mut hub = match state.hub.lock() {
        Ok(h) => h,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("hub record unavailable: {e}") })),
            )
                .into_response();
        }
    };
    match super::erase_note(&mut hub, token.as_deref(), &body, &now) {
        Ok(c) => (StatusCode::OK, Json(json!(c))).into_response(),
        Err(refusal) => {
            let code = match &refusal {
                Refusal::NotAuthorised(_) => StatusCode::UNAUTHORIZED,
                _ => StatusCode::BAD_REQUEST,
            };
            (code, Json(json!({ "error": refusal.to_string() }))).into_response()
        }
    }
}

/// Take a delivery of notes. Same authentication as `post_ingest`, different cargo, and a
/// per-note answer: a batch is not all-or-nothing, so the sender learns which note it
/// should not have offered instead of only that something was wrong.
async fn post_notes(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    body: String,
) -> Response {
    let token = bearer(&headers);
    let now = jiff::Timestamp::now().to_string();
    let mut hub = match state.hub.lock() {
        Ok(h) => h,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("hub record unavailable: {e}") })),
            )
                .into_response();
        }
    };
    let licence = LicenceState::read(&hub, jiff::Timestamp::now());
    match super::ingest_notes(&mut hub, &licence, token.as_deref(), &body, &now) {
        Ok(a) => (StatusCode::OK, Json(json!(a))).into_response(),
        Err(refusal) => {
            let code = match &refusal {
                Refusal::NotAuthorised(_) => StatusCode::UNAUTHORIZED,
                Refusal::NotCollecting(_) => StatusCode::SERVICE_UNAVAILABLE,
                _ => StatusCode::BAD_REQUEST,
            };
            (code, Json(json!({ "error": refusal.to_string() }))).into_response()
        }
    }
}

async fn post_ingest(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    body: String,
) -> Response {
    let token = bearer(&headers);
    let version = client_version(&headers);
    let machine = client_machine(&headers);
    let now = jiff::Timestamp::now().to_string();

    let mut hub = match state.hub.lock() {
        Ok(h) => h,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("hub record unavailable: {e}") })),
            )
                .into_response();
        }
    };

    // Read per request, not at startup: a licence that lapses while the service runs has to
    // take effect without somebody remembering to restart it.
    let licence = LicenceState::read(&hub, jiff::Timestamp::now());

    match ingest(
        &mut hub,
        &licence,
        token.as_deref(),
        &body,
        version.as_deref(),
        &now,
    ) {
        Ok(a) => {
            // Which machine this device is on, for the seat count. Best effort: a delivery
            // that was taken is not turned into a failure over a name.
            if let Some(m) = &machine {
                let _ = hub.set_machine(&a.device, m);
            }
            (StatusCode::OK, Json(json!(a))).into_response()
        }
        Err(refusal) => {
            // The status code carries the difference the sender has to act on: fix your
            // credentials, fix your file, or send what is missing first.
            let code = match &refusal {
                Refusal::NotAuthorised(_) => StatusCode::UNAUTHORIZED,
                Refusal::BadBundle(_) => StatusCode::BAD_REQUEST,
                Refusal::WrongAnchor { .. } => StatusCode::CONFLICT,
                // 503, not 402: the sender did nothing wrong and should try again later,
                // which is exactly what this code tells every retrying client on earth.
                Refusal::NotCollecting(_) => StatusCode::SERVICE_UNAVAILABLE,
            };
            let mut body = json!({ "error": refusal.to_string() });
            if let Refusal::WrongAnchor { expected, got } = &refusal {
                body["expected_anchor"] = json!(expected);
                body["got_anchor"] = json!(got);
            }
            (code, Json(body)).into_response()
        }
    }
}

/// Who is out there, when they were last heard from, and how far their chain has come.
///
/// No row content: this answers "is the fleet reporting", not "what did people do". The
/// second question has its own path, and in the design it needs two people to walk it.
async fn get_fleet(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    ConnectInfo(from): ConnectInfo<std::net::SocketAddr>,
) -> Response {
    // Device names and when each was last heard from are not row content, but they are still
    // a picture of an organisation, and this had no authentication at all.
    if !matches!(who(&state, &headers, &from), Who::Admin) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "sign in at / first" })),
        )
            .into_response();
    }
    let hub = match state.hub.lock() {
        Ok(h) => h,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("hub record unavailable: {e}") })),
            )
                .into_response();
        }
    };
    match hub.devices() {
        Ok(devices) => (StatusCode::OK, Json(json!({ "devices": devices }))).into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

// ---------------------------------------------------------------------------------------
// The two roles the two-person rule rests on. Before this they had a credential, a login
// box that accepted it, and nowhere to go: approving a request and countersigning a bereich
// were reachable only from a shell on the hub's own machine — the machine whose operator
// they are there to check.

/// The signing view, for a countersigner or an auditor. `None` for anybody else.
fn signer_of(
    state: &HubState,
    headers: &HeaderMap,
) -> Option<(String, String, super::access::Role)> {
    use super::access::Role;
    match signed_in(state, headers)? {
        super::admin::Who::Principal { id, name, role }
            if matches!(role, Role::Auditor | Role::Countersigner) =>
        {
            Some((id, name, role))
        }
        _ => None,
    }
}

async fn get_requests(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
    use super::access::Role;
    let Some((id, name, role)) = signer_of(&state, &headers) else {
        return Redirect::to("/login").into_response();
    };
    let Ok(hub) = state.hub.lock() else {
        return (StatusCode::INTERNAL_SERVER_ERROR, PLAINTEXT).into_response();
    };
    let now = jiff::Timestamp::now();
    let all = hub.requests().unwrap_or_default();
    // An auditor sees their own and nobody else's: the reasons other people wrote are not
    // their business, and a page that lists them would make the reason field unusable.
    let requests: Vec<_> = all
        .into_iter()
        .filter(|r| role == Role::Countersigner || r.requester == id)
        .map(|r| {
            let st = r.state(now);
            (r, st)
        })
        .collect();
    let grants = if role == Role::Countersigner {
        hub.devices()
            .unwrap_or_default()
            .into_iter()
            .filter_map(|d| hub.grants_for_device(&d.id).ok())
            .flatten()
            .filter(|g| g.is_pending())
            .collect()
    } else {
        Vec::new()
    };
    let purges = if role == Role::Countersigner {
        hub.purges()
            .unwrap_or_default()
            .into_iter()
            .filter(|p| p.is_pending())
            .collect()
    } else {
        Vec::new()
    };
    let log = if role == Role::Countersigner {
        hub.hub_events(200).unwrap_or_default()
    } else {
        Vec::new()
    };
    let devices = hub
        .devices()
        .unwrap_or_default()
        .into_iter()
        .filter(|d| d.is_active())
        .map(|d| (d.id, d.name))
        .collect();
    let flash = state.flash.lock().ok().and_then(|mut f| f.take());
    let view = super::page::SigningView {
        name: &name,
        role,
        requests,
        grants,
        purges,
        log,
        devices,
        flash,
    };
    html(super::page::signing_page(&view))
}

/// The second signature on a purge, from the page. Carries it out, like the command does.
async fn countersign_purge(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Response {
    use super::access::Role;
    use super::store::PurgeOutcome as O;
    let Some((_, name, role)) = signer_of(&state, &headers) else {
        return Redirect::to("/login").into_response();
    };
    if role != Role::Countersigner {
        return Redirect::to("/requests").into_response();
    }
    let now = jiff::Timestamp::now().to_string();
    {
        let Ok(hub) = state.hub.lock() else {
            return (StatusCode::INTERNAL_SERVER_ERROR, PLAINTEXT).into_response();
        };
        let token =
            super::admin::cookie_from(headers.get(header::COOKIE).and_then(|v| v.to_str().ok()));
        let Some(who) = session_principal(&state, token.as_deref(), &hub) else {
            return Redirect::to("/login").into_response();
        };
        let message = match hub.countersign_purge(&id, &who, &now) {
            Ok(O::CarriedOut { rows, devices }) => Ok(format!(
                "{id} carried out, countersigned by {name}: {rows} row(s) removed from {} device(s).",
                devices.len()
            )),
            Ok(O::Unknown) => Err(format!("{id}: no purge with that id.")),
            Ok(O::AlreadyDone { by }) => Err(format!(
                "{id} was already carried out, countersigned by {by}."
            )),
            Ok(O::SamePerson) => Err(format!(
                "{id} was proposed by you. Two signatures from one hand are one signature."
            )),
            Err(e) => Err(e.to_string()),
        };
        if let Ok(mut f) = state.flash.lock() {
            *f = Some(message);
        }
    }
    Redirect::to("/requests").into_response()
}

#[derive(serde::Deserialize)]
struct EnrolBody {
    code: String,
    machine: String,
    project: String,
}

/// A machine asking for a device of its own, with the code from a fleet invitation.
///
/// No token: the code is the credential, and only its hash is on record. Every refusal is a
/// reason a person can act on, except an unknown code, which gets the same answer whether it
/// never existed or was withdrawn.
async fn post_enrol(State(state): State<Arc<HubState>>, Json(body): Json<EnrolBody>) -> Response {
    use super::store::EnrolRefusal as R;
    let now = jiff::Timestamp::now();
    let Ok(hub) = state.hub.lock() else {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": "hub record unavailable" })),
        )
            .into_response();
    };
    let licence = LicenceState::read(&hub, now);
    match hub.enrol_with_code(
        &body.code,
        &body.machine,
        &body.project,
        &licence,
        &now.to_string(),
    ) {
        Ok(Ok((device, token))) => (
            StatusCode::OK,
            Json(json!({
                "device": device.id, "name": device.name, "machine": device.machine,
                "token": token, "hub_cert_sha256": super::pin_to_offer(&hub),
            })),
        )
            .into_response(),
        Ok(Err(refusal)) => {
            let status = match &refusal {
                R::UnknownCode => StatusCode::UNAUTHORIZED,
                R::Expired(_) | R::UsedUp(_) => StatusCode::FORBIDDEN,
                R::NotLicensed(_) => StatusCode::SERVICE_UNAVAILABLE,
                R::NoSeat(_) => StatusCode::CONFLICT,
                R::BadRequest(_) => StatusCode::BAD_REQUEST,
            };
            (
                status,
                Json(json!({ "error": refusal.to_string(), "refused": refusal })),
            )
                .into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

#[derive(serde::Deserialize)]
struct AskForm {
    device: String,
    reason: String,
}

async fn post_request(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    Form(form): Form<AskForm>,
) -> Response {
    use super::access::Role;
    let Some((_, _, role)) = signer_of(&state, &headers) else {
        return Redirect::to("/login").into_response();
    };
    if role != Role::Auditor {
        return Redirect::to("/requests").into_response();
    }
    let now = jiff::Timestamp::now().to_string();
    {
        let Ok(hub) = state.hub.lock() else {
            return (StatusCode::INTERNAL_SERVER_ERROR, PLAINTEXT).into_response();
        };
        // Through `principal_for`, not through the session alone: it is the one place that
        // authenticates and checks the role in a single step, and `create_request` wants a
        // `Principal` rather than a name off a cookie.
        let token =
            super::admin::cookie_from(headers.get(header::COOKIE).and_then(|v| v.to_str().ok()));
        let who = match session_principal(&state, token.as_deref(), &hub) {
            Some(p) => p,
            None => return Redirect::to("/login").into_response(),
        };
        let reason = form.reason.trim();
        let outcome = if reason.is_empty() {
            Err(
                "a request needs a reason: it is the only thing the countersigner reads"
                    .to_string(),
            )
        } else {
            let device = (!form.device.trim().is_empty()).then(|| form.device.trim());
            hub.create_request(&who, device, None, None, reason, &now)
                .map(|r| {
                    format!(
                        "Asked. {} is waiting for somebody else to countersign it.",
                        r.id
                    )
                })
                .map_err(|e| e.to_string())
        };
        if let Ok(mut f) = state.flash.lock() {
            *f = Some(outcome);
        }
    }
    Redirect::to("/requests").into_response()
}

/// The `Principal` behind a live session, for the calls that need one.
fn session_principal(
    state: &HubState,
    token: Option<&str>,
    hub: &super::store::HubStore,
) -> Option<super::access::Principal> {
    let who = state.sessions.who(token?, jiff::Timestamp::now())?;
    let super::admin::Who::Principal { id, .. } = who else {
        return None;
    };
    hub.principals().ok()?.into_iter().find(|p| p.id == id)
}

async fn approve(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Response {
    use super::access::Role;
    let Some((_, _, role)) = signer_of(&state, &headers) else {
        return Redirect::to("/login").into_response();
    };
    if role != Role::Countersigner {
        return Redirect::to("/requests").into_response();
    }
    let now = jiff::Timestamp::now();
    {
        let Ok(hub) = state.hub.lock() else {
            return (StatusCode::INTERNAL_SERVER_ERROR, PLAINTEXT).into_response();
        };
        let token =
            super::admin::cookie_from(headers.get(header::COOKIE).and_then(|v| v.to_str().ok()));
        let Some(who) = session_principal(&state, token.as_deref(), &hub) else {
            return Redirect::to("/login").into_response();
        };
        // Seven days, which is the window `hub approve` offers by default. It is a decision
        // with a clock on it: an approval without one is a permanent right nobody granted.
        let until = (now + jiff::Span::new().days(7)).to_string();
        let message = match hub.approve_request(&id, &who, &until, &now.to_string()) {
            Ok(r) => Ok(format!(
                "{} is open until {}.",
                r.id,
                r.expires_at.as_deref().unwrap_or(&until)
            )),
            Err(d) => Err(d.to_string()),
        };
        if let Ok(mut f) = state.flash.lock() {
            *f = Some(message);
        }
    }
    Redirect::to("/requests").into_response()
}

async fn countersign(
    State(state): State<Arc<HubState>>,
    headers: HeaderMap,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Response {
    use super::access::Role;
    use super::store::CountersignOutcome as O;
    let Some((_, name, role)) = signer_of(&state, &headers) else {
        return Redirect::to("/login").into_response();
    };
    if role != Role::Countersigner {
        return Redirect::to("/requests").into_response();
    }
    let now = jiff::Timestamp::now().to_string();
    {
        let Ok(hub) = state.hub.lock() else {
            return (StatusCode::INTERNAL_SERVER_ERROR, PLAINTEXT).into_response();
        };
        let token =
            super::admin::cookie_from(headers.get(header::COOKIE).and_then(|v| v.to_str().ok()));
        let Some(who) = session_principal(&state, token.as_deref(), &hub) else {
            return Redirect::to("/login").into_response();
        };
        // Each outcome is its own sentence, and only one of them is good news. The page
        // colours them apart, which is why they are not flattened into a string here.
        let message = match hub.countersign_grant(&id, &who, &now) {
            Ok(O::Signed) => Ok(format!("{id} takes effect now, countersigned by {name}.")),
            Ok(O::Unknown) => Err(format!("{id}: no grant with that id.")),
            Ok(O::Withdrawn) => Err(format!(
                "{id} was withdrawn. Reviving it is a new decision: it needs a new grant, \
                 with its reason."
            )),
            Ok(O::AlreadySigned { by }) => Err(format!("{id} was already countersigned by {by}.")),
            Ok(O::SamePerson) => Err(format!(
                "{id} was written by you. Two signatures from one hand are one signature."
            )),
            Err(e) => Err(e.to_string()),
        };
        if let Ok(mut f) = state.flash.lock() {
            *f = Some(message);
        }
    }
    Redirect::to("/requests").into_response()
}