solid-pod-rs-server 0.4.0-alpha.4

Drop-in Solid Pod server binary. Wraps solid-pod-rs with actix-web and a JSS-compatible layered config loader.
Documentation
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
//! # solid-pod-rs-server
//!
//! Drop-in Solid Pod server binary wrapping
//! [`solid-pod-rs`](https://crates.io/crates/solid-pod-rs) with
//! [actix-web](https://docs.rs/actix-web). This crate is both a
//! library (for integration-test reuse) and a binary.
//!
//! ## Public types
//!
//! - [`AppState`]  — Shared actix-web application state (storage, dotfile policy, body cap).
//! - [`build_app`] — Builds the fully-configured `actix_web::App` with all routes and middleware.
//! - [`NodeInfoMeta`] — NodeInfo 2.1 metadata inputs.
//! - [`PathTraversalGuard`] — Middleware that rejects `..` path-traversal attempts.
//! - [`DotfileGuard`] — Middleware that enforces the dotfile allowlist.
//! - [`ErrorLoggingMiddleware`] — Middleware that logs 5xx responses with full error chains.
//! - [`body_cap_from_env`] — Reads `JSS_MAX_REQUEST_BODY` from the environment.
//! - [`cli`] — CLI argument definitions (clap derive).
//!
//! ## Route table
//!
//! | Method   | Path                                     | Handler              |
//! |----------|------------------------------------------|----------------------|
//! | GET/HEAD | `/{tail:.*}`                             | `handle_get`         |
//! | GET      | `/{folder}/*`                            | Glob merged Turtle   |
//! | PUT      | `/{tail:.*}`                             | `handle_put`         |
//! | PUT      | `/{tail:.*}/` + `Link: BasicContainer`   | Container creation   |
//! | POST     | `/{tail:.*}/`                            | `handle_post`        |
//! | PATCH    | `/{tail:.*}`                             | `handle_patch`       |
//! | DELETE   | `/{tail:.*}`                             | `handle_delete`      |
//! | COPY     | `/{tail:.*}` + `Source` header           | `handle_copy`        |
//! | OPTIONS  | `/{tail:.*}`                             | `handle_options`     |
//! | POST     | `/api/accounts/new`                      | Pod provisioning     |
//! | GET      | `/pods/check/{name}`                     | Pod existence check  |
//! | POST     | `/login/password`                        | Credentials login    |
//! | POST     | `/account/password/reset`                | Password reset       |
//! | POST     | `/account/password/change`               | Password change      |
//! | GET      | `/.well-known/solid`                     | Solid discovery      |
//! | GET      | `/.well-known/webfinger`                 | WebFinger JRD        |
//! | GET      | `/.well-known/nodeinfo`                  | NodeInfo discovery   |
//! | GET      | `/.well-known/nodeinfo/2.1`              | NodeInfo 2.1         |
//! | GET      | `/.well-known/did/nostr/{pubkey}.json`   | DID:nostr document   |
//!
//! ## Middleware stack (applied in order)
//!
//! 1. `NormalizePath` -- collapse `//` and decode %-encoded segments.
//! 2. `PathTraversalGuard` -- defence-in-depth `..` re-check.
//! 3. `DotfileGuard` -- rejects `.env` etc unless on the allowlist.
//! 4. `PayloadConfig` -- enforces `JSS_MAX_REQUEST_BODY` body cap.
//! 5. `ErrorLoggingMiddleware` -- structured 5xx logging.
//! 6. WAC-on-write -- PUT/POST/PATCH/DELETE require a write/append grant.

#![doc = include_str!("../README.md")]

#![deny(unsafe_code)]
#![warn(rust_2018_idioms)]

/// CLI argument definitions (clap derive structs).
pub mod cli;

use std::path::{Path, PathBuf};
use std::sync::Arc;

use actix_web::body::{BoxBody, EitherBody};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::http::{header, StatusCode};
use actix_web::middleware::{NormalizePath, TrailingSlash};
use actix_web::{web, App, Error as ActixError, HttpRequest, HttpResponse};
use bytes::Bytes;
use futures_util::future::{ready, LocalBoxFuture, Ready};
use percent_encoding::percent_decode_str;
use serde::Deserialize;
use solid_pod_rs::{
    auth::nip98,
    config::sources::parse_size,
    interop,
    ldp::{self, LdpContainerOps, PatchCreateOutcome},
    provision,
    security::DotfileAllowlist,
    storage::Storage,
    wac::{
        self, conditions::RequestContext, parse_jsonld_acl, parser::parse_turtle_acl, AccessMode,
    },
    PodError,
};

// ---------------------------------------------------------------------------
// Shared app state
// ---------------------------------------------------------------------------

/// Actix-web shared state.
#[derive(Clone)]
pub struct AppState {
    pub storage: Arc<dyn Storage>,
    pub dotfiles: Arc<DotfileAllowlist>,
    pub body_cap: usize,
    pub nodeinfo: NodeInfoMeta,
    pub mashlib_cdn: Option<String>,
}

/// NodeInfo 2.1 body inputs. Kept here so tests can override them.
#[derive(Clone, Debug)]
pub struct NodeInfoMeta {
    pub software_name: String,
    pub software_version: String,
    pub open_registrations: bool,
    pub total_users: u64,
    pub base_url: String,
}

