proxy-nostr-relay 0.3.1

A Nostr proxy relay with advanced bot filtering and an admin UI.
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
use axum::{
    extract::{Extension, Path, Query, State},
    routing::{delete, get, post, put},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use sqlx::SqlitePool;
use std::sync::Arc;

use crate::{auth, parser::filter_query, relay_pool::RelayPool};

pub fn router(pool: SqlitePool, relay_pool: Arc<RelayPool>) -> Router {
    Router::new()
        .route("/relay", get(get_relays).put(put_relays))
        .route("/relay-status", get(get_relay_status))
        .route("/relay-nip11", get(get_relay_nip11))
        .route("/safelist", get(list_safelist).post(upsert_safelist))
        .route("/safelist/:npub", delete(delete_safelist))
        .route("/safelist/:npub/ban", put(ban_npub))
        .route("/safelist/:npub/unban", put(unban_npub))
        .route("/filters", get(list_filters).post(create_filter))
        .route("/filters/:id", put(update_filter).delete(delete_filter))
        .route("/filters/validate", post(validate_filter))
        .route("/ip-access-control", get(list_ip_access_control).post(create_ip_access_control))
        .route("/ip-access-control/:id", put(update_ip_access_control).delete(delete_ip_access_control))
        .route("/req-kind-blacklist", get(list_req_kind_blacklist).post(create_req_kind_blacklist))
        .route("/req-kind-blacklist/:id", put(update_req_kind_blacklist).delete(delete_req_kind_blacklist))
        .route("/connection-logs", get(get_connection_logs))
        .route("/event-rejection-logs", get(get_event_rejection_logs))
        .route("/stats", get(get_stats))
        .route("/stats/timeseries", get(get_stats_timeseries))
        .route("/relay-info", get(get_relay_info).put(put_relay_info))
        .route("/app-version", get(get_app_version))
        .route("/simple-ban-rules", get(list_simple_ban_rules).post(create_simple_ban_rule))
        .route("/simple-ban-rules/:id", put(update_simple_ban_rule).delete(delete_simple_ban_rule))
        .with_state(pool.clone())
        .layer(Extension(relay_pool))
        .layer(axum::middleware::from_fn_with_state(pool, auth::basic_auth))
}

async fn get_relay_status(Extension(relay_pool): Extension<Arc<RelayPool>>) -> Json<serde_json::Value> {
    let relays = relay_pool.status_snapshot().await;
    Json(serde_json::json!({ "relays": relays }))
}

#[derive(Serialize)]
struct AppVersionResponse {
    version: &'static str,
}

async fn get_app_version() -> Json<AppVersionResponse> {
    Json(AppVersionResponse {
        version: env!("CARGO_PKG_VERSION"),
    })
}

#[derive(Debug, serde::Deserialize)]
pub struct RelayNip11Query {
    pub url: String,
}

async fn get_relay_nip11(Query(q): Query<RelayNip11Query>) -> Result<Json<serde_json::Value>, (axum::http::StatusCode, String)> {
    let url = q.url.trim();
    if url.is_empty() {
        return Err((axum::http::StatusCode::BAD_REQUEST, "missing url".to_string()));
    }
    let http_url = url
        .replace("wss://", "https://")
        .replace("ws://", "http://");
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(10))
        .build()
        .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    let resp = client
        .get(&http_url)
        .header("Accept", "application/nostr+json")
        .send()
        .await
        .map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, e.to_string()))?;
    if !resp.status().is_success() {
        return Err((
            axum::http::StatusCode::BAD_GATEWAY,
            format!("relay returned {}", resp.status()),
        ));
    }
    let body = resp
        .json::<serde_json::Value>()
        .await
        .map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, e.to_string()))?;
    Ok(Json(body))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelayConfigRow {
    pub url: String,
    pub enabled: bool,
}

