oxipage-core 0.2.0

Oxipage 코어 라이브러리 — Axum 서버 부트스트랩, SQLite 마이그레이션, 인증, Extension trait, SSR 스냅샷, 레이트리밋
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
use crate::auth::{self, AdminAuth, PatRow};
use crate::build::build_site;
use crate::build_writer::write_build_output;
use crate::setup;
use crate::error::ApiError;
use crate::extension::{CliArgSpec, CliCommandManifest, CliCommandSpec, CliSubcommandSpec, Extension, Lang};
use crate::search::SearchHit;
use crate::state::AppState;
use std::sync::Arc;
use axum::extract::{Path, Query, Request, State};
use axum::http::StatusCode;
use axum::http::{Uri, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use axum::middleware::Next;
use rust_embed::RustEmbed;
use tower_http::trace::TraceLayer;

#[derive(RustEmbed)]
#[folder = "embedded-spa"]
struct Assets;

#[derive(serde::Serialize)]
struct DataEnvelope<T: serde::Serialize> {
    data: T,
}

#[derive(serde::Serialize)]
struct ManifestSite {
    name: String,
    base_url: String,
    default_lang: String,
    languages: Vec<String>,
}

#[derive(serde::Serialize)]
struct ManifestLocalized {
    ko: String,
    en: String,
}

#[derive(serde::Serialize)]
struct ManifestExtension {
    id: String,
    display_name: ManifestLocalized,
    lobby: LobbyConfigInfo,
}

#[derive(serde::Serialize, Clone, Default)]
struct LobbyConfigInfo {
    enabled: bool,
    display_mode: String,
    display_order: i64,
    style_params: serde_json::Value,
}

#[derive(serde::Serialize)]
struct Manifest {
    site: ManifestSite,
    extensions: Vec<ManifestExtension>,
}

pub fn build_app(state: AppState) -> Router {
    let mut api = Router::new()
        .route("/lobby/manifest", get(lobby_manifest))
        .route("/lobby/config", get(lobby_config_list))
        .route("/lobby/config/{ext_id}", axum::routing::put(lobby_config_update))
        .route("/auth/tokens", get(auth_tokens_list).post(auth_tokens_create))
        .route("/auth/tokens/{id}", axum::routing::delete(auth_tokens_revoke))
        .route("/search", get(search_handler))
        .route("/docs", get(docs_ui))
        .route("/docs/openapi.json", get(docs_spec))
        .route("/extensions", get(extensions_list))
        .route("/extensions/{id}/enable", axum::routing::post(extension_enable))
        .route("/extensions/{id}/disable", axum::routing::post(extension_disable))
        .route("/extensions/{id}", axum::routing::delete(extension_purge))
        .route("/extensions/install", axum::routing::post(extension_install))
        .route("/backup/snapshot", axum::routing::post(backup_snapshot))
        .route("/cli/commands", get(cli_commands_handler))
        .route("/cli/exec/{ext_id}/{sub_command}", axum::routing::post(cli_exec_handler))
        .route("/theme", get(theme_get).put(theme_put))
        .route("/themes", get(theme_catalog))
        .route("/build", axum::routing::post(build_handler))
        .route("/cache/refresh", axum::routing::post(cache_refresh_handler));
    // Setup API (loopback-only, unauthenticated, doc/13)
    api = setup::setup_routes(api);
    // setup_gate: /setup/* 경로만 loopback-only + 완료 후 410
    // 다른 경로는 통과 (확장 라우트 등에 영향 없음)
    api = api.layer(axum::middleware::from_fn_with_state(
        state.clone(),
        setup::setup_gate,
    ));

    for ext in state.registry.iter() {
        // WASM(런타임 적재) 확장은 route_dispatcher()가 Some → 네스팅하지 않고
        // 폴백 핸들러가 요청 시점에 동적 디스패치한다. 핫 리로드 지원.
        if ext.route_dispatcher().is_some() {
            continue;
        }
        api = api.nest(&format!("/{}", ext.id()), ext.routes());
    }
    let api = api
        .fallback(api_fallback)
        .layer(axum::middleware::from_fn_with_state(
            state.clone(),
            extension_gate,
        ));

    let limiter = crate::rate_limit::RateLimiter::new(120); // IP당 120/min
    Router::new()
        .route("/healthz", get(healthz))
        .nest("/api/console", api)
        .fallback(static_handler)
        .with_state(state)
        .layer(axum::middleware::from_fn_with_state(
            limiter,
            crate::rate_limit::rate_limit_middleware,
        ))
        .layer(TraceLayer::new_for_http())
}

async fn healthz() -> Json<serde_json::Value> {
    Json(serde_json::json!({ "status": "ok" }))
}


async fn docs_spec(State(state): State<AppState>) -> Json<serde_json::Value> {
    Json(crate::openapi::openapi_spec(&state.config.site.base_url))
}

async fn build_handler(
    State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let config = &state.config;
    let out_dir = config.server.data_dir.join("out");
    let media_dir = config.server.data_dir.join("media");
    let web_dist = std::path::PathBuf::from("web/dist");

    let output = build_site(&state.db, &state.builders)
        .map_err(|e| ApiError::internal(anyhow::anyhow!("{}", e)))?;

    write_build_output(&output, &out_dir, &media_dir, &web_dist)
        .map_err(|e| ApiError::internal(anyhow::anyhow!("{}", e)))?;

    Ok(Json(serde_json::json!({
        "success": true,
        "pages": output.pages.len(),
        "extensions": output.extensions_data.len(),
        "out_dir": out_dir.to_string_lossy(),
    })))
}

async fn cache_refresh_handler(
    State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let mut scheduler = crate::scheduler::Scheduler::new();
    for ext in state.registry.iter() {
        for job in ext.background_jobs() {
            scheduler.register(job);
        }
    }

    let job_count = scheduler.jobs().len();
    scheduler.run_all_once(&state).await;

    Ok(Json(serde_json::json!({
        "success": true,
        "jobs_run": job_count,
    })))
}

async fn docs_ui() -> axum::response::Response {
    let html = crate::openapi::swagger_ui_html("/api/console/docs/openapi.json");
    (
        [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
        html,
    )
        .into_response()
}
/// 동적 라우트 폴백. WASM(런타임 적재) 확장의 HTTP 요청을 디스패치한다.
/// `/api/console/{ext_id}/**` 경로에서 ext_id가 WASM 확장이면 route_dispatcher 로 위임.
/// 그 외에는 일반 404.
async fn api_fallback(State(state): State<AppState>, request: Request) -> Response {
    let path = request.uri().path().to_string();
    let method = request.method().to_string();
    if let Some(ext_id) = extension_id_from_path(&path)
        && let Some(ext) = state.registry.find(&ext_id)
        && let Some(dispatcher) = ext.route_dispatcher()
    {
        // 확장 prefix 이후 경로 추출 ("/wasm-demo/info" → "/info").
        let prefix_len = 1 + ext_id.len(); // '/' + ext_id
        let sub_path = if path.len() > prefix_len {
            &path[prefix_len..]
        } else {
            "/"
        };
        let body = axum::body::to_bytes(request.into_body(), 1024 * 1024)
            .await
            .unwrap_or_default()
            .to_vec();
        let resp = dispatcher.dispatch(&method, sub_path, body, &state).await;
        return (
            StatusCode::from_u16(resp.status).unwrap_or(StatusCode::OK),
            [(header::CONTENT_TYPE, "application/json; charset=utf-8")],
            resp.body,
        )
            .into_response();
    }
    ApiError::new(StatusCode::NOT_FOUND, "not_found", "resource not found").into_response()
}

#[derive(serde::Deserialize)]
struct SearchQuery {
    q: String,
    lang: Option<String>,
    limit: Option<i64>,
}

async fn search_handler(
    State(state): State<AppState>,
    Query(q): Query<SearchQuery>,
) -> Result<Json<DataEnvelope<Vec<SearchHit>>>, ApiError> {
    let limit = q.limit.unwrap_or(20).clamp(1, 100);
    let hits = crate::search::search(&state.db, &q.q, q.lang.as_deref(), limit)
        .await
        .map_err(ApiError::internal)?;
    Ok(Json(DataEnvelope { data: hits }))
}

async fn lobby_manifest(State(state): State<AppState>) -> Json<DataEnvelope<Manifest>> {
    let mut extensions = Vec::new();
    for (idx, e) in state.registry.iter().into_iter().enumerate() {
        if !state.registry.is_active(e.id()).await {
            continue;
        }
        let lobby = lobby_config_for(&state, e.id(), idx as i64).await;
        extensions.push(ManifestExtension {
            id: e.id().to_string(),
            display_name: ManifestLocalized {
                ko: e.display_name(Lang::Ko),
                en: e.display_name(Lang::En),
            },
            lobby,
        });
    }
    Json(DataEnvelope {
        data: Manifest {
            site: ManifestSite {
                name: state.effective_site_name().await,
                base_url: state.effective_base_url().await,
                default_lang: state.config.site.default_lang.clone(),
                languages: state.config.site.languages.clone(),
            },
            extensions,
        },
    })
}

async fn lobby_config_for(state: &AppState, ext_id: &str, default_order: i64) -> LobbyConfigInfo {
    let row: Option<(bool, String, i64, String)> = sqlx::query_as(
        "SELECT enabled, display_mode, display_order, style_params
         FROM lobby_config WHERE extension_id = ?",
    )
    .bind(ext_id)
    .fetch_optional(&state.db)
    .await
    .ok()
    .flatten();
    match row {
        Some((enabled, mode, order, params)) => LobbyConfigInfo {
            enabled,
            display_mode: mode,
            display_order: order,
            style_params: serde_json::from_str(&params).unwrap_or_default(),
        },
        None => LobbyConfigInfo {
            enabled: true,
            display_mode: state.config.lobby.default_mode.clone(),
            display_order: default_order,
            style_params: serde_json::json!({}),
        },
    }
}

async fn lobby_config_list(
    State(state): State<AppState>,
) -> Json<DataEnvelope<Vec<LobbyConfigEntry>>> {
    let mut entries = Vec::new();
    for (idx, e) in state.registry.iter().into_iter().enumerate() {
        if !state.registry.is_active(e.id()).await {
            continue;
        }
        let info = lobby_config_for(&state, e.id(), idx as i64).await;
        entries.push(LobbyConfigEntry {
            extension_id: e.id().to_string(),
            enabled: info.enabled,
            display_mode: info.display_mode,
            display_order: info.display_order,
            style_params: info.style_params,
        });
    }
    Json(DataEnvelope { data: entries })
}

#[derive(serde::Serialize)]
struct LobbyConfigEntry {
    extension_id: String,
    enabled: bool,
    display_mode: String,
    display_order: i64,
    style_params: serde_json::Value,
}

#[derive(serde::Deserialize)]
struct LobbyConfigUpdate {
    #[serde(default)]
    enabled: Option<bool>,
    #[serde(default)]
    display_mode: Option<String>,
    #[serde(default)]
    display_order: Option<i64>,
    #[serde(default)]
    style_params: Option<serde_json::Value>,
}

async fn lobby_config_update(
    _auth: AdminAuth,
    State(state): State<AppState>,
    Path(ext_id): Path<String>,
    Json(input): Json<LobbyConfigUpdate>,
) -> Result<Json<DataEnvelope<LobbyConfigEntry>>, ApiError> {
    if state.registry.find(&ext_id).is_none() {
        return Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "not_found",
            "extension not registered",
        ));
    }
    if let Some(ref mode) = input.display_mode
        && !matches!(mode.as_str(), "canvas" | "grid" | "list")
    {
        return Err(ApiError::validation(
            "display_mode",
            "display_mode must be canvas|grid|list",
        ));
    }
    let info = lobby_config_for(&state, &ext_id, 0).await;
    let enabled = input.enabled.unwrap_or(info.enabled);
    let mode = input.display_mode.unwrap_or(info.display_mode);
    let order = input.display_order.unwrap_or(info.display_order);
    let params = input.style_params.unwrap_or(info.style_params);
    let params_str = serde_json::to_string(&params).unwrap_or_else(|_| "{}".into());

    sqlx::query(
        "INSERT INTO lobby_config (extension_id, enabled, display_mode, display_order, style_params)
         VALUES (?1, ?2, ?3, ?4, ?5)
         ON CONFLICT (extension_id) DO UPDATE SET
            enabled = ?2, display_mode = ?3, display_order = ?4, style_params = ?5",
    )
    .bind(&ext_id)
    .bind(enabled)
    .bind(&mode)
    .bind(order)
    .bind(&params_str)
    .execute(&state.db)
    .await
    .map_err(|e| ApiError::internal(anyhow::anyhow!(e)))?;

    Ok(Json(DataEnvelope {
        data: LobbyConfigEntry {
            extension_id: ext_id,
            enabled,
            display_mode: mode,
            display_order: order,
            style_params: params,
        },
    }))
}

