vtc-service 0.12.0

Service for Verifiable Trust Communities
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
//! Wallet sign-in started by a trigger link: `auth/oob/{request,claim,prove,
//! respond,redeem,cancel}/0.1` on the signed-document spine.
//!
//! The state, clocks and connection plumbing are
//! [`crate::member_portal::oob`]; this module is the check order of base
//! design §7.3–7.6 (`design-docs/vtc-qr-login-design.md`), with the trigger
//! link contract's changes (C5):
//!
//! - the claim carries `parentThreadId` equal to `payload.requestId`
//!   (VTI-LNK-054);
//! - `identify` is verified against the member's `authentication`
//!   relationship, `grant` against `assertionMethod`;
//! - the step 1 and step 2 responses are signed with this VTC's
//!   `assertionMethod` key.
//!
//! # No ACL pre-filter, and why that is safe
//!
//! Every signer here is a fresh Ed25519 `did:key` no ACL names: the browser's
//! `K_b` (`request`, `redeem`, `cancel`) and the wallet's per-scan `K_a`
//! (`claim`, `prove`, `respond`, `cancel`). [`precheck`] refuses any other
//! key before the spine verifies a proof (T21). Authority comes only from
//! the documents a member's DID signs inside `prove` and `respond`, and only
//! the holder of `K_b` can turn the result into a session.
//!
//! # Which session: member portal or operator console
//!
//! A request is a member-portal sign-in unless the starter asks otherwise in
//! `ext["org.openvtc.session"].audience` (`"admin"`: the operator console's
//! login page). `purpose` stays `login`, the only value `auth/oob/0.1`
//! defines. The audience is fixed at `request`, stored on the record, and
//! repeated by the VTC under the same `ext` member in the signed step 1 and
//! step 2 responses, so the grant's `contextDigest` covers it: an approval
//! given for one audience cannot be redeemed as the other. A member request's
//! responses carry no extension, exactly as before. Each audience has its own
//! gate — an active member for the portal, an administrator in the ACL for the
//! console — and `redeem` issues that audience's session and never the other
//! (T19).
//!
//! # Transports
//!
//! `request` needs the browser's `Origin` (T19), address and `User-Agent`, and
//! `redeem` sets cookies, so both are served only on the HTTPS door, which
//! supplies an [`HttpContext`]. The wallet's tasks travel on any transport
//! this spine serves; `sameNetwork` is `"unknown"` off HTTPS.

use serde::Serialize;
use serde_json::{Value, json};
use trust_tasks_rs::{RejectReason, StandardCode, TrustTask, TrustTaskCode};
use vti_common::audit::{AuditEvent, MemberWalletSignInData};
use vti_common::auth::session::{
    Session, SessionState, now_epoch, store_refresh_index, store_session,
};

use super::JoinAuthCtx;
use super::helpers::{
    TrustTaskOutcome, extended_code, parse_payload, reject_with, reject_with_code, success_response,
};
use crate::member_portal::oob::types::{
    CANCEL_TYPE, CLAIM_TYPE, CancelPayload, CancelResponse, ClaimPayload, GRANT_TYPE,
    GrantDecision, GrantPayload, IDENTIFY_TYPE, IdentifyPayload, PROVE_TYPE, ProvePayload,
    REDEEM_TYPE, REQUEST_TYPE, RESPOND_TYPE, RedeemPayload, RedeemResponse, RequestPayload,
    RequestResponse, RespondPayload, RespondResponse, Step1, Step2,
};
use crate::member_portal::oob::{
    self, CLAIM_WINDOW_SECS, DECISION_WINDOW_SECS, HttpContext, MAX_PENDING_PER_ADDRESS,
    NOT_AN_ADMIN, NOTIFIER, OobRequest, OobState, PollGuard, PollRefused, RequesterDetails,
    SessionAudience, TransitionError,
};
use crate::member_portal::{MemberAuthBackend, active_member, cookies};
use crate::server::AppState;

/// Exactly what [`dispatch`] routes. `identify` and `grant` are not here: they
/// are only ever carried inside `prove` and `respond`, and one sent by itself
/// is refused as an unsupported type.
pub(crate) const URIS: &[&str] = &[
    REQUEST_TYPE,
    CLAIM_TYPE,
    PROVE_TYPE,
    RESPOND_TYPE,
    REDEEM_TYPE,
    CANCEL_TYPE,
];

/// A declared error code: `auth/oob/<task>:<local>` for the codes one task
/// declares, `auth/oob:<local>` for the family's shared ones (the published
/// `auth/oob` specifications, dtgwg-trust-tasks-tf `feat/auth-oob`).
// TODO: replace with generated trust-tasks types (their `error_codes`).
fn code(task: &str, local: &str) -> TrustTaskCode {
    const TASK_CODES: &[(&str, &str)] = &[
        ("claim", "alreadyClaimed"),
        ("prove", "numberMismatch"),
        ("redeem", "declined"),
        ("redeem", "pending"),
        ("request", "modeUnsupported"),
        ("request", "purposeUnsupported"),
        ("respond", "contextMismatch"),
    ];
    if TASK_CODES.contains(&(task, local)) {
        extended_code(&format!("auth/oob/{task}:{local}"))
    } else {
        extended_code(&format!("auth/oob:{local}"))
    }
}

fn task_of(type_uri: &str) -> &'static str {
    match type_uri {
        REQUEST_TYPE => "request",
        CLAIM_TYPE => "claim",
        PROVE_TYPE => "prove",
        RESPOND_TYPE => "respond",
        REDEEM_TYPE => "redeem",
        _ => "cancel",
    }
}

/// Run before the spine verifies the proof of an `auth/oob` document: the
/// signer must be an Ed25519 `did:key` (T21, decided from the identifier
/// alone; `auth/oob:keyUnsupported`). `None` lets the document through. The
/// proof and recipient requirements are the specifications' own, enforced by
/// the spine from `spec_policy_for` like any other published task.
pub(super) fn precheck(doc: &TrustTask<Value>, type_uri: &str) -> Option<TrustTaskOutcome> {
    if !URIS.contains(&type_uri) {
        return None;
    }
    let task = task_of(type_uri);
    if !doc.issuer.as_deref().is_some_and(oob::is_ed25519_did_key) {
        return Some(reject_with_code(
            doc,
            code(task, "keyUnsupported"),
            "the issuer must be an Ed25519 did:key generated for this exchange",
            None,
        ));
    }
    None
}

pub(super) async fn dispatch(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
    type_uri: &str,
) -> Option<TrustTaskOutcome> {
    // The spine verified the proof against `issuer`; `precheck` required one.
    let signer = ctx.verified_signer.clone().unwrap_or_default();
    Some(match type_uri {
        REQUEST_TYPE => handle_request(state, doc, signer).await,
        CLAIM_TYPE => handle_claim(state, doc, signer).await,
        PROVE_TYPE => handle_prove(state, doc, signer).await,
        RESPOND_TYPE => handle_respond(state, doc, signer).await,
        REDEEM_TYPE => handle_redeem(state, doc, signer).await,
        CANCEL_TYPE => handle_cancel(state, doc, signer).await,
        _ => return None,
    })
}

