solid-pod-rs 0.4.0-alpha.4

Rust-native Solid Pod server library — LDP, WAC, WebID, Solid-OIDC, Solid Notifications, NIP-98. Framework-agnostic.
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
//! Config source precedence + merge logic.
//!
//! # JSS env var mapping (canonical `JSS_*` prefix)
//!
//! The loader honours the following env vars 1:1 with their JSS
//! semantics. Where a var is listed with `[TODO verify JSS]` it means
//! solid-pod-rs introduces it to parity a Rust-side primitive that JSS
//! handles implicitly or not at all.
//!
//! | Env var | Maps to | JSS source |
//! |---|---|---|
//! | `JSS_HOST` | `server.host` | `config.js:98` |
//! | `JSS_PORT` | `server.port` | `config.js:97` |
//! | `JSS_BASE_URL` | `server.base_url` | `config.js:*` (bin/jss.js) |
//! | `JSS_ROOT` | `storage.Fs{root}` (fs kind only) | `config.js:99` |
//! | `JSS_STORAGE_TYPE` | `storage.type` (`fs`/`memory`/`s3`) | JSS uses storage adapters via `config.json`; env wrapper added here for CLI parity |
//! | `JSS_STORAGE_ROOT` | `storage.Fs{root}` | alias for `JSS_ROOT` restricted to fs backend |
//! | `JSS_S3_BUCKET` | `storage.S3{bucket}` | not in upstream JSS env (adapter config) — `[TODO verify JSS]` |
//! | `JSS_S3_REGION` | `storage.S3{region}` | `[TODO verify JSS]` |
//! | `JSS_S3_PREFIX` | `storage.S3{prefix}` | `[TODO verify JSS]` |
//! | `JSS_OIDC_ENABLED` | `auth.oidc_enabled` | JSS uses `JSS_IDP` (config.js:107); `JSS_IDP` accepted as alias |
//! | `JSS_IDP` | `auth.oidc_enabled` (alias of `JSS_OIDC_ENABLED`) | `config.js:107` |
//! | `JSS_OIDC_ISSUER` | `auth.oidc_issuer` | JSS `JSS_IDP_ISSUER` (config.js:108); `JSS_IDP_ISSUER` accepted as alias |
//! | `JSS_IDP_ISSUER` | `auth.oidc_issuer` (alias) | `config.js:108` |
//! | `JSS_DPOP_REPLAY_TTL_SECONDS` | `auth.dpop_replay_ttl_seconds` | `[TODO verify JSS]` — Rust-side DPoP cache tuning |
//! | `JSS_NOTIFICATIONS_WS2023` | `notifications.ws2023_enabled` | subset of JSS `JSS_NOTIFICATIONS` (config.js:104) |
//! | `JSS_NOTIFICATIONS_WEBHOOK` | `notifications.webhook2023_enabled` | subset of JSS `JSS_NOTIFICATIONS` |
//! | `JSS_NOTIFICATIONS_LEGACY` | `notifications.legacy_solid_01_enabled` | subset of JSS `JSS_NOTIFICATIONS` |
//! | `JSS_NOTIFICATIONS` | toggles **all three** notification channels on/off | `config.js:104` (coarse master switch) |
//! | `JSS_SSRF_ALLOW_PRIVATE` | `security.ssrf_allow_private` | `[TODO verify JSS]` — F1 security primitive |
//! | `JSS_SSRF_ALLOWLIST` | `security.ssrf_allowlist` (comma-separated) | `[TODO verify JSS]` |
//! | `JSS_SSRF_DENYLIST` | `security.ssrf_denylist` (comma-separated) | `[TODO verify JSS]` |
//! | `JSS_DOTFILE_ALLOWLIST` | `security.dotfile_allowlist` (comma-separated) | `[TODO verify JSS]` |
//! | `JSS_ACL_ORIGIN_ENABLED` | `security.acl_origin_enabled` | `[TODO verify JSS]` — F4 primitive |
//!
//! Unknown `JSS_*` vars are **ignored silently** at the sources layer
//! (warnings are a loader-level concern, see
//! [`crate::config::loader::ConfigLoader`]). This supports forward
//! compat with newer JSS releases.
//!
//! # Precedence
//!
//! ```text
//! Defaults  <  File  <  EnvVars
//! (lowest)                (highest)
//! ```
//!
//! Later sources overwrite earlier ones, matching JSS's
//! `{...defaults, ...fileConfig, ...envConfig}` model
//! (`config.js:219-224`). CLI overlay (if added later) would sit above
//! env vars.

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

