rss-proxy 0.2.0

A high-performance, extensible RSS/Atom proxy and filtering server written in Rust
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
use crate::config::{AppConfig, FeedConfig, FeedFilterConfig};
use crate::fetcher::FeedFetcher;
use crate::opml::{generate_grouped_opml, ExportableFeed};
use crate::plugin::builtin::{
    AgeFilterPlugin, FeedCleanerPlugin, KeywordFilterPlugin, LimitPlugin, LinkCleanerPlugin,
    NopHandlerPlugin, RegexFilterPlugin,
};
use crate::plugin::rhai_plugin::RhaiPlugin;
use crate::plugin::{Plugin, PluginPipeline};
use axum::{
    extract::{Path, Query, State},
    http::{header, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{error, info};
use url::Url;

pub struct AppState {
    pub config: Arc<RwLock<AppConfig>>,
    pub config_path: PathBuf,
    pub fetcher: FeedFetcher,
}

/// Validate URL to prevent Server-Side Request Forgery (SSRF) attacks
fn validate_url_for_ssrf(url: &str) -> Result<(), &'static str> {
    let parsed = Url::parse(url).map_err(|_| "Invalid URL")?;

    // Only allow http and https schemes
    if parsed.scheme() != "http" && parsed.scheme() != "https" {
        return Err("URL must use http or https scheme");
    }

    // Get the host
    let host = parsed.host_str().ok_or("URL must have a valid host")?;

    // Check if host is localhost or loopback variants
    if host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]" {
        return Err("URL cannot point to localhost or loopback address");
    }

    // Check if host is an IP address
    if let Ok(ip) = host.parse::<IpAddr>() {
        // Check for private/internal IP addresses and cloud metadata endpoints
        match ip {
            IpAddr::V4(ipv4) => {
                if ipv4.is_loopback()
                    || ipv4.is_private()
                    || ipv4.is_link_local()
                    || ipv4.is_broadcast()
                    || ipv4 == std::net::Ipv4Addr::new(169, 254, 169, 254)
                // AWS/GCP metadata
                {
                    return Err("URL cannot point to private or internal IP address");
                }
            }
            IpAddr::V6(ipv6) => {
                if ipv6.is_loopback() || ipv6.is_unique_local() || ipv6.is_unicast_link_local() {
                    return Err("URL cannot point to private or internal IP address");
                }
            }
        }
    }

    Ok(())
}

#[derive(Debug, Deserialize)]
pub struct ProxyQuery {
    pub url: String,
    pub group: Option<String>,
    pub include: Option<String>,
    pub exclude: Option<String>,
    pub include_regex: Option<String>,
    pub exclude_regex: Option<String>,
    pub clean_links: Option<bool>,
    pub max_age_days: Option<i64>,
    pub limit: Option<usize>,
    pub script: Option<String>,
}

pub fn create_router(state: Arc<AppState>) -> Router {
    Router::new()
        .route("/", get(handle_root))
        .route("/health", get(handle_health))
        .route("/plugins", get(handle_list_plugins))
        .route("/opml", get(handle_export_opml))
        .route("/feeds", get(handle_all_feeds))
        .route("/feeds/", get(handle_all_feeds))
        .route("/feeds/{slug}", get(handle_configured_feed))
        .route("/feeds/{slug}/", get(handle_configured_feed))
        .route("/groups/{group}", get(handle_group_feed))
        .route("/groups/{group}/", get(handle_group_feed))
        .route("/categories/{group}", get(handle_group_feed))
        .route("/categories/{group}/", get(handle_group_feed))
        .route("/proxy", get(handle_proxy_feed))
        .with_state(state)
}

#[derive(Serialize)]
struct StatusResponse {
    status: &'static str,
    version: &'static str,
    configured_feeds: Vec<String>,
    groups: Vec<String>,
    available_plugins: Vec<String>,
    auto_register_proxy_feeds: bool,
}

async fn handle_root(State(state): State<Arc<AppState>>) -> Json<StatusResponse> {
    let (configured_feeds, groups, plugins_dir, auto_register) = {
        let cfg = state.config.read().await;
        let feeds = cfg.feeds.keys().cloned().collect();
        let mut groups_set = HashSet::new();
        for f in cfg.feeds.values() {
            if let Some(ref g) = f.group {
                groups_set.insert(g.clone());
            }
        }
        let mut groups: Vec<String> = groups_set.into_iter().collect();
        groups.sort();
        (
            feeds,
            groups,
            cfg.plugins_dir.clone(),
            cfg.auto_register_proxy_feeds,
        )
    };

    let plugins = RhaiPlugin::load_directory(&plugins_dir);
    let available_plugins = plugins.iter().map(|p| p.name().to_string()).collect();

    Json(StatusResponse {
        status: "running",
        version: env!("CARGO_PKG_VERSION"),
        configured_feeds,
        groups,
        available_plugins,
        auto_register_proxy_feeds: auto_register,
    })
}