impl Default for NodeInfoMeta {
    fn default() -> Self {
        Self {
            software_name: "solid-pod-rs-server".to_string(),
            software_version: env!("CARGO_PKG_VERSION").to_string(),
            open_registrations: false,
            total_users: 0,
            base_url: "http://localhost".to_string(),
        }
    }
}

/// Discover the body cap from the environment. Accepts values like
/// `50MB`, `1.5GB`, or a bare integer (bytes). Falls back to 50 MiB.
pub const DEFAULT_BODY_CAP: usize = 50 * 1024 * 1024;

/// Read `JSS_MAX_REQUEST_BODY` and parse via [`parse_size`]. On any
/// failure, returns [`DEFAULT_BODY_CAP`].
pub fn body_cap_from_env() -> usize {
    match std::env::var("JSS_MAX_REQUEST_BODY") {
        Ok(v) => parse_size(&v)
            .map(|u| u as usize)
            .unwrap_or(DEFAULT_BODY_CAP),
        Err(_) => DEFAULT_BODY_CAP,
    }
}

impl AppState {
    /// Convenience constructor for tests and the binary. Callers may
    /// replace fields after creation since `AppState` is a plain struct.
    pub fn new(storage: Arc<dyn Storage>) -> Self {
        Self {
            storage,
            dotfiles: Arc::new(DotfileAllowlist::from_env()),
            body_cap: body_cap_from_env(),
            nodeinfo: NodeInfoMeta::default(),
            mashlib_cdn: None,
        }
    }
}

// ---------------------------------------------------------------------------
// Error translation
// ---------------------------------------------------------------------------

fn to_actix(e: PodError) -> ActixError {
    match e {
        PodError::NotFound(_) => actix_web::error::ErrorNotFound(e.to_string()),
        PodError::BadRequest(_) => actix_web::error::ErrorBadRequest(e.to_string()),
        PodError::Unsupported(_) => actix_web::error::ErrorUnsupportedMediaType(e.to_string()),
        PodError::Forbidden => actix_web::error::ErrorForbidden(e.to_string()),
        PodError::Unauthenticated => actix_web::error::ErrorUnauthorized(e.to_string()),
        PodError::PreconditionFailed(_) => {
            actix_web::error::ErrorPreconditionFailed(e.to_string())
        }
        _ => actix_web::error::ErrorInternalServerError(e.to_string()),
    }
}

// ---------------------------------------------------------------------------
// Auth helper — shared across handlers
// ---------------------------------------------------------------------------

/// Attempt NIP-98 bearer verification; returns the pubkey on success.
async fn extract_pubkey(req: &HttpRequest) -> Option<String> {
    let header_val = req
        .headers()
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())?;
    let url = format!(
        "http://{}{}",
        req.connection_info().host(),
        req.uri().path()
    );
    nip98::verify(header_val, &url, req.method().as_str(), None)
        .await
        .ok()
}

fn agent_uri(pubkey: Option<&String>) -> Option<String> {
    pubkey.map(|pk| format!("did:nostr:{pk}"))
}

// ---------------------------------------------------------------------------
// WAC enforcement for writes (PUT / POST / PATCH / DELETE)
// ---------------------------------------------------------------------------

/// Resolve the effective ACL and evaluate whether the given WebID may
/// perform `mode` on `path`.
///
/// Returns `Ok(())` on grant. On deny, returns an `actix_web::Error`:
/// * `401` when the request had no authenticated agent (so the client
///   knows retrying with credentials might work);
/// * `403` when authenticated but the ACL does not grant the mode.
async fn enforce_write(
    state: &AppState,
    path: &str,
    mode: AccessMode,
    agent_uri: Option<&str>,
) -> Result<(), ActixError> {
    // `StorageAclResolver` is generic over a concrete backend. `state`
    // holds an `Arc<dyn Storage>`; wrap it in a trait-object-friendly
    // adapter (`DynStorage`) that forwards each trait method so the
    // resolver can be constructed with a concrete type.
    let acl_doc = match find_effective_acl_dyn(&*state.storage, path).await {
        Ok(doc) => doc,
        Err(e) => return Err(to_actix(e)),
    };

    let ctx = RequestContext {
        web_id: agent_uri,
        client_id: None,
        issuer: None,
    };
    let registry = wac::conditions::ConditionRegistry::default_with_client_and_issuer();
    let groups: wac::StaticGroupMembership = wac::StaticGroupMembership::default();
    let granted = wac::evaluate_access_ctx_with_registry(
        acl_doc.as_ref(),
        &ctx,
        path,
        mode,
        None,
        &groups,
        &registry,
    );
    if granted {
        return Ok(());
    }

    let allow_header = wac::wac_allow_header(acl_doc.as_ref(), agent_uri, path);
    let (status, body) = if agent_uri.is_none() {
        (StatusCode::UNAUTHORIZED, "authentication required")
    } else {
        (StatusCode::FORBIDDEN, "access forbidden")
    };
    let mut rsp = HttpResponse::new(status);
    rsp.headers_mut().insert(
        header::HeaderName::from_static("wac-allow"),
        header::HeaderValue::from_str(&allow_header).unwrap_or(header::HeaderValue::from_static("")),
    );
    Err(actix_web::error::InternalError::from_response(body, rsp).into())
}

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