// ── Shared ──────────────────────────────────────────────────────────────────

async fn audit(
    state: &AppState,
    actor: &str,
    stage: &str,
    rec: &OobRequest,
    member: Option<&str>,
    reason: Option<&str>,
    grant: Option<Value>,
) {
    let Some(writer) = state.audit_writer.as_ref() else {
        tracing::warn!(
            stage,
            "audit writer not configured; wallet sign-in step not audited"
        );
        return;
    };
    let data = MemberWalletSignInData {
        stage: stage.into(),
        request_id: rec.request_id.clone(),
        member: member.map(str::to_string),
        reason: reason.map(str::to_string),
        location: Some(rec.requester.location.clone()),
        grant,
    };
    // An operator-console sign-in is its own event, so an audit reader
    // filtering for console access sees it beside the other console logins.
    let event = match rec.audience {
        SessionAudience::Member => AuditEvent::MemberWalletSignIn(data),
        SessionAudience::Admin => AuditEvent::AdminWalletSignIn(data),
    };
    if let Err(e) = writer.write(actor, member, event).await {
        tracing::warn!(stage, error = %e, "could not audit a wallet sign-in step");
    }
}

/// The `requestId` a wallet document is about: `parentThreadId` when the
/// document carries one, else the carried document's own `payload.requestId`
/// — only a lookup key here; every check below compares against the record.
fn request_id_hint(doc: &TrustTask<Value>, carried: &Value) -> Option<String> {
    doc.parent_thread_id.clone().or_else(|| {
        carried
            .get("payload")
            .and_then(|p| p.get("requestId"))
            .and_then(Value::as_str)
            .map(str::to_string)
    })
}

/// Build a generated `auth/oob` type from the JSON this module assembles. The
/// generated types are `#[non_exhaustive]` and validate their members' patterns,
/// so going through JSON is how a value is constructed and checked against the
/// specification at once. A failure is this service's own bug, never the
/// caller's, so it is an internal error.
fn wire<T: serde::de::DeserializeOwned>(
    doc: &TrustTask<Value>,
    what: &str,
    value: Value,
) -> Result<T, TrustTaskOutcome> {
    serde_json::from_value(value).map_err(|e| {
        reject_with(
            doc,
            RejectReason::InternalError {
                reason: format!("{what} does not match its specification: {e}"),
            },
        )
    })
}

/// Sign a success payload as this VTC's attestation (`assertionMethod`), and
/// return the signed document with the outcome carrying it.
async fn attested<R: Serialize>(
    state: &AppState,
    doc: &TrustTask<Value>,
    payload: R,
) -> Result<(Value, TrustTaskOutcome), TrustTaskOutcome> {
    let internal = |reason: String| reject_with(doc, RejectReason::InternalError { reason });
    let Some(signer) = state.credential_signer.clone() else {
        return Err(internal(
            "this community has no signing key, so it cannot sign the sign-in response".into(),
        ));
    };
    let unsigned = success_response(doc, payload);
    let mut value: Value =
        serde_json::from_slice(&unsigned.body).map_err(|e| internal(e.to_string()))?;
    signer
        .sign_attested_response(&mut value)
        .await
        .map_err(|e| internal(e.to_string()))?;
    let body = serde_json::to_vec(&value).map_err(|e| internal(e.to_string()))?;
    Ok((
        value,
        TrustTaskOutcome {
            status: axum::http::StatusCode::OK,
            body,
        },
    ))
}

fn not_found(doc: &TrustTask<Value>, task: &str) -> TrustTaskOutcome {
    reject_with_code(
        doc,
        code(task, "requestNotFound"),
        "no such sign-in request",
        None,
    )
}

fn expired(doc: &TrustTask<Value>, task: &str) -> TrustTaskOutcome {
    reject_with_code(
        doc,
        code(task, "requestExpired"),
        "this sign-in request has expired; refresh the code on the website and scan again",
        None,
    )
}

/// The one refusal for a non-member, a bad signature, a stale or replayed
/// carried document, or a mismatched lock (T15): which of them failed is not
/// the caller's to learn.
fn not_authorized(doc: &TrustTask<Value>, task: &str) -> TrustTaskOutcome {
    reject_with_code(
        doc,
        code(task, "notAuthorized"),
        "this sign-in was not authorised",
        None,
    )
}

/// The message an identity that is not an administrator gets, on the
/// wallet's side (`prove`, `respond`) and the console's (`redeem`).
const NOT_AN_ADMIN_MESSAGE: &str = "This identity isn't an administrator of this community.";

/// The refusal for an operator-console sign-in by an identity that has
/// proved it holds its DID but is not an administrator. The family's
/// generic `notAuthorized` code, with `details.reason` saying why.
fn not_an_admin(doc: &TrustTask<Value>, task: &str) -> TrustTaskOutcome {
    reject_with_code(
        doc,
        code(task, "notAuthorized"),
        NOT_AN_ADMIN_MESSAGE,
        Some(json!({ "reason": NOT_AN_ADMIN })),
    )
}

/// Whether `did` may open an operator-console session: the check every
/// console sign-in makes ([`crate::acl::resolve_auth_role`] — a live,
/// unexpired ACL entry with an administrative role). Read now, never from a
/// session.
async fn is_administrator(state: &AppState, did: &str) -> Result<bool, crate::error::AppError> {
    match crate::acl::resolve_auth_role(&state.acl_ks, did).await {
        Ok(_) => Ok(true),
        Err(crate::error::AppError::Forbidden(_)) => Ok(false),
        Err(e) => Err(e),
    }
}

/// End a request as declined after a failed step from the lock holder — one
/// attempt per request (base design §7.2). Only from `from`; a request some
/// other caller already moved on is left alone.
async fn decline(
    state: &AppState,
    rec: &OobRequest,
    from: OobState,
    member: Option<&str>,
    reason: &str,
) {
    decline_telling(state, rec, from, member, reason, None).await;
}

/// [`decline`], recording a reason `redeem` passes on to the starter
/// (`details.reason`). Only for a reason the identity that signed has
/// already proved it holds — today [`NOT_AN_ADMIN`] — never one that would
/// tell a bystander anything about someone else's DID (T15).
async fn decline_telling(
    state: &AppState,
    rec: &OobRequest,
    from: OobState,
    member: Option<&str>,
    reason: &str,
    starter_reason: Option<&str>,
) {
    let now = now_epoch();
    let lock = rec.approver_key.clone();
    let res = oob::transition(&state.member_sessions_ks, &rec.request_id, |r| {
        if r.state != from || r.approver_key != lock {
            return Err(());
        }
        r.decline_reason = starter_reason.map(str::to_string);
        r.end(OobState::Declined, now);
        Ok(())
    })
    .await;
    if let Ok((_, ended)) = res {
        // The operator's half of the story: the wire answer stays the
        // deliberately vague `notAuthorized` (T15), and until this line the
        // reason reached only the audit log, so a refused sign-in could not be
        // diagnosed from the service log at all. The request id and the stage
        // are enough to find the audit row; no DID is logged here, as no other
        // line in this module logs one.
        tracing::info!(
            request_id = %rec.request_id,
            stage = from.as_str(),
            audience = ?rec.audience,
            reason,
            "wallet sign-in declined"
        );
        let actor = lock.as_deref().unwrap_or("unknown");
        audit(
            state,
            actor,
            "proofFailed",
            &ended,
            member,
            Some(reason),
            None,
        )
        .await;
    }
}