async fn handle_health() -> &'static str {
    "OK"
}

async fn handle_list_plugins(State(state): State<Arc<AppState>>) -> Json<Vec<String>> {
    let plugins_dir = {
        let cfg = state.config.read().await;
        cfg.plugins_dir.clone()
    };
    let plugins = RhaiPlugin::load_directory(&plugins_dir);
    Json(plugins.into_iter().map(|p| p.name().to_string()).collect())
}

async fn handle_export_opml(State(state): State<Arc<AppState>>) -> Response {
    let feeds = {
        let cfg = state.config.read().await;
        let base = format!("http://{}:{}", cfg.server.host, cfg.server.port);
        let list: Vec<ExportableFeed> = cfg
            .feeds
            .iter()
            .map(|(slug, f)| {
                let title = f.title_override.clone().unwrap_or_else(|| slug.clone());
                let proxy_url = format!("{}/feeds/{}", base, slug);
                ExportableFeed {
                    title,
                    xml_url: proxy_url,
                    html_url: None,
                    group: f.group.clone(),
                }
            })
            .collect();
        list
    };

    let opml_xml = generate_grouped_opml("RSS Proxy Filtered Subscriptions", &feeds);

    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "text/x-opml; charset=utf-8"),
            (
                header::CONTENT_DISPOSITION,
                "attachment; filename=\"rss-proxy-subscriptions.opml\"",
            ),
        ],
        opml_xml,
    )
        .into_response()
}

fn build_pipeline_for_feed(
    feed_cfg: &FeedConfig,
    plugins_dir: &str,
) -> Result<PluginPipeline, String> {
    let mut pipeline = PluginPipeline::new();

    // 0. Feed cleaner (sanitizes broken or empty items)
    pipeline.add_plugin(Box::new(FeedCleanerPlugin::new()));

    // 0.1 NOP handler fallback (catches fetch/parse errors and serves valid NOP feed)
    pipeline.add_plugin(Box::new(NopHandlerPlugin::new()));

    // 1. Built-in keyword filter
    if !feed_cfg.filters.include_keywords.is_empty()
        || !feed_cfg.filters.exclude_keywords.is_empty()
    {
        pipeline.add_plugin(Box::new(KeywordFilterPlugin::new(
            feed_cfg.filters.include_keywords.clone(),
            feed_cfg.filters.exclude_keywords.clone(),
        )));
    }

    // 2. Built-in regex filter
    if !feed_cfg.filters.include_regex.is_empty() || !feed_cfg.filters.exclude_regex.is_empty() {
        match RegexFilterPlugin::new(
            &feed_cfg.filters.include_regex,
            &feed_cfg.filters.exclude_regex,
        ) {
            Ok(plugin) => pipeline.add_plugin(Box::new(plugin)),
            Err(e) => return Err(format!("Invalid regex configuration: {}", e)),
        }
    }

    // 3. Built-in link cleaner
    if feed_cfg.filters.clean_links {
        pipeline.add_plugin(Box::new(LinkCleanerPlugin::new()));
    }

    // 4. Built-in max age filter
    if let Some(days) = feed_cfg.filters.max_age_days {
        pipeline.add_plugin(Box::new(AgeFilterPlugin::from_days(days)));
    }

    // 5. Rhai script plugins
    for script_name in &feed_cfg.filters.scripts {
        let script_file = if script_name.ends_with(".rhai") {
            script_name.clone()
        } else {
            format!("{}.rhai", script_name)
        };
        let path = PathBuf::from(plugins_dir).join(&script_file);
        match RhaiPlugin::from_file(&path) {
            Ok(plugin) => pipeline.add_plugin(Box::new(plugin)),
            Err(e) => {
                error!("Failed to load plugin script {}: {}", path.display(), e);
            }
        }
    }

    // 6. Built-in limit plugin
    if let Some(limit) = feed_cfg.filters.max_items {
        pipeline.add_plugin(Box::new(LimitPlugin::new(limit)));
    }

    Ok(pipeline)
}

/// Serves an aggregated RSS feed containing posts from ALL configured feeds
async fn handle_all_feeds(State(state): State<Arc<AppState>>) -> Response {
    let (feeds_list, host, port, plugins_dir) = {
        let cfg = state.config.read().await;
        let list: Vec<(String, FeedConfig)> = cfg
            .feeds
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        (
            list,
            cfg.server.host.clone(),
            cfg.server.port,
            cfg.plugins_dir.clone(),
        )
    };

    render_aggregated_feed(
        &state,
        "RSS Proxy - All Feeds",
        &feeds_list,
        &host,
        port,
        &plugins_dir,
    )
    .await
}