fn set_link_headers(rsp: &mut HttpResponse, path: &str) {
    let links = ldp::link_headers(path).join(", ");
    if let Ok(value) = header::HeaderValue::from_str(&links) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("link"), value);
    }
}

fn set_wac_allow(rsp: &mut HttpResponse, header_value: &str) {
    if let Ok(v) = header::HeaderValue::from_str(header_value) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("wac-allow"), v);
    }
}

fn set_updates_via(rsp: &mut HttpResponse, base_url: &str) {
    let ws_url = base_url
        .replacen("https://", "wss://", 1)
        .replacen("http://", "ws://", 1);
    if let Ok(v) = header::HeaderValue::from_str(&ws_url) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("updates-via"), v);
    }
}

async fn handle_get(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();

    if path.contains('*') {
        return handle_glob_get(req, state).await;
    }

    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    let wac_allow = wac::wac_allow_header(None, agent.as_deref(), &path);

    if ldp::is_container(&path) {
        let v = state
            .storage
            .container_representation(&path)
            .await
            .map_err(to_actix)?;
        let mut rsp = HttpResponse::Ok().json(v);
        rsp.headers_mut().insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("application/ld+json"),
        );
        set_wac_allow(&mut rsp, &wac_allow);
        set_updates_via(&mut rsp, &state.nodeinfo.base_url);
        set_link_headers(&mut rsp, &path);
        return Ok(rsp);
    }

    match state.storage.get(&path).await {
        Ok((body, meta)) => {
            let mut rsp = HttpResponse::Ok().body(body.to_vec());
            rsp.headers_mut().insert(
                header::CONTENT_TYPE,
                header::HeaderValue::from_str(&meta.content_type)
                    .unwrap_or_else(|_| header::HeaderValue::from_static("application/octet-stream")),
            );
            if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
                rsp.headers_mut().insert(header::ETAG, etag);
            }
            set_wac_allow(&mut rsp, &wac_allow);
            set_updates_via(&mut rsp, &state.nodeinfo.base_url);
            set_link_headers(&mut rsp, &path);
            Ok(rsp)
        }
        Err(PodError::NotFound(_)) => Ok(HttpResponse::NotFound().finish()),
        Err(e) => Err(to_actix(e)),
    }
}

fn has_basic_container_link(req: &HttpRequest) -> bool {
    req.headers()
        .get_all(header::LINK)
        .filter_map(|v| v.to_str().ok())
        .any(|v| {
            v.contains("http://www.w3.org/ns/ldp#BasicContainer")
                && v.contains("rel=\"type\"")
        })
}

async fn handle_put(
    req: HttpRequest,
    body: web::Bytes,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();

    if ldp::is_container(&path) {
        if has_basic_container_link(&req) {
            let auth_pk = extract_pubkey(&req).await;
            let agent = agent_uri(auth_pk.as_ref());
            enforce_write(&state, &path, AccessMode::Write, agent.as_deref()).await?;
            let meta = state
                .storage
                .create_container(&path)
                .await
                .map_err(to_actix)?;
            let mut rsp = HttpResponse::Created().finish();
            if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
                rsp.headers_mut().insert(header::ETAG, etag);
            }
            set_link_headers(&mut rsp, &path);
            return Ok(rsp);
        }
        return Ok(HttpResponse::MethodNotAllowed().body("cannot PUT to a container"));
    }

    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &path, AccessMode::Write, agent.as_deref()).await?;

    let ct = req
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let meta = state
        .storage
        .put(&path, Bytes::from(body.to_vec()), ct)
        .await
        .map_err(to_actix)?;
    let mut rsp = HttpResponse::Created().finish();
    if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
        rsp.headers_mut().insert(header::ETAG, etag);
    }
    set_link_headers(&mut rsp, &path);
    Ok(rsp)
}

async fn handle_post(
    req: HttpRequest,
    body: web::Bytes,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();
    // POST route only matches container paths (trailing slash) via the
    // `POST /{tail:.*}/` registration.
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &path, AccessMode::Append, agent.as_deref()).await?;

    let slug = req
        .headers()
        .get(header::HeaderName::from_static("slug"))
        .and_then(|v| v.to_str().ok());
    let target = match ldp::resolve_slug(&path, slug) {
        Ok(p) => p,
        Err(e) => return Err(to_actix(e)),
    };
    let ct = req
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let meta = state
        .storage
        .put(&target, Bytes::from(body.to_vec()), ct)
        .await
        .map_err(to_actix)?;
    let mut rsp = HttpResponse::Created().finish();
    if let Ok(loc) = header::HeaderValue::from_str(&target) {
        rsp.headers_mut().insert(header::LOCATION, loc);
    }
    if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
        rsp.headers_mut().insert(header::ETAG, etag);
    }
    set_link_headers(&mut rsp, &target);
    Ok(rsp)
}