async fn get_relays(State(pool): State<SqlitePool>) -> Json<Vec<RelayConfigRow>> {
    let rows = sqlx::query_as::<_, (String, i64)>("SELECT url, enabled FROM relay_config ORDER BY id ASC")
        .fetch_all(&pool)
        .await
        .unwrap_or_default();
    Json(
        rows.into_iter()
            .map(|(url, enabled)| RelayConfigRow {
                url,
                enabled: enabled != 0,
            })
            .collect(),
    )
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PutRelaysBody {
    pub relays: Vec<RelayConfigRow>,
}

async fn put_relays(State(pool): State<SqlitePool>, Json(body): Json<PutRelaysBody>) -> Json<()> {
    // Collect URLs from the request to determine which relays to keep
    let submitted_urls: Vec<&str> = body.relays.iter().map(|r| r.url.as_str()).collect();

    // Delete relays not in the submitted list
    if submitted_urls.is_empty() {
        let _ = sqlx::query("DELETE FROM relay_config")
            .execute(&pool)
            .await;
    } else {
        // Build placeholders for IN clause
        let placeholders: Vec<String> = (0..submitted_urls.len()).map(|_| "?".to_string()).collect();
        let query_str = format!(
            "DELETE FROM relay_config WHERE url NOT IN ({})",
            placeholders.join(", ")
        );
        let mut query = sqlx::query(&query_str);
        for url in &submitted_urls {
            query = query.bind(url);
        }
        let _ = query.execute(&pool).await;
    }

    // Upsert remaining relays
    for r in body.relays {
        let enabled = if r.enabled { 1i64 } else { 0i64 };
        let _ = sqlx::query(
            "INSERT INTO relay_config (url, enabled) VALUES (?, ?) \
             ON CONFLICT(url) DO UPDATE SET enabled = excluded.enabled, updated_at = datetime('now')",
        )
        .bind(r.url)
        .bind(enabled)
        .execute(&pool)
        .await;
    }
    Json(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafelistRow {
    pub npub: String,
    pub flags: i64,
    pub memo: String,
}

async fn list_safelist(State(pool): State<SqlitePool>) -> Json<Vec<SafelistRow>> {
    let rows = sqlx::query_as::<_, (String, i64, String)>(
        "SELECT npub, flags, memo FROM safelist ORDER BY created_at ASC",
    )
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    Json(
        rows.into_iter()
            .map(|(npub, flags, memo)| SafelistRow { npub, flags, memo })
            .collect(),
    )
}

async fn upsert_safelist(State(pool): State<SqlitePool>, Json(body): Json<SafelistRow>) -> Json<()> {
    match sqlx::query(
        "INSERT INTO safelist (npub, flags, memo) VALUES (?, ?, ?) \
         ON CONFLICT(npub) DO UPDATE SET flags = excluded.flags, memo = excluded.memo",
    )
    .bind(&body.npub)
    .bind(body.flags)
    .bind(&body.memo)
    .execute(&pool)
    .await {
        Ok(_) => {
            tracing::info!(npub = %body.npub, flags = body.flags, "Upserted safelist entry");
        }
        Err(e) => {
            tracing::error!(npub = %body.npub, error = %e, "Failed to upsert safelist entry");
        }
    }
    Json(())
}

async fn delete_safelist(State(pool): State<SqlitePool>, Path(npub): Path<String>) -> Json<()> {
    let _ = sqlx::query("DELETE FROM safelist WHERE npub = ?")
        .bind(npub)
        .execute(&pool)
        .await;
    Json(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterRow {
    pub id: i64,
    pub name: String,
    pub nl_text: String,
    pub parsed_json: String,
    pub enabled: bool,
    pub rule_order: i64,
}

async fn list_filters(State(pool): State<SqlitePool>) -> Json<Vec<FilterRow>> {
    let rows = sqlx::query_as::<_, (i64, String, String, String, i64, i64)>(
        "SELECT id, name, nl_text, parsed_json, enabled, rule_order FROM filter_rules ORDER BY rule_order ASC, id ASC",
    )
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    Json(
        rows.into_iter()
            .map(|(id, name, nl_text, parsed_json, enabled, rule_order)| FilterRow {
                id,
                name,
                nl_text,
                parsed_json,
                enabled: enabled != 0,
                rule_order,
            })
            .collect(),
    )
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateFilterBody {
    pub name: String,
    pub nl_text: String,
}

/// Response for filter creation/update operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterResponse {
    pub success: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i64>,
}

async fn create_filter(State(pool): State<SqlitePool>, Json(body): Json<CreateFilterBody>) -> Json<FilterResponse> {
    // Validate DSL query
    let validation = filter_query::validate(&body.nl_text);
    if !validation.valid {
        return Json(FilterResponse {
            success: false,
            error: validation.error,
            id: None,
        });
    }
    
    // Store DSL query directly (nl_text contains the DSL query, parsed_json also stores it for filtering)
    match sqlx::query(
        "INSERT INTO filter_rules (name, nl_text, parsed_json, enabled, rule_order) VALUES (?, ?, ?, 1, 0)",
    )
    .bind(&body.name)
    .bind(&body.nl_text)  // DSL query
    .bind(&body.nl_text)  // Store same DSL query in parsed_json for FilterEngine
    .execute(&pool)
    .await {
        Ok(result) => {
            let id = result.last_insert_rowid();
            tracing::info!(name = %body.name, id = id, "Created filter rule");
            Json(FilterResponse {
                success: true,
                error: None,
                id: Some(id),
            })
        }
        Err(e) => {
            tracing::error!(error = %e, "Failed to create filter rule");
            Json(FilterResponse {
                success: false,
                error: Some(format!("Database error: {}", e)),
                id: None,
            })
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateFilterBody {
    pub name: String,
    pub nl_text: String,
    pub enabled: bool,
    pub rule_order: i64,
}

async fn update_filter(
    State(pool): State<SqlitePool>,
    Path(id): Path<i64>,
    Json(body): Json<UpdateFilterBody>,
) -> Json<FilterResponse> {
    // Validate DSL query
    let validation = filter_query::validate(&body.nl_text);
    if !validation.valid {
        return Json(FilterResponse {
            success: false,
            error: validation.error,
            id: Some(id),
        });
    }
    
    let enabled = if body.enabled { 1i64 } else { 0i64 };
    match sqlx::query(
        "UPDATE filter_rules SET name = ?, nl_text = ?, parsed_json = ?, enabled = ?, rule_order = ?, updated_at = datetime('now') WHERE id = ?",
    )
    .bind(&body.name)
    .bind(&body.nl_text)  // DSL query
    .bind(&body.nl_text)  // Store same DSL query in parsed_json
    .bind(enabled)
    .bind(body.rule_order)
    .bind(id)
    .execute(&pool)
    .await {
        Ok(_) => {
            tracing::info!(name = %body.name, id = id, "Updated filter rule");
            Json(FilterResponse {
                success: true,
                error: None,
                id: Some(id),
            })
        }
        Err(e) => {
            tracing::error!(error = %e, id = id, "Failed to update filter rule");
            Json(FilterResponse {
                success: false,
                error: Some(format!("Database error: {}", e)),
                id: Some(id),
            })
        }
    }
}

async fn delete_filter(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> Json<()> {
    let _ = sqlx::query("DELETE FROM filter_rules WHERE id = ?")
        .bind(id)
        .execute(&pool)
        .await;
    Json(())
}

// Filter Query Validation

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidateFilterBody {
    pub query: String,
}

async fn validate_filter(Json(body): Json<ValidateFilterBody>) -> Json<filter_query::ValidationResult> {
    Json(filter_query::validate(&body.query))
}

// IP管理エンドポイント

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpAccessControlRow {
    pub id: Option<i64>,
    pub ip_address: String,
    pub banned: bool,
    pub whitelisted: bool,
    pub memo: String,
}

async fn list_ip_access_control(State(pool): State<SqlitePool>) -> Json<Vec<IpAccessControlRow>> {
    let rows = sqlx::query_as::<_, (i64, String, i64, i64, String)>(
        "SELECT id, ip_address, banned, whitelisted, memo FROM ip_access_control ORDER BY created_at DESC",
    )
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    Json(
        rows.into_iter()
            .map(|(id, ip_address, banned, whitelisted, memo)| IpAccessControlRow {
                id: Some(id),
                ip_address,
                banned: banned != 0,
                whitelisted: whitelisted != 0,
                memo,
            })
            .collect(),
    )
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateIpAccessControlBody {
    pub ip_address: String,
    pub banned: bool,
    pub whitelisted: bool,
    pub memo: String,
}

async fn create_ip_access_control(
    State(pool): State<SqlitePool>,
    Json(body): Json<CreateIpAccessControlBody>,
) -> Json<()> {
    let banned = if body.banned { 1i64 } else { 0i64 };
    let whitelisted = if body.whitelisted { 1i64 } else { 0i64 };
    let _ = sqlx::query(
        "INSERT INTO ip_access_control (ip_address, banned, whitelisted, memo) VALUES (?, ?, ?, ?)
         ON CONFLICT(ip_address) DO UPDATE SET banned = excluded.banned, whitelisted = excluded.whitelisted, memo = excluded.memo, updated_at = datetime('now')",
    )
    .bind(body.ip_address)
    .bind(banned)
    .bind(whitelisted)
    .bind(body.memo)
    .execute(&pool)
    .await;
    Json(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateIpAccessControlBody {
    pub ip_address: String,
    pub banned: bool,
    pub whitelisted: bool,
    pub memo: String,
}

async fn update_ip_access_control(
    State(pool): State<SqlitePool>,
    Path(id): Path<i64>,
    Json(body): Json<UpdateIpAccessControlBody>,
) -> Json<()> {
    let banned = if body.banned { 1i64 } else { 0i64 };
    let whitelisted = if body.whitelisted { 1i64 } else { 0i64 };
    let _ = sqlx::query(
        "UPDATE ip_access_control SET ip_address = ?, banned = ?, whitelisted = ?, memo = ?, updated_at = datetime('now') WHERE id = ?",
    )
    .bind(body.ip_address)
    .bind(banned)
    .bind(whitelisted)
    .bind(body.memo)
    .bind(id)
    .execute(&pool)
    .await;
    Json(())
}

async fn delete_ip_access_control(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> Json<()> {
    let _ = sqlx::query("DELETE FROM ip_access_control WHERE id = ?")
        .bind(id)
        .execute(&pool)
        .await;
    Json(())
}

// Npub BAN管理エンドポイント

async fn ban_npub(State(pool): State<SqlitePool>, Path(npub): Path<String>) -> Json<()> {
    let _ = sqlx::query("UPDATE safelist SET banned = 1 WHERE npub = ?")
        .bind(npub)
        .execute(&pool)
        .await;
    Json(())
}

async fn unban_npub(State(pool): State<SqlitePool>, Path(npub): Path<String>) -> Json<()> {
    let _ = sqlx::query("UPDATE safelist SET banned = 0 WHERE npub = ?")
        .bind(npub)
        .execute(&pool)
        .await;
    Json(())
}

// REQ Kindブラックリストエンドポイント

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReqKindBlacklistRow {
    pub id: i64,
    pub kind_value: Option<i64>,
    pub kind_min: Option<i64>,
    pub kind_max: Option<i64>,
    pub enabled: bool,
}

async fn list_req_kind_blacklist(State(pool): State<SqlitePool>) -> Json<Vec<ReqKindBlacklistRow>> {
    let rows = sqlx::query_as::<_, (i64, Option<i64>, Option<i64>, Option<i64>, i64)>(
        "SELECT id, kind_value, kind_min, kind_max, enabled FROM req_kind_blacklist ORDER BY created_at DESC",
    )
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    Json(
        rows.into_iter()
            .map(|(id, kind_value, kind_min, kind_max, enabled)| ReqKindBlacklistRow {
                id,
                kind_value,
                kind_min,
                kind_max,
                enabled: enabled != 0,
            })
            .collect(),
    )
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateReqKindBlacklistBody {
    pub kind_value: Option<i64>,
    pub kind_min: Option<i64>,
    pub kind_max: Option<i64>,
    pub enabled: bool,
}

async fn create_req_kind_blacklist(
    State(pool): State<SqlitePool>,
    Json(body): Json<CreateReqKindBlacklistBody>,
) -> Json<()> {
    let enabled = if body.enabled { 1i64 } else { 0i64 };
    let _ = sqlx::query(
        "INSERT INTO req_kind_blacklist (kind_value, kind_min, kind_max, enabled) VALUES (?, ?, ?, ?)",
    )
    .bind(body.kind_value)
    .bind(body.kind_min)
    .bind(body.kind_max)
    .bind(enabled)
    .execute(&pool)
    .await;
    Json(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateReqKindBlacklistBody {
    pub kind_value: Option<i64>,
    pub kind_min: Option<i64>,
    pub kind_max: Option<i64>,
    pub enabled: bool,
}

async fn update_req_kind_blacklist(
    State(pool): State<SqlitePool>,
    Path(id): Path<i64>,
    Json(body): Json<UpdateReqKindBlacklistBody>,
) -> Json<()> {
    let enabled = if body.enabled { 1i64 } else { 0i64 };
    let _ = sqlx::query(
        "UPDATE req_kind_blacklist SET kind_value = ?, kind_min = ?, kind_max = ?, enabled = ?, updated_at = datetime('now') WHERE id = ?",
    )
    .bind(body.kind_value)
    .bind(body.kind_min)
    .bind(body.kind_max)
    .bind(enabled)
    .bind(id)
    .execute(&pool)
    .await;
    Json(())
}

async fn delete_req_kind_blacklist(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> Json<()> {
    let _ = sqlx::query("DELETE FROM req_kind_blacklist WHERE id = ?")
        .bind(id)
        .execute(&pool)
        .await;
    Json(())
}

// ログ・統計エンドポイント

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionLogRow {
    pub id: i64,
    pub ip_address: String,
    pub connected_at: String,
    pub disconnected_at: Option<String>,
    pub event_count: i64,
    pub rejected_event_count: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetConnectionLogsQuery {
    #[serde(default)]
    pub limit: Option<i64>,
    #[serde(default)]
    pub offset: Option<i64>,
    #[serde(default)]
    pub ip_address: Option<String>,
    #[serde(default)]
    pub from: Option<String>,
    #[serde(default)]
    pub to: Option<String>,
}

async fn get_connection_logs(
    State(pool): State<SqlitePool>,
    axum::extract::Query(params): axum::extract::Query<GetConnectionLogsQuery>,
) -> Json<Vec<ConnectionLogRow>> {
    let limit = params.limit.unwrap_or(100).min(500);
    let offset = params.offset.unwrap_or(0);
    let rows = sqlx::query_as::<_, (i64, String, String, Option<String>, i64, i64)>(
        "SELECT id, ip_address, connected_at, disconnected_at, event_count, rejected_event_count 
         FROM connection_logs 
         WHERE (? IS NULL OR ip_address LIKE '%' || ? || '%')
           AND (connected_at >= ? OR ? IS NULL)
           AND (connected_at <= ? OR ? IS NULL)
         ORDER BY connected_at DESC 
         LIMIT ? OFFSET ?",
    )
    .bind(params.ip_address.as_deref())
    .bind(params.ip_address.as_deref().unwrap_or(""))
    .bind(params.from.as_deref())
    .bind(params.from.as_deref())
    .bind(params.to.as_deref())
    .bind(params.to.as_deref())
    .bind(limit)
    .bind(offset)
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    Json(
        rows.into_iter()
            .map(|(id, ip_address, connected_at, disconnected_at, event_count, rejected_event_count)| {
                ConnectionLogRow {
                    id,
                    ip_address,
                    connected_at,
                    disconnected_at,
                    event_count,
                    rejected_event_count,
                }
            })
            .collect(),
    )
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventRejectionLogRow {
    pub id: i64,
    pub event_id: String,
    pub pubkey_hex: String,
    pub npub: String,
    pub ip_address: Option<String>,
    pub kind: i64,
    pub reason: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetEventRejectionLogsQuery {
    #[serde(default)]
    pub limit: Option<i64>,
    #[serde(default)]
    pub offset: Option<i64>,
    #[serde(default)]
    pub npub: Option<String>,
    #[serde(default)]
    pub kind: Option<i64>,
    #[serde(default)]
    pub reason: Option<String>,
    #[serde(default)]
    pub from: Option<String>,
    #[serde(default)]
    pub to: Option<String>,
}

async fn get_event_rejection_logs(
    State(pool): State<SqlitePool>,
    axum::extract::Query(params): axum::extract::Query<GetEventRejectionLogsQuery>,
) -> Json<Vec<EventRejectionLogRow>> {
    let limit = params.limit.unwrap_or(100).min(500);
    let offset = params.offset.unwrap_or(0);
    let rows = sqlx::query_as::<_, (i64, String, String, String, Option<String>, i64, String, String)>(
        "SELECT id, event_id, pubkey_hex, npub, ip_address, kind, reason, created_at 
         FROM event_rejection_logs 
         WHERE (? IS NULL OR npub LIKE '%' || ? || '%')
           AND (kind = ? OR ? IS NULL)
           AND (? IS NULL OR reason LIKE '%' || ? || '%')
           AND (created_at >= ? OR ? IS NULL)
           AND (created_at <= ? OR ? IS NULL)
         ORDER BY created_at DESC 
         LIMIT ? OFFSET ?",
    )
    .bind(params.npub.as_deref())
    .bind(params.npub.as_deref().unwrap_or(""))
    .bind(params.kind)
    .bind(params.kind)
    .bind(params.reason.as_deref())
    .bind(params.reason.as_deref().unwrap_or(""))
    .bind(params.from.as_deref())
    .bind(params.from.as_deref())
    .bind(params.to.as_deref())
    .bind(params.to.as_deref())
    .bind(limit)
    .bind(offset)
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    Json(
        rows.into_iter()
            .map(|(id, event_id, pubkey_hex, npub, ip_address, kind, reason, created_at)| {
                EventRejectionLogRow {
                    id,
                    event_id,
                    pubkey_hex,
                    npub,
                    ip_address,
                    kind,
                    reason,
                    created_at,
                }
            })
            .collect(),
    )
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatsResponse {
    pub total_connections: i64,
    pub active_connections: i64,
    pub total_rejections: i64,
    pub rejections_by_reason: Vec<RejectionReasonCount>,
    pub top_npubs_by_rejections: Vec<NpubRejectionCount>,
    pub top_ips_by_rejections: Vec<IpRejectionCount>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RejectionReasonCount {
    pub reason: String,
    pub count: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NpubRejectionCount {
    pub npub: String,
    pub count: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpRejectionCount {
    pub ip_address: String,
    pub count: i64,
}

async fn get_stats(State(pool): State<SqlitePool>) -> Json<StatsResponse> {
    // 総接続数
    let total_connections: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM connection_logs")
        .fetch_one(&pool)
        .await
        .unwrap_or((0,));

    // アクティブ接続数(切断時刻がNULL)
    let active_connections: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM connection_logs WHERE disconnected_at IS NULL")
        .fetch_one(&pool)
        .await
        .unwrap_or((0,));

    // 総拒否数
    let total_rejections: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM event_rejection_logs")
        .fetch_one(&pool)
        .await
        .unwrap_or((0,));

    // 拒否理由別の内訳
    let rejections_by_reason_rows = sqlx::query_as::<_, (String, i64)>(
        "SELECT reason, COUNT(*) as count FROM event_rejection_logs GROUP BY reason ORDER BY count DESC",
    )
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    let rejections_by_reason: Vec<RejectionReasonCount> = rejections_by_reason_rows
        .into_iter()
        .map(|(reason, count)| RejectionReasonCount { reason, count })
        .collect();

    // トップNpub(拒否数順)
    let top_npubs_rows = sqlx::query_as::<_, (String, i64)>(
        "SELECT npub, COUNT(*) as count FROM event_rejection_logs GROUP BY npub ORDER BY count DESC LIMIT 10",
    )
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    let top_npubs_by_rejections: Vec<NpubRejectionCount> = top_npubs_rows
        .into_iter()
        .map(|(npub, count)| NpubRejectionCount { npub, count })
        .collect();

    // トップIP(拒否数順)
    let top_ips_rows = sqlx::query_as::<_, (String, i64)>(
        "SELECT ip_address, COUNT(*) as count FROM event_rejection_logs WHERE ip_address IS NOT NULL GROUP BY ip_address ORDER BY count DESC LIMIT 10",
    )
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    let top_ips_by_rejections: Vec<IpRejectionCount> = top_ips_rows
        .into_iter()
        .map(|(ip_address, count)| IpRejectionCount { ip_address, count })
        .collect();

    Json(StatsResponse {
        total_connections: total_connections.0,
        active_connections: active_connections.0,
        total_rejections: total_rejections.0,
        rejections_by_reason,
        top_npubs_by_rejections,
        top_ips_by_rejections,
    })
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetStatsTimeseriesQuery {
    #[serde(default)]
    pub period: Option<String>,
    #[serde(default)]
    pub from: Option<String>,
    #[serde(default)]
    pub to: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatsTimeseriesBucket {
    pub time: String,
    pub rejections: i64,
    pub events: i64,
}

async fn get_stats_timeseries(
    State(pool): State<SqlitePool>,
    axum::extract::Query(params): axum::extract::Query<GetStatsTimeseriesQuery>,
) -> Json<Vec<StatsTimeseriesBucket>> {
    let period = params.period.as_deref().unwrap_or("1h");
    let format_str = if period == "1d" {
        "%Y-%m-%d"
    } else {
        "%Y-%m-%d %H:00"
    };
    let rows = sqlx::query_as::<_, (String, i64)>(
        "SELECT strftime(?, created_at) as bucket, COUNT(*) as cnt 
         FROM event_rejection_logs 
         WHERE (created_at >= ? OR ? IS NULL) AND (created_at <= ? OR ? IS NULL)
         GROUP BY bucket ORDER BY bucket ASC LIMIT 168",
    )
    .bind(format_str)
    .bind(params.from.as_deref())
    .bind(params.from.as_deref())
    .bind(params.to.as_deref())
    .bind(params.to.as_deref())
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    let buckets: Vec<StatsTimeseriesBucket> = rows
        .into_iter()
        .map(|(time, rejections)| StatsTimeseriesBucket {
            time,
            rejections,
            events: 0,
        })
        .collect();
    Json(buckets)
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimpleBanRuleRow {
    pub id: i64,
    pub rule_type: String,
    pub npub_list: Option<String>,
    pub kind_list: Option<String>,
    pub tag_name: Option<String>,
    pub tag_value_pattern: Option<String>,
    pub enabled: bool,
    pub memo: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSimpleBanRuleBody {
    pub rule_type: String,
    pub npub_list: Option<String>,
    pub kind_list: Option<String>,
    pub tag_name: Option<String>,
    pub tag_value_pattern: Option<String>,
    pub enabled: Option<bool>,
    pub memo: Option<String>,
}

async fn list_simple_ban_rules(State(pool): State<SqlitePool>) -> Json<Vec<SimpleBanRuleRow>> {
    let rows = sqlx::query_as::<_, (i64, String, Option<String>, Option<String>, Option<String>, Option<String>, i64, Option<String>, String, String)>(
        "SELECT id, rule_type, npub_list, kind_list, tag_name, tag_value_pattern, enabled, memo, created_at, updated_at FROM simple_ban_rules ORDER BY id ASC",
    )
    .fetch_all(&pool)
    .await
    .unwrap_or_default();
    Json(
        rows.into_iter()
            .map(|(id, rule_type, npub_list, kind_list, tag_name, tag_value_pattern, enabled, memo, created_at, updated_at)| {
                SimpleBanRuleRow {
                    id,
                    rule_type,
                    npub_list,
                    kind_list,
                    tag_name,
                    tag_value_pattern,
                    enabled: enabled != 0,
                    memo,
                    created_at,
                    updated_at,
                }
            })
            .collect(),
    )
}

async fn create_simple_ban_rule(
    State(pool): State<SqlitePool>,
    Json(body): Json<CreateSimpleBanRuleBody>,
) -> Json<SimpleBanRuleRow> {
    let enabled = body.enabled.unwrap_or(true);
    let _ = sqlx::query(
        "INSERT INTO simple_ban_rules (rule_type, npub_list, kind_list, tag_name, tag_value_pattern, enabled, memo) VALUES (?, ?, ?, ?, ?, ?, ?)",
    )
    .bind(&body.rule_type)
    .bind(body.npub_list.as_deref())
    .bind(body.kind_list.as_deref())
    .bind(body.tag_name.as_deref())
    .bind(body.tag_value_pattern.as_deref())
    .bind(if enabled { 1i64 } else { 0i64 })
    .bind(body.memo.as_deref())
    .execute(&pool)
    .await;
    let row: (i64, String, Option<String>, Option<String>, Option<String>, Option<String>, i64, Option<String>, String, String) = sqlx::query_as(
        "SELECT id, rule_type, npub_list, kind_list, tag_name, tag_value_pattern, enabled, memo, created_at, updated_at FROM simple_ban_rules ORDER BY id DESC LIMIT 1",
    )
    .fetch_one(&pool)
    .await
    .unwrap_or((0, String::new(), None, None, None, None, 0, None, String::new(), String::new()));
    Json(SimpleBanRuleRow {
        id: row.0,
        rule_type: row.1,
        npub_list: row.2,
        kind_list: row.3,
        tag_name: row.4,
        tag_value_pattern: row.5,
        enabled: row.6 != 0,
        memo: row.7,
        created_at: row.8,
        updated_at: row.9,
    })
}

async fn update_simple_ban_rule(
    State(pool): State<SqlitePool>,
    Path(id): Path<i64>,
    Json(body): Json<CreateSimpleBanRuleBody>,
) -> Json<()> {
    let enabled = body.enabled.unwrap_or(true);
    let _ = sqlx::query(
        "UPDATE simple_ban_rules SET rule_type = ?, npub_list = ?, kind_list = ?, tag_name = ?, tag_value_pattern = ?, enabled = ?, memo = ?, updated_at = datetime('now') WHERE id = ?",
    )
    .bind(&body.rule_type)
    .bind(body.npub_list.as_deref())
    .bind(body.kind_list.as_deref())
    .bind(body.tag_name.as_deref())
    .bind(body.tag_value_pattern.as_deref())
    .bind(if enabled { 1i64 } else { 0i64 })
    .bind(body.memo.as_deref())
    .bind(id)
    .execute(&pool)
    .await;
    Json(())
}

async fn delete_simple_ban_rule(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> Json<()> {
    let _ = sqlx::query("DELETE FROM simple_ban_rules WHERE id = ?")
        .bind(id)
        .execute(&pool)
        .await;
    Json(())
}

// NIP-11 Relay Information

#[derive(Debug, Clone, sqlx::FromRow)]
struct RelayInfoRowDb {
    pub name: Option<String>,
    pub description: Option<String>,
    pub pubkey: Option<String>,
    pub contact: Option<String>,
    pub supported_nips: Option<String>,
    pub software: Option<String>,
    pub version: Option<String>,
    pub limitation_max_limit: Option<i64>,
    pub limitation_max_message_length: Option<i64>,
    pub limitation_max_subscriptions: Option<i64>,
    pub limitation_max_filters: Option<i64>,
    pub limitation_max_event_tags: Option<i64>,
    pub limitation_max_content_length: Option<i64>,
    pub limitation_auth_required: i64,
    pub limitation_payment_required: i64,
    pub icon: Option<String>,
    pub negentropy: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelayInfoRow {
    pub name: Option<String>,
    pub description: Option<String>,
    pub pubkey: Option<String>,
    pub contact: Option<String>,
    pub supported_nips: Option<String>,
    pub software: Option<String>,
    pub version: Option<String>,
    pub limitation_max_limit: Option<i64>,
    pub limitation_max_message_length: Option<i64>,
    pub limitation_max_subscriptions: Option<i64>,
    pub limitation_max_filters: Option<i64>,
    pub limitation_max_event_tags: Option<i64>,
    pub limitation_max_content_length: Option<i64>,
    pub limitation_auth_required: bool,
    pub limitation_payment_required: bool,
    pub icon: Option<String>,
    pub negentropy: Option<i64>,
}

async fn get_relay_info(State(pool): State<SqlitePool>) -> Json<RelayInfoRow> {
    let row = sqlx::query_as::<_, RelayInfoRowDb>(
        "SELECT name, description, pubkey, contact, supported_nips, software, version, 
         limitation_max_limit, limitation_max_message_length, limitation_max_subscriptions, limitation_max_filters,
         limitation_max_event_tags, limitation_max_content_length, limitation_auth_required,
         limitation_payment_required, icon, negentropy
         FROM relay_info WHERE id = 1",
    )
    .fetch_optional(&pool)
    .await
    .unwrap_or(None);

    match row {
        Some(row) => Json(RelayInfoRow {
            name: row.name,
            description: row.description,
            pubkey: row.pubkey,
            contact: row.contact,
            supported_nips: row.supported_nips,
            software: row.software,
            version: row.version,
            limitation_max_limit: row.limitation_max_limit,
            limitation_max_message_length: row.limitation_max_message_length,
            limitation_max_subscriptions: row.limitation_max_subscriptions,
            limitation_max_filters: row.limitation_max_filters,
            limitation_max_event_tags: row.limitation_max_event_tags,
            limitation_max_content_length: row.limitation_max_content_length,
            limitation_auth_required: row.limitation_auth_required != 0,
            limitation_payment_required: row.limitation_payment_required != 0,
            icon: row.icon,
            negentropy: if row.negentropy != 0 { Some(row.negentropy) } else { None },
        }),
        None => Json(RelayInfoRow {
            name: Some("Proxy Nostr Relay".to_string()),
            description: Some("A proxy relay with bot filtering capabilities".to_string()),
            pubkey: None,
            contact: None,
            supported_nips: Some("[1, 11]".to_string()),
            software: Some("https://github.com/ShinoharaTa/nostr-proxy-relay".to_string()),
            version: Some("0.1.0".to_string()),
            limitation_max_limit: None,
            limitation_max_message_length: None,
            limitation_max_subscriptions: None,
            limitation_max_filters: None,
            limitation_max_event_tags: None,
            limitation_max_content_length: None,
            limitation_auth_required: false,
            limitation_payment_required: false,
            icon: None,
            negentropy: None,
        }),
    }
}

async fn put_relay_info(State(pool): State<SqlitePool>, Json(body): Json<RelayInfoRow>) -> Json<()> {
    let auth_required = if body.limitation_auth_required { 1i64 } else { 0i64 };
    let payment_required = if body.limitation_payment_required { 1i64 } else { 0i64 };
    let negentropy = body.negentropy.unwrap_or(0i64);
    
    let _ = sqlx::query(
        "INSERT INTO relay_info (id, name, description, pubkey, contact, supported_nips, software, version,
         limitation_max_limit, limitation_max_message_length, limitation_max_subscriptions, limitation_max_filters,
         limitation_max_event_tags, limitation_max_content_length, limitation_auth_required,
         limitation_payment_required, icon, negentropy)
         VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
         ON CONFLICT(id) DO UPDATE SET
         name = excluded.name, description = excluded.description, pubkey = excluded.pubkey,
         contact = excluded.contact, supported_nips = excluded.supported_nips, software = excluded.software,
         version = excluded.version, limitation_max_limit = excluded.limitation_max_limit,
         limitation_max_message_length = excluded.limitation_max_message_length,
         limitation_max_subscriptions = excluded.limitation_max_subscriptions,
         limitation_max_filters = excluded.limitation_max_filters,
         limitation_max_event_tags = excluded.limitation_max_event_tags,
         limitation_max_content_length = excluded.limitation_max_content_length,
         limitation_auth_required = excluded.limitation_auth_required,
         limitation_payment_required = excluded.limitation_payment_required,
         icon = excluded.icon, negentropy = excluded.negentropy,
         updated_at = datetime('now')",
    )
    .bind(&body.name)
    .bind(&body.description)
    .bind(&body.pubkey)
    .bind(&body.contact)
    .bind(&body.supported_nips)
    .bind(&body.software)
    .bind(&body.version)
    .bind(body.limitation_max_limit)
    .bind(body.limitation_max_message_length)
    .bind(body.limitation_max_subscriptions)
    .bind(body.limitation_max_filters)
    .bind(body.limitation_max_event_tags)
    .bind(body.limitation_max_content_length)
    .bind(auth_required)
    .bind(payment_required)
    .bind(&body.icon)
    .bind(negentropy)
    .execute(&pool)
    .await;
    
    Json(())
}