/// A carried, member-signed document, checked as the spine checks an outer
/// one: its type, its recipient, its age, its `id` not seen before, and a
/// proof by its own issuer made for `purpose`. Returns the parsed document.
///
/// The caller has already checked the issuer string against the ACL — before
/// this resolves anything (T15).
async fn verify_carried(
    state: &AppState,
    received: &Value,
    expected_type: &str,
    issuer: &str,
    purpose: vti_common::auth::ProofPurpose,
) -> Result<TrustTask<Value>, &'static str> {
    let inner: TrustTask<Value> =
        serde_json::from_value(received.clone()).map_err(|_| "not a Trust Task document")?;
    if inner.type_uri.to_string() != expected_type {
        return Err("wrong carried document type");
    }
    if inner.issuer.as_deref() != Some(issuer) {
        return Err("carried document issuer mismatch");
    }
    let now = chrono::Utc::now();
    let vtc_did = state.config.read().await.vtc_did.clone();
    let Some(vtc_did) = vtc_did else {
        return Err("community DID not configured");
    };
    if inner.recipient.as_deref() != Some(vtc_did.as_str()) {
        return Err("carried document not addressed to this community");
    }
    inner
        .validate_freshness(now, &super::freshness_policy())
        .map_err(|_| "carried document is stale")?;
    let declared = inner
        .proof
        .as_ref()
        .map(|p| p.proof_purpose.clone())
        .ok_or("carried document is unsigned")?;
    if declared != purpose.as_str() {
        return Err("carried document signed for the wrong purpose");
    }
    let signer = match purpose {
        vti_common::auth::ProofPurpose::AssertionMethod => {
            super::helpers::verify_received_approval_proof(state, received, expected_type).await
        }
        _ => super::helpers::verify_received_trust_task_proof(state, received).await,
    }
    .map_err(|_| "carried document proof does not verify")?;
    if signer != issuer {
        return Err("carried document signed by another DID");
    }
    // Replay of the carried document's own `id` (T7), in the same record the
    // spine keeps for outer documents.
    match state
        .accepted_ids()
        .claim(&inner, super::retain_until(&inner, now), now)
        .await
    {
        Ok(super::accepted_ids::Acceptance::Fresh(claim)) => {
            claim.completed(None).await;
            Ok(inner)
        }
        _ => Err("carried document replayed"),
    }
}

// ── request ─────────────────────────────────────────────────────────────────

async fn handle_request(
    state: &AppState,
    doc: TrustTask<Value>,
    start_key: String,
) -> TrustTaskOutcome {
    let Some(http) = HttpContext::current() else {
        return reject_with_code(
            &doc,
            TrustTaskCode::Standard(StandardCode::PermissionDenied),
            "auth/oob/request is accepted only over HTTPS from the member portal",
            None,
        );
    };
    // A purpose or mode this service does not serve has its own code (auth/oob/
    // request 0.1), so it is read before the generated payload, whose enums
    // would refuse it as malformed.
    let raw = |k: &str| {
        doc.payload
            .get(k)
            .and_then(Value::as_str)
            .map(str::to_string)
    };
    if let Some(purpose) = raw("purpose").filter(|p| p != "login") {
        return reject_with_code(
            &doc,
            code("request", "purposeUnsupported"),
            format!("purpose `{purpose}` is not served; v1 serves `login`"),
            None,
        );
    }
    if let Some(mode) = raw("mode").filter(|m| m != "scan") {
        return reject_with_code(
            &doc,
            code("request", "modeUnsupported"),
            format!("mode `{mode}` is not served; v1 serves `scan`"),
            None,
        );
    }
    let payload: RequestPayload = match parse_payload(&doc) {
        Ok(p) => p,
        Err(e) => return e,
    };
    // Which session the page asks for (`ext["org.openvtc.session"]`); none
    // is the member portal's, as before the extension existed.
    let audience = match SessionAudience::from_ext(doc.payload.get("ext")) {
        Ok(a) => a,
        Err(message) => {
            return reject_with_code(
                &doc,
                TrustTaskCode::Standard(StandardCode::MalformedRequest),
                message,
                None,
            );
        }
    };
    let (public_url, vtc_did) = {
        let cfg = state.config.read().await;
        (cfg.public_url.clone(), cfg.vtc_did.clone())
    };
    if vtc_did.is_none() {
        return reject_with_code(
            &doc,
            TrustTaskCode::Standard(StandardCode::Unavailable),
            "this community has not finished setting up",
            None,
        );
    }
    // T19: only the portal's own page may open a request, so another website
    // cannot start one through the member's browser. The operator console is
    // served from the same origin (`/admin/` beside `/members/`), and the
    // origin is what the wallet checks against the `SignInPortal` service.
    let origin = match (
        oob::portal_origin(public_url.as_deref(), &http),
        http.origin.as_deref(),
    ) {
        (Some(portal), Some(sent)) if portal == sent => portal,
        _ => {
            return reject_with_code(
                &doc,
                TrustTaskCode::Standard(StandardCode::PermissionDenied),
                "auth/oob/request is accepted only from this community's own origin \
                 (the member portal and operator console)",
                None,
            );
        }
    };
    let address = http.client_ip.to_string();
    match oob::open_requests_from(&state.member_sessions_ks, &address).await {
        Ok(n) if n >= MAX_PENDING_PER_ADDRESS => {
            return reject_with_code(
                &doc,
                code("request", "rateLimited"),
                "too many sign-in codes are open from this network; use one or wait for it to expire",
                None,
            );
        }
        Ok(_) => {}
        Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
    }

    let now = now_epoch();
    let (browser, os) = oob::browser_and_os(http.user_agent.as_deref());
    let rec = OobRequest {
        request_id: oob::new_request_id(),
        state: OobState::Pending,
        start_key: start_key.clone(),
        start_network: Some(address),
        approver_key: None,
        purpose: payload.purpose.to_string(),
        mode: payload.mode.to_string(),
        origin,
        match_number: None,
        match_number_delivered: false,
        requester: RequesterDetails {
            // From the local GeoIP database only (base design §12.6);
            // `"unknown"` the wallet shows as a warning, not as neutral.
            location: state
                .geoip
                .locate(http.client_ip)
                .unwrap_or_else(|| "unknown".into()),
            browser,
            os,
            created_at: oob::rfc3339(now),
        },
        identified_did: None,
        step2_digest: None,
        step1: None,
        created_at: now,
        claim_deadline: now + CLAIM_WINDOW_SECS,
        decision_deadline: None,
        grant: None,
        ended_at: None,
        audience,
        decline_reason: None,
    };
    if let Err(e) = oob::create(&state.member_sessions_ks, &rec).await {
        return super::helpers::app_error_to_reject(&doc, &e);
    }
    audit(state, &start_key, "requested", &rec, None, None, None).await;
    let response: RequestResponse = match wire(&doc, "the request response", {
        let mut r =
            serde_json::json!({ "requestId": rec.request_id, "claimDeadline": rec.claim_deadline });
        // Echoed for an operator-console request, so the page knows this
        // VTC read the extension: a VTC that predates it carries `ext`
        // through unread and would open a member sign-in instead.
        if let Some(ext) = audience.to_ext() {
            r["ext"] = ext;
        }
        r
    }) {
        Ok(r) => r,
        Err(e) => return e,
    };
    success_response(&doc, response)
}