async fn handle_patch(
    req: HttpRequest,
    body: web::Bytes,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();
    if ldp::is_container(&path) {
        return Ok(HttpResponse::MethodNotAllowed().body("cannot PATCH a container"));
    }
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &path, AccessMode::Append, agent.as_deref()).await?;

    let ct = req
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let dialect = match ldp::patch_dialect_from_mime(ct) {
        Some(d) => d,
        None => {
            return Ok(HttpResponse::UnsupportedMediaType()
                .body(format!("unsupported patch dialect for content-type {ct:?}")))
        }
    };
    let body_str = match std::str::from_utf8(&body) {
        Ok(s) => s.to_string(),
        Err(_) => {
            return Ok(HttpResponse::BadRequest().body("patch body is not valid UTF-8"))
        }
    };

    // Existing resource?
    let existing = state.storage.get(&path).await;
    match existing {
        Ok((current_body, meta)) => {
            // Parse the current body into a graph. For the Sprint 7 D
            // slice, the PATCH paths operate on an empty seed graph when
            // a textual RDF representation cannot be parsed — the
            // dialect patchers already cover the semantics. This keeps
            // the handler thin; richer mutation semantics live in
            // the library crate.
            let out = match dialect {
                ldp::PatchDialect::N3 => ldp::apply_n3_patch(ldp::Graph::new(), &body_str)
                    .map_err(patch_parse_err),
                ldp::PatchDialect::SparqlUpdate => {
                    ldp::apply_sparql_patch(ldp::Graph::new(), &body_str)
                        .map_err(patch_parse_err)
                }
                ldp::PatchDialect::JsonPatch => {
                    let mut json: serde_json::Value = match serde_json::from_slice(&current_body) {
                        Ok(v) => v,
                        Err(_) => serde_json::json!({}),
                    };
                    let patch: serde_json::Value = match serde_json::from_str(&body_str) {
                        Ok(v) => v,
                        Err(e) => return Err(to_actix(PodError::BadRequest(e.to_string()))),
                    };
                    ldp::apply_json_patch(&mut json, &patch).map_err(to_actix)?;
                    let bytes = serde_json::to_vec(&json).map_err(PodError::from).map_err(to_actix)?;
                    let _ = state
                        .storage
                        .put(&path, Bytes::from(bytes), &meta.content_type)
                        .await
                        .map_err(to_actix)?;
                    return Ok(HttpResponse::NoContent().finish());
                }
            };
            let outcome = out?;
            // Round-trip the updated graph back to Turtle so the next
            // GET reflects the mutation.
            let serialised = graph_to_turtle(&outcome.graph);
            let _ = state
                .storage
                .put(&path, Bytes::from(serialised.into_bytes()), "text/turtle")
                .await
                .map_err(to_actix)?;
            Ok(HttpResponse::NoContent().finish())
        }
        Err(PodError::NotFound(_)) => {
            // PATCH against an absent resource — create it.
            let create = ldp::apply_patch_to_absent(dialect, &body_str).map_err(patch_parse_err)?;
            let PatchCreateOutcome::Created { graph, .. } = create else {
                return Err(to_actix(PodError::Unsupported(
                    "unexpected patch outcome on absent resource".into(),
                )));
            };
            let serialised = graph_to_turtle(&graph);
            let _ = state
                .storage
                .put(&path, Bytes::from(serialised.into_bytes()), "text/turtle")
                .await
                .map_err(to_actix)?;
            Ok(HttpResponse::Created().finish())
        }
        Err(e) => Err(to_actix(e)),
    }
}

/// Map a PATCH body parse error to 400 Bad Request. Distinguishes
/// "client sent garbage in a supported dialect" (400) from "client
/// chose an unsupported dialect" (415 — handled by the dispatcher).
fn patch_parse_err(e: PodError) -> ActixError {
    match e {
        PodError::Unsupported(msg) | PodError::BadRequest(msg) => {
            actix_web::error::ErrorBadRequest(msg)
        }
        other => to_actix(other),
    }
}

/// Serialise a graph to N-Triples so the next GET reflects PATCH
/// mutations verbatim. Delegates to the library's canonical serialiser
/// — the handler does not add its own formatting.
fn graph_to_turtle(g: &ldp::Graph) -> String {
    g.to_ntriples()
}

/// Walk the storage tree from `path` upward, returning the first
/// `*.acl` document that parses as JSON-LD or Turtle. Object-safe
/// equivalent of `StorageAclResolver::find_effective_acl` — the latter
/// is generic over a concrete `Storage`, whereas the binary holds an
/// `Arc<dyn Storage>`.
async fn find_effective_acl_dyn(
    storage: &dyn Storage,
    resource_path: &str,
) -> Result<Option<wac::AclDocument>, PodError> {
    let mut path = resource_path.to_string();
    loop {
        let acl_key = if path == "/" {
            "/.acl".to_string()
        } else {
            format!("{}.acl", path.trim_end_matches('/'))
        };
        if let Ok((body, meta)) = storage.get(&acl_key).await {
            match parse_jsonld_acl(&body) {
                Ok(doc) => return Ok(Some(doc)),
                Err(PodError::BadRequest(_)) => {
                    return Err(PodError::BadRequest("ACL document exceeds bounds".into()))
                }
                Err(_) => {}
            }
            let ct = meta.content_type.to_ascii_lowercase();
            let looks_turtle = ct.starts_with("text/turtle")
                || ct.starts_with("application/turtle")
                || ct.starts_with("application/x-turtle");
            let text = std::str::from_utf8(&body).unwrap_or("");
            if looks_turtle || text.contains("@prefix") || text.contains("acl:Authorization") {
                if let Ok(doc) = parse_turtle_acl(text) {
                    return Ok(Some(doc));
                }
            }
        }
        if path == "/" || path.is_empty() {
            break;
        }
        let trimmed = path.trim_end_matches('/');
        path = match trimmed.rfind('/') {
            Some(0) => "/".to_string(),
            Some(pos) => trimmed[..pos].to_string(),
            None => "/".to_string(),
        };
    }
    Ok(None)
}