// ─── auth tokens (PAT, doc/01 §1.8, doc/04 §4.2) ───

#[derive(serde::Deserialize)]
struct PatCreate {
    label: String,
    #[serde(default)]
    scopes: Vec<String>,
}

#[derive(serde::Serialize)]
struct PatCreated {
    plain_token: String,
    id: i64,
    label: String,
    token_prefix: String,
    scopes: Vec<String>,
}

async fn auth_tokens_create(
    auth: AdminAuth,
    State(state): State<AppState>,
    Json(input): Json<PatCreate>,
) -> Result<Json<DataEnvelope<PatCreated>>, ApiError> {
    auth.require_scope("admin")?;
    if input.label.trim().is_empty() {
        return Err(ApiError::validation("label", "label must not be empty"));
    }
    for s in &input.scopes {
        if !matches!(s.as_str(), "post:write" | "post:publish" | "read" | "admin") {
            return Err(ApiError::validation(
                "scopes",
                "scope must be post:write|post:publish|read|admin",
            ));
        }
    }
    let (plain, row) = auth::create_pat(&state, &input.label, &input.scopes)
        .await
        .map_err(ApiError::internal)?;
    Ok(Json(DataEnvelope {
        data: PatCreated {
            plain_token: plain,
            id: row.id,
            label: row.label,
            token_prefix: row.token_prefix,
            scopes: input.scopes,
        },
    }))
}