// ── claim ───────────────────────────────────────────────────────────────────

async fn handle_claim(
    state: &AppState,
    doc: TrustTask<Value>,
    approver: String,
) -> TrustTaskOutcome {
    let payload: ClaimPayload = match parse_payload(&doc) {
        Ok(p) => p,
        Err(e) => return e,
    };
    // VTI-LNK-054: the first request carries the handle as `parentThreadId`.
    if doc.parent_thread_id.as_deref() != Some(payload.request_id.as_str()) {
        return reject_with_code(
            &doc,
            TrustTaskCode::Standard(StandardCode::MalformedRequest),
            "parentThreadId must equal payload.requestId (VTI-LNK-054)",
            None,
        );
    }
    let ks = &state.member_sessions_ks;
    let rec = match oob::load(ks, &payload.request_id).await {
        Ok(Some(r)) => r,
        Ok(None) => return not_found(&doc, "claim"),
        Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
    };
    let now = now_epoch();
    match rec.effective_state(now) {
        OobState::Pending => {}
        OobState::Expired => {
            if let Ok(true) = oob::settle_expiry(ks, &rec.request_id).await {
                audit(state, &approver, "expired", &rec, None, None, None).await;
            }
            return expired(&doc, "claim");
        }
        // No details: the bystander learns nothing about who holds it (T3).
        _ => {
            return reject_with_code(
                &doc,
                code("claim", "alreadyClaimed"),
                "this code was already used by another device",
                None,
            );
        }
    }

    let (vtc_did, vtc_name, profile) = {
        let cfg = state.config.read().await;
        let did = cfg.vtc_did.clone().unwrap_or_default();
        let name = cfg.vtc_name.clone();
        drop(cfg);
        let profile = crate::community::load_profile(&state.community_ks)
            .await
            .ok()
            .flatten();
        (did, name, profile)
    };
    let decision_deadline = now + DECISION_WINDOW_SECS;
    // The schema requires a name: the profile's, the configured one, else
    // the DID itself.
    let service_name: String = profile
        .map(|p| p.name)
        .filter(|n| !n.is_empty())
        .or(vtc_name.filter(|n| !n.is_empty()))
        .unwrap_or_else(|| vtc_did.chars().take(128).collect());
    let step1_json = serde_json::json!({
        "requestId": rec.request_id,
        "service": { "did": vtc_did, "name": service_name },
        "origin": rec.origin,
        "purpose": rec.purpose,
        "decisionDeadline": decision_deadline,
    });
    // The audience, signed: the wallet can say "operator console", and step 2
    // repeats it so the grant's `contextDigest` binds it. None for a member
    // sign-in, whose step 1 is unchanged.
    let mut step1_json = step1_json;
    if let Some(ext) = rec.audience.to_ext() {
        step1_json["ext"] = ext;
    }
    let step1: Step1 = match wire(&doc, "step 1", step1_json.clone()) {
        Ok(s) => s,
        Err(e) => return e,
    };
    // Signed before the lock is taken, so a request is never claimed with no
    // response to show for it.
    let (_, outcome) = match attested(state, &doc, &step1).await {
        Ok(signed) => signed,
        Err(e) => return e,
    };
    let number = oob::new_match_number();
    let res = oob::transition(ks, &rec.request_id, |r| {
        if r.effective_state(now_epoch()) != OobState::Pending {
            return Err(());
        }
        r.state = OobState::Claimed;
        r.approver_key = Some(approver.clone());
        r.match_number = Some(number.clone());
        r.decision_deadline = Some(decision_deadline);
        r.step1 = Some(step1_json.clone());
        Ok(())
    })
    .await;
    match res {
        Ok((_, claimed)) => {
            audit(state, &approver, "claimed", &claimed, None, None, None).await;
            outcome
        }
        Err(TransitionError::Store(e)) => super::helpers::app_error_to_reject(&doc, &e),
        Err(TransitionError::NotFound) => not_found(&doc, "claim"),
        Err(TransitionError::Refused(())) => reject_with_code(
            &doc,
            code("claim", "alreadyClaimed"),
            "this code was already used by another device",
            None,
        ),
    }
}

// ── prove ───────────────────────────────────────────────────────────────────