use serde_json::{Map, Value};

use crate::config::schema::ServerConfig;
use crate::error::PodError;

// ---------------------------------------------------------------------------
// ConfigSource
// ---------------------------------------------------------------------------

/// One layer of the precedence stack.
#[derive(Debug, Clone)]
pub enum ConfigSource {
    /// Hard-coded defaults (always first).
    Defaults,

    /// Config file at the given path. Format auto-detected from the
    /// extension: `.json`, `.yaml`/`.yml`, `.toml` (YAML/TOML require
    /// the `config-loader` feature). Missing / malformed is a hard
    /// error; unknown fields are tolerated.
    File(PathBuf),

    /// Read `JSS_*` env vars from `std::env`.
    EnvVars,

    /// Sprint 11 (row 121): highest-precedence CLI overlay, carried as
    /// a pre-built JSON value so the loader can deep-merge it without
    /// caring about the CLI parser.
    CliOverlay(Value),
}

// ---------------------------------------------------------------------------
// Resolution / merging
// ---------------------------------------------------------------------------

/// Resolve a source into a JSON value tree.
///
/// The returned value is a `serde_json::Value::Object` that is merged
/// into the accumulator by [`merge_json`] in precedence order.
pub(crate) fn resolve_source(source: &ConfigSource) -> Result<Value, PodError> {
    match source {
        ConfigSource::Defaults => {
            // Serialise the Default impl; this gives us the same
            // structure as a file-sourced config for easy merging.
            let cfg = ServerConfig::default();
            serde_json::to_value(&cfg).map_err(PodError::Json)
        }

        ConfigSource::File(path) => load_file(path),

        ConfigSource::EnvVars => Ok(load_env()),

        ConfigSource::CliOverlay(v) => Ok(v.clone()),
    }
}

fn load_file(path: &Path) -> Result<Value, PodError> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| PodError::Backend(format!("config file {path:?}: {e}")))?;

    // Auto-detect format from extension. Unknown extensions fall back to
    // JSON, preserving the Sprint-4 behaviour.
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .map(|s| s.to_ascii_lowercase());

    let v: Value = match ext.as_deref() {
        #[cfg(feature = "config-loader")]
        Some("yaml") | Some("yml") => serde_yaml::from_str(&content).map_err(|e| {
            PodError::Backend(format!("config file {path:?} is not valid YAML: {e}"))
        })?,

        #[cfg(feature = "config-loader")]
        Some("toml") => {
            let toml_v: toml::Value = toml::from_str(&content).map_err(|e| {
                PodError::Backend(format!("config file {path:?} is not valid TOML: {e}"))
            })?;
            // Convert toml::Value -> serde_json::Value via serde round-trip.
            serde_json::to_value(toml_v).map_err(PodError::Json)?
        }

        // Default / JSON extension / config-loader off: try JSON.
        _ => serde_json::from_str(&content).map_err(|e| {
            PodError::Backend(format!("config file {path:?} is not valid JSON: {e}"))
        })?,
    };

    if !v.is_object() {
        return Err(PodError::Backend(format!(
            "config file {path:?}: top-level must be an object, got {}",
            type_name(&v)
        )));
    }

    // JSS accepts a flat config.json (host/port at root). Normalise
    // both flat and nested shapes into the nested ServerConfig
    // structure that ServerConfig expects.
    Ok(normalise_file_shape(v))
}

/// Translate a JSS-style flat `config.json` into solid-pod-rs's nested
/// shape. A nested config passes through untouched.
///
/// JSS flat:
/// ```json
/// { "host": "0.0.0.0", "port": 3000, "storage": { "type": "fs", "root": "./data" } }
/// ```
///
/// Nested (solid-pod-rs native):
/// ```json
/// { "server": { "host": "…", "port": 3000 }, "storage": {…} }
/// ```
fn normalise_file_shape(v: Value) -> Value {
    let obj = match v {
        Value::Object(m) => m,
        other => return other,
    };

    // If a `server` key already exists, assume nested shape — pass through.
    if obj.contains_key("server") {
        return Value::Object(obj);
    }

    let mut out = Map::new();
    let mut server = Map::new();
    let mut remaining = Map::new();

    for (k, v) in obj {
        match k.as_str() {
            "host" | "port" | "base_url" | "baseUrl" => {
                // camelCase → snake_case for baseUrl
                let key = if k == "baseUrl" {
                    "base_url".to_string()
                } else {
                    k
                };
                server.insert(key, v);
            }
            _ => {
                remaining.insert(k, v);
            }
        }
    }

    if !server.is_empty() {
        out.insert("server".to_string(), Value::Object(server));
    }
    for (k, v) in remaining {
        out.insert(k, v);
    }

    Value::Object(out)
}