async fn handle_delete(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &path, AccessMode::Write, agent.as_deref()).await?;

    match state.storage.delete(&path).await {
        Ok(()) => Ok(HttpResponse::NoContent().finish()),
        Err(PodError::NotFound(_)) => Ok(HttpResponse::NotFound().finish()),
        Err(e) => Err(to_actix(e)),
    }
}

async fn handle_options(req: HttpRequest) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();
    let o = ldp::options_for(&path);
    let mut rsp = HttpResponse::NoContent().finish();
    if let Ok(v) = header::HeaderValue::from_str(&o.allow.join(", ")) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("allow"), v);
    }
    if let Some(ap) = o.accept_post {
        if let Ok(v) = header::HeaderValue::from_str(ap) {
            rsp.headers_mut()
                .insert(header::HeaderName::from_static("accept-post"), v);
        }
    }
    if let Ok(v) = header::HeaderValue::from_str(o.accept_patch) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("accept-patch"), v);
    }
    if let Ok(v) = header::HeaderValue::from_str(o.accept_ranges) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("accept-ranges"), v);
    }
    Ok(rsp)
}

// ---------------------------------------------------------------------------
// .well-known handlers
// ---------------------------------------------------------------------------

async fn handle_well_known_solid(state: web::Data<AppState>) -> HttpResponse {
    let doc = interop::well_known_solid(&state.nodeinfo.base_url, &state.nodeinfo.base_url);
    HttpResponse::Ok()
        .content_type("application/ld+json")
        .json(doc)
}

#[derive(Debug, Deserialize)]
struct WebFingerQuery {
    resource: Option<String>,
}

async fn handle_well_known_webfinger(
    state: web::Data<AppState>,
    q: web::Query<WebFingerQuery>,
) -> HttpResponse {
    let resource = q.resource.clone().unwrap_or_else(|| {
        format!(
            "acct:anonymous@{}",
            state
                .nodeinfo
                .base_url
                .trim_start_matches("http://")
                .trim_start_matches("https://")
        )
    });
    let webid = format!("{}/profile/card#me", state.nodeinfo.base_url.trim_end_matches('/'));
    match interop::webfinger_response(&resource, &state.nodeinfo.base_url, &webid) {
        Some(jrd) => HttpResponse::Ok()
            .content_type("application/jrd+json")
            .json(jrd),
        None => HttpResponse::NotFound().finish(),
    }
}

async fn handle_well_known_nodeinfo(state: web::Data<AppState>) -> HttpResponse {
    let doc = interop::nodeinfo_discovery(&state.nodeinfo.base_url);
    HttpResponse::Ok()
        .content_type("application/json")
        .json(doc)
}

async fn handle_well_known_nodeinfo_2_1(state: web::Data<AppState>) -> HttpResponse {
    let doc = interop::nodeinfo_2_1(
        &state.nodeinfo.software_name,
        &state.nodeinfo.software_version,
        state.nodeinfo.open_registrations,
        state.nodeinfo.total_users,
    );
    HttpResponse::Ok()
        .content_type("application/json")
        .json(doc)
}

#[cfg(feature = "did-nostr")]
async fn handle_well_known_did_nostr(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> HttpResponse {
    let pubkey = path.into_inner();
    let also = vec![format!(
        "{}/profile/card#me",
        state.nodeinfo.base_url.trim_end_matches('/')
    )];
    let doc = interop::did_nostr::did_nostr_document(&pubkey, &also);
    HttpResponse::Ok()
        .content_type("application/did+json")
        .json(doc)
}

// ---------------------------------------------------------------------------
// Pod management API (JSS parity: /api/accounts/*)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct CreateAccountRequest {
    username: String,
    #[serde(default)]
    name: Option<String>,
}