async fn auth_tokens_list(
    auth: AdminAuth,
    State(state): State<AppState>,
) -> Result<Json<DataEnvelope<Vec<PatRow>>>, ApiError> {
    auth.require_scope("admin")?;
    let rows = auth::list_pats(&state)
        .await
        .map_err(ApiError::internal)?;
    Ok(Json(DataEnvelope { data: rows }))
}

async fn auth_tokens_revoke(
    auth: AdminAuth,
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<DataEnvelope<serde_json::Value>>, ApiError> {
    auth.require_scope("admin")?;
    let removed = auth::revoke_pat(&state, id)
        .await
        .map_err(ApiError::internal)?;
    if !removed {
        return Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "not_found",
            "active token with that id not found",
        ));
    }
    Ok(Json(DataEnvelope {
        data: serde_json::json!({ "id": id, "revoked": true }),
    }))
}

// ─── backup (doc/05 §5.4) ───

/// `VACUUM INTO` 포인트-인-타임 스냅샷. admin 스코프 필요.
/// `data_dir/backups/oxipage-<epoch>.db`에 일관된 DB 복사본을 생성한다.
async fn backup_snapshot(
    auth: AdminAuth,
    State(state): State<AppState>,
) -> Result<Json<DataEnvelope<serde_json::Value>>, ApiError> {
    auth.require_scope("admin")?;
    let backups_dir = state.config.server.data_dir.join("backups");
    tokio::fs::create_dir_all(&backups_dir)
        .await
        .map_err(|e| ApiError::internal(e.into()))?;
    let epoch = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let filename = crate::backup::snapshot_filename(epoch);
    let dest = backups_dir.join(&filename);
    crate::backup::vacuum_into(&state.db, &dest)
        .await
        .map_err(ApiError::internal)?;
    Ok(Json(DataEnvelope {
        data: serde_json::json!({
            "path": dest.display().to_string(),
            "filename": filename,
        }),
    }))
}