// ---------------------------------------------------------------------------
// Env var loading
// ---------------------------------------------------------------------------

/// Read the known `JSS_*` env vars and build a sparse JSON object
/// reflecting whichever were set.
///
/// Unknown `JSS_*` vars are ignored (warnings happen at the loader
/// level if requested).
fn load_env() -> Value {
    env_from(|k| std::env::var(k).ok())
}

/// Test-friendly variant that reads env via a closure.
pub(crate) fn env_from<F>(mut get: F) -> Value
where
    F: FnMut(&str) -> Option<String>,
{
    let mut out = Map::new();
    let mut server = Map::new();
    let mut storage = Map::new();
    let mut auth = Map::new();
    let mut notifications = Map::new();
    let mut security = Map::new();

    // --- server.*
    if let Some(v) = get("JSS_HOST") {
        server.insert("host".into(), Value::String(v));
    }
    if let Some(v) = get("JSS_PORT") {
        if let Ok(n) = v.parse::<u16>() {
            server.insert("port".into(), Value::Number(n.into()));
        }
    }
    if let Some(v) = get("JSS_BASE_URL") {
        server.insert("base_url".into(), Value::String(v));
    }

    // --- storage.*
    //
    // Precedence inside storage: JSS_STORAGE_TYPE > (JSS_STORAGE_ROOT | JSS_ROOT)
    // A bare JSS_ROOT implies fs backend.
    let storage_type = get("JSS_STORAGE_TYPE").map(|s| s.to_ascii_lowercase());
    let storage_root = get("JSS_STORAGE_ROOT").or_else(|| get("JSS_ROOT"));

    match storage_type.as_deref() {
        Some("memory") => {
            storage.insert("type".into(), Value::String("memory".into()));
            // JSS_STORAGE_ROOT=... while JSS_STORAGE_TYPE=memory is
            // nonsensical; loader emits a warning. Here we honour
            // memory and drop root.
        }
        Some("s3") => {
            storage.insert("type".into(), Value::String("s3".into()));
            if let Some(v) = get("JSS_S3_BUCKET") {
                storage.insert("bucket".into(), Value::String(v));
            }
            if let Some(v) = get("JSS_S3_REGION") {
                storage.insert("region".into(), Value::String(v));
            }
            if let Some(v) = get("JSS_S3_PREFIX") {
                storage.insert("prefix".into(), Value::String(v));
            }
        }
        Some("fs") | None if storage_root.is_some() => {
            storage.insert("type".into(), Value::String("fs".into()));
            if let Some(v) = storage_root {
                storage.insert("root".into(), Value::String(v));
            }
        }
        Some("fs") => {
            storage.insert("type".into(), Value::String("fs".into()));
        }
        Some(_) => {
            // Unknown storage type — leave unset; loader will flag.
        }
        None => {}
    }

    // --- auth.*
    if let Some(v) = get("JSS_OIDC_ENABLED").or_else(|| get("JSS_IDP")) {
        if let Some(b) = parse_bool(&v) {
            auth.insert("oidc_enabled".into(), Value::Bool(b));
        }
    }
    if let Some(v) = get("JSS_OIDC_ISSUER").or_else(|| get("JSS_IDP_ISSUER")) {
        auth.insert("oidc_issuer".into(), Value::String(v));
    }
    if let Some(v) = get("JSS_NIP98_ENABLED") {
        if let Some(b) = parse_bool(&v) {
            auth.insert("nip98_enabled".into(), Value::Bool(b));
        }
    }
    if let Some(v) = get("JSS_DPOP_REPLAY_TTL_SECONDS") {
        if let Ok(n) = v.parse::<u64>() {
            auth.insert("dpop_replay_ttl_seconds".into(), Value::Number(n.into()));
        }
    }

    // --- notifications.*
    // Coarse master switch — drives all three sub-toggles if individual
    // toggles aren't set.
    let master = get("JSS_NOTIFICATIONS").and_then(|v| parse_bool(&v));

    let ws = get("JSS_NOTIFICATIONS_WS2023")
        .and_then(|v| parse_bool(&v))
        .or(master);
    let webhook = get("JSS_NOTIFICATIONS_WEBHOOK")
        .and_then(|v| parse_bool(&v))
        .or(master);
    let legacy = get("JSS_NOTIFICATIONS_LEGACY")
        .and_then(|v| parse_bool(&v))
        .or(master);

    if let Some(b) = ws {
        notifications.insert("ws2023_enabled".into(), Value::Bool(b));
    }
    if let Some(b) = webhook {
        notifications.insert("webhook2023_enabled".into(), Value::Bool(b));
    }
    if let Some(b) = legacy {
        notifications.insert("legacy_solid_01_enabled".into(), Value::Bool(b));
    }

    // --- security.*
    if let Some(v) = get("JSS_SSRF_ALLOW_PRIVATE") {
        if let Some(b) = parse_bool(&v) {
            security.insert("ssrf_allow_private".into(), Value::Bool(b));
        }
    }
    if let Some(v) = get("JSS_SSRF_ALLOWLIST") {
        security.insert("ssrf_allowlist".into(), parse_csv(&v));
    }
    if let Some(v) = get("JSS_SSRF_DENYLIST") {
        security.insert("ssrf_denylist".into(), parse_csv(&v));
    }
    if let Some(v) = get("JSS_DOTFILE_ALLOWLIST") {
        security.insert("dotfile_allowlist".into(), parse_csv(&v));
    }
    if let Some(v) = get("JSS_ACL_ORIGIN_ENABLED") {
        if let Some(b) = parse_bool(&v) {
            security.insert("acl_origin_enabled".into(), Value::Bool(b));
        }
    }

    // Sprint 7: JSS_DEFAULT_QUOTA decoded via parse_size (`50MB`, `1.5GB`).
    // Surfaces under `security.default_quota_bytes` when valid;
    // malformed values are ignored (forward-compat with unknown units).
    if let Some(v) = get("JSS_DEFAULT_QUOTA").or_else(|| get("JSS_QUOTA_DEFAULT_BYTES")) {
        if let Ok(bytes) = parse_size(&v) {
            security.insert(
                "default_quota_bytes".into(),
                Value::Number(bytes.into()),
            );
        }
    }

    // Sprint 11 (row 120-124): JSS parity knobs that surface under the
    // forward-compat / operator-facing extras. Malformed values ignored
    // where parsing applies, same forward-compat rule as above.
    //
    // These vars do not yet have dedicated serde fields on
    // `ServerConfig` — they are stored under `extras.*` so operator
    // scripts can set them today and call sites can consult the loaded
    // tree via `ServerConfig::extras()` once wired. Keeping the env
    // map complete means a binary restart with new flags Just Works.
    let mut extras = Map::new();

    if let Some(v) = get("JSS_CONNEG") {
        if let Some(b) = parse_bool(&v) {
            extras.insert("conneg_enabled".into(), Value::Bool(b));
        }
    }
    if let Some(v) = get("JSS_CORS_ALLOWED_ORIGINS") {
        extras.insert("cors_allowed_origins".into(), parse_csv(&v));
    }
    if let Some(v) = get("JSS_MAX_BODY_SIZE").or_else(|| get("JSS_MAX_REQUEST_BODY")) {
        if let Ok(bytes) = parse_size(&v) {
            extras.insert("max_body_size_bytes".into(), Value::Number(bytes.into()));
        }
    }
    if let Some(v) = get("JSS_MAX_ACL_BYTES") {
        if let Ok(bytes) = parse_size(&v) {
            extras.insert("max_acl_bytes".into(), Value::Number(bytes.into()));
        }
    }
    if let Some(v) = get("JSS_RATE_LIMIT_WRITES_PER_MIN") {
        if let Ok(n) = v.parse::<u64>() {
            extras.insert(
                "rate_limit_writes_per_min".into(),
                Value::Number(n.into()),
            );
        }
    }
    if let Some(v) = get("JSS_SUBDOMAINS") {
        if let Some(b) = parse_bool(&v) {
            extras.insert("subdomains_enabled".into(), Value::Bool(b));
        }
    }
    if let Some(v) = get("JSS_BASE_DOMAIN") {
        extras.insert("base_domain".into(), Value::String(v));
    }
    if let Some(v) = get("JSS_IDP_ENABLED") {
        if let Some(b) = parse_bool(&v) {
            extras.insert("idp_enabled".into(), Value::Bool(b));
        }
    }
    if let Some(v) = get("JSS_INVITE_ONLY") {
        if let Some(b) = parse_bool(&v) {
            extras.insert("invite_only".into(), Value::Bool(b));
        }
    }
    if let Some(v) = get("JSS_ADMIN_KEY") {
        extras.insert("admin_key".into(), Value::String(v));
    }

    if !server.is_empty() {
        out.insert("server".into(), Value::Object(server));
    }
    if !storage.is_empty() {
        out.insert("storage".into(), Value::Object(storage));
    }
    if !auth.is_empty() {
        out.insert("auth".into(), Value::Object(auth));
    }
    if !notifications.is_empty() {
        out.insert("notifications".into(), Value::Object(notifications));
    }
    if !security.is_empty() {
        out.insert("security".into(), Value::Object(security));
    }
    if !extras.is_empty() {
        out.insert("extras".into(), Value::Object(extras));
    }

    Value::Object(out)
}