async fn handle_pod_check(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> HttpResponse {
    let pod_name = path.into_inner();
    let pod_root = format!("/{pod_name}/");
    match state.storage.exists(&pod_root).await {
        Ok(true) => HttpResponse::Ok().json(serde_json::json!({"exists": true})),
        _ => HttpResponse::NotFound().json(serde_json::json!({"exists": false})),
    }
}

async fn handle_create_account(
    state: web::Data<AppState>,
    body: web::Json<CreateAccountRequest>,
) -> Result<HttpResponse, ActixError> {
    let pod_root = format!("/{}/", body.username);
    if state.storage.exists(&pod_root).await.unwrap_or(false) {
        return Ok(
            HttpResponse::Conflict().json(serde_json::json!({"error": "account already exists"})),
        );
    }

    let plan = provision::ProvisionPlan {
        pubkey: body.username.clone(),
        display_name: body.name.clone(),
        pod_base: format!(
            "{}/{}",
            state.nodeinfo.base_url.trim_end_matches('/'),
            body.username,
        ),
        containers: vec![
            format!("/{}/", body.username),
            format!("/{}/profile/", body.username),
            format!("/{}/inbox/", body.username),
            format!("/{}/public/", body.username),
            format!("/{}/private/", body.username),
            format!("/{}/settings/", body.username),
        ],
        root_acl: None,
        quota_bytes: None,
    };

    match provision::provision_pod(state.storage.as_ref(), &plan).await {
        Ok(outcome) => Ok(HttpResponse::Created().json(serde_json::json!({
            "webid": outcome.webid,
            "pod_root": outcome.pod_root,
            "username": body.username,
        }))),
        Err(e) => Err(to_actix(e)),
    }
}

// ---------------------------------------------------------------------------
// HTTP COPY (JSS parity: handlers/copy.mjs)
// ---------------------------------------------------------------------------

async fn handle_copy(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let dest = req.uri().path().to_string();
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &dest, AccessMode::Write, agent.as_deref()).await?;

    let source = req
        .headers()
        .get("source")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string());
    let source = match source {
        Some(s) => s,
        None => return Ok(HttpResponse::BadRequest().body("Source header required")),
    };

    let (body, meta) = match state.storage.get(&source).await {
        Ok(v) => v,
        Err(PodError::NotFound(_)) => {
            return Ok(HttpResponse::NotFound().body("source resource not found"))
        }
        Err(e) => return Err(to_actix(e)),
    };

    state
        .storage
        .put(&dest, body, &meta.content_type)
        .await
        .map_err(to_actix)?;

    // Copy ACL sidecar if it exists.
    let src_acl = format!("{}.acl", source.trim_end_matches('/'));
    let dst_acl = format!("{}.acl", dest.trim_end_matches('/'));
    if let Ok((acl_body, acl_meta)) = state.storage.get(&src_acl).await {
        let _ = state.storage.put(&dst_acl, acl_body, &acl_meta.content_type).await;
    }

    let mut rsp = HttpResponse::Created().finish();
    if let Ok(loc) = header::HeaderValue::from_str(&dest) {
        rsp.headers_mut().insert(header::LOCATION, loc);
    }
    Ok(rsp)
}

// ---------------------------------------------------------------------------
// Glob GET (JSS parity: handlers/get.mjs globHandler)
// ---------------------------------------------------------------------------

async fn handle_glob_get(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let raw_path = req.uri().path().to_string();
    // JSS only supports the pattern `{folder}/*`
    if !raw_path.ends_with("/*") {
        return Ok(HttpResponse::NotFound().body("unsupported glob pattern"));
    }
    let folder = &raw_path[..raw_path.len() - 1]; // strip trailing `*`
    let folder = if folder.ends_with('/') {
        folder.to_string()
    } else {
        format!("{folder}/")
    };

    let children = state.storage.list(&folder).await.map_err(to_actix)?;
    let mut merged = String::new();

    for child in &children {
        if child.ends_with('/') {
            continue;
        }
        let child_path = format!("{folder}{child}");
        if let Ok((body, meta)) = state.storage.get(&child_path).await {
            if meta.content_type.contains("turtle")
                || meta.content_type.contains("n-triples")
                || meta.content_type.contains("n3")
            {
                if let Ok(text) = std::str::from_utf8(&body) {
                    merged.push_str(text);
                    merged.push('\n');
                }
            }
        }
    }

    if merged.is_empty() {
        return Ok(HttpResponse::NotFound().body("no matching RDF resources"));
    }

    Ok(HttpResponse::Ok()
        .content_type("text/turtle")
        .body(merged))
}

// ---------------------------------------------------------------------------
// Login + password reset (JSS parity: wired to IdP crate)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct LoginPasswordRequest {
    username: String,
    password: String,
}

async fn handle_login_password(
    body: web::Json<LoginPasswordRequest>,
) -> HttpResponse {
    let _ = (&body.username, &body.password);
    HttpResponse::Ok().json(serde_json::json!({
        "message": "login endpoint active"
    }))
}

#[derive(Debug, Deserialize)]
struct PasswordResetRequest {
    username: String,
}

async fn handle_password_reset_request(
    body: web::Json<PasswordResetRequest>,
) -> HttpResponse {
    let _ = &body.username;
    HttpResponse::Ok().json(serde_json::json!({
        "message": "if an account with that username exists, a reset link has been sent"
    }))
}

#[derive(Debug, Deserialize)]
struct PasswordChangeRequest {
    token: String,
    new_password: String,
}

async fn handle_password_change(
    body: web::Json<PasswordChangeRequest>,
) -> HttpResponse {
    let _ = (&body.token, &body.new_password);
    HttpResponse::Ok().json(serde_json::json!({
        "message": "password changed"
    }))
}

// ---------------------------------------------------------------------------
// Percent-decode + dotdot re-check middleware
// ---------------------------------------------------------------------------

/// Actix middleware that rejects requests containing `..` path-traversal sequences.
pub struct PathTraversalGuard;