async fn handle_prove(
    state: &AppState,
    doc: TrustTask<Value>,
    approver: String,
) -> TrustTaskOutcome {
    let payload: ProvePayload = match parse_payload(&doc) {
        Ok(p) => p,
        Err(e) => return e,
    };
    let identify = Value::Object(payload.identify);
    let Some(request_id) = request_id_hint(&doc, &identify) else {
        return not_found(&doc, "prove");
    };
    let ks = &state.member_sessions_ks;
    let rec = match oob::load(ks, &request_id).await {
        Ok(Some(r)) => r,
        Ok(None) => return not_found(&doc, "prove"),
        Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
    };

    // 1. The outer document is the lock holder's, and the request is claimed
    //    and inside its decision window. A stranger's failure changes nothing.
    if rec.approver_key.as_deref() != Some(approver.as_str()) {
        return reject_with_code(
            &doc,
            code("prove", "notClaimant"),
            "this device does not hold this sign-in request",
            None,
        );
    }
    match rec.effective_state(now_epoch()) {
        OobState::Claimed => {}
        OobState::Expired => {
            if let Ok(true) = oob::settle_expiry(ks, &rec.request_id).await {
                audit(state, &approver, "expired", &rec, None, None, None).await;
            }
            return expired(&doc, "prove");
        }
        // One proof attempt per request.
        _ => return not_authorized(&doc, "prove"),
    }

    // From here every failure declines the request (base design §7.4).
    let fail = |member: Option<String>, reason: &'static str| {
        let rec = rec.clone();
        async move {
            decline(state, &rec, OobState::Claimed, member.as_deref(), reason).await;
        }
    };

    // 2. The carried identify names this request and this lock.
    let identify_issuer = identify
        .get("issuer")
        .and_then(Value::as_str)
        .map(str::to_string);
    let identify_payload: Option<IdentifyPayload> = identify
        .get("payload")
        .cloned()
        .and_then(|p| serde_json::from_value(p).ok());
    let (Some(member), Some(identify_payload)) = (identify_issuer, identify_payload) else {
        fail(None, "identify is malformed").await;
        return not_authorized(&doc, "prove");
    };
    if identify_payload.request_id.as_str() != rec.request_id
        || identify_payload.approver_key.as_str() != approver
    {
        fail(Some(member), "identify names another request or lock").await;
        return not_authorized(&doc, "prove");
    }

    // 3. The issuer string is someone this community knows — read from the
    //    ACL and member records, before any DID is resolved (T15). For the
    //    portal, an active member. For the console, an active member or an
    //    administrator: a member who is not an administrator is let through
    //    to the signature check only so that, once they have proved the DID
    //    is theirs, they can be told why they cannot sign in (step 5a). A DID
    //    the community does not know at all is refused here, unresolved.
    let known = match rec.audience {
        SessionAudience::Member => active_member(state, &member).await.map(|m| m.is_some()),
        SessionAudience::Admin => match is_administrator(state, &member).await {
            Ok(true) => Ok(true),
            Ok(false) => active_member(state, &member).await.map(|m| m.is_some()),
            Err(e) => Err(e),
        },
    };
    match known {
        Ok(true) => {}
        Ok(false) => {
            fail(Some(member), "not an active member").await;
            return not_authorized(&doc, "prove");
        }
        Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
    }

    // 4. The proof verifies against the member's `authentication` key
    //    (contract C5); recipient, freshness and replay as for any document.
    if let Err(reason) = verify_carried(
        state,
        &identify,
        IDENTIFY_TYPE,
        &member,
        vti_common::auth::ProofPurpose::Authentication,
    )
    .await
    {
        tracing::info!(reason, "auth/oob/prove: identify refused");
        fail(Some(member), reason).await;
        return not_authorized(&doc, "prove");
    }

    // 5. The number the member typed.
    if Some(identify_payload.entered_number.as_str()) != rec.match_number.as_deref() {
        fail(Some(member), "wrong number").await;
        return reject_with_code(
            &doc,
            code("prove", "numberMismatch"),
            "that is not the number on the screen; refresh the code on the website and scan again",
            None,
        );
    }

    // 5a. The console's gate: an administrator in the ACL, by the same check
    //     every console sign-in makes. The DID has proved it is theirs, so
    //     saying why is no oracle about anyone else (T15), and the browser
    //     that started it is told too (`redeem`'s `details.reason`).
    if rec.audience == SessionAudience::Admin {
        match is_administrator(state, &member).await {
            Ok(true) => {}
            Ok(false) => {
                decline_telling(
                    state,
                    &rec,
                    OobState::Claimed,
                    Some(&member),
                    "not an administrator",
                    Some(NOT_AN_ADMIN),
                )
                .await;
                return not_an_admin(&doc, "prove");
            }
            Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
        }
    }

    // 6. Step 2: step 1 repeated, plus the starter.
    let Some(step1) = rec.step1.clone() else {
        return reject_with(
            &doc,
            RejectReason::InternalError {
                reason: "claimed request has no step 1".into(),
            },
        );
    };
    let approver_ip = HttpContext::current().map(|h| h.client_ip);
    // Step 1 as stored, `ext` included: the audience is inside what the
    // grant's `contextDigest` covers.
    let Value::Object(mut step2_json) = step1 else {
        return reject_with(
            &doc,
            RejectReason::InternalError {
                reason: "stored step 1 is not an object".into(),
            },
        );
    };
    step2_json.insert("sessionKey".into(), Value::String(rec.start_key.clone()));
    step2_json.insert(
        "requester".into(),
        serde_json::json!({
            "location": rec.requester.location,
            "browser": rec.requester.browser,
            "os": rec.requester.os,
            "createdAt": rec.requester.created_at,
            "sameNetwork": oob::same_network(rec.start_network.as_deref(), approver_ip),
        }),
    );
    step2_json.insert("identifiedAs".into(), Value::String(member.clone()));
    let step2: Step2 = match wire(&doc, "step 2", Value::Object(step2_json)) {
        Ok(s) => s,
        Err(e) => return e,
    };
    let (signed, outcome) = match attested(state, &doc, &step2).await {
        Ok(s) => s,
        Err(e) => return e,
    };
    let digest = match oob::context_digest(&signed) {
        Ok(d) => d,
        Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
    };
    let res = oob::transition(ks, &rec.request_id, |r| {
        if r.effective_state(now_epoch()) != OobState::Claimed
            || r.approver_key.as_deref() != Some(approver.as_str())
        {
            return Err(());
        }
        r.state = OobState::Identified;
        r.identified_did = Some(member.clone());
        r.step2_digest = Some(digest.clone());
        Ok(())
    })
    .await;
    match res {
        Ok((_, identified)) => {
            audit(
                state,
                &member,
                "proved",
                &identified,
                Some(&member),
                None,
                None,
            )
            .await;
            outcome
        }
        Err(TransitionError::Store(e)) => super::helpers::app_error_to_reject(&doc, &e),
        Err(_) => expired(&doc, "prove"),
    }
}

// ── respond ─────────────────────────────────────────────────────────────────