/// Parse a human-friendly size string into bytes.
///
/// Accepts a decimal number (optionally with fractional part) followed
/// by an optional suffix. Whitespace around / between the number and
/// suffix is tolerated. Empty suffix (or bare digits) is treated as raw
/// bytes.
///
/// # Multipliers
///
/// Supports **both SI (decimal, 1000-based) and IEC (binary, 1024-based)**
/// suffixes; case-insensitive:
///
/// | Suffix | Multiplier | Family |
/// |--------|-----------|--------|
/// | `B` or bare | 1 | — |
/// | `KB` | 1_000 | SI |
/// | `MB` | 1_000_000 | SI |
/// | `GB` | 1_000_000_000 | SI |
/// | `TB` | 1_000_000_000_000 | SI |
/// | `KiB` | 1_024 | IEC |
/// | `MiB` | 1_024² | IEC |
/// | `GiB` | 1_024³ | IEC |
/// | `TiB` | 1_024⁴ | IEC |
///
/// Sprint 7 tests relied on SI (`1.5GB → 1_500_000_000`). Sprint 11 adds
/// IEC suffixes so operators can mirror JSS's native 1024-based sizing
/// (`50MiB → 50 * 1024 * 1024`). JSS itself accepts only SI-style
/// suffixes (`K/M/G/T`) but multiplies them by 1024 — neither strictly
/// matches. We implement both and let the operator pick.
///
/// # JSS parity: `src/config.js::parseSize`
///
/// ```js
/// const match = str.match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)?$/i);
/// ```
///
/// Rust mirror: fraction-capable leading number, optional unit, case-
/// insensitive. JSS falls back to `parseInt(str, 10) || 0` on mismatch;
/// we return `Err` instead — callers decide whether to default.
pub fn parse_size(s: &str) -> Result<u64, String> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err("parse_size: empty input".into());
    }

    // Split number / suffix at the first non-digit / non-dot char.
    let cut = trimmed
        .find(|c: char| !(c.is_ascii_digit() || c == '.'))
        .unwrap_or(trimmed.len());
    let (num_part, suffix_part) = trimmed.split_at(cut);
    let num_part = num_part.trim();
    // Preserve case for `iB` detection, but match lookups case-insensitively.
    let suffix_raw = suffix_part.trim();
    let suffix = suffix_raw.to_ascii_uppercase();

    if num_part.is_empty() {
        return Err(format!("parse_size: missing number in {s:?}"));
    }

    // Reject malformed numerics (multi-dot, leading/trailing dot).
    if num_part.matches('.').count() > 1
        || num_part.starts_with('.')
        || num_part.ends_with('.')
    {
        return Err(format!("parse_size: invalid number {num_part:?}"));
    }

    let num: f64 = num_part
        .parse()
        .map_err(|e| format!("parse_size: bad number {num_part:?}: {e}"))?;

    if !num.is_finite() || num < 0.0 {
        return Err(format!("parse_size: non-negative finite number required, got {num}"));
    }

    // IEC (binary) suffixes carry the `i` between the prefix and B.
    // Upper-case comparison loses the lowercase `i`, so dispatch via the
    // already-uppercased suffix (which turns `KiB` into `KIB`).
    let multiplier: u64 = match suffix.as_str() {
        "" | "B" => 1,
        // SI (1000-based)
        "KB" => 1_000,
        "MB" => 1_000_000,
        "GB" => 1_000_000_000,
        "TB" => 1_000_000_000_000,
        // IEC (1024-based) — case-insensitive match since we upper-cased.
        "KIB" => 1_024,
        "MIB" => 1_024u64.pow(2),
        "GIB" => 1_024u64.pow(3),
        "TIB" => 1_024u64.pow(4),
        other => return Err(format!("parse_size: unknown suffix {other:?}")),
    };

    // floor(num * multiplier) — match JSS Math.floor behaviour.
    let bytes = (num * multiplier as f64).floor();
    if !bytes.is_finite() || bytes < 0.0 || bytes > u64::MAX as f64 {
        return Err(format!("parse_size: result out of u64 range: {bytes}"));
    }
    Ok(bytes as u64)
}