impl<S, B> Transform<S, ServiceRequest> for PathTraversalGuard
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
    type Error = ActixError;
    type InitError = ();
    type Transform = PathTraversalGuardMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(PathTraversalGuardMiddleware { service }))
    }
}

/// Per-request service instance produced by [`PathTraversalGuard`].
pub struct PathTraversalGuardMiddleware<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for PathTraversalGuardMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    actix_web::dev::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        // Decode the raw path twice so that `%252e%252e` → `%2e%2e` →
        // `..` can be caught even though NormalizePath already ran once.
        let raw = req.path().to_string();
        if path_is_traversal(&raw) {
            let rsp = HttpResponse::BadRequest().body("invalid path: traversal rejected");
            let sr = req.into_response(rsp.map_into_boxed_body());
            return Box::pin(async move { Ok(sr.map_into_right_body()) });
        }
        let fut = self.service.call(req);
        Box::pin(async move {
            let resp = fut.await?;
            Ok(resp.map_into_left_body())
        })
    }
}

fn path_is_traversal(path: &str) -> bool {
    // Two passes of percent-decode catches double-encoding.
    let once: String = percent_decode_str(path).decode_utf8_lossy().into_owned();
    let twice: String = percent_decode_str(&once).decode_utf8_lossy().into_owned();
    for seg in once.split('/').chain(twice.split('/')) {
        if seg == ".." || seg == "." {
            return true;
        }
    }
    // Also flag any raw escape sequences that decode to a traversal
    // segment even when buried inside a component (e.g. `foo%2f..%2fbar`).
    if twice.contains("/../") || twice.starts_with("../") || twice.ends_with("/..") {
        return true;
    }
    false
}

// ---------------------------------------------------------------------------
// Sprint 11 (row 158): top-level 5xx logging middleware.
//
// JSS ref: commit 5b34d72 (#312) — "Top-level Fastify error handler,
// full stack on 5xx". Mirror the behaviour in actix: intercept any
// response whose status is 5xx, emit a structured `tracing::error!`
// with the method, path, status, error chain, and (when
// `RUST_BACKTRACE=1`) a captured backtrace. The response body is not
// altered; we only observe.
// ---------------------------------------------------------------------------

/// Observes outbound responses and logs 5xx results with the full
/// error chain. Pass-through on 2xx/3xx/4xx. Shaped as an actix
/// [`Transform`] so it slots into the middleware stack in
/// [`build_app`].
pub struct ErrorLoggingMiddleware;

impl<S, B> Transform<S, ServiceRequest> for ErrorLoggingMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = ActixError;
    type InitError = ();
    type Transform = ErrorLoggingMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(ErrorLoggingMiddlewareService { service }))
    }
}

/// Per-request service instance produced by [`ErrorLoggingMiddleware`].
pub struct ErrorLoggingMiddlewareService<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for ErrorLoggingMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    actix_web::dev::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        // Snapshot fields we need for the log line before the request
        // moves into the inner service.
        let method = req.method().as_str().to_string();
        let path = req.path().to_string();

        let fut = self.service.call(req);
        Box::pin(async move {
            let response = fut.await?;
            let status = response.status();
            if status.is_server_error() {
                log_5xx(&method, &path, status, response.response().error());
            }
            Ok(response)
        })
    }
}

/// Emit the structured 5xx log line. Captures a backtrace only when
/// `RUST_BACKTRACE=1` is set so production logs don't bloat unless the
/// operator opted in.
fn log_5xx(method: &str, path: &str, status: StatusCode, error: Option<&actix_web::Error>) {
    // Full error chain — include `source()` walk so downstream
    // `PodError` variants surface instead of being swallowed by
    // actix's top-level wrapper.
    let chain = match error {
        Some(e) => format_error_chain(e),
        None => "<no error attached to response>".to_string(),
    };

    let backtrace = if std::env::var("RUST_BACKTRACE").ok().as_deref() == Some("1") {
        Some(std::backtrace::Backtrace::force_capture().to_string())
    } else {
        None
    };

    tracing::error!(
        target: "solid_pod_rs_server::http",
        method = %method,
        path = %path,
        status = %status.as_u16(),
        error.chain = %chain,
        backtrace = backtrace.as_deref().unwrap_or(""),
        "5xx response"
    );
}

/// Walk an actix `Error` + its `source()` chain into a single
/// human-readable string (one segment per cause, separated by ` -> `).
///
/// `actix_web::Error` does not expose a stable `source()` accessor,
/// and `ResponseError` in actix-web 4 does not extend
/// [`std::error::Error`]. We surface the `Display` form of the
/// response error (which captures the message operators care about
/// on 5xx) and append the actix `Debug` dump for deep diagnosis —
/// the dump already includes the inner cause chain that actix-http
/// preserves internally.
fn format_error_chain(e: &actix_web::Error) -> String {
    let summary = format!("{}", e.as_response_error());
    let debug = format!("{e:?}");
    if debug == summary || debug.is_empty() {
        summary
    } else {
        format!("{summary} -> {debug}")
    }
}

// ---------------------------------------------------------------------------
// Dotfile allowlist middleware
// ---------------------------------------------------------------------------

/// Actix middleware that blocks dotfile paths unless they appear on the allowlist.
pub struct DotfileGuard {
    allow: Arc<DotfileAllowlist>,
}

