ferripfs-config 0.1.0

IPFS node configuration types, compatible with Kubo config format
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
// Ported from: kubo/config/config.go
// Kubo version: v0.39.0
// Original: https://github.com/ipfs/kubo/blob/v0.39.0/config/config.go
//
// Original work: Copyright (c) Protocol Labs, Inc.
// Port: Copyright (c) 2026 ferripfs contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Configuration types for ferripfs, ported from Kubo's config package.

mod addresses;
mod api;
mod datastore;
mod gateway;
mod identity;
mod profile;
mod routing;
mod swarm;
mod types;

pub use addresses::*;
pub use api::*;
pub use datastore::*;
pub use gateway::*;
pub use identity::*;
pub use profile::*;
pub use routing::*;
pub use swarm::*;
pub use types::*;

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Default IPFS path name
pub const DEFAULT_PATH_NAME: &str = ".ipfs";

/// Default IPFS path root
pub const DEFAULT_PATH_ROOT: &str = "~/.ipfs";

/// Default config file name
pub const DEFAULT_CONFIG_FILE: &str = "config";

/// Environment variable for IPFS path
pub const ENV_DIR: &str = "IPFS_PATH";

/// Main configuration struct, matching Kubo's Config
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Config {
    /// Node identity (PeerID and private key)
    #[serde(default)]
    pub identity: Identity,

    /// Datastore configuration
    #[serde(default)]
    pub datastore: Datastore,

    /// Network addresses
    #[serde(default)]
    pub addresses: Addresses,

    /// Mount points configuration
    #[serde(default)]
    pub mounts: Mounts,

    /// Discovery settings
    #[serde(default)]
    pub discovery: Discovery,

    /// Routing configuration
    #[serde(default)]
    pub routing: Routing,

    /// IPNS settings
    #[serde(default, rename = "Ipns")]
    pub ipns: Ipns,

    /// Bootstrap peers (multiaddrs)
    #[serde(default, rename = "Bootstrap")]
    pub bootstrap: Vec<String>,

    /// Gateway configuration
    #[serde(default)]
    pub gateway: Gateway,

    /// API configuration
    #[serde(default, rename = "API")]
    pub api: Api,

    /// Swarm configuration
    #[serde(default)]
    pub swarm: SwarmConfig,

    /// AutoNAT configuration
    #[serde(default, rename = "AutoNAT")]
    pub auto_nat: AutoNatConfig,

    /// Pubsub configuration
    #[serde(default)]
    pub pubsub: PubsubConfig,

    /// Peering configuration
    #[serde(default)]
    pub peering: Peering,

    /// DNS configuration
    #[serde(default, rename = "DNS")]
    pub dns: DnsConfig,

    /// Migration settings
    #[serde(default)]
    pub migration: Migration,

    /// Experimental features
    #[serde(default)]
    pub experimental: Experiments,

    /// Pinning configuration
    #[serde(default)]
    pub pinning: Pinning,

    /// Import settings
    #[serde(default)]
    pub import: Import,

    /// Internal settings
    #[serde(default)]
    pub internal: Internal,
}

impl Config {
    /// Parse config from JSON string.
    ///
    /// # Security
    ///
    /// This performs only JSON deserialization. Call `validate()` after
    /// deserialization to perform security-relevant validation.
    pub fn parse(s: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(s)
    }

    /// Parse config from reader.
    ///
    /// # Security
    ///
    /// This performs only JSON deserialization. Call `validate()` after
    /// deserialization to perform security-relevant validation.
    pub fn from_reader<R: std::io::Read>(reader: R) -> Result<Self, serde_json::Error> {
        serde_json::from_reader(reader)
    }