/// Serves an aggregated RSS feed for a specific group/category of feeds
async fn handle_group_feed(
    Path(group_param): Path<String>,
    State(state): State<Arc<AppState>>,
) -> Response {
    let clean_group = group_param.trim_end_matches('/').to_lowercase();
    let (matching_feeds, host, port, plugins_dir) = {
        let cfg = state.config.read().await;
        let list: Vec<(String, FeedConfig)> = cfg
            .feeds
            .iter()
            .filter(|(_, f)| {
                f.group
                    .as_ref()
                    .map(|g| g.to_lowercase() == clean_group)
                    .unwrap_or(false)
            })
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        (
            list,
            cfg.server.host.clone(),
            cfg.server.port,
            cfg.plugins_dir.clone(),
        )
    };

    if matching_feeds.is_empty() {
        return (
            StatusCode::NOT_FOUND,
            format!("No feeds found in group '{}'", group_param),
        )
            .into_response();
    }

    let group_title = matching_feeds
        .first()
        .and_then(|(_, cfg)| cfg.group.clone())
        .unwrap_or(group_param);

    render_aggregated_feed(
        &state,
        &format!("RSS Proxy - {}", group_title),
        &matching_feeds,
        &host,
        port,
        &plugins_dir,
    )
    .await
}

async fn render_aggregated_feed(
    state: &Arc<AppState>,
    feed_title: &str,
    feeds_to_include: &[(String, FeedConfig)],
    host: &str,
    port: u16,
    plugins_dir: &str,
) -> Response {
    if feeds_to_include.is_empty() {
        let empty_feed = crate::model::Feed {
            title: feed_title.to_string(),
            link: format!("http://{}:{}/feeds", host, port),
            description: "No feeds in this view".to_string(),
            language: Some("en".to_string()),
            items: Vec::new(),
        };
        return match empty_feed.to_rss_xml() {
            Ok(xml) => (
                StatusCode::OK,
                [(header::CONTENT_TYPE, "application/rss+xml; charset=utf-8")],
                xml,
            )
                .into_response(),
            Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
        };
    }

    let mut all_items = Vec::new();

    for (slug, feed_cfg) in feeds_to_include {
        // Skip NOP feeds in aggregate view so dead feeds don't clutter the timeline
        if feed_cfg.nop {
            continue;
        }

        let mut feed = match state.fetcher.fetch(&feed_cfg.url).await {
            Ok(f) => f,
            Err(e) => {
                // Skip dead feeds in the aggregated view instead of failing
                error!("Skipping failed feed in aggregate view {}: {}", slug, e);
                continue;
            }
        };

        if let Some(ref override_title) = feed_cfg.title_override {
            feed.title = override_title.clone();
        }

        let pipeline = match build_pipeline_for_feed(feed_cfg, plugins_dir) {
            Ok(p) => p,
            Err(e) => {
                error!("Error building pipeline for {}: {}", slug, e);
                continue;
            }
        };

        if let Err(e) = pipeline.process(&mut feed).await {
            error!("Error processing pipeline for {}: {}", slug, e);
            continue;
        }

        all_items.extend(feed.items);
    }

    // Sort by publication date, newest first
    all_items.sort_by(|a, b| {
        let date_a = a.published.or(a.updated);
        let date_b = b.published.or(b.updated);
        date_b.cmp(&date_a)
    });

    // Deduplicate items by ID or link
    let mut seen_ids = HashSet::new();
    all_items.retain(|item| {
        let key = if !item.id.is_empty() {
            item.id.clone()
        } else {
            item.link.clone()
        };
        seen_ids.insert(key)
    });

    if all_items.len() > 100 {
        all_items.truncate(100);
    }

    let aggregate_feed = crate::model::Feed {
        title: feed_title.to_string(),
        link: format!("http://{}:{}/feeds", host, port),
        description: format!("Aggregated and filtered feeds for {}", feed_title),
        language: Some("en".to_string()),
        items: all_items,
    };

    match aggregate_feed.to_rss_xml() {
        Ok(xml) => (
            StatusCode::OK,
            [(header::CONTENT_TYPE, "application/rss+xml; charset=utf-8")],
            xml,
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("XML generation error: {}", e),
        )
            .into_response(),
    }
}

