aidaemon-nodes 0.27.3

Nodes for aidaemon agents: enrolled hardware companions with server-issued identity, their HTTP Gateway, store, OTA releases, speech, monitoring and the tools that read and command them; implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
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
use std::sync::Arc;
use std::time::Duration;
use std::{collections::HashMap, time::Instant};

use axum::body::{Body, Bytes};
use axum::extract::{DefaultBodyLimit, Path, Query, State};
use axum::http::{HeaderMap, Request, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post, put};
use axum::{Json, Router};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use tokio::io::AsyncWriteExt;

use crate::config::NodesConfig;
use aidaemon_channels::hub::ChannelHub;

use super::domain::NODE_CHANNEL_NAME;
use super::protocol::*;
use super::service::{NodeConversationIngress, NodeService};

#[derive(Clone)]
pub struct NodeGatewayState {
    pub service: Arc<NodeService>,
    pub ingress: Arc<dyn NodeConversationIngress>,
    pub hub: Arc<ChannelHub>,
    pub config: NodesConfig,
    pub rate_limiter: Arc<NodeRateLimiter>,
}

/// Per-minute budgets. Nodes that signed in are counted by their id in a
/// map of their own; what anyone can send before signing in (offer and
/// credential ids it names itself) is counted apart, so names made up in
/// bulk never touch a signed-in Node's budget. Before signing in, each
/// source address has budgets of its own: per id it names, and in all
/// (`UNAUTHENTICATED_IDS_PER_SOURCE` times one id's), so one machine making
/// up names can neither go past its budget nor push another machine's
/// windows out. A full map makes room by dropping its oldest window, never
/// by refusing everyone.
#[derive(Default)]
pub struct NodeRateLimiter {
    windows: tokio::sync::Mutex<HashMap<(String, &'static str), RateWindow>>,
    unauthenticated: tokio::sync::Mutex<HashMap<std::net::IpAddr, SourceWindows>>,
    /// Whether the visitor address Cloudflare's edge names is believed
    /// ([`Self::trusting_cloudflare`]); off by default.
    trusts_cloudflare: bool,
}

/// One source address's windows before signing in.
#[derive(Default)]
struct SourceWindows {
    /// Everything this source sent, per bucket.
    total: HashMap<&'static str, RateWindow>,
    /// Per id it named, per bucket.
    ids: HashMap<(String, &'static str), RateWindow>,
    last_seen: Option<Instant>,
}

struct RateWindow {
    started: Instant,
    units: u64,
}

impl NodeRateLimiter {
    const MAX_WINDOWS: usize = 4096;

    /// Count requests before sign-in by the visitor address Cloudflare's
    /// edge names (`cf-connecting-ip`). Only for a Node Gateway published
    /// through the Cloudflare adapter: through any other tunnel the client
    /// writes those headers itself, and a new made-up address per request
    /// would get a fresh budget each time and push real sources' windows
    /// out.
    pub fn trusting_cloudflare(mut self) -> Self {
        self.trusts_cloudflare = true;
        self
    }

    /// Count `units` against a signed-in Node's (`identity`) budget.
    async fn consume(
        &self,
        identity: &str,
        bucket: &'static str,
        units: u64,
        limit: u64,
    ) -> Result<(), GatewayError> {
        Self::take(
            &mut *self.windows.lock().await,
            (identity.to_string(), bucket),
            units,
            limit,
            Self::MAX_WINDOWS,
        )
    }

    /// Source addresses tracked before signing in.
    const MAX_SOURCES: usize = 1024;
    /// Ids one source may name in a minute, per bucket, as a multiple of
    /// one id's budget: its budget in all. Also bounds the ids one source
    /// keeps windows for.
    const UNAUTHENTICATED_IDS_PER_SOURCE: u64 = 4;

    /// Count `units` against a name a request made before signing in gives
    /// itself (an offer or credential id), from `source` (the address it
    /// came from).
    async fn consume_unauthenticated(
        &self,
        source: std::net::IpAddr,
        identity: &str,
        bucket: &'static str,
        units: u64,
        limit: u64,
    ) -> Result<(), GatewayError> {
        if limit == 0 {
            return Err(GatewayError::rate_limited());
        }
        let mut sources = self.unauthenticated.lock().await;
        if sources.len() >= Self::MAX_SOURCES && !sources.contains_key(&source) {
            let stale = |s: &SourceWindows| {
                s.last_seen
                    .is_none_or(|seen| seen.elapsed() >= Duration::from_secs(60))
            };
            sources.retain(|_, s| !stale(s));
            if sources.len() >= Self::MAX_SOURCES
                && let Some(oldest) = sources
                    .iter()
                    .min_by_key(|(_, s)| s.last_seen)
                    .map(|(ip, _)| *ip)
            {
                sources.remove(&oldest);
            }
        }
        let windows = sources.entry(source).or_default();
        windows.last_seen = Some(Instant::now());
        let total_limit = limit.saturating_mul(Self::UNAUTHENTICATED_IDS_PER_SOURCE);
        // Check both before spending either.
        let key = (identity.to_string(), bucket);
        let fresh = |w: Option<&RateWindow>| {
            w.filter(|w| w.started.elapsed() < Duration::from_secs(60))
                .map_or(0, |w| w.units)
        };
        if fresh(windows.total.get(bucket)).saturating_add(units) > total_limit
            || fresh(windows.ids.get(&key)).saturating_add(units) > limit
        {
            return Err(GatewayError::rate_limited());
        }
        let id_cap = usize::try_from(total_limit).unwrap_or(usize::MAX).max(1);
        Self::take(
            &mut windows.total,
            bucket,
            units,
            total_limit,
            Self::MAX_WINDOWS,
        )?;
        Self::take(&mut windows.ids, key, units, limit, id_cap)
    }