async fn static_handler(uri: Uri) -> Response {
    let path = uri.path().trim_start_matches('/');
    serve_asset(path)
        .or_else(|| serve_asset("index.html"))
        .unwrap_or_else(|| StatusCode::NOT_FOUND.into_response())
}

fn serve_asset(path: &str) -> Option<Response> {
    Assets::get(path).map(|content| {
        let mime = mime_guess::from_path(path).first_or_octet_stream();
        ([(header::CONTENT_TYPE, mime.as_ref())], content.data).into_response()
    })
}

/// SSR 스냅샷용 — `web/dist/index.html`의 UTF-8 본문을 반환한다.
/// 없으면(개발 환경 등에서 `web/dist` 미빌드) `None`.
pub fn spa_index_html() -> Option<String> {
    Assets::get("index.html")
        .and_then(|f| std::str::from_utf8(f.data.as_ref()).ok().map(str::to_owned))
}

// ─── extension lifecycle (doc/02 §2.13, doc/04 §4.3) ───

#[derive(serde::Serialize)]
struct ExtensionInfo {
    id: String,
    display_name: ManifestLocalized,
    enabled: bool,
    purged: bool,
}

async fn extension_info(state: &AppState, ext: &Arc<dyn Extension>) -> ExtensionInfo {
    let s = state.registry.status_of(ext.id()).await;
    ExtensionInfo {
        id: ext.id().to_string(),
        display_name: ManifestLocalized {
            ko: ext.display_name(Lang::Ko),
            en: ext.display_name(Lang::En),
        },
        enabled: s.map(|s| s.enabled).unwrap_or(false),
        purged: s.map(|s| s.purged).unwrap_or(false),
    }
}

async fn extensions_list(
    auth: AdminAuth,
    State(state): State<AppState>,
) -> Result<Json<DataEnvelope<Vec<ExtensionInfo>>>, ApiError> {
    auth.require_scope("admin")?;
    let snapshot = state.registry.status_snapshot().await;
    let mut out = Vec::new();
    for e in state.registry.iter() {
        let s = snapshot.get(e.id()).copied();
        out.push(ExtensionInfo {
            id: e.id().to_string(),
            display_name: ManifestLocalized {
                ko: e.display_name(Lang::Ko),
                en: e.display_name(Lang::En),
            },
            enabled: s.map(|s| s.enabled).unwrap_or(false),
            purged: s.map(|s| s.purged).unwrap_or(false),
        });
    }
    Ok(Json(DataEnvelope { data: out }))
}

async fn extension_enable(
    auth: AdminAuth,
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<Json<DataEnvelope<ExtensionInfo>>, ApiError> {
    auth.require_scope("admin")?;
    let ext = state
        .registry.find(&id)
        .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "extension_not_found", "unknown extension id"))?;
    let prev = state.registry.status_of(&id).await;
    let was_purged = prev.map(|s| s.purged).unwrap_or(false);
    let was_enabled = prev.map(|s| s.enabled).unwrap_or(false);
    if was_purged {
        // purge 복구: 플래그 클리어. 실제 마이그레이션은 다음 부팅 시 run_migrations가
        // schema_migrations 행 부재를 감지해 재실행한다 (run_migrations future가
        // 핸들러 컨텍스트에서 non-Send라 직접 await 불가 — 부팅 시점에 해결).
        state.registry.set_purged(&state.db, &id, false).await?;
    }
    state.registry.set_enabled(&state.db, &id, true).await?;
    if !was_enabled || was_purged {
        match ext.on_startup(&state).await {
            Ok(_) => {}
            Err(e) => tracing::warn!(extension = %id, error = %e, "on_startup failed"),
        }
    }
    Ok(Json(DataEnvelope {
        data: extension_info(&state, &ext).await,
    }))
}