fn parse_bool(s: &str) -> Option<bool> {
    match s.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" | "" => Some(false),
        _ => None,
    }
}

fn parse_csv(s: &str) -> Value {
    Value::Array(
        s.split(',')
            .map(|p| p.trim())
            .filter(|p| !p.is_empty())
            .map(|p| Value::String(p.to_string()))
            .collect(),
    )
}

fn type_name(v: &Value) -> &'static str {
    match v {
        Value::Null => "null",
        Value::Bool(_) => "bool",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

// ---------------------------------------------------------------------------
// Merge logic
// ---------------------------------------------------------------------------

/// Recursively deep-merge `overlay` into `base`. Objects are merged
/// key-by-key; non-object leaves are replaced wholesale.
///
/// This matches JSS's shallow-spread behaviour at the top level
/// (`{...defaults, ...fileConfig, ...envConfig}` — `config.js:219`)
/// but extends it to nested objects so a partial `server` override
/// doesn't wipe unset siblings.
pub(crate) fn merge_json(base: &mut Value, overlay: Value) {
    match (base, overlay) {
        (Value::Object(b), Value::Object(o)) => {
            for (k, v) in o {
                match b.get_mut(&k) {
                    Some(existing) => merge_json(existing, v),
                    None => {
                        b.insert(k, v);
                    }
                }
            }
        }
        (slot, overlay) => {
            *slot = overlay;
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn merge_nested_objects_preserves_siblings() {
        let mut base = serde_json::json!({
            "server": { "host": "0.0.0.0", "port": 3000 },
            "auth":   { "oidc_enabled": false }
        });
        let overlay = serde_json::json!({
            "server": { "port": 8080 }
        });

        merge_json(&mut base, overlay);

        assert_eq!(base["server"]["host"], "0.0.0.0");
        assert_eq!(base["server"]["port"], 8080);
        assert_eq!(base["auth"]["oidc_enabled"], false);
    }

    #[test]
    fn env_host_port() {
        let v = env_from(|k| match k {
            "JSS_HOST" => Some("127.0.0.1".into()),
            "JSS_PORT" => Some("4242".into()),
            _ => None,
        });
        assert_eq!(v["server"]["host"], "127.0.0.1");
        assert_eq!(v["server"]["port"], 4242);
    }

    #[test]
    fn env_memory_storage_ignores_root() {
        let v = env_from(|k| match k {
            "JSS_STORAGE_TYPE" => Some("memory".into()),
            "JSS_STORAGE_ROOT" => Some("/ignored".into()),
            _ => None,
        });
        assert_eq!(v["storage"]["type"], "memory");
        assert!(v["storage"].get("root").is_none());
    }

    #[test]
    fn env_fs_storage_from_jss_root_alias() {
        let v = env_from(|k| match k {
            "JSS_ROOT" => Some("/pods".into()),
            _ => None,
        });
        assert_eq!(v["storage"]["type"], "fs");
        assert_eq!(v["storage"]["root"], "/pods");
    }

    #[test]
    fn env_csv_parses_to_array() {
        let v = env_from(|k| match k {
            "JSS_SSRF_ALLOWLIST" => Some("10.0.0.0/8, 192.168.1.5".into()),
            _ => None,
        });
        assert_eq!(
            v["security"]["ssrf_allowlist"],
            serde_json::json!(["10.0.0.0/8", "192.168.1.5"])
        );
    }

    #[test]
    fn flat_file_shape_normalised_to_nested() {
        let flat = serde_json::json!({
            "host": "0.0.0.0",
            "port": 3000,
            "baseUrl": "https://example.org",
            "storage": { "type": "fs", "root": "./data" }
        });
        let nested = normalise_file_shape(flat);

        assert_eq!(nested["server"]["host"], "0.0.0.0");
        assert_eq!(nested["server"]["port"], 3000);
        assert_eq!(nested["server"]["base_url"], "https://example.org");
        assert_eq!(nested["storage"]["type"], "fs");
    }

    #[test]
    fn nested_file_shape_passes_through() {
        let nested = serde_json::json!({
            "server": { "host": "0.0.0.0", "port": 3000 }
        });
        let out = normalise_file_shape(nested.clone());
        assert_eq!(out, nested);
    }
}