    /// Spend `units` of `key`'s window in `windows` (at most `max` of
    /// them: a full map drops its oldest window).
    fn take<K: Clone + Eq + std::hash::Hash>(
        windows: &mut HashMap<K, RateWindow>,
        key: K,
        units: u64,
        limit: u64,
        max: usize,
    ) -> Result<(), GatewayError> {
        if limit == 0 {
            return Err(GatewayError::rate_limited());
        }
        if windows.len() >= max && !windows.contains_key(&key) {
            windows.retain(|_, window| window.started.elapsed() < Duration::from_secs(60));
            if windows.len() >= max
                && let Some(oldest) = windows
                    .iter()
                    .min_by_key(|(_, window)| window.started)
                    .map(|(key, _)| key.clone())
            {
                windows.remove(&oldest);
            }
        }
        let window = windows.entry(key).or_insert_with(|| RateWindow {
            started: Instant::now(),
            units: 0,
        });
        if window.started.elapsed() >= Duration::from_secs(60) {
            window.started = Instant::now();
            window.units = 0;
        }
        if window.units.saturating_add(units) > limit {
            return Err(GatewayError::rate_limited());
        }
        window.units = window.units.saturating_add(units);
        Ok(())
    }
}

/// The address a request made before signing in is counted against: the
/// local-network peer, or, when the gateway is published through
/// Cloudflare (`trust_cloudflare`), the visitor its edge names (it sets
/// `cf-connecting-ip` itself, an HTTP header name), or else this computer
/// (a loopback request, or one through any other tunnel).
fn request_source(
    lan_peer: Option<&axum::Extension<crate::lan::LanPeer>>,
    headers: &HeaderMap,
    trust_cloudflare: bool,
) -> std::net::IpAddr {
    if let Some(peer) = lan_peer {
        return peer.0.0;
    }
    if trust_cloudflare
        && headers.contains_key("cf-ray")
        && let Some(ip) = headers
            .get("cf-connecting-ip")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.trim().parse().ok())
    {
        return ip;
    }
    std::net::IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)
}

async fn rate_limit_authenticated_request(
    state: &NodeGatewayState,
    node_id: &str,
) -> Result<(), GatewayError> {
    state
        .rate_limiter
        .consume(
            node_id,
            "requests",
            1,
            u64::from(state.config.limits.requests_per_minute),
        )
        .await
}

#[derive(Debug)]
struct GatewayError {
    status: StatusCode,
    code: &'static str,
    message: String,
    retryable: bool,
}

impl GatewayError {
    fn bad_request(error: impl std::fmt::Display) -> Self {
        Self {
            status: StatusCode::BAD_REQUEST,
            code: "invalid_request",
            message: error.to_string(),
            retryable: false,
        }
    }
    fn unauthorized(error: impl std::fmt::Display) -> Self {
        Self {
            status: StatusCode::UNAUTHORIZED,
            code: "authentication_failed",
            message: error.to_string(),
            retryable: false,
        }
    }
    fn forbidden(error: impl std::fmt::Display) -> Self {
        Self {
            status: StatusCode::FORBIDDEN,
            code: "not_authorized",
            message: error.to_string(),
            retryable: false,
        }
    }
    fn internal(error: impl std::fmt::Display) -> Self {
        tracing::warn!(error = %error, "Node Gateway request failed");
        Self {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            code: "internal_error",
            message: "The Node Gateway could not complete the request".to_string(),
            retryable: true,
        }
    }
    fn rate_limited() -> Self {
        Self {
            status: StatusCode::TOO_MANY_REQUESTS,
            code: "rate_limited",
            message: "Node request rate exceeded the server limit".to_string(),
            retryable: true,
        }
    }
}

impl IntoResponse for GatewayError {
    fn into_response(self) -> Response {
        (
            self.status,
            Json(ProtocolErrorBody {
                error: ProtocolError {
                    code: self.code.to_string(),
                    message: self.message,
                    retryable: self.retryable,
                    request_id: None,
                },
            }),
        )
            .into_response()
    }
}

pub fn router(state: NodeGatewayState) -> Router {
    let limit = state.config.limits.control_message_bytes;
    Router::new()
        .route("/node/v1/enrollments/redeem", post(redeem))
        .route("/node/v1/sessions/challenge", post(challenge))
        .route("/node/v1/sessions", post(open_session))
        .route(
            "/node/v1/credentials/rotation-challenge",
            post(credential_rotation_challenge),
        )
        .route("/node/v1/credentials/rotate", post(rotate_credential))
        .route("/node/v1/heartbeats", post(heartbeat))
        .route("/node/v1/sensor-readings", post(report_sensor_readings))
        .route("/node/v1/outbox", get(node_outbox))
        .route("/node/v1/outbox/{cursor}/ack", post(ack_node_outbox))
        .route("/node/v1/turns", post(create_turn))
        .route("/node/v1/firmware/{release_id}", get(download_firmware))
        .route("/node/v1/uploads/{slot_id}", put(upload_media))
        .route("/node/v1/turns/{turn_id}/commit", post(commit_turn))
        .route("/node/v1/media/{media_id}", get(download_media))
        .route("/node/v1/turns/{turn_id}/events", get(turn_events))
        .route("/node/v1/turns/{turn_id}/cancel", post(cancel_turn))
        .layer(DefaultBodyLimit::max(
            limit
                .max(state.config.limits.audio_upload_bytes)
                .max(state.config.limits.image_upload_bytes),
        ))
        .layer(middleware::from_fn(security_headers))
        .with_state(state)
}

pub async fn serve(state: NodeGatewayState) -> anyhow::Result<()> {
    let bind: std::net::IpAddr = state.config.gateway.bind.parse()?;
    anyhow::ensure!(
        bind.is_loopback(),
        "Node Gateway bind address must be loopback"
    );
    let address = std::net::SocketAddr::new(bind, state.config.gateway.port);
    let listener = tokio::net::TcpListener::bind(address).await?;
    tracing::info!(%address, "Node Gateway listening");
    axum::serve(listener, router(state)).await?;
    Ok(())
}