async fn extension_disable(
    auth: AdminAuth,
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<Json<DataEnvelope<ExtensionInfo>>, ApiError> {
    auth.require_scope("admin")?;
    let ext = state
        .registry.find(&id)
        .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "extension_not_found", "unknown extension id"))?;
    let prev = state.registry.set_enabled(&state.db, &id, false).await?;
    if prev.map(|s| s.enabled).unwrap_or(false) {
        // enabled→disabled 전환 시에만 FTS 색인 즉시 정리 (doc/02 §2.13).
        match ext.on_disable(&state).await {
            Ok(_) => {}
            Err(e) => tracing::warn!(extension = %id, error = %e, "on_disable failed"),
        }
    }
    Ok(Json(DataEnvelope {
        data: extension_info(&state, &ext).await,
    }))
}

async fn extension_purge(
    auth: AdminAuth,
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<Json<DataEnvelope<serde_json::Value>>, ApiError> {
    auth.require_scope("admin")?;
    let ext = state
        .registry.find(&id)
        .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "extension_not_found", "unknown extension id"))?;
    // 1. disable + FTS 정리.
    state.registry.set_enabled(&state.db, &id, false).await?;
    let _ = ext.on_disable(&state).await;
    // 2. 확장 테이블 DROP. table_names()는 &'static str이지만 방어적으로 식별자 검증.
    for table in ext.table_names() {
        if !is_safe_ident(table) {
            return Err(ApiError::new(
                StatusCode::INTERNAL_SERVER_ERROR,
                "unsafe_table_name",
                "extension returned an invalid table name",
            ));
        }
        sqlx::query(&format!("DROP TABLE IF EXISTS {table}"))
            .execute(&state.db)
            .await
            .map_err(|e| ApiError::from(anyhow::anyhow!(e)))?;
    }
    // 3. 미디어 디렉토리 rm (data/media/{id}/).
    let media = state.config.server.data_dir.join("media").join(&id);
    if media.exists() {
        match std::fs::remove_dir_all(&media) {
            Ok(_) => {}
            Err(e) => tracing::warn!(path = %media.display(), error = %e, "failed to remove media dir during purge"),
        }
    }
    // 4. 마이그레이션 기록 제거 — enable-after-purge가 재실행하도록.
    sqlx::query("DELETE FROM schema_migrations WHERE extension = ?")
        .bind(&id)
        .execute(&state.db)
        .await
        .map_err(|e| ApiError::from(anyhow::anyhow!(e)))?;
    // 5. purge 플래그 세팅 (부팅 시 마이그레이션 스킵).
    state.registry.set_purged(&state.db, &id, true).await?;
    Ok(Json(DataEnvelope {
        data: serde_json::json!({ "extension_id": id, "purged": true }),
    }))
}

// ─── wasm runtime install (doc/08 §8.4) ───
//
// install 은 wasm 바이트를 data/extensions/<name>.wasm 에 저장하고 extension_state
// 행을 추가만 한다. 실제 적재(인스턴스화)는 oxipage-wasm 이 다음 부팅 시 수행
// (server `wasm` feature). 따라서 이 핸들러 자체는 wasmtime/oxipage-wasm 에 의존하지
// 않는다 — 코어 어디서나 동작.

/// 임베드된 레지스트리 카탈로그 (빌드 시점 snapshot of registry/index.json).
const REGISTRY_INDEX_JSON: &str = include_str!("../_registry.json");
/// 임베드된 데모 wasm 아티팩트 — install 오프라인 검증용 (remote 다운로드 경로와 별개).
const DEMO_WASM_BYTES: &[u8] =
    include_bytes!("../_wasm-demo.wasm");

/// 신뢰하는 ed25519 공개키 (base64). .wasm 아티팩트 서명 검증에 사용.
/// 프로덕션에서는 config 로 주입 가능. 데모용 고정 키.
const TRUSTED_WASM_PUBKEY_B64: &str = "Yokw8k5OJv9Ty0b1PhaZ3zYitU9tY7q9Yvebjxa8aiA=";

#[derive(serde::Deserialize)]
struct RegistryIndex {
    extensions: Vec<RegistryEntry>,
}

#[derive(serde::Deserialize)]
struct RegistryEntry {
    name: String,
    #[serde(default)]
    runtime_loadable: bool,
    #[serde(default)]
    wasm_url: Option<String>,
    /// base64 ed25519 서명. 있으면 install 시 검증.
    #[serde(default)]
    signature: Option<String>,
}

/// .wasm 바이트의 ed25519 서명을 검증. 실패 시 CONFLICT 에러.
fn verify_wasm_signature(bytes: &[u8], signature_b64: &str) -> Result<(), ApiError> {
    use base64::Engine;
    use ed25519_dalek::{Signature, Verifier, VerifyingKey};

    let pubkey_raw = base64::engine::general_purpose::STANDARD
        .decode(TRUSTED_WASM_PUBKEY_B64)
        .map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "sig_key_error", &e.to_string()))?;
    let pubkey_arr: [u8; 32] = pubkey_raw
        .as_slice()
        .try_into()
        .map_err(|_| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "sig_key_error", "pubkey not 32 bytes"))?;
    let pubkey = VerifyingKey::from_bytes(&pubkey_arr)
        .map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "sig_key_error", &e.to_string()))?;

    let sig_raw = base64::engine::general_purpose::STANDARD
        .decode(signature_b64)
        .map_err(|e| ApiError::new(StatusCode::BAD_REQUEST, "bad_signature", &e.to_string()))?;
    let sig = Signature::from_slice(&sig_raw)
        .map_err(|_| ApiError::new(StatusCode::BAD_REQUEST, "bad_signature", "malformed signature bytes"))?;

    pubkey
        .verify(bytes, &sig)
        .map_err(|_| ApiError::new(StatusCode::CONFLICT, "signature_mismatch", "wasm artifact signature verification failed"))
}