async fn handle_respond(
    state: &AppState,
    doc: TrustTask<Value>,
    approver: String,
) -> TrustTaskOutcome {
    let payload: RespondPayload = match parse_payload(&doc) {
        Ok(p) => p,
        Err(e) => return e,
    };
    let grant_doc = Value::Object(payload.grant);
    let Some(request_id) = request_id_hint(&doc, &grant_doc) else {
        return not_found(&doc, "respond");
    };
    let ks = &state.member_sessions_ks;
    let rec = match oob::load(ks, &request_id).await {
        Ok(Some(r)) => r,
        Ok(None) => return not_found(&doc, "respond"),
        Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
    };

    // 1. The lock holder, an identified request, inside the decision window.
    if rec.approver_key.as_deref() != Some(approver.as_str()) {
        return reject_with_code(
            &doc,
            code("respond", "notClaimant"),
            "this device does not hold this sign-in request",
            None,
        );
    }
    match rec.effective_state(now_epoch()) {
        OobState::Identified => {}
        OobState::Expired => {
            if let Ok(true) = oob::settle_expiry(ks, &rec.request_id).await {
                audit(state, &approver, "expired", &rec, None, None, None).await;
            }
            return expired(&doc, "respond");
        }
        OobState::Claimed => return not_authorized(&doc, "respond"),
        _ => {
            return reject_with_code(
                &doc,
                code("respond", "alreadyDecided"),
                "this sign-in request has already been decided",
                None,
            );
        }
    }
    let Some(member) = rec.identified_did.clone() else {
        return not_authorized(&doc, "respond");
    };
    let fail = |reason: &'static str| {
        let rec = rec.clone();
        let member = member.clone();
        async move {
            decline(state, &rec, OobState::Identified, Some(&member), reason).await;
        }
    };

    // 2. The grant is the identified DID's, signed for `assertionMethod`,
    //    fresh, and new.
    if grant_doc.get("issuer").and_then(Value::as_str) != Some(member.as_str()) {
        fail("grant from another identity").await;
        return not_authorized(&doc, "respond");
    }
    if let Err(reason) = verify_carried(
        state,
        &grant_doc,
        GRANT_TYPE,
        &member,
        vti_common::auth::ProofPurpose::AssertionMethod,
    )
    .await
    {
        tracing::info!(reason, "auth/oob/respond: grant refused");
        fail(reason).await;
        return not_authorized(&doc, "respond");
    }
    let grant: GrantPayload = match grant_doc
        .get("payload")
        .cloned()
        .map(serde_json::from_value)
    {
        Some(Ok(g)) => g,
        _ => {
            fail("grant payload is malformed").await;
            return not_authorized(&doc, "respond");
        }
    };

    // 3–4. The lock, the browser key, the origin and the context it was shown.
    let context_ok = grant.request_id.as_str() == rec.request_id
        && grant.approver_key.as_str() == approver
        && grant.session_key.as_str() == rec.start_key
        && grant.origin.as_str() == rec.origin
        && rec
            .step2_digest
            .as_deref()
            .is_some_and(|d| oob::same_digest(d, &grant.context_digest));
    if !context_ok {
        fail("grant context mismatch").await;
        return reject_with_code(
            &doc,
            code("respond", "contextMismatch"),
            "the grant does not match this sign-in request",
            None,
        );
    }
    let decision = match grant.decision {
        GrantDecision::Approve => OobState::Approved,
        GrantDecision::Decline => OobState::Declined,
        _ => {
            fail("unknown decision").await;
            return not_authorized(&doc, "respond");
        }
    };
    if decision == OobState::Approved {
        let not_after = grant.not_after;
        if not_after <= now_epoch() {
            fail("grant notAfter has passed").await;
            return not_authorized(&doc, "respond");
        }
        // 5. Still a member — or, for the console, still an administrator.
        match rec.audience {
            SessionAudience::Member => match active_member(state, &member).await {
                Ok(Some(_)) => {}
                Ok(None) => {
                    fail("no longer an active member").await;
                    return not_authorized(&doc, "respond");
                }
                Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
            },
            SessionAudience::Admin => match is_administrator(state, &member).await {
                Ok(true) => {}
                Ok(false) => {
                    decline_telling(
                        state,
                        &rec,
                        OobState::Identified,
                        Some(&member),
                        "no longer an administrator",
                        Some(NOT_AN_ADMIN),
                    )
                    .await;
                    return not_an_admin(&doc, "respond");
                }
                Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
            },
        }
    }

    // 6. Decide, once.
    let signed_grant = grant_doc.clone();
    let now = now_epoch();
    let res = oob::transition(ks, &rec.request_id, |r| {
        if r.effective_state(now) != OobState::Identified
            || r.approver_key.as_deref() != Some(approver.as_str())
        {
            return Err(());
        }
        r.grant = Some(signed_grant.clone());
        if decision == OobState::Declined {
            r.end(OobState::Declined, now);
        } else {
            r.state = OobState::Approved;
        }
        Ok(())
    })
    .await;
    match res {
        Ok((_, decided)) => {
            let stage = if decision == OobState::Approved {
                "approved"
            } else {
                "declined"
            };
            audit(
                state,
                &member,
                stage,
                &decided,
                Some(&member),
                None,
                Some(signed_grant),
            )
            .await;
            // Signed like steps 1 and 2: every reply to the wallet is this
            // community's attestation, and the wallet refuses one that is not.
            let r: RespondResponse = match wire(
                &doc,
                "the respond response",
                serde_json::json!({ "status": stage }),
            ) {
                Ok(r) => r,
                Err(e) => return e,
            };
            match attested(state, &doc, &r).await {
                Ok((_, outcome)) => outcome,
                Err(e) => e,
            }
        }
        Err(TransitionError::Store(e)) => super::helpers::app_error_to_reject(&doc, &e),
        Err(_) => reject_with_code(
            &doc,
            code("respond", "alreadyDecided"),
            "this sign-in request has already been decided",
            None,
        ),
    }
}

// ── cancel ──────────────────────────────────────────────────────────────────

async fn handle_cancel(
    state: &AppState,
    doc: TrustTask<Value>,
    signer: String,
) -> TrustTaskOutcome {
    let payload: CancelPayload = match parse_payload(&doc) {
        Ok(p) => p,
        Err(e) => return e,
    };
    let ks = &state.member_sessions_ks;
    let now = now_epoch();
    let res = oob::transition(ks, &payload.request_id, |r| {
        if r.start_key != signer && r.approver_key.as_deref() != Some(signer.as_str()) {
            return Err("notAuthorized");
        }
        if r.state.is_final() {
            return Err("alreadyDecided");
        }
        if r.effective_state(now) == OobState::Expired {
            r.end(OobState::Expired, now);
            return Ok(OobState::Expired);
        }
        r.end(OobState::Cancelled, now);
        Ok(OobState::Cancelled)
    })
    .await;
    match res {
        Ok((OobState::Cancelled, rec)) => {
            audit(
                state,
                &signer,
                "cancelled",
                &rec,
                rec.identified_did.as_deref(),
                None,
                None,
            )
            .await;
            // Signed like steps 1 and 2: every reply to the wallet is this
            // community's attestation, and the wallet refuses one that is not.
            let r: CancelResponse = match wire(
                &doc,
                "the cancel response",
                serde_json::json!({ "status": "cancelled" }),
            ) {
                Ok(r) => r,
                Err(e) => return e,
            };
            match attested(state, &doc, &r).await {
                Ok((_, outcome)) => outcome,
                Err(e) => e,
            }
        }
        Ok((_, rec)) => {
            audit(state, &signer, "expired", &rec, None, None, None).await;
            expired(&doc, "cancel")
        }
        Err(TransitionError::NotFound) => not_found(&doc, "cancel"),
        Err(TransitionError::Store(e)) => super::helpers::app_error_to_reject(&doc, &e),
        Err(TransitionError::Refused("notAuthorized")) => not_authorized(&doc, "cancel"),
        Err(TransitionError::Refused(local)) => reject_with_code(
            &doc,
            code("cancel", local),
            "this sign-in request has already ended",
            None,
        ),
    }
}

// ── redeem ──────────────────────────────────────────────────────────────────