async fn security_headers(request: Request<Body>, next: Next) -> Response {
    let mut response = next.run(request).await;
    response
        .headers_mut()
        .insert("cache-control", "no-store".parse().unwrap());
    response
        .headers_mut()
        .insert("x-content-type-options", "nosniff".parse().unwrap());
    response
}

async fn redeem(
    State(state): State<NodeGatewayState>,
    lan_peer: Option<axum::Extension<crate::lan::LanPeer>>,
    headers: HeaderMap,
    Json(request): Json<RedeemEnrollmentRequest>,
) -> Result<Json<RedeemEnrollmentResponse>, GatewayError> {
    state
        .rate_limiter
        .consume_unauthenticated(
            request_source(
                lan_peer.as_ref(),
                &headers,
                state.rate_limiter.trusts_cloudflare,
            ),
            &request.offer_id,
            "enrollment",
            1,
            10,
        )
        .await?;
    state
        .service
        .redeem(request)
        .await
        .map(Json)
        .map_err(GatewayError::bad_request)
}

async fn challenge(
    State(state): State<NodeGatewayState>,
    lan_peer: Option<axum::Extension<crate::lan::LanPeer>>,
    headers: HeaderMap,
    Json(request): Json<SessionChallengeRequest>,
) -> Result<Json<SessionChallengeResponse>, GatewayError> {
    state
        .rate_limiter
        .consume_unauthenticated(
            request_source(
                lan_peer.as_ref(),
                &headers,
                state.rate_limiter.trusts_cloudflare,
            ),
            &request.credential_id,
            "authentication",
            1,
            30,
        )
        .await?;
    state
        .service
        .challenge(request)
        .await
        .map(Json)
        .map_err(GatewayError::bad_request)
}

async fn open_session(
    State(state): State<NodeGatewayState>,
    lan_peer: Option<axum::Extension<crate::lan::LanPeer>>,
    headers: HeaderMap,
    Json(request): Json<OpenSessionRequest>,
) -> Result<Json<OpenSessionResponse>, GatewayError> {
    state
        .rate_limiter
        .consume_unauthenticated(
            request_source(
                lan_peer.as_ref(),
                &headers,
                state.rate_limiter.trusts_cloudflare,
            ),
            &request.credential_id,
            "authentication",
            1,
            30,
        )
        .await?;
    state
        .service
        .open_session(request)
        .await
        .map(Json)
        .map_err(GatewayError::unauthorized)
}

async fn credential_rotation_challenge(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Json(request): Json<CredentialRotationChallengeRequest>,
) -> Result<Json<CredentialRotationChallengeResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    state
        .service
        .create_credential_rotation_challenge(&context, request)
        .await
        .map(Json)
        .map_err(GatewayError::bad_request)
}

async fn rotate_credential(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Json(request): Json<RotateCredentialRequest>,
) -> Result<Json<RotateCredentialResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    state
        .service
        .rotate_credential(&context, request)
        .await
        .map(Json)
        .map_err(GatewayError::unauthorized)
}

fn bearer(headers: &HeaderMap) -> Result<&str, GatewayError> {
    let value = headers
        .get("authorization")
        .and_then(|value| value.to_str().ok())
        .ok_or_else(|| GatewayError::unauthorized("missing bearer token"))?;
    value
        .strip_prefix("Bearer ")
        .filter(|token| !token.is_empty())
        .ok_or_else(|| GatewayError::unauthorized("invalid bearer token"))
}

async fn heartbeat(
    State(state): State<NodeGatewayState>,
    local_network: Option<axum::Extension<crate::lan::ArrivedOnLocalNetwork>>,
    headers: HeaderMap,
    Json(request): Json<HeartbeatRequest>,
) -> Result<Json<HeartbeatResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    // For the owner to see only, never identity or policy: Cloudflare's edge
    // adds `cf-ray` to every request it forwards (an HTTP header name).
    let link = if local_network.is_some() {
        crate::domain::NodeLink::LocalNetwork
    } else if headers.contains_key("cf-ray") {
        crate::domain::NodeLink::Tunnel
    } else {
        crate::domain::NodeLink::Local
    };
    state.service.note_link(&context.node_id, link);
    state
        .rate_limiter
        .consume(
            &context.node_id,
            "requests",
            1,
            u64::from(state.config.limits.requests_per_minute),
        )
        .await?;
    state
        .service
        .heartbeat(&context, request)
        .await
        .map(Json)
        .map_err(GatewayError::forbidden)
}

async fn report_sensor_readings(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Json(request): Json<ReportSensorReadingsRequest>,
) -> Result<Json<ReportSensorReadingsResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    state
        .service
        .report_sensor_readings(&context, request)
        .await
        .map(Json)
        .map_err(GatewayError::forbidden)
}

#[derive(Debug, Deserialize)]
struct NodeOutboxQuery {
    #[serde(default)]
    after: u64,
    #[serde(default)]
    wait_seconds: u64,
}