async fn handle_configured_feed(
    Path(slug): Path<String>,
    State(state): State<Arc<AppState>>,
) -> Response {
    let clean_slug = slug.trim_end_matches('/');

    let (feed_cfg, plugins_dir) = {
        let cfg = state.config.read().await;
        match cfg.feeds.get(clean_slug) {
            Some(c) => (c.clone(), cfg.plugins_dir.clone()),
            None => {
                return (
                    StatusCode::NOT_FOUND,
                    format!("Feed with slug '{}' not found in config", clean_slug),
                )
                    .into_response();
            }
        }
    };

    let feed_title = feed_cfg.title_override.as_deref().unwrap_or(clean_slug);

    // 0. If marked as NOP in config, serve NOP feed immediately without fetching upstream
    if feed_cfg.nop {
        let reason = feed_cfg
            .nop_reason
            .as_deref()
            .unwrap_or("Marked as NOP in configuration");
        let nop_feed = NopHandlerPlugin::make_nop_feed(&feed_cfg.url, feed_title, reason);
        return match nop_feed.to_rss_xml() {
            Ok(xml) => (
                StatusCode::OK,
                [(header::CONTENT_TYPE, "application/rss+xml; charset=utf-8")],
                xml,
            )
                .into_response(),
            Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
        };
    }

    // 1. Build pipeline
    let pipeline = match build_pipeline_for_feed(&feed_cfg, &plugins_dir) {
        Ok(p) => p,
        Err(e) => {
            error!("Invalid config for feed {}: {}", clean_slug, e);
            return (StatusCode::INTERNAL_SERVER_ERROR, e).into_response();
        }
    };

    // 2. Fetch feed (with automatic NOP fallback if upstream fails)
    let mut feed = match state.fetcher.fetch(&feed_cfg.url).await {
        Ok(f) => f,
        Err(e) => {
            if let Some(nop_feed) = pipeline
                .handle_fetch_error(&feed_cfg.url, feed_title, &e)
                .await
            {
                return match nop_feed.to_rss_xml() {
                    Ok(xml) => (
                        StatusCode::OK,
                        [(header::CONTENT_TYPE, "application/rss+xml; charset=utf-8")],
                        xml,
                    )
                        .into_response(),
                    Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, err).into_response(),
                };
            }

            error!("Failed to fetch upstream feed {}: {}", feed_cfg.url, e);
            return (
                StatusCode::BAD_GATEWAY,
                format!("Failed to fetch upstream feed: {}", e),
            )
                .into_response();
        }
    };

    if let Some(ref override_title) = feed_cfg.title_override {
        feed.title = override_title.clone();
    }

    // 3. Run through pipeline
    if let Err(e) = pipeline.process(&mut feed).await {
        error!("Pipeline processing failed for {}: {}", clean_slug, e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Pipeline error: {}", e),
        )
            .into_response();
    }

    // 4. Render XML
    match feed.to_rss_xml() {
        Ok(xml) => (
            StatusCode::OK,
            [(header::CONTENT_TYPE, "application/rss+xml; charset=utf-8")],
            xml,
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("XML generation error: {}", e),
        )
            .into_response(),
    }
}