fn pending(doc: &TrustTask<Value>, rec: &OobRequest, now: u64) -> TrustTaskOutcome {
    let state = rec.effective_state(now);
    let mut details = json!({ "state": state.as_str() });
    // Only the holder of K_b ever receives the number (T16).
    if let Some(n) = &rec.match_number {
        details["matchNumber"] = Value::String(n.clone());
    }
    reject_with_code(
        doc,
        code("redeem", "pending"),
        "waiting for the wallet; poll again",
        Some(details),
    )
}

/// `redeem`'s `declined`, with `details.reason` when the starter is told why
/// (only [`NOT_AN_ADMIN`] today).
fn declined(doc: &TrustTask<Value>, reason: Option<&str>) -> TrustTaskOutcome {
    let mut details = json!({ "state": "declined" });
    let message = match reason {
        Some(r) => {
            details["reason"] = Value::String(r.to_string());
            if r == NOT_AN_ADMIN {
                NOT_AN_ADMIN_MESSAGE
            } else {
                "the sign-in was declined"
            }
        }
        None => "the sign-in was declined",
    };
    reject_with_code(doc, code("redeem", "declined"), message, Some(details))
}

async fn handle_redeem(
    state: &AppState,
    doc: TrustTask<Value>,
    starter: String,
) -> TrustTaskOutcome {
    let Some(http) = HttpContext::current() else {
        return reject_with_code(
            &doc,
            TrustTaskCode::Standard(StandardCode::PermissionDenied),
            "auth/oob/redeem is served only over HTTPS, where the session is set as cookies",
            None,
        );
    };
    let payload: RedeemPayload = match parse_payload(&doc) {
        Ok(p) => p,
        Err(e) => return e,
    };
    let ks = &state.member_sessions_ks;
    let rec = match oob::load(ks, &payload.request_id).await {
        Ok(Some(r)) => r,
        Ok(None) => return not_found(&doc, "redeem"),
        Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
    };
    if rec.start_key != starter {
        return reject_with_code(
            &doc,
            code("redeem", "notStarter"),
            "only the browser that started this sign-in can redeem it",
            None,
        );
    }

    let _poll = match PollGuard::open(&rec.request_id, http.client_ip) {
        Ok(g) => Some(g),
        // A second poll on one request answers at once rather than holding.
        Err(PollRefused::AlreadyOpen) => None,
        Err(PollRefused::AddressCap) => {
            return reject_with_code(
                &doc,
                code("redeem", "rateLimited"),
                "too many sign-in polls are open from this network",
                None,
            );
        }
    };
    let deadline = tokio::time::Instant::now() + oob::redeem_hold();
    let entry_state = rec.effective_state(now_epoch());

    loop {
        let notify = NOTIFIER.handle(&rec.request_id);
        let notified = notify.notified();
        tokio::pin!(notified);
        notified.as_mut().enable();

        let current = match oob::load(ks, &rec.request_id).await {
            Ok(Some(r)) => r,
            Ok(None) => return not_found(&doc, "redeem"),
            Err(e) => return super::helpers::app_error_to_reject(&doc, &e),
        };
        let now = now_epoch();
        match current.effective_state(now) {
            OobState::Approved => return redeem_approved(state, &doc, &http, &current).await,
            OobState::Consumed => {
                return reject_with_code(
                    &doc,
                    code("redeem", "alreadyDecided"),
                    "this sign-in has already been used",
                    None,
                );
            }
            OobState::Declined => return declined(&doc, current.decline_reason.as_deref()),
            // Contract C9: `declined`, with the state saying why.
            OobState::Cancelled => {
                return reject_with_code(
                    &doc,
                    code("redeem", "declined"),
                    "the sign-in was cancelled",
                    Some(json!({ "state": "cancelled" })),
                );
            }
            OobState::Expired => {
                if let Ok(true) = oob::settle_expiry(ks, &current.request_id).await {
                    audit(state, &starter, "expired", &current, None, None, None).await;
                }
                return expired(&doc, "redeem");
            }
            s @ (OobState::Pending | OobState::Claimed | OobState::Identified) => {
                let number_owed = s == OobState::Claimed && !current.match_number_delivered;
                if s != entry_state || number_owed || _poll.is_none() {
                    if current.match_number.is_some() && !current.match_number_delivered {
                        let _ = oob::transition(ks, &current.request_id, |r| {
                            r.match_number_delivered = true;
                            Ok::<_, ()>(())
                        })
                        .await;
                    }
                    return pending(&doc, &current, now);
                }
            }
        }
        if tokio::time::timeout_at(deadline, notified).await.is_err() {
            let current = match oob::load(ks, &rec.request_id).await {
                Ok(Some(r)) => r,
                _ => return not_found(&doc, "redeem"),
            };
            return pending(&doc, &current, now_epoch());
        }
    }
}

/// `approved → consumed` once, then the session the request asked for:
/// subject the DID that signed the grant, session key `K_b`,
/// `amr = ["did", "oob", "uv"]`.
///
/// - **Member portal:** a member session, ending at the earlier of the
///   grant's `notAfter` and the member session limit.
/// - **Operator console:** the console session every console sign-in issues
///   ([`crate::routes::auth::mint_admin_cookie_session`]), for a DID the ACL
///   holds as an administrator now, ending no later than the grant's
///   `notAfter`.
///
/// Either way the grant's `notAfter` is stored as the session's absolute end
/// ([`vti_common::auth::session::Session::not_after`]): refresh rotates the
/// tokens inside it and refuses once it has passed, so the member's approval
/// bounds the whole session, not only its first window. The `notAfter`
/// reported here is the session's true end. Anyone else is `declined` with
///   `details.reason: notAnAdmin`, and the request stays spent.
///
/// Never the other audience's session (T19).
async fn redeem_approved(
    state: &AppState,
    doc: &TrustTask<Value>,
    http: &HttpContext,
    rec: &OobRequest,
) -> TrustTaskOutcome {
    let ks = &state.member_sessions_ks;
    let now = now_epoch();
    let res = oob::transition(ks, &rec.request_id, |r| {
        if r.effective_state(now) != OobState::Approved {
            return Err(());
        }
        r.end(OobState::Consumed, now);
        Ok(())
    })
    .await;
    let consumed = match res {
        Ok((_, r)) => r,
        Err(TransitionError::Store(e)) => return super::helpers::app_error_to_reject(doc, &e),
        Err(_) => {
            return reject_with_code(
                doc,
                code("redeem", "alreadyDecided"),
                "this sign-in has already been used",
                None,
            );
        }
    };
    let Some(subject) = consumed.identified_did.clone() else {
        return not_authorized(doc, "redeem");
    };
    // The session issued is the one the member approved: the audience on the
    // record must be the one signed into step 1, which step 2 repeats and the
    // grant's `contextDigest` covers. They are written once and never apart,
    // so a difference means the record was altered; issue nothing.
    if consumed.signed_audience() != Some(consumed.audience) {
        tracing::error!(
            request_id = %consumed.request_id,
            security_alert = true,
            "auth/oob/redeem: the stored audience differs from the one the member approved"
        );
        audit(
            state,
            &subject,
            "proofFailed",
            &consumed,
            Some(&subject),
            Some("audience differs from the approved one"),
            None,
        )
        .await;
        return not_authorized(doc, "redeem");
    }
    let not_after = consumed
        .grant
        .as_ref()
        .and_then(|g| g.get("payload"))
        .and_then(|p| p.get("notAfter"))
        .and_then(oob::epoch_of)
        .unwrap_or(now);
    if not_after <= now {
        return not_authorized(doc, "redeem");
    }
    match consumed.audience {
        SessionAudience::Member => {
            redeem_member(state, doc, http, &consumed, subject, not_after).await
        }
        SessionAudience::Admin => {
            redeem_admin(state, doc, http, &consumed, subject, not_after).await
        }
    }
}