async fn node_outbox(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Query(query): Query<NodeOutboxQuery>,
) -> Result<Json<NodeOutboxResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(query.wait_seconds.min(25));
    loop {
        let response = state
            .service
            .node_outbox(&context, query.after)
            .await
            .map_err(GatewayError::forbidden)?;
        if !response.events.is_empty() || tokio::time::Instant::now() >= deadline {
            return Ok(Json(response));
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

async fn ack_node_outbox(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Path(cursor): Path<u64>,
    Json(request): Json<AckNodeOutboxRequest>,
) -> Result<Json<AckNodeOutboxResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    state
        .service
        .acknowledge_node_outbox(&context, cursor, request)
        .await
        .map(Json)
        .map_err(GatewayError::forbidden)
}

async fn create_turn(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Json(request): Json<CreateTurnRequest>,
) -> Result<(StatusCode, Json<CreateTurnResponse>), GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    state
        .rate_limiter
        .consume(
            &context.node_id,
            "requests",
            1,
            u64::from(state.config.limits.requests_per_minute),
        )
        .await?;
    state
        .rate_limiter
        .consume(
            &context.node_id,
            "turns",
            1,
            u64::from(state.config.limits.turns_per_minute),
        )
        .await?;
    let idempotency_key = headers
        .get("idempotency-key")
        .and_then(|value| value.to_str().ok())
        .ok_or_else(|| GatewayError::bad_request("Idempotency-Key is required"))?;
    state.hub.session_map().write().await.insert(
        context.conversation_session_id.clone(),
        NODE_CHANNEL_NAME.to_string(),
    );
    let (outcome, upload_slots) = match request {
        CreateTurnRequest::Text { request_id, text } => {
            let outcome = state
                .service
                .create_text_turn(&context, idempotency_key, &request_id, &text)
                .await
                .map_err(GatewayError::forbidden)?;
            if !outcome.duplicate {
                let service = state.service.clone();
                let ingress = state.ingress.clone();
                let turn_id = outcome.turn_id.clone();
                tokio::spawn(async move {
                    service.process_text_turn(context, turn_id, ingress).await;
                });
            }
            (outcome, Vec::new())
        }
        media => {
            let (outcome, slot) = state
                .service
                .create_media_turn(&context, idempotency_key, media)
                .await
                .map_err(GatewayError::forbidden)?;
            (outcome, vec![slot])
        }
    };
    let status = if outcome.duplicate {
        StatusCode::OK
    } else {
        StatusCode::ACCEPTED
    };
    Ok((
        status,
        Json(CreateTurnResponse {
            turn_id: outcome.turn_id,
            state: outcome.state,
            cursor: outcome.cursor,
            upload_slots,
        }),
    ))
}

async fn upload_media(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Path(slot_id): Path<String>,
    body: Bytes,
) -> Result<Json<UploadMediaResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    state
        .rate_limiter
        .consume(
            &context.node_id,
            "requests",
            1,
            u64::from(state.config.limits.requests_per_minute),
        )
        .await?;
    state
        .rate_limiter
        .consume(
            &context.node_id,
            "media_bytes",
            body.len() as u64,
            state.config.limits.media_bytes_per_minute as u64,
        )
        .await?;
    let upload = state
        .service
        .store()
        .upload_slot(&context.node_id, &slot_id)
        .await
        .map_err(GatewayError::bad_request)?;
    if upload.state != "pending" {
        return Err(GatewayError::bad_request("upload slot is not pending"));
    }
    let content_type = headers
        .get("content-type")
        .and_then(|value| value.to_str().ok())
        .unwrap_or("");
    if content_type != upload.content_type {
        return Err(GatewayError::bad_request(
            "upload Content-Type does not match slot",
        ));
    }
    if body.len() as u64 != upload.expected_bytes {
        return Err(GatewayError::bad_request(
            "upload size does not match declaration",
        ));
    }
    let digest = hex::encode(Sha256::digest(&body));
    if digest != upload.expected_sha256 {
        return Err(GatewayError::bad_request(
            "upload digest does not match declaration",
        ));
    }
    let directory = std::path::PathBuf::from(
        shellexpand::tilde(&state.config.retention.media_dir).into_owned(),
    );
    tokio::fs::create_dir_all(&directory)
        .await
        .map_err(GatewayError::internal)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        tokio::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700))
            .await
            .map_err(GatewayError::internal)?;
    }
    let partial = directory.join(format!("{slot_id}.part"));
    let final_path = directory.join(format!("{slot_id}.bin"));
    let mut file = tokio::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&partial)
        .await
        .map_err(GatewayError::bad_request)?;
    file.write_all(&body)
        .await
        .map_err(GatewayError::internal)?;
    file.sync_all().await.map_err(GatewayError::internal)?;
    drop(file);
    tokio::fs::rename(&partial, &final_path)
        .await
        .map_err(GatewayError::internal)?;
    if let Err(error) = state
        .service
        .store()
        .mark_slot_uploaded(&context.node_id, &slot_id, &final_path.to_string_lossy())
        .await
    {
        let _ = tokio::fs::remove_file(&final_path).await;
        return Err(GatewayError::bad_request(error));
    }
    Ok(Json(UploadMediaResponse {
        slot_id,
        received_bytes: body.len() as u64,
        sha256: digest,
    }))
}

async fn commit_turn(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Path(turn_id): Path<String>,
    Json(request): Json<CommitTurnRequest>,
) -> Result<Json<CommitTurnResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    let upload = state
        .service
        .store()
        .upload_slot(&context.node_id, &request.slot_id)
        .await
        .map_err(GatewayError::bad_request)?;
    if upload.turn_id != turn_id {
        return Err(GatewayError::bad_request(
            "upload slot does not belong to turn",
        ));
    }
    if upload.state != "uploaded" {
        return Err(GatewayError::bad_request("media upload is not complete"));
    }
    let service = state.service.clone();
    let ingress = state.ingress.clone();
    let context_for_task = context;
    tokio::spawn(async move {
        service
            .process_media_turn(context_for_task, upload, ingress)
            .await;
    });
    Ok(Json(CommitTurnResponse {
        turn_id,
        state: super::domain::NodeTurnState::Accepted,
    }))
}

async fn download_media(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Path(media_id): Path<String>,
) -> Result<Response, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    let (path, content_type, expected_bytes) = state
        .service
        .store()
        .response_media(&context.node_id, &media_id)
        .await
        .map_err(GatewayError::bad_request)?;
    if expected_bytes > state.config.limits.response_audio_bytes as u64 {
        return Err(GatewayError::bad_request("response media exceeds limit"));
    }
    let bytes = tokio::fs::read(path)
        .await
        .map_err(GatewayError::internal)?;
    if bytes.len() as u64 != expected_bytes {
        return Err(GatewayError::internal("response media size changed"));
    }
    Response::builder()
        .status(StatusCode::OK)
        .header("content-type", content_type)
        .header("content-length", expected_bytes)
        .header("cache-control", "private, no-store")
        .body(Body::from(bytes))
        .map_err(GatewayError::internal)
}