    /// Validate configuration values.
    ///
    /// # Security
    ///
    /// This validates:
    /// - Address formats (API, Gateway, Swarm)
    /// - Bootstrap peer multiaddrs
    /// - Peer ID format (when present)
    /// - Numeric values are within reasonable ranges
    ///
    /// Returns a list of validation warnings (non-fatal issues) and
    /// returns an error for critical validation failures.
    pub fn validate(&self) -> Result<Vec<String>, ConfigError> {
        let mut warnings = Vec::new();

        // Validate swarm addresses
        for addr in &self.addresses.swarm {
            if !Self::is_valid_multiaddr_format(addr) {
                warnings.push(format!("Swarm address may be malformed: {}", addr));
            }
        }

        // Validate API addresses
        for addr in self.addresses.api.iter() {
            if !Self::is_valid_multiaddr_format(addr) {
                warnings.push(format!("API address may be malformed: {}", addr));
            }
        }

        // Validate Gateway addresses
        for addr in self.addresses.gateway.iter() {
            if !Self::is_valid_multiaddr_format(addr) {
                warnings.push(format!("Gateway address may be malformed: {}", addr));
            }
        }

        // Validate bootstrap peers
        for addr in &self.bootstrap {
            if !Self::is_valid_multiaddr_format(addr) {
                warnings.push(format!("Bootstrap address may be malformed: {}", addr));
            }
        }

        // Validate peer ID format (should be base58 encoded)
        if !self.identity.peer_id.is_empty()
            && !Self::is_valid_peer_id_format(&self.identity.peer_id)
        {
            return Err(ConfigError::InvalidKey(format!(
                "Invalid PeerID format: {}",
                self.identity.peer_id
            )));
        }

        // Validate connection manager values if present
        let conn_mgr = &self.swarm.conn_mgr;
        if let (Some(ref low), Some(ref high)) = (&conn_mgr.low_water, &conn_mgr.high_water) {
            if let (Some(low_val), Some(high_val)) = (low.value(), high.value()) {
                if low_val > high_val {
                    warnings.push(format!(
                        "ConnMgr.LowWater ({}) > HighWater ({})",
                        low_val, high_val
                    ));
                }
            }
        }

        Ok(warnings)
    }

    /// Check if a string looks like a valid multiaddr format.
    ///
    /// This is a basic format check, not full multiaddr validation.
    fn is_valid_multiaddr_format(addr: &str) -> bool {
        // Basic checks: must start with /, contain valid protocol names
        if !addr.starts_with('/') {
            return false;
        }
        // Should contain at least one known protocol
        let known_protocols = [
            "/ip4/",
            "/ip6/",
            "/tcp/",
            "/udp/",
            "/quic/",
            "/quic-v1/",
            "/ws/",
            "/wss/",
            "/p2p/",
            "/ipfs/",
            "/dns/",
            "/dns4/",
            "/dns6/",
            "/dnsaddr/",
            "/unix/",
        ];
        known_protocols.iter().any(|p| addr.contains(p))
    }

    /// Check if a string looks like a valid peer ID format.
    ///
    /// Peer IDs are typically base58-encoded multihashes starting with "12D3" or "Qm".
    fn is_valid_peer_id_format(peer_id: &str) -> bool {
        // Peer IDs are base58 encoded, common prefixes are:
        // - "12D3K" for Ed25519 keys
        // - "Qm" for RSA keys (sha256)
        // - "16U" for secp256k1
        if peer_id.is_empty() {
            return false;
        }
        // Must be valid base58 characters
        peer_id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() && c != '0' && c != 'O' && c != 'I' && c != 'l')
    }

    /// Serialize config to JSON string
    pub fn to_string_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Get a config value by dot-separated key path
    pub fn get_key(&self, key: &str) -> Option<serde_json::Value> {
        let json = serde_json::to_value(self).ok()?;
        let parts: Vec<&str> = key.split('.').collect();
        let mut current = &json;

        for part in parts {
            current = current.get(part)?;
        }

        Some(current.clone())
    }

    /// Set a config value by dot-separated key path
    pub fn set_key(&mut self, key: &str, value: serde_json::Value) -> Result<(), ConfigError> {
        let mut json = serde_json::to_value(&self)?;
        let parts: Vec<&str> = key.split('.').collect();

        if parts.is_empty() {
            return Err(ConfigError::InvalidKey(key.to_string()));
        }

        // Navigate to the parent object
        let mut current = &mut json;
        for part in &parts[..parts.len() - 1] {
            current = current
                .get_mut(*part)
                .ok_or_else(|| ConfigError::InvalidKey(key.to_string()))?;
        }

        // Set the final value
        let last_part = parts.last().unwrap();
        if let Some(obj) = current.as_object_mut() {
            obj.insert(last_part.to_string(), value);
        } else {
            return Err(ConfigError::InvalidKey(key.to_string()));
        }

        *self = serde_json::from_value(json)?;
        Ok(())
    }
}