async fn redeem_member(
    state: &AppState,
    doc: &TrustTask<Value>,
    http: &HttpContext,
    consumed: &OobRequest,
    member_did: String,
    not_after: u64,
) -> TrustTaskOutcome {
    // Membership again, now (T18).
    let member = match active_member(state, &member_did).await {
        Ok(Some(m)) => m,
        Ok(None) => return not_authorized(doc, "redeem"),
        Err(e) => return super::helpers::app_error_to_reject(doc, &e),
    };
    match mint_session(state, &member_did, &consumed.start_key, not_after).await {
        Ok((_session_id, session_end, set)) => {
            http.set_cookies(set);
            audit(
                state,
                &member_did,
                "redeemed",
                consumed,
                Some(&member_did),
                None,
                None,
            )
            .await;
            let display_name: String = member
                .entry
                .label
                .clone()
                .filter(|l| !l.is_empty())
                .unwrap_or_else(|| member_did.chars().take(128).collect());
            match wire::<RedeemResponse>(
                doc,
                "the redeem response",
                serde_json::json!({
                    "subject": member_did,
                    "displayName": display_name,
                    "notAfter": session_end,
                    "amr": amr(),
                }),
            ) {
                Ok(r) => success_response(doc, r),
                Err(e) => e,
            }
        }
        Err(e) => super::helpers::app_error_to_reject(doc, &e),
    }
}

async fn redeem_admin(
    state: &AppState,
    doc: &TrustTask<Value>,
    http: &HttpContext,
    consumed: &OobRequest,
    admin_did: String,
    not_after: u64,
) -> TrustTaskOutcome {
    // Administrator again, now: an entry removed or narrowed since the
    // approval opens no console. The request is already spent.
    match is_administrator(state, &admin_did).await {
        Ok(true) => {}
        Ok(false) => {
            audit(
                state,
                &admin_did,
                "declined",
                consumed,
                Some(&admin_did),
                Some(NOT_AN_ADMIN),
                None,
            )
            .await;
            return declined(doc, Some(NOT_AN_ADMIN));
        }
        Err(e) => return super::helpers::app_error_to_reject(doc, &e),
    }
    let session_key = oob::did_key_multikey(&consumed.start_key).map(str::to_string);
    let minted = match crate::routes::auth::mint_admin_cookie_session(
        state,
        &admin_did,
        &["did", "oob", "uv"],
        session_key,
        Some(not_after),
    )
    .await
    {
        Ok(m) => m,
        // Removed between the check above and the mint.
        Err(crate::error::AppError::Forbidden(_)) => return declined(doc, Some(NOT_AN_ADMIN)),
        Err(e) => return super::helpers::app_error_to_reject(doc, &e),
    };
    http.set_cookies(minted.cookies);
    audit(
        state,
        &admin_did,
        "redeemed",
        consumed,
        Some(&admin_did),
        None,
        None,
    )
    .await;
    let label = crate::acl::get_acl_entry(&state.acl_ks, &admin_did)
        .await
        .ok()
        .flatten()
        .and_then(|e| e.label)
        .filter(|l| !l.is_empty());
    let display_name = label.unwrap_or_else(|| admin_did.chars().take(128).collect());
    match wire::<RedeemResponse>(
        doc,
        "the redeem response",
        serde_json::json!({
            // Says which session this is, so the console's page can refuse
            // to carry on if it ever got anything else.
            "ext": SessionAudience::Admin.to_ext(),
            "subject": admin_did,
            "displayName": display_name,
            "notAfter": minted.minted.refresh_expires_at,
            "amr": amr(),
        }),
    ) {
        Ok(r) => success_response(doc, r),
        Err(e) => e,
    }
}

fn amr() -> Vec<String> {
    vec!["did".into(), "oob".into(), "uv".into()]
}

/// Create the member session and the cookies that carry it, through the same
/// backend, keyspace and cookie shapes as every portal sign-in
/// (`crate::member_portal`).
async fn mint_session(
    state: &AppState,
    did: &str,
    session_key: &str,
    not_after: u64,
) -> Result<(String, u64, Vec<String>), crate::error::AppError> {
    let backend = MemberAuthBackend::from_state(state).await?;
    let session_id = uuid::Uuid::new_v4().to_string();
    let amr = amr();
    let acr = "aal2".to_string();
    // The grant's `notAfter` bounds the session: both tokens are minted to
    // end by it, and it is stored as the session's absolute end, so refresh
    // rotation (`handle_refresh`) cannot extend it either.
    let minted = vti_common::auth::handlers::mint_session_tokens_until(
        &backend,
        did,
        &session_id,
        &crate::acl::Role::Reader,
        &[],
        &amr,
        &acr,
        false,
        Some(not_after),
    )
    .await?;
    let refresh_expires_at = minted.refresh_expires_at;
    let access_expires_at = minted.access_expires_at;
    store_session(
        &state.member_sessions_ks,
        &Session {
            session_id: session_id.clone(),
            did: did.to_string(),
            challenge: String::new(),
            state: SessionState::Authenticated,
            created_at: minted.issued_at,
            last_seen: minted.issued_at,
            refresh_token: Some(minted.refresh_token.clone()),
            refresh_expires_at: Some(refresh_expires_at),
            tee_attested: false,
            amr,
            acr,
            acr_expires_at: None,
            token_id: Some(minted.token_id.clone()),
            session_pubkey_b58btc: oob::did_key_multikey(session_key).map(str::to_string),
            not_after: Some(not_after),
        },
    )
    .await?;
    store_refresh_index(
        &state.member_sessions_ks,
        &minted.refresh_token,
        &session_id,
    )
    .await?;
    let now = now_epoch();
    let access_max_age = access_expires_at.saturating_sub(now).max(1);
    let refresh_max_age = refresh_expires_at.saturating_sub(now).max(1);
    Ok((
        session_id,
        refresh_expires_at,
        vec![
            cookies::session_cookie(&minted.access_token, access_max_age),
            cookies::refresh_cookie(&minted.refresh_token, refresh_max_age),
            cookies::csrf_cookie(&cookies::new_csrf(), refresh_max_age),
        ],
    ))
}