async fn download_firmware(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Path(release_id): Path<String>,
) -> Result<Response, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    let image = state
        .service
        .firmware_image(&context, &release_id)
        .await
        .map_err(GatewayError::forbidden)?;
    let digest = hex::encode(Sha256::digest(image.as_ref()));
    Response::builder()
        .status(StatusCode::OK)
        .header("content-type", "application/octet-stream")
        .header("content-length", image.len())
        .header("x-content-sha256", digest)
        .header("cache-control", "private, no-store")
        .body(Body::from(image.to_vec()))
        .map_err(GatewayError::internal)
}

#[derive(Debug, Deserialize)]
struct EventQuery {
    #[serde(default)]
    after: u64,
    #[serde(default = "default_wait_seconds")]
    wait_seconds: u64,
}
fn default_wait_seconds() -> u64 {
    20
}

async fn turn_events(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Path(turn_id): Path<String>,
    Query(query): Query<EventQuery>,
) -> Result<Json<TurnEventsResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(query.wait_seconds.min(25));
    loop {
        let events = state
            .service
            .store()
            .events_after(&context.node_id, &turn_id, query.after, 50)
            .await
            .map_err(GatewayError::bad_request)?;
        if !events.is_empty() || tokio::time::Instant::now() >= deadline {
            let next_cursor = events
                .last()
                .map(|event| event.cursor)
                .unwrap_or(query.after);
            return Ok(Json(TurnEventsResponse {
                events,
                next_cursor,
            }));
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

async fn cancel_turn(
    State(state): State<NodeGatewayState>,
    headers: HeaderMap,
    Path(turn_id): Path<String>,
) -> Result<Json<CancelTurnResponse>, GatewayError> {
    let context = state
        .service
        .authenticate(bearer(&headers)?)
        .await
        .map_err(GatewayError::unauthorized)?;
    rate_limit_authenticated_request(&state, &context.node_id).await?;
    let state_value = state
        .service
        .store()
        .cancel_turn(&context.node_id, &turn_id)
        .await
        .map_err(GatewayError::bad_request)?;
    Ok(Json(CancelTurnResponse {
        turn_id,
        state: state_value,
    }))
}

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

    /// Every route this listener mounts sits under `/node/v1`: an exposure
    /// adapter forwards the whole port, so nothing else may be served here.
    #[test]
    fn every_route_is_under_the_service_prefix() {
        let source = include_str!("gateway.rs");
        let body = source
            .split("pub fn router(state: NodeGatewayState) -> Router {")
            .nth(1)
            .expect("router() is in this file")
            .split("\n}\n")
            .next()
            .unwrap();
        let routes: Vec<&str> = body
            .split(".route(")
            .skip(1)
            .map(|rest| rest.trim_start().trim_start_matches('"'))
            .collect();
        assert!(!routes.is_empty());
        for route in routes {
            assert!(
                route.starts_with("/node/v1/"),
                "route outside /node/v1: {}",
                route.lines().next().unwrap_or_default()
            );
        }
        assert!(!body.contains(".nest(") && !body.contains(".fallback("));
    }
    use aidaemon_tools::testing::CallWithFacts;
    use async_trait::async_trait;
    use sqlx::sqlite::SqlitePoolOptions;
    use std::collections::HashMap;

    use crate::domain::{AuthenticatedNodeContext, CHILD_COMPANION_POLICY};
    use crate::service::NodeConversationIngress;
    use crate::simulator::NodeSimulator;
    use crate::store::NodeStore;
    use crate::tool::{ReadNodeHealthTool, ReadNodeSensorsTool};
    use aidaemon_channels::hub::SessionMap;

    struct EchoIngress;
    #[async_trait]
    impl NodeConversationIngress for EchoIngress {
        async fn respond(
            &self,
            _context: &AuthenticatedNodeContext,
            text: &str,
        ) -> anyhow::Result<String> {
            Ok(format!("Companion heard: {text}"))
        }
    }

    #[tokio::test]
    async fn rate_limiter_enforces_limits_and_bounds_untrusted_identities() {
        let limiter = NodeRateLimiter::default();
        limiter.consume("node-1", "turns", 1, 1).await.unwrap();
        let error = limiter.consume("node-1", "turns", 1, 1).await.unwrap_err();
        assert_eq!(error.status, StatusCode::TOO_MANY_REQUESTS);

        limiter.consume("node-2", "requests", 1, 10).await.unwrap();
        let attacker: std::net::IpAddr = "192.0.2.7".parse().unwrap();
        let node: std::net::IpAddr = "192.0.2.8".parse().unwrap();
        // The node starts signing in.
        limiter
            .consume_unauthenticated(node, "cred-real", "authentication", 1, 30)
            .await
            .unwrap();
        // One address making up names in bulk runs out of its own budget
        // (4 ids' worth) and keeps windows for no more than that.
        let mut allowed = 0;
        for index in 0..NodeRateLimiter::MAX_WINDOWS + 100 {
            if limiter
                .consume_unauthenticated(
                    attacker,
                    &format!("untrusted-{index}"),
                    "authentication",
                    1,
                    30,
                )
                .await
                .is_ok()
            {
                allowed += 1;
            }
        }
        assert_eq!(allowed, 120);
        {
            let sources = limiter.unauthenticated.lock().await;
            assert!(sources[&attacker].ids.len() <= 120);
            assert_eq!(sources.len(), 2);
        }
        // The node's budget is its own.
        for _ in 0..29 {
            limiter
                .consume_unauthenticated(node, "cred-real", "authentication", 1, 30)
                .await
                .unwrap();
        }
        // Each id keeps its own budget too.
        assert!(
            limiter
                .consume_unauthenticated(node, "cred-real", "authentication", 1, 30)
                .await
                .is_err()
        );
        // Many addresses: the map stays bounded, and makes room.
        for index in 0..NodeRateLimiter::MAX_SOURCES + 50 {
            let ip = std::net::IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000u32 + index as u32));
            limiter
                .consume_unauthenticated(ip, "x", "authentication", 1, 30)
                .await
                .expect("a full map makes room, it never refuses everyone");
        }
        assert!(limiter.unauthenticated.lock().await.len() <= NodeRateLimiter::MAX_SOURCES);
        // Names made up before signing in never touch a signed-in Node's.
        assert_eq!(limiter.windows.lock().await.len(), 2);
        limiter.consume("node-2", "requests", 1, 10).await.unwrap();
    }

    #[test]
    fn requests_before_sign_in_are_counted_by_where_they_came_from() {
        let mut headers = HeaderMap::new();
        let local = request_source(None, &headers, true);
        assert!(local.is_loopback());
        // Without Cloudflare's own header the visitor header is not believed.
        headers.insert("cf-connecting-ip", "198.51.100.4".parse().unwrap());
        assert!(request_source(None, &headers, true).is_loopback());
        headers.insert("cf-ray", "abc".parse().unwrap());
        assert_eq!(
            request_source(None, &headers, true),
            "198.51.100.4".parse::<std::net::IpAddr>().unwrap()
        );
        // Published any other way, a client writes both headers itself.
        assert!(request_source(None, &headers, false).is_loopback());
        assert!(!NodeRateLimiter::default().trusts_cloudflare);
        assert!(
            NodeRateLimiter::default()
                .trusting_cloudflare()
                .trusts_cloudflare
        );
        let peer = axum::Extension(crate::lan::LanPeer("192.168.1.9".parse().unwrap()));
        assert_eq!(
            request_source(Some(&peer), &headers, true),
            "192.168.1.9".parse::<std::net::IpAddr>().unwrap()
        );
    }

    /// A Node that observes `gateway.trust` learns the local listener and
    /// its CA from a heartbeat over the channel it already uses, then
    /// carries on over the local network, verifying the listener against
    /// that CA; a Node without the capability is never offered it.
    #[tokio::test]
    async fn a_node_moves_to_the_local_listener_it_learned_from_a_heartbeat() {
        let pool = SqlitePoolOptions::new()
            .max_connections(1)
            .connect("sqlite::memory:")
            .await
            .unwrap();
        crate::store::migrate(&pool).await.unwrap();
        let store = Arc::new(NodeStore::new(pool, [7_u8; 32]));
        let mut config = NodesConfig::default();
        config.gateway.advertised_endpoints = vec!["https://node.example.test".to_string()];
        let dir = tempfile::tempdir().unwrap();
        let authority =
            Arc::new(crate::lan::LanAuthority::load_or_create(&dir.path().join("ca.key")).unwrap());
        let lan_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let lan_port = lan_listener.local_addr().unwrap().port();
        let service = Arc::new(NodeService::new(store.clone(), config.clone()).with_lan(
            crate::lan::LanEndpoint {
                port: lan_port,
                authority: authority.clone(),
                address: Some("127.0.0.1".parse().unwrap()),
            },
        ));
        let offer = service
            .create_pairing_offer(
                "parent",
                "simulator",
                "Test Companion",
                CHILD_COMPANION_POLICY,
            )
            .await
            .unwrap();
        let sessions: SessionMap = Arc::new(tokio::sync::RwLock::new(HashMap::new()));
        let state_service = service.clone();
        let state = NodeGatewayState {
            service,
            ingress: Arc::new(EchoIngress),
            hub: Arc::new(ChannelHub::new(Vec::new(), sessions)),
            config,
            rate_limiter: Arc::new(NodeRateLimiter::default()),
        };
        tokio::spawn(crate::lan::serve_on(
            lan_listener,
            router(state.clone()),
            authority,
            "127.0.0.1".parse().unwrap(),
        ));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, router(state)).await.unwrap();
        });

        let mut simulator = NodeSimulator::new(format!("http://{address}")).unwrap();
        let node_id = simulator
            .enroll(&offer.offer_id, &offer.offer_secret)
            .await
            .unwrap()
            .node_id;
        simulator.open_session().await.unwrap();
        let trust = CapabilityObservation {
            capability_id: crate::service::GATEWAY_TRUST_CAPABILITY.to_string(),
            version: 1,
            limits: serde_json::json!({}),
        };

        // Without the capability, nothing new is offered.
        let plain = simulator.heartbeat(Vec::new()).await.unwrap();
        assert_eq!(plain.gateway_endpoints, vec!["https://node.example.test"]);
        assert!(plain.gateway_trust.is_empty());

        // With it, the local listener comes first, with its CA.
        let offered = simulator.heartbeat(vec![trust.clone()]).await.unwrap();
        let lan = format!("https://127.0.0.1:{lan_port}");
        assert_eq!(
            offered.gateway_endpoints,
            vec![lan.clone(), "https://node.example.test".to_string()]
        );
        let ca = aidaemon_node_sdk_trust(&offered, &lan).expect("a CA for the local origin");

        // The Node carries on over the local network, its session intact.
        assert_eq!(
            state_service.link(&node_id),
            Some(crate::domain::NodeLink::Local)
        );
        simulator.switch_gateway(&lan, Some(ca)).unwrap();
        let over_lan = simulator.heartbeat(vec![trust]).await.unwrap();
        assert!(over_lan.accepted);
        assert_eq!(
            state_service.link(&node_id),
            Some(crate::domain::NodeLink::LocalNetwork)
        );

        // Without the CA, the listener is not trusted.
        simulator.switch_gateway(&lan, None).unwrap();
        assert!(simulator.heartbeat(Vec::new()).await.is_err());
    }

    fn aidaemon_node_sdk_trust<'a>(
        response: &'a crate::protocol::HeartbeatResponse,
        origin: &str,
    ) -> Option<&'a str> {
        response
            .gateway_trust
            .iter()
            .find(|trust| trust.origin == origin)
            .map(|trust| trust.ca_pem.as_str())
    }

    #[tokio::test]
    async fn enrolled_node_authenticates_and_completes_idempotent_turn() {
        let pool = SqlitePoolOptions::new()
            .max_connections(1)
            .connect("sqlite::memory:")
            .await
            .unwrap();
        crate::store::migrate(&pool).await.unwrap();
        let store = Arc::new(NodeStore::new(pool, [7_u8; 32]));
        let media_dir = tempfile::tempdir().unwrap();
        let mut config = NodesConfig::default();
        config.retention.media_dir = media_dir.path().to_string_lossy().into_owned();
        config.announcements.enabled = true;
        config.monitoring.enabled = true;
        config.ota.enabled = true;
        config.gateway.advertised_endpoints = vec![
            "https://node.example.test".to_string(),
            "https://node-lan.example.test".to_string(),
        ];
        let firmware_image = b"synthetic signed K10 application image";
        let firmware_release =
            crate::ota::FirmwareRelease::signed_for_test(firmware_image, "0.4.0", 1);
        let service = Arc::new(
            NodeService::new(store.clone(), config.clone()).with_firmware_release(firmware_release),
        );
        let offer = service
            .create_pairing_offer(
                "parent",
                "simulator",
                "Test Companion",
                CHILD_COMPANION_POLICY,
            )
            .await
            .unwrap();
        let sessions: SessionMap = Arc::new(tokio::sync::RwLock::new(HashMap::new()));
        let hub = Arc::new(ChannelHub::new(Vec::new(), sessions));
        let state = NodeGatewayState {
            service: service.clone(),
            ingress: Arc::new(EchoIngress),
            hub,
            config,
            rate_limiter: Arc::new(NodeRateLimiter::default()),
        };
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            axum::serve(listener, router(state)).await.unwrap();
        });

        let mut simulator = NodeSimulator::new(format!("http://{address}")).unwrap();
        let enrollment = simulator
            .enroll(&offer.offer_id, &offer.offer_secret)
            .await
            .unwrap();
        store
            .set_authorization(
                &enrollment.node_id,
                crate::domain::NodeAction::SubmitAudioTurn,
                true,
                serde_json::json!({"max_duration_ms":10000}),
            )
            .await
            .unwrap();
        store
            .set_authorization(
                &enrollment.node_id,
                crate::domain::NodeAction::ReportSensor,
                true,
                serde_json::json!({"capabilities":[
                    "sensor.environment.temperature",
                    "sensor.environment.humidity"
                ]}),
            )
            .await
            .unwrap();
        simulator.open_session().await.unwrap();
        let heartbeat_without_audio_authorization = simulator
            .heartbeat(vec![
                CapabilityObservation {
                    capability_id: "sensor.environment.temperature".to_string(),
                    version: 1,
                    limits: serde_json::json!({"unit":"celsius"}),
                },
                CapabilityObservation {
                    capability_id: "sensor.environment.humidity".to_string(),
                    version: 1,
                    limits: serde_json::json!({"unit":"percent_rh"}),
                },
                CapabilityObservation {
                    capability_id: "output.audio".to_string(),
                    version: 1,
                    limits: serde_json::json!({"content_type":"audio/wav","max_bytes":1048576}),
                },
                CapabilityObservation {
                    capability_id: "firmware.ota".to_string(),
                    version: 1,
                    limits: serde_json::json!({"board":"unihiker_k10","slot_bytes":2621440}),
                },
            ])
            .await
            .unwrap();
        assert_eq!(heartbeat_without_audio_authorization.outbox_poll_seconds, 0);
        assert_eq!(
            heartbeat_without_audio_authorization.gateway_endpoints,
            vec![
                "https://node.example.test".to_string(),
                "https://node-lan.example.test".to_string(),
            ]
        );
        assert!(
            heartbeat_without_audio_authorization
                .firmware_update
                .is_none()
        );
        store
            .set_authorization(
                &enrollment.node_id,
                crate::domain::NodeAction::ReceiveAudio,
                true,
                serde_json::json!({"content_types":["audio/wav"]}),
            )
            .await
            .unwrap();
        store
            .set_authorization(
                &enrollment.node_id,
                crate::domain::NodeAction::ReceiveOta,
                true,
                serde_json::json!({"board":"unihiker_k10","channel":"stable"}),
            )
            .await
            .unwrap();
        simulator.open_session().await.unwrap();
        let heartbeat_with_audio_authorization = simulator
            .heartbeat(vec![
                CapabilityObservation {
                    capability_id: "sensor.environment.temperature".to_string(),
                    version: 1,
                    limits: serde_json::json!({"unit":"celsius"}),
                },
                CapabilityObservation {
                    capability_id: "sensor.environment.humidity".to_string(),
                    version: 1,
                    limits: serde_json::json!({"unit":"percent_rh"}),
                },
                CapabilityObservation {
                    capability_id: "output.audio".to_string(),
                    version: 1,
                    limits: serde_json::json!({"content_type":"audio/wav","max_bytes":1048576}),
                },
                CapabilityObservation {
                    capability_id: "firmware.ota".to_string(),
                    version: 1,
                    limits: serde_json::json!({"board":"unihiker_k10","slot_bytes":2621440}),
                },
            ])
            .await
            .unwrap();
        assert_eq!(heartbeat_with_audio_authorization.outbox_poll_seconds, 3);
        let firmware_offer = heartbeat_with_audio_authorization
            .firmware_update
            .as_ref()
            .expect("authorized OTA-capable Node should receive the release");
        assert_eq!(firmware_offer.version, "0.4.0");
        assert_eq!(firmware_offer.sequence, 1);
        assert_eq!(
            simulator
                .download_firmware(&firmware_offer.download_path)
                .await
                .unwrap(),
            firmware_image
        );
        let heartbeat_at_release_sequence = simulator
            .heartbeat(vec![
                CapabilityObservation {
                    capability_id: "sensor.environment.temperature".to_string(),
                    version: 1,
                    limits: serde_json::json!({"unit":"celsius"}),
                },
                CapabilityObservation {
                    capability_id: "sensor.environment.humidity".to_string(),
                    version: 1,
                    limits: serde_json::json!({"unit":"percent_rh"}),
                },
                CapabilityObservation {
                    capability_id: "output.audio".to_string(),
                    version: 1,
                    limits: serde_json::json!({
                        "content_type":"audio/wav",
                        "max_bytes":1048576
                    }),
                },
                CapabilityObservation {
                    capability_id: "firmware.ota".to_string(),
                    version: 1,
                    limits: serde_json::json!({
                        "board":"unihiker_k10",
                        "slot_bytes":2621440,
                        "sequence":1
                    }),
                },
            ])
            .await
            .unwrap();
        assert!(
            heartbeat_at_release_sequence.firmware_update.is_none(),
            "the Gateway must not re-offer a release at the Device's current or rejected sequence"
        );
        let sensor_response = simulator
            .report_sensor_readings(vec![
                SensorReading {
                    capability_id: "sensor.environment.temperature".to_string(),
                    capability_version: 1,
                    value: 22.75,
                    unit: "celsius".to_string(),
                },
                SensorReading {
                    capability_id: "sensor.environment.humidity".to_string(),
                    capability_version: 1,
                    value: 48.5,
                    unit: "percent_rh".to_string(),
                },
            ])
            .await
            .unwrap();
        assert!(sensor_response.accepted);
        let history_count: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM node_sensor_readings_history WHERE node_id = ?",
        )
        .bind(&enrollment.node_id)
        .fetch_one(store.pool())
        .await
        .unwrap();
        assert_eq!(history_count, 2);
        let tool = ReadNodeSensorsTool::new(store.pool().clone());
        let tool_output = tool
            .call_with(
                r#"{}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Owner),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert!(tool_output.contains("22.75"));
        assert!(tool_output.contains("72.95"));
        let health_tool = ReadNodeHealthTool::new(store.pool().clone());
        let health_output = health_tool
            .call_with(
                r#"{}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Owner),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert!(health_output.contains("recently_connected"));
        assert!(health_output.contains("aidaemon.runtime.recovery.v1"));
        assert!(health_output.contains("test_restart"));
        assert!(health_output.contains("reported_capabilities"));
        assert!(health_output.contains("output.audio"));
        assert!(health_output.contains("current_authorizations"));
        assert!(health_output.contains("receive_audio"));
        assert!(
            !health_output.contains("output.audio.volume"),
            "the capability snapshot must not invent an unreported volume control"
        );
        let events = simulator.text_turn("hello").await.unwrap();
        assert!(
            events
                .iter()
                .any(|event| event.event_type == "turn.thinking")
        );
        let complete = events
            .iter()
            .find(|event| event.event_type == "turn.complete")
            .unwrap();
        assert_eq!(complete.payload["text"], "Companion heard: hello");
        let media_events = simulator
            .media_turn(b"bounded fake wav fixture", "audio/wav", Some(800))
            .await
            .unwrap();
        assert!(
            media_events
                .iter()
                .any(|event| event.event_type == "turn.complete")
        );
        assert_eq!(
            std::fs::read_dir(media_dir.path()).unwrap().count(),
            0,
            "raw media should be deleted after processing"
        );

        let audio_bytes = b"RIFF bounded synthetic WAVE fixture";
        let announcement_path = media_dir.path().join("announcement.wav");
        tokio::fs::write(&announcement_path, audio_bytes)
            .await
            .unwrap();
        let target = store
            .resolve_audio_announcement_target(Some("Test Companion"))
            .await
            .unwrap();
        let digest = hex::encode(Sha256::digest(audio_bytes));
        let queued = store
            .queue_audio_announcement(
                &target,
                "audio/wav",
                audio_bytes.len() as u64,
                &digest,
                &announcement_path.to_string_lossy(),
                120,
                4,
            )
            .await
            .unwrap();
        let outbox = simulator.outbox(0).await.unwrap();
        assert_eq!(outbox.events.len(), 1);
        assert_eq!(outbox.events[0].event_type, "channel.audio");
        assert!(outbox.events[0].payload.get("text").is_none());
        let download_path = outbox.events[0].payload["audio"]["download_path"]
            .as_str()
            .unwrap();
        assert_eq!(
            simulator.download_media(download_path).await.unwrap(),
            audio_bytes
        );
        let acknowledgement = simulator
            .acknowledge_outbox(queued.cursor, NodeOutboxAckStatus::Played, None)
            .await
            .unwrap();
        assert!(acknowledgement.accepted);
        assert_eq!(acknowledgement.status, NodeOutboxAckStatus::Played);
        assert!(!announcement_path.exists());
        assert!(simulator.outbox(0).await.unwrap().events.is_empty());
        assert_eq!(
            store
                .node_outbox_receipt(&enrollment.node_id, queued.cursor)
                .await
                .unwrap()
                .unwrap()
                .status,
            "played"
        );

        let context = service
            .authenticate(simulator.identity.access_token.as_deref().unwrap())
            .await
            .unwrap();
        assert!(
            service
                .authorize(&context, crate::domain::NodeAction::ReceiveActuatorCommand)
                .await
                .is_err()
        );
        let old_token = simulator.identity.access_token.clone().unwrap();
        let rotated = simulator.rotate_credential().await.unwrap();
        assert!(rotated.sessions_closed);
        assert!(service.authenticate(&old_token).await.is_err());
        simulator.open_session().await.unwrap();
        assert!(
            service
                .authenticate(simulator.identity.access_token.as_deref().unwrap())
                .await
                .is_ok()
        );
        store.revoke_node(&context.node_id).await.unwrap();
        assert!(
            service
                .authenticate(simulator.identity.access_token.as_deref().unwrap())
                .await
                .is_err()
        );
        server.abort();
    }
}