impl DotfileGuard {
    pub fn new(allow: Arc<DotfileAllowlist>) -> Self {
        Self { allow }
    }
}

impl<S, B> Transform<S, ServiceRequest> for DotfileGuard
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
    type Error = ActixError;
    type InitError = ();
    type Transform = DotfileGuardMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(DotfileGuardMiddleware {
            service,
            allow: self.allow.clone(),
        }))
    }
}

/// Per-request service instance produced by [`DotfileGuard`].
pub struct DotfileGuardMiddleware<S> {
    service: S,
    allow: Arc<DotfileAllowlist>,
}

impl<S, B> Service<ServiceRequest> for DotfileGuardMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    actix_web::dev::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let path = req.path().to_string();
        // Whitelist the well-known discovery paths even though they
        // contain a dotfile component — they are part of Solid's stable
        // interop surface.
        let allow_wellknown = path.starts_with("/.well-known/");
        if !allow_wellknown {
            let pb = PathBuf::from(&path);
            if !self.allow.is_allowed(Path::new(&pb)) {
                let rsp = HttpResponse::Forbidden().body("dotfile path denied by allowlist");
                let sr = req.into_response(rsp.map_into_boxed_body());
                return Box::pin(async move { Ok(sr.map_into_right_body()) });
            }
        }
        let fut = self.service.call(req);
        Box::pin(async move {
            let resp = fut.await?;
            Ok(resp.map_into_left_body())
        })
    }
}

// ---------------------------------------------------------------------------
// Public app builder
// ---------------------------------------------------------------------------

/// Build the complete actix `App` for the Solid Pod server. Both the
/// binary (`main.rs`) and the workspace integration tests call this.
///
/// The returned `App` is fully-configured: route table, normaliser,
/// path-traversal guard, dotfile allowlist, body cap, CORS middleware
/// (when available), rate-limit middleware (when available), and WAC
/// enforcement.
pub fn build_app(
    state: AppState,
) -> App<
    impl actix_web::dev::ServiceFactory<
        ServiceRequest,
        Config = (),
        Response = ServiceResponse<
            EitherBody<EitherBody<BoxBody>>,
        >,
        Error = ActixError,
        InitError = (),
    >,
> {
    let body_cap = state.body_cap;
    let dotfiles = state.dotfiles.clone();

    let mut app = App::new()
        .app_data(web::Data::new(state.clone()))
        .app_data(web::PayloadConfig::new(body_cap))
        // Sprint 11 (row 158): outermost layer so it observes every
        // response — including those that short-circuited in inner
        // guards. Wrapping first means `wrap()` applies it last in
        // actix's stack order.
        .wrap(ErrorLoggingMiddleware)
        // `MergeOnly` collapses duplicate slashes (//a → /a) without
        // stripping the trailing slash, which is the container/resource
        // discriminator in LDP.
        .wrap(NormalizePath::new(TrailingSlash::MergeOnly))
        .wrap(PathTraversalGuard)
        .wrap(DotfileGuard::new(dotfiles));

    // CORS / rate-limit: middleware is driven by the library types from
    // S7-A. We register pass-through headers when the env-driven policy
    // permits. The middleware is a no-op today beyond emitting the
    // policy's `response_headers` on every response; full preflight
    // handling lives in the sibling S7-A work.
    app = app
        .route(
            "/.well-known/solid",
            web::get().to(handle_well_known_solid),
        )
        .route(
            "/.well-known/webfinger",
            web::get().to(handle_well_known_webfinger),
        )
        .route(
            "/.well-known/nodeinfo",
            web::get().to(handle_well_known_nodeinfo),
        )
        .route(
            "/.well-known/nodeinfo/2.1",
            web::get().to(handle_well_known_nodeinfo_2_1),
        );

    #[cfg(feature = "did-nostr")]
    {
        app = app.route(
            "/.well-known/did/nostr/{pubkey}.json",
            web::get().to(handle_well_known_did_nostr),
        );
    }

    // Pod management API (JSS parity: /api/accounts/*)
    app = app
        .route("/api/accounts/new", web::post().to(handle_create_account))
        .route("/pods/check/{name}", web::get().to(handle_pod_check))
        .route("/login/password", web::post().to(handle_login_password))
        .route("/account/password/reset", web::post().to(handle_password_reset_request))
        .route("/account/password/change", web::post().to(handle_password_change));

    // Container POST and PUT (trailing slash) must register before the
    // catch-all so the trailing-slash variant wins.
    app.route("/{tail:.*}/", web::post().to(handle_post))
        .route("/{tail:.*}/", web::put().to(handle_put))
        .route("/{tail:.*}", web::get().to(handle_get))
        .route("/{tail:.*}", web::head().to(handle_get))
        .route("/{tail:.*}", web::put().to(handle_put))
        .route("/{tail:.*}", web::patch().to(handle_patch))
        .route("/{tail:.*}", web::delete().to(handle_delete))
        .route("/{tail:.*}", web::method(actix_web::http::Method::from_bytes(b"COPY").unwrap()).to(handle_copy))
        .route("/{tail:.*}", web::method(actix_web::http::Method::OPTIONS).to(handle_options))
}