async fn handle_proxy_feed(
    Query(params): Query<ProxyQuery>,
    State(state): State<Arc<AppState>>,
) -> Response {
    if params.url.trim().is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            "Missing required 'url' query parameter",
        )
            .into_response();
    }

    // Validate URL to prevent SSRF attacks
    if let Err(e) = validate_url_for_ssrf(&params.url) {
        return (
            StatusCode::BAD_REQUEST,
            format!("Invalid or unsafe URL: {}", e),
        )
            .into_response();
    }

    let mut pipeline = PluginPipeline::new();

    // Default cleaner & NOP fallback
    pipeline.add_plugin(Box::new(FeedCleanerPlugin::new()));
    pipeline.add_plugin(Box::new(NopHandlerPlugin::new()));

    // Keywords
    let include_kws: Vec<String> = params
        .include
        .map(|s| s.split(',').map(|k| k.trim().to_string()).collect())
        .unwrap_or_default();
    let exclude_kws: Vec<String> = params
        .exclude
        .map(|s| s.split(',').map(|k| k.trim().to_string()).collect())
        .unwrap_or_default();

    if !include_kws.is_empty() || !exclude_kws.is_empty() {
        pipeline.add_plugin(Box::new(KeywordFilterPlugin::new(
            include_kws.clone(),
            exclude_kws.clone(),
        )));
    }

    // Regex
    let include_regex = params.include_regex.map(|r| vec![r]).unwrap_or_default();
    let exclude_regex = params.exclude_regex.map(|r| vec![r]).unwrap_or_default();

    if !include_regex.is_empty() || !exclude_regex.is_empty() {
        match RegexFilterPlugin::new(&include_regex, &exclude_regex) {
            Ok(p) => pipeline.add_plugin(Box::new(p)),
            Err(e) => {
                return (
                    StatusCode::BAD_REQUEST,
                    format!("Invalid regex parameter: {}", e),
                )
                    .into_response();
            }
        }
    }

    // Link cleaner (default true)
    if params.clean_links.unwrap_or(true) {
        pipeline.add_plugin(Box::new(LinkCleanerPlugin::new()));
    }

    // Max age
    if let Some(days) = params.max_age_days {
        pipeline.add_plugin(Box::new(AgeFilterPlugin::from_days(days)));
    }

    // Custom Rhai script
    let plugins_dir = {
        let cfg = state.config.read().await;
        cfg.plugins_dir.clone()
    };

    if let Some(ref script_name) = params.script {
        let script_file = if script_name.ends_with(".rhai") {
            script_name.clone()
        } else {
            format!("{}.rhai", script_name)
        };
        let path = PathBuf::from(&plugins_dir).join(&script_file);
        match RhaiPlugin::from_file(&path) {
            Ok(p) => pipeline.add_plugin(Box::new(p)),
            Err(e) => {
                return (
                    StatusCode::BAD_REQUEST,
                    format!("Failed to load plugin '{}': {}", script_file, e),
                )
                    .into_response();
            }
        }
    }

    // Limit
    if let Some(limit) = params.limit {
        pipeline.add_plugin(Box::new(LimitPlugin::new(limit)));
    }

    // Fetch feed (with automatic fallback to NOP feed on error)
    let mut feed = match state.fetcher.fetch(&params.url).await {
        Ok(f) => f,
        Err(e) => match pipeline
            .handle_fetch_error(&params.url, &params.url, &e)
            .await
        {
            Some(nop_feed) => nop_feed,
            None => {
                return (
                    StatusCode::BAD_GATEWAY,
                    format!("Failed to fetch upstream feed: {}", e),
                )
                    .into_response();
            }
        },
    };

    // Auto-register in config if it doesn't exist
    let auto_register = {
        let cfg = state.config.read().await;
        cfg.auto_register_proxy_feeds
    };

    let mut registered_slug = None;

    if auto_register {
        let mut cfg = state.config.write().await;
        let existing = cfg
            .feeds
            .iter()
            .find(|(_, f)| f.url == params.url)
            .map(|(s, _)| s.clone());
        if let Some(slug) = existing {
            registered_slug = Some(slug);
        } else {
            let base_slug = crate::opml::slugify(&feed.title);
            let existing_slugs: HashSet<String> = cfg.feeds.keys().cloned().collect();
            let slug = crate::opml::unique_slug(&base_slug, &existing_slugs);

            let feed_config = FeedConfig {
                url: params.url.clone(),
                title_override: Some(feed.title.clone()),
                group: params.group.clone().or_else(|| Some("Proxied".to_string())),
                nop: false,
                nop_reason: None,
                filters: FeedFilterConfig {
                    include_keywords: include_kws,
                    exclude_keywords: exclude_kws,
                    include_regex,
                    exclude_regex,
                    clean_links: params.clean_links.unwrap_or(true),
                    max_age_days: params.max_age_days,
                    max_items: params.limit,
                    scripts: params.script.into_iter().collect(),
                },
            };

            cfg.feeds.insert(slug.clone(), feed_config);
            registered_slug = Some(slug.clone());

            if let Ok(yaml) = serde_yaml::to_string(&*cfg) {
                if let Err(e) = std::fs::write(&state.config_path, yaml) {
                    error!(
                        "Failed to persist auto-registered feed to {:?}: {}",
                        state.config_path, e
                    );
                } else {
                    info!(
                        "Auto-registered new feed '{}' as '/feeds/{}' in {:?}",
                        feed.title, slug, state.config_path
                    );
                }
            }
        }
    }

    // Filter feed
    if let Err(e) = pipeline.process(&mut feed).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Pipeline error: {}", e),
        )
            .into_response();
    }

    // Render XML
    match feed.to_rss_xml() {
        Ok(xml) => {
            let mut response = (
                StatusCode::OK,
                [(header::CONTENT_TYPE, "application/rss+xml; charset=utf-8")],
                xml,
            )
                .into_response();

            if let Some(slug) = registered_slug {
                if let Ok(val) = HeaderValue::from_str(&slug) {
                    response.headers_mut().insert("X-Feed-Slug", val);
                }
            }

            response
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("XML generation error: {}", e),
        )
            .into_response(),
    }
}