#[derive(serde::Deserialize)]
struct InstallInput {
    name: String,
}

async fn extension_install(
    auth: AdminAuth,
    State(state): State<AppState>,
    Json(input): Json<InstallInput>,
) -> Result<Json<DataEnvelope<serde_json::Value>>, ApiError> {
    auth.require_scope("admin")?;
    let name = input.name;
    if !is_safe_extension_name(&name) {
        return Err(ApiError::new(
            StatusCode::BAD_REQUEST,
            "bad_request",
            "invalid extension name",
        ));
    }
    let index: RegistryIndex = serde_json::from_str(REGISTRY_INDEX_JSON)
        .map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "registry_error", &e.to_string()))?;
    let entry = index
        .extensions
        .iter()
        .find(|e| e.name == name)
        .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "not_found", "unknown extension name"))?;
    if !entry.runtime_loadable {
        return Err(ApiError::new(
            StatusCode::CONFLICT,
            "not_runtime_loadable",
            "this extension is compile-time only; it cannot be installed at runtime",
        ));
    }
    // wasm 바이트 획득: 데모는 임베드, 그 외는 wasm_url 에서 다운로드.
    let bytes: Vec<u8> = if name == "wasm-demo" {
        DEMO_WASM_BYTES.to_vec()
    } else {
        let url = entry
            .wasm_url
            .as_deref()
            .ok_or_else(|| ApiError::new(StatusCode::CONFLICT, "no_wasm_url", "registry entry has no wasm_url"))?;
        let resp = reqwest::get(url)
            .await
            .map_err(|e| ApiError::new(StatusCode::BAD_GATEWAY, "download_failed", &e.to_string()))?;
        if !resp.status().is_success() {
            return Err(ApiError::new(
                StatusCode::BAD_GATEWAY,
                "download_failed",
                &format!("registry returned {}", resp.status()),
            ));
        }
        resp.bytes()
            .await
            .map_err(|e| ApiError::new(StatusCode::BAD_GATEWAY, "download_failed", &e.to_string()))?
            .to_vec()
    };

    // 서명 검증: registry entry 에 signature 가 있으면 ed25519 검증 (§7 #5).
    if let Some(sig) = &entry.signature {
        verify_wasm_signature(&bytes, sig)?;
    }
    let dir = state.config.server.data_dir.join("extensions");
    std::fs::create_dir_all(&dir)
        .map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "fs_error", &e.to_string()))?;
    let path = dir.join(format!("{name}.wasm"));
    std::fs::write(&path, &bytes)
        .map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "fs_error", &e.to_string()))?;

    // 라이브 활성화: wasm_loader 가 있으면 즉시 로드·등록·활성화 (재기동 불필요).
    if let Some(loader) = &state.wasm_loader {
        match loader.load(&path) {
            Ok(ext) => {
                // extension_state 행 (enabled=1 — 라이브 활성화됨).
                sqlx::query(
                    "INSERT INTO extension_state (extension_id, enabled, purged)
                     VALUES (?1, 1, 0)
                     ON CONFLICT(extension_id) DO UPDATE SET purged = 0, enabled = 1",
                )
                .bind(&name)
                .execute(&state.db)
                .await
                .map_err(|e| ApiError::from(anyhow::anyhow!(e)))?;

                let id = state.registry.register_and_activate(ext.clone()).await;

                if let Err(e) = ext.on_startup(&state).await {
                    tracing::warn!(extension = %id, error = %e, "on_startup failed for live-loaded extension");
                }
                tracing::info!(
                    extension = %id,
                    path = %path.display(),
                    bytes = bytes.len(),
                    "installed wasm extension (live activated)"
                );
                return Ok(Json(DataEnvelope {
                    data: serde_json::json!({
                        "name": name,
                        "path": path.display().to_string(),
                        "bytes": bytes.len(),
                        "activated": true,
                    }),
                }));
            }
            Err(e) => {
                tracing::warn!(
                    extension = %name,
                    error = %e,
                    "wasm live-activation failed — restart to retry"
                );
            }
        }
    }

    // extension_state 행 (enabled=0). wasm_loader 가 없거나 로드 실패 → 재기동 필요.
    sqlx::query(
        "INSERT INTO extension_state (extension_id, enabled, purged)
         VALUES (?1, 0, 0)
         ON CONFLICT(extension_id) DO UPDATE SET purged = 0",
    )
    .bind(&name)
    .execute(&state.db)
    .await
    .map_err(|e| ApiError::from(anyhow::anyhow!(e)))?;
    tracing::info!(
        extension = %name,
        path = %path.display(),
        bytes = bytes.len(),
        "installed wasm extension (restart to activate)"
    );
    Ok(Json(DataEnvelope {
        data: serde_json::json!({
            "name": name,
            "path": path.display().to_string(),
            "bytes": bytes.len(),
            "activated": false,
            "note": "restart oxipage-console (built with --features wasm) to activate",
        }),
    }))
}