/// Mount points configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Mounts {
    #[serde(default, rename = "IPFS")]
    pub ipfs: String,
    #[serde(default, rename = "IPNS")]
    pub ipns: String,
    #[serde(default, rename = "FuseAllowOther")]
    pub fuse_allow_other: bool,
}

/// Discovery configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Discovery {
    #[serde(default, rename = "MDNS")]
    pub mdns: Mdns,
}

/// mDNS discovery settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Mdns {
    #[serde(default)]
    pub enabled: bool,
}

/// IPNS configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Ipns {
    #[serde(default)]
    pub republish_period: String,
    #[serde(default)]
    pub record_lifetime: String,
    #[serde(default)]
    pub resolve_cache_size: i32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_cache_ttl: Option<OptionalDuration>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub use_pubsub: Option<Flag>,
}

/// AutoNAT configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AutoNatConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service_mode: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub throttle: Option<AutoNatThrottle>,
}

/// AutoNAT throttle settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AutoNatThrottle {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub global_limit: Option<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub peer_limit: Option<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval: Option<OptionalDuration>,
}

/// Pubsub configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PubsubConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<Flag>,
    #[serde(default)]
    pub router: String,
}

/// Peering configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Peering {
    #[serde(default)]
    pub peers: Vec<PeeringPeer>,
}

/// A peer in the peering list
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PeeringPeer {
    #[serde(default, rename = "ID")]
    pub id: String,
    #[serde(default)]
    pub addrs: Vec<String>,
}

/// DNS configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct DnsConfig {
    #[serde(default)]
    pub resolvers: HashMap<String, String>,
}

/// Migration settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Migration {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub download_sources: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep: Option<String>,
}

/// Experimental features
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Experiments {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filestore_enabled: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url_store_enabled: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "GraphsyncEnabled"
    )]
    pub graphsync_enabled: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub libp2p_stream_mounting: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub p2p_http_proxy: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "OptimisticProvide"
    )]
    pub optimistic_provide: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "OptimisticProvideJobsPoolSize"
    )]
    pub optimistic_provide_jobs_pool_size: Option<i32>,
}

/// Pinning configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Pinning {
    #[serde(default)]
    pub remote_services: HashMap<String, RemotePinningService>,
}

/// Remote pinning service configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RemotePinningService {
    #[serde(default, rename = "API")]
    pub api: RemotePinningApi,
    #[serde(default)]
    pub policies: RemotePinningPolicies,
}

/// Remote pinning API settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RemotePinningApi {
    #[serde(default)]
    pub endpoint: String,
    #[serde(default)]
    pub key: String,
}

/// Remote pinning policies
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RemotePinningPolicies {
    #[serde(default, rename = "MFS")]
    pub mfs: MfsPinPolicy,
}

/// MFS pin policy
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MfsPinPolicy {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub pin_name: String,
    #[serde(default)]
    pub repinning_interval: String,
}

/// Import configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Import {
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "CidVersion"
    )]
    pub cid_version: Option<OptionalInteger>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hash_function: Option<OptionalString>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unixfs_raw_leaves: Option<Flag>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "UnixFSChunker"
    )]
    pub unixfs_chunker: Option<OptionalString>,
}

/// Internal settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Internal {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bitswap: Option<InternalBitswap>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "UnixFSShardingSizeThreshold"
    )]
    pub unixfs_sharding_size_threshold: Option<OptionalString>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub libp2p_force_pnet: Option<Flag>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backoff_init: Option<OptionalDuration>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backoff_max: Option<OptionalDuration>,
}

/// Internal bitswap settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct InternalBitswap {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_worker_count: Option<OptionalInteger>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub engine_block_store_worker_count: Option<OptionalInteger>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub engine_task_worker_count: Option<OptionalInteger>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_outstanding_bytes_per_peer: Option<OptionalInteger>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provide_enabled: Option<Flag>,
}

/// Configuration error type
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("Invalid key: {0}")]
    InvalidKey(String),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        let json = config.to_string_pretty().unwrap();
        assert!(json.contains("Identity"));
    }

    #[test]
    fn test_config_roundtrip() {
        let config = Config::default();
        let json = config.to_string_pretty().unwrap();
        let parsed: Config = Config::parse(&json).unwrap();
        assert_eq!(config.identity.peer_id, parsed.identity.peer_id);
    }
}