fn is_safe_ident(name: &str) -> bool {
    !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// 런타임 설치 확장 이름 검증. is_safe_ident 와 달리 하이픈을 허용한다 —
/// 이름은 파일명(data/extensions/<name>.wasm)과 매개변수화 SQL 바인드에만 쓰이므로
/// 하이픈이 안전하다 (경로 순회 차단: `/` `\` `.` 는 여전히 거부). SQL 식별자로
/// 보간되는 table_names() 에는 이 함수를 쓰면 안 된다 — is_safe_ident 를 쓸 것.
fn is_safe_extension_name(name: &str) -> bool {
    !name.is_empty()
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

/// `/api/console/{ext}/**` 경로에서 ext 세그먼트 추출. 코어 라우트(lobby/auth/search/docs)는
/// registry.find 가 None이므로 게이트 대상이 아니다.
fn extension_id_from_path(path: &str) -> Option<String> {
    // nest 내부 layer라 path는 /api/console prefix가 벗겨진 상태다 ("/dummy", "/lobby/manifest").
    let seg = path.trim_start_matches('/').split('/').next()?;
    if seg.is_empty() {
        None
    } else {
        Some(seg.to_string())
    }
}

/// 런타임 게이트 미들웨어. registry에 있는 확장이 비활성/purged면 404.
async fn extension_gate(
    State(state): State<AppState>,
    request: Request,
    next: Next,
) -> Response {
    if let Some(ext_id) = extension_id_from_path(request.uri().path())
        && state.registry.find(&ext_id).is_some()
        && !state.registry.is_active(&ext_id).await
    {
        return ApiError::new(
            StatusCode::NOT_FOUND,
            "extension_disabled",
            "extension is disabled or purged",
        )
        .into_response();
    }
    next.run(request).await
}

// ─── CLI 동적 명령 (doc/11) ───

async fn cli_commands_handler(
    State(state): State<AppState>,
) -> Json<CliCommandManifest> {
    // 활성 확장 상태 스냅샷을 미리 수집 (async boundary)
    let statuses = state.registry.status_snapshot().await;

    let extensions: Vec<CliCommandSpec> = state
        .registry
        .iter()
        .into_iter()
        .filter(|ext| {
            statuses
                .get(ext.id())
                .map(|s| s.active())
                .unwrap_or(false)
        })
        .flat_map(|ext| {
            let id = ext.id().to_string();
            ext.cli_commands().into_iter().map(move |cmd| CliCommandSpec {
                extension_id: id.clone(),
                name: cmd.name.to_string(),
                about: cmd.about.to_string(),
                subcommands: cmd
                    .subcommands
                    .into_iter()
                    .map(|sub| CliSubcommandSpec {
                        name: sub.name.to_string(),
                        about: sub.about.to_string(),
                        args: sub
                            .args
                            .into_iter()
                            .map(|a| CliArgSpec {
                                long: a.long.to_string(),
                                short: a.short,
                                help: a.help.to_string(),
                                required: a.required,
                            })
                            .collect(),
                    })
                    .collect(),
            })
        })
        .collect();
    Json(CliCommandManifest { extensions })
}

#[derive(serde::Deserialize)]
struct CliExecInput {
    args: std::collections::BTreeMap<String, String>,
}

/// WASM 확장이 핸들러 없는 CLI 명령을 위임받아 실행.
/// 핸들러가 None인 확장의 CLI 명령은 이 엔드포인트로 요청이 온다.
/// 컴파일 확장은 직접 `CliHandler`를 가지므로 이 경로를 거치지 않는다.
async fn cli_exec_handler(
    State(state): State<AppState>,
    Path((ext_id, sub_command)): Path<(String, String)>,
    Json(input): Json<CliExecInput>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let ext = state
        .registry
        .find(&ext_id)
        .ok_or_else(|| {
            let msg = format!("extension '{ext_id}' not found");
            ApiError::new(
                axum::http::StatusCode::NOT_FOUND,
                "extension_not_found",
                &msg,
            )
        })?;

    // 확장의 cli_commands()에서 서브커맨드 찾기
    let cmd = ext
        .cli_commands()
        .into_iter()
        .find_map(|c| {
            c.subcommands
                .into_iter()
                .find(|s| s.name == sub_command)
        })
        .ok_or_else(|| {
            let msg = format!(
                "subcommand '{sub_command}' not found in extension '{ext_id}'"
            );
            ApiError::new(
                axum::http::StatusCode::NOT_FOUND,
                "subcommand_not_found",
                &msg,
            )
        })?;

    // 핸들러가 있으면 서버에서 실행할 수 없다 — 컴파일 확장 전용
    if cmd.handler.is_some() {
        let msg = format!(
            "command '{ext_id} {sub_command}' has a native handler and cannot be proxied"
        );
        return Err(ApiError::new(
            axum::http::StatusCode::BAD_REQUEST,
            "handler_not_proxyable",
            &msg,
        ));
    }

    // TODO: WASM 확장은 여기서 arg 검증 후 적절한 API 호출로 변환.
    // 현재 Phase 1: stub — args를 그대로 반영해 echo
    tracing::info!(
        "cli exec proxy: ext={ext_id} sub={sub_command} args={:?}",
        input.args
    );
    Ok(Json(serde_json::json!({
        "status": "stub",
        "ext_id": ext_id,
        "sub_command": sub_command,
        "args": input.args,
    })))
}

// ─── theme (doc/12 §12.7) ───

/// 큐레이션 테마 카탈로그 엔트리.
struct ThemeCatalogEntry {
    id: &'static str,
    name_ko: &'static str,
    name_en: &'static str,
    mode: &'static str,
    accent_hue: f64,
    description_ko: &'static str,
    description_en: &'static str,
}

/// v1 큐레이션 테마 4종.
const THEMES: &[ThemeCatalogEntry] = &[
    ThemeCatalogEntry {
        id: "paper",
        name_ko: "종이",
        name_en: "Paper",
        mode: "light",
        accent_hue: 290.0,
        description_ko: "따뜻한 종이 배경, 인디고-바이올렛 악센트",
        description_en: "Warm paper background, indigo-violet accent",
    },
    ThemeCatalogEntry {
        id: "midnight",
        name_ko: "한밤",
        name_en: "Midnight",
        mode: "dark",
        accent_hue: 230.0,
        description_ko: "깊은 밤하늘, 시안-블루 악센트",
        description_en: "Deep night sky, cyan-blue accent",
    },
    ThemeCatalogEntry {
        id: "sepia",
        name_ko: "세피아",
        name_en: "Sepia",
        mode: "light",
        accent_hue: 70.0,
        description_ko: "오래된 책장, 앰버-골드 악센트",
        description_en: "Old bookshelf, amber-gold accent",
    },
    ThemeCatalogEntry {
        id: "forest",
        name_ko: "",
        name_en: "Forest",
        mode: "dark",
        accent_hue: 155.0,
        description_ko: "이끼 낀 숲, 에메랄드 악센트",
        description_en: "Mossy forest, emerald accent",
    },
];

/// GET /api/console/themes — 카탈로그 (인증 불요, 공개 웹이 읽음)
async fn theme_catalog() -> Json<DataEnvelope<Vec<serde_json::Value>>> {
    let list: Vec<serde_json::Value> = THEMES
        .iter()
        .map(|t| {
            serde_json::json!({
                "id": t.id,
                "name": { "ko": t.name_ko, "en": t.name_en },
                "mode": t.mode,
                "accent_hue": t.accent_hue,
                "description": { "ko": t.description_ko, "en": t.description_en },
            })
        })
        .collect();
    Json(DataEnvelope { data: list })
}

/// GET /api/console/theme — 현재 적용 테마 (인증 불요, 공개 웹이 읽음)
async fn theme_get(State(state): State<AppState>) -> Result<Json<DataEnvelope<serde_json::Value>>, ApiError> {
    let row: Option<(String,)> = sqlx::query_as(
        "SELECT theme_id FROM theme_config WHERE id = 1",
    )
    .fetch_optional(&state.db)
    .await
    .map_err(|e| ApiError::internal(anyhow::anyhow!("db: {e}")))?;

    let theme_id = row.map(|r| r.0).unwrap_or_else(|| "paper".to_string());
    Ok(Json(DataEnvelope {
        data: serde_json::json!({"theme_id": theme_id}),
    }))
}

/// PUT /api/console/theme — 테마 변경 (admin 스코프)
#[derive(serde::Deserialize)]
struct ThemePutInput {
    theme_id: String,
}

async fn theme_put(
    auth: AdminAuth,
    State(state): State<AppState>,
    Json(input): Json<ThemePutInput>,
) -> Result<Json<DataEnvelope<serde_json::Value>>, ApiError> {
    auth.require_scope("admin")?;

    // 유효한 테마인지 확인
    let valid = THEMES.iter().any(|t| t.id == input.theme_id);
    if !valid {
        return Err(ApiError::new(
            axum::http::StatusCode::BAD_REQUEST,
            "invalid_theme",
            &format!("'{}' is not a valid theme", input.theme_id),
        ));
    }

    sqlx::query(
        "INSERT INTO theme_config (id, theme_id, updated_at) VALUES (1, ?1, datetime('now'))
         ON CONFLICT(id) DO UPDATE SET theme_id = ?1, updated_at = datetime('now')",
    )
    .bind(&input.theme_id)
    .execute(&state.db)
    .await
    .map_err(|e| ApiError::internal(anyhow::anyhow!("db: {e}")))?;

    Ok(Json(DataEnvelope {
        data: serde_json::json!({"theme_id": input.theme_id}),
    }))
}