Compare commits
4 Commits
secrets-mc
...
secrets-mc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7afd7f819 | ||
|
|
719bdd7e08 | ||
|
|
1e597559a2 | ||
|
|
e3ca43ca3f |
10
AGENTS.md
10
AGENTS.md
@@ -112,7 +112,7 @@ oauth_accounts (
|
||||
- 错误:业务层 `anyhow::Result`,避免生产路径 `unwrap()`。
|
||||
- 异步:`tokio` + `sqlx` async。
|
||||
- SQL:`sqlx::query` / `query_as` 参数绑定;动态 WHERE 仍须用占位符绑定。
|
||||
- 日志:运维用 `tracing`;面向用户的 Web 响应走 axum handler。
|
||||
- 日志:运维用 `tracing`;面向用户的 Web 响应走 axum handler。tracing 字段风格:变量名即字段名时用简写(`%var`、`?var`、`var`),否则用显式形式(`field = %expr`)。
|
||||
- 审计:写操作成功后尽量 `audit::log_tx`;失败可 `warn`,不掩盖主错误。
|
||||
- 加密:密钥由用户密码短语通过 **PBKDF2-SHA256(600k 次)** 在客户端派生,服务端只存 `key_salt`/`key_check`/`key_params`,不持有原始密钥。Web 客户端在浏览器本地完成加解密;MCP 客户端通过 `X-Encryption-Key` 请求头传递密钥,服务端临时解密后返回明文。
|
||||
- MCP:tools 参数与 JSON Schema(`schemars`)保持同步,鉴权以请求扩展中的用户上下文为准。
|
||||
@@ -140,10 +140,10 @@ git tag -l 'secrets-mcp-*'
|
||||
|
||||
## CI/CD
|
||||
|
||||
- **触发**:任意分支 `push`,且路径含 `crates/**`、`deploy/**`、根目录 `Cargo.toml`、`Cargo.lock`(见 `.gitea/workflows/secrets.yml`)。
|
||||
- **版本与 tag**:从 `crates/secrets-mcp/Cargo.toml` 读版本;若远程已存在同名 `secrets-mcp-<version>` tag,则复用现有 tag 继续构建;否则由 CI 创建并推送该 tag。
|
||||
- **触发**:任意分支 `push`,且路径含 `crates/**`、`deploy/**`、根目录 `Cargo.toml`、`Cargo.lock`、`.gitea/workflows/**`(见 `.gitea/workflows/secrets.yml`)。
|
||||
- **版本与 tag**:从 `crates/secrets-mcp/Cargo.toml` 读版本;构建成功后打 `secrets-mcp-<version>`:若远端已存在同名 tag,CI 会先删后于**当前提交**重建并推送(覆盖式发版)。
|
||||
- **质量与构建**:`fmt` / `clippy --locked` / `test --locked` → `x86_64-unknown-linux-musl` 发布构建 `secrets-mcp`。
|
||||
- **Release(可选)**:`secrets.RELEASE_TOKEN`(Gitea PAT)用于创建草稿 Release、上传 `tar.gz` + `.sha256`、构建成功后发布;未配置则跳过 API Release,仅 tag + 构建。
|
||||
- **Release(可选)**:`secrets.RELEASE_TOKEN`(Gitea PAT)用于通过 API **创建或更新**该 tag 的 Release(非 draft)、上传 `tar.gz` + `.sha256`;未配置则跳过 API Release,仅 tag + 构建。
|
||||
- **部署(可选)**:仅 `main`、`feat/mcp`、`mcp` 分支在构建成功时跑 `deploy-mcp`;需 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER`、`secrets.DEPLOY_SSH_KEY`。勿把 OAuth/DB 等写进 workflow,用 `deploy/.env.example` 在目标机配置。
|
||||
- **Secrets 写法**:Actions **secrets 须为原始值**(PEM、PAT 明文),**勿** base64;否则 SSH/Release 会失败。**勿**在 CI 中保存 `GOOGLE_CLIENT_SECRET`、DB 密码。
|
||||
- **通知**:`vars.WEBHOOK_URL`(可选,飞书)。
|
||||
@@ -154,7 +154,7 @@ git tag -l 'secrets-mcp-*'
|
||||
|------|------|
|
||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL URL。 |
|
||||
| `BASE_URL` | 对外基址;OAuth 回调 `${BASE_URL}/auth/google/callback`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `0.0.0.0:9315`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`(容器/远程直接暴露时需改为 `0.0.0.0:9315`)。 |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;仅运行时配置。 |
|
||||
| `RUST_LOG` | 如 `secrets_mcp=debug`。 |
|
||||
|
||||
|
||||
39
Cargo.lock
generated
39
Cargo.lock
generated
@@ -1809,6 +1809,25 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmp"
|
||||
version = "0.8.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmp-serde"
|
||||
version = "1.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
|
||||
dependencies = [
|
||||
"rmp",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rsa"
|
||||
version = "0.9.10"
|
||||
@@ -1949,7 +1968,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "secrets-mcp"
|
||||
version = "0.1.11"
|
||||
version = "0.2.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
@@ -1967,10 +1986,12 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sqlx",
|
||||
"time",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-sessions",
|
||||
"tower-sessions-sqlx-store-chrono",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"urlencoding",
|
||||
@@ -2766,6 +2787,22 @@ dependencies = [
|
||||
"tower-sessions-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-sessions-sqlx-store-chrono"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b295c8fc08db03246e92773c5e10119b72db6bc4240112135bebb0e49670804f"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"chrono",
|
||||
"rmp-serde",
|
||||
"sqlx",
|
||||
"thiserror",
|
||||
"time",
|
||||
"tower-sessions-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
|
||||
@@ -19,8 +19,9 @@ cargo build --release -p secrets-mcp
|
||||
|------|------|
|
||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(建议专用库,如 `secrets-mcp`)。 |
|
||||
| `BASE_URL` | 对外访问基址;OAuth 回调为 `{BASE_URL}/auth/google/callback`。默认 `http://localhost:9315`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `0.0.0.0:9315`。反代时常为 `127.0.0.1:9315`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`。容器内或直接对外暴露端口时请改为 `0.0.0.0:9315`;反代时常为 `127.0.0.1:9315`。 |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;不配置则无 Google 登录入口。运行时从环境读取,勿写入 CI、勿打入二进制。 |
|
||||
| `RUST_LOG` | 可选;日志级别,如 `secrets_mcp=debug`。 |
|
||||
|
||||
```bash
|
||||
cargo run -p secrets-mcp
|
||||
@@ -165,9 +166,9 @@ deploy/ # systemd、.env 示例
|
||||
|
||||
见 [`.gitea/workflows/secrets.yml`](.gitea/workflows/secrets.yml)。
|
||||
|
||||
- **触发**:任意分支 `push`,且变更路径包含 `crates/**`、`deploy/**`、根目录 `Cargo.toml` / `Cargo.lock`。
|
||||
- **流水线**:解析 `crates/secrets-mcp/Cargo.toml` 版本 → 若 `secrets-mcp-<version>` 的 tag 已存在则**复用现有 tag 继续构建**,否则自动打 tag → `cargo fmt` / `clippy --locked` / `test --locked` → 交叉编译 `x86_64-unknown-linux-musl` 的 `secrets-mcp`。
|
||||
- **Release(可选)**:配置仓库 Secret `RELEASE_TOKEN`(Gitea PAT,明文勿 base64)时,会通过 API 创建**草稿** Release、在 Linux 构建成功后上传 `tar.gz` 与 `.sha256`,再自动将草稿**正式发布**;未配置则跳过创建 Release 与产物上传,仅保留 tag 与构建结果。
|
||||
- **触发**:任意分支 `push`,且变更路径包含 `crates/**`、`deploy/**`、根目录 `Cargo.toml` / `Cargo.lock`、`.gitea/workflows/**`。
|
||||
- **流水线**:解析 `crates/secrets-mcp/Cargo.toml` 版本 → `cargo fmt` / `clippy --locked` / `test --locked` → 交叉编译 `x86_64-unknown-linux-musl` 的 `secrets-mcp` → 构建成功后打 tag `secrets-mcp-<version>`(若远端已存在同名 tag,会先删除再于**当前提交**重建并推送,覆盖式发版)。
|
||||
- **Release(可选)**:配置仓库 Secret `RELEASE_TOKEN`(Gitea PAT,明文勿 base64)时,会通过 API **创建或更新**已指向该 tag 的 Release(非 draft)、上传 `tar.gz` 与 `.sha256`;未配置则跳过 API Release,仅 tag + 构建结果。
|
||||
- **部署(可选)**:仅在 `main`、`feat/mcp` 或 `mcp` 分支且构建成功时,若已配置 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER` 与 `secrets.DEPLOY_SSH_KEY`,则 `deploy-mcp` 通过 SCP/SSH 更新目标机二进制并 `systemctl restart secrets-mcp`。
|
||||
- **通知(可选)**:`vars.WEBHOOK_URL` 为飞书 Webhook 时,构建/部署/发布节点会推送简要状态。
|
||||
|
||||
|
||||
@@ -55,35 +55,6 @@ pub fn decrypt_json(master_key: &[u8; 32], data: &[u8]) -> Result<Value> {
|
||||
serde_json::from_slice(&bytes).context("deserialize decrypted JSON")
|
||||
}
|
||||
|
||||
// ─── Per-user key management (DEPRECATED — kept only for migration) ───────────
|
||||
|
||||
/// Generate a new random 32-byte per-user encryption key.
|
||||
#[allow(dead_code)]
|
||||
pub fn generate_user_key() -> [u8; 32] {
|
||||
use aes_gcm::aead::rand_core::RngCore;
|
||||
let mut key = [0u8; 32];
|
||||
OsRng.fill_bytes(&mut key);
|
||||
key
|
||||
}
|
||||
|
||||
/// Wrap a per-user key with the server master key using AES-256-GCM.
|
||||
#[allow(dead_code)]
|
||||
pub fn wrap_user_key(server_master_key: &[u8; 32], user_key: &[u8; 32]) -> Result<Vec<u8>> {
|
||||
encrypt(server_master_key, user_key.as_ref())
|
||||
}
|
||||
|
||||
/// Unwrap a per-user key using the server master key.
|
||||
#[allow(dead_code)]
|
||||
pub fn unwrap_user_key(server_master_key: &[u8; 32], wrapped: &[u8]) -> Result<[u8; 32]> {
|
||||
let bytes = decrypt(server_master_key, wrapped)?;
|
||||
if bytes.len() != 32 {
|
||||
bail!("unwrapped user key has unexpected length {}", bytes.len());
|
||||
}
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&bytes);
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
// ─── Client-supplied key extraction ──────────────────────────────────────────
|
||||
|
||||
/// Parse a 64-char hex string (from X-Encryption-Key header) into a 32-byte key.
|
||||
@@ -100,33 +71,6 @@ pub fn extract_key_from_hex(hex_str: &str) -> Result<[u8; 32]> {
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
// ─── Server master key ────────────────────────────────────────────────────────
|
||||
|
||||
/// Load the server master key from `SERVER_MASTER_KEY` environment variable (64 hex chars).
|
||||
pub fn load_master_key_auto() -> Result<[u8; 32]> {
|
||||
let hex_str = std::env::var("SERVER_MASTER_KEY").map_err(|_| {
|
||||
anyhow::anyhow!(
|
||||
"SERVER_MASTER_KEY is not set. \
|
||||
Generate one with: openssl rand -hex 32"
|
||||
)
|
||||
})?;
|
||||
|
||||
if hex_str.is_empty() {
|
||||
bail!("SERVER_MASTER_KEY is set but empty");
|
||||
}
|
||||
|
||||
let bytes = hex::decode_hex(hex_str.trim())?;
|
||||
if bytes.len() != 32 {
|
||||
bail!(
|
||||
"SERVER_MASTER_KEY must be 64 hex chars (32 bytes), got {} bytes",
|
||||
bytes.len()
|
||||
);
|
||||
}
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&bytes);
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
// ─── Public hex helpers ───────────────────────────────────────────────────────
|
||||
|
||||
pub mod hex {
|
||||
@@ -186,22 +130,4 @@ mod tests {
|
||||
let dec = decrypt_json(&key, &enc).unwrap();
|
||||
assert_eq!(dec, value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_key_wrap_unwrap_roundtrip() {
|
||||
let server_key = [0xABu8; 32];
|
||||
let user_key = [0xCDu8; 32];
|
||||
let wrapped = wrap_user_key(&server_key, &user_key).unwrap();
|
||||
let unwrapped = unwrap_user_key(&server_key, &wrapped).unwrap();
|
||||
assert_eq!(unwrapped, user_key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_key_wrap_wrong_server_key_fails() {
|
||||
let server_key1 = [0xABu8; 32];
|
||||
let server_key2 = [0xEFu8; 32];
|
||||
let user_key = [0xCDu8; 32];
|
||||
let wrapped = wrap_user_key(&server_key1, &user_key).unwrap();
|
||||
assert!(unwrap_user_key(&server_key2, &wrapped).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +156,37 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
CREATE INDEX IF NOT EXISTS idx_oauth_accounts_user ON oauth_accounts(user_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_accounts_user_provider
|
||||
ON oauth_accounts(user_id, provider);
|
||||
|
||||
-- FK: user_id columns -> users(id) (nullable = legacy rows; ON DELETE SET NULL)
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'fk_entries_user_id'
|
||||
) THEN
|
||||
ALTER TABLE entries
|
||||
ADD CONSTRAINT fk_entries_user_id
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'fk_entries_history_user_id'
|
||||
) THEN
|
||||
ALTER TABLE entries_history
|
||||
ADD CONSTRAINT fk_entries_history_user_id
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'fk_audit_log_user_id'
|
||||
) THEN
|
||||
ALTER TABLE audit_log
|
||||
ADD CONSTRAINT fk_audit_log_user_id
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "secrets-mcp"
|
||||
version = "0.1.11"
|
||||
version = "0.2.2"
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
@@ -19,6 +19,8 @@ axum-extra = { version = "0.10", features = ["typed-header"] }
|
||||
tower = "0.5"
|
||||
tower-http = { version = "0.6", features = ["cors", "trace"] }
|
||||
tower-sessions = "0.14"
|
||||
tower-sessions-sqlx-store-chrono = { version = "0.14", features = ["postgres"] }
|
||||
time = "0.3"
|
||||
|
||||
# OAuth (manual token exchange via reqwest)
|
||||
reqwest.workspace = true
|
||||
|
||||
@@ -5,11 +5,11 @@ use axum::{
|
||||
body::{Body, Bytes, to_bytes},
|
||||
extract::{ConnectInfo, Request},
|
||||
http::{
|
||||
HeaderMap, Method,
|
||||
HeaderMap, Method, StatusCode,
|
||||
header::{CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},
|
||||
},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
/// Axum middleware that logs structured info for every HTTP request.
|
||||
@@ -68,10 +68,23 @@ pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(path, error = %e, "failed to buffer MCP request body for logging");
|
||||
// Reconstruct with empty body; request was consumed — return 500.
|
||||
// This branch is highly unlikely in practice.
|
||||
let resp = next.run(Request::from_parts(parts, Body::empty())).await;
|
||||
return resp;
|
||||
let elapsed = start.elapsed().as_millis();
|
||||
tracing::info!(
|
||||
method = method.as_str(),
|
||||
path,
|
||||
status = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
|
||||
elapsed_ms = elapsed,
|
||||
client_ip = ip.as_deref(),
|
||||
ua = ua.as_deref(),
|
||||
content_length = content_len,
|
||||
mcp_session = mcp_session.as_deref(),
|
||||
"mcp request",
|
||||
);
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"failed to read request body",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,11 @@ use rmcp::transport::streamable_http_server::{
|
||||
use sqlx::PgPool;
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
use tower_sessions::cookie::SameSite;
|
||||
use tower_sessions::{MemoryStore, SessionManagerLayer};
|
||||
use tower_sessions::session_store::ExpiredDeletion;
|
||||
use tower_sessions::{Expiry, SessionManagerLayer};
|
||||
use tower_sessions_sqlx_store_chrono::PostgresStore;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use tracing_subscriber::fmt::time::FormatTime;
|
||||
|
||||
use secrets_core::config::resolve_db_url;
|
||||
use secrets_core::db::{create_pool, migrate};
|
||||
@@ -47,12 +50,27 @@ fn load_oauth_config(prefix: &str, base_url: &str, path: &str) -> Option<OAuthCo
|
||||
})
|
||||
}
|
||||
|
||||
/// Log line timestamps in the process local timezone (honors `TZ` / system zone).
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct LocalRfc3339Time;
|
||||
|
||||
impl FormatTime for LocalRfc3339Time {
|
||||
fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
w,
|
||||
"{}",
|
||||
chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, false)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
// Load .env if present
|
||||
let _ = dotenvy::dotenv();
|
||||
|
||||
tracing_subscriber::fmt()
|
||||
.with_timer(LocalRfc3339Time)
|
||||
.with_env_filter(
|
||||
EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "secrets_mcp=info,tower_http=info".into()),
|
||||
@@ -72,7 +90,8 @@ async fn main() -> Result<()> {
|
||||
|
||||
// ── Configuration ─────────────────────────────────────────────────────────
|
||||
let base_url = load_env_var("BASE_URL").unwrap_or_else(|| "http://localhost:9315".to_string());
|
||||
let bind_addr = load_env_var("SECRETS_MCP_BIND").unwrap_or_else(|| "0.0.0.0:9315".to_string());
|
||||
let bind_addr =
|
||||
load_env_var("SECRETS_MCP_BIND").unwrap_or_else(|| "127.0.0.1:9315".to_string());
|
||||
|
||||
// ── OAuth providers ───────────────────────────────────────────────────────
|
||||
let google_config = load_oauth_config("GOOGLE", &base_url, "/auth/google/callback");
|
||||
@@ -83,12 +102,23 @@ async fn main() -> Result<()> {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Session store ─────────────────────────────────────────────────────────
|
||||
let session_store = MemoryStore::default();
|
||||
// ── Session store (PostgreSQL-backed) ─────────────────────────────────────
|
||||
let session_store = PostgresStore::new(pool.clone());
|
||||
session_store
|
||||
.migrate()
|
||||
.await
|
||||
.context("failed to run session table migration")?;
|
||||
// Prune expired rows every hour; task is aborted when the server shuts down.
|
||||
let session_cleanup = tokio::spawn(
|
||||
session_store
|
||||
.clone()
|
||||
.continuously_delete_expired(tokio::time::Duration::from_secs(3600)),
|
||||
);
|
||||
// Strict would drop the session cookie on redirect from Google → our origin (cross-site nav).
|
||||
let session_layer = SessionManagerLayer::new(session_store)
|
||||
.with_secure(base_url.starts_with("https://"))
|
||||
.with_same_site(SameSite::Lax);
|
||||
.with_same_site(SameSite::Lax)
|
||||
.with_expiry(Expiry::OnInactivity(time::Duration::days(14)));
|
||||
|
||||
// ── App state ─────────────────────────────────────────────────────────────
|
||||
let app_state = AppState {
|
||||
@@ -149,6 +179,7 @@ async fn main() -> Result<()> {
|
||||
.await
|
||||
.context("server error")?;
|
||||
|
||||
session_cleanup.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use secrets_core::models::ExportFormat;
|
||||
use secrets_core::service::{
|
||||
add::{AddParams, run as svc_add},
|
||||
delete::{DeleteParams, run as svc_delete},
|
||||
@@ -30,6 +31,32 @@ use secrets_core::service::{
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
|
||||
// ── MCP client-facing errors (no internal details) ───────────────────────────
|
||||
|
||||
fn mcp_err_missing_http_parts() -> rmcp::ErrorData {
|
||||
rmcp::ErrorData::internal_error("Invalid MCP request context.", None)
|
||||
}
|
||||
|
||||
fn mcp_err_internal_logged(
|
||||
tool: &'static str,
|
||||
user_id: Option<Uuid>,
|
||||
err: impl std::fmt::Display,
|
||||
) -> rmcp::ErrorData {
|
||||
tracing::warn!(tool, ?user_id, error = %err, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(
|
||||
"Request failed due to a server error. Check service logs if you need details.",
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn mcp_err_invalid_encryption_key_logged(err: impl std::fmt::Display) -> rmcp::ErrorData {
|
||||
tracing::warn!(error = %err, "invalid X-Encryption-Key");
|
||||
rmcp::ErrorData::invalid_request(
|
||||
"Invalid X-Encryption-Key: must be exactly 64 hexadecimal characters (32-byte key).",
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
// ── Shared state ──────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -51,7 +78,7 @@ impl SecretsService {
|
||||
let parts = ctx
|
||||
.extensions
|
||||
.get::<http::request::Parts>()
|
||||
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?;
|
||||
.ok_or_else(mcp_err_missing_http_parts)?;
|
||||
Ok(parts.extensions.get::<AuthUser>().map(|a| a.user_id))
|
||||
}
|
||||
|
||||
@@ -60,7 +87,7 @@ impl SecretsService {
|
||||
let parts = ctx
|
||||
.extensions
|
||||
.get::<http::request::Parts>()
|
||||
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?;
|
||||
.ok_or_else(mcp_err_missing_http_parts)?;
|
||||
parts
|
||||
.extensions
|
||||
.get::<AuthUser>()
|
||||
@@ -74,7 +101,7 @@ impl SecretsService {
|
||||
let parts = ctx
|
||||
.extensions
|
||||
.get::<http::request::Parts>()
|
||||
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?;
|
||||
.ok_or_else(mcp_err_missing_http_parts)?;
|
||||
let hex_str = parts
|
||||
.headers
|
||||
.get("x-encryption-key")
|
||||
@@ -89,8 +116,29 @@ impl SecretsService {
|
||||
.map_err(|_| {
|
||||
rmcp::ErrorData::invalid_request("Invalid X-Encryption-Key header value", None)
|
||||
})?;
|
||||
let trimmed = hex_str.trim();
|
||||
if trimmed.len() != 64 {
|
||||
tracing::warn!(
|
||||
got_len = trimmed.len(),
|
||||
"X-Encryption-Key has wrong length after trim"
|
||||
);
|
||||
return Err(rmcp::ErrorData::invalid_request(
|
||||
format!(
|
||||
"X-Encryption-Key must be exactly 64 hex characters (32-byte key), got {} characters.",
|
||||
trimmed.len()
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
if !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
tracing::warn!("X-Encryption-Key contains non-hexadecimal characters");
|
||||
return Err(rmcp::ErrorData::invalid_request(
|
||||
"X-Encryption-Key contains non-hexadecimal characters.",
|
||||
None,
|
||||
));
|
||||
}
|
||||
secrets_core::crypto::extract_key_from_hex(hex_str)
|
||||
.map_err(|e| rmcp::ErrorData::invalid_request(e.to_string(), None))
|
||||
.map_err(mcp_err_invalid_encryption_key_logged)
|
||||
}
|
||||
|
||||
/// Require both user_id and encryption key.
|
||||
@@ -250,8 +298,13 @@ struct EnvMapInput {
|
||||
#[tool_router]
|
||||
impl SecretsService {
|
||||
#[tool(
|
||||
description = "Search entries in the secrets store. Returns entries with metadata and \
|
||||
secret field names (not values). Use secrets_get to decrypt secret values."
|
||||
description = "Search entries in the secrets store. Requires Bearer API key. Returns \
|
||||
entries with metadata and secret field names (not values). Use secrets_get to decrypt secret values.",
|
||||
annotations(
|
||||
title = "Search Secrets",
|
||||
read_only_hint = true,
|
||||
idempotent_hint = true
|
||||
)
|
||||
)]
|
||||
async fn secrets_search(
|
||||
&self,
|
||||
@@ -259,7 +312,7 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let user_id = Self::user_id_from_ctx(&ctx)?;
|
||||
let user_id = Self::require_user_id(&ctx)?;
|
||||
tracing::info!(
|
||||
tool = "secrets_search",
|
||||
?user_id,
|
||||
@@ -281,14 +334,11 @@ impl SecretsService {
|
||||
sort: input.sort.as_deref().unwrap_or("name"),
|
||||
limit: input.limit.unwrap_or(20),
|
||||
offset: input.offset.unwrap_or(0),
|
||||
user_id,
|
||||
user_id: Some(user_id),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_search", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_search", Some(user_id), e))?;
|
||||
|
||||
let summary = input.summary.unwrap_or(false);
|
||||
let entries: Vec<serde_json::Value> = result
|
||||
@@ -341,7 +391,12 @@ impl SecretsService {
|
||||
#[tool(
|
||||
description = "Get decrypted secret field values for an entry. Requires your \
|
||||
encryption key via X-Encryption-Key header (64 hex chars, PBKDF2-derived). \
|
||||
Returns all fields, or a specific field if 'field' is provided."
|
||||
Returns all fields, or a specific field if 'field' is provided.",
|
||||
annotations(
|
||||
title = "Get Secret Values",
|
||||
read_only_hint = true,
|
||||
idempotent_hint = true
|
||||
)
|
||||
)]
|
||||
async fn secrets_get(
|
||||
&self,
|
||||
@@ -371,10 +426,7 @@ impl SecretsService {
|
||||
Some(user_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_get", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_get", Some(user_id), e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_get",
|
||||
@@ -395,10 +447,7 @@ impl SecretsService {
|
||||
Some(user_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_get", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_get", Some(user_id), e))?;
|
||||
|
||||
let count = secrets.len();
|
||||
tracing::info!(
|
||||
@@ -416,7 +465,8 @@ impl SecretsService {
|
||||
#[tool(
|
||||
description = "Add or upsert an entry with metadata and encrypted secret fields. \
|
||||
Requires X-Encryption-Key header. \
|
||||
Meta and secret values use 'key=value', 'key=@file', or 'key:=<json>' format."
|
||||
Meta and secret values use 'key=value', 'key=@file', or 'key:=<json>' format.",
|
||||
annotations(title = "Add Secret Entry")
|
||||
)]
|
||||
async fn secrets_add(
|
||||
&self,
|
||||
@@ -452,10 +502,7 @@ impl SecretsService {
|
||||
&user_key,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_add", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_add", Some(user_id), e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_add",
|
||||
@@ -472,7 +519,8 @@ impl SecretsService {
|
||||
|
||||
#[tool(
|
||||
description = "Incrementally update an existing entry. Requires X-Encryption-Key header. \
|
||||
Only the fields you specify are changed; everything else is preserved."
|
||||
Only the fields you specify are changed; everything else is preserved.",
|
||||
annotations(title = "Update Secret Entry")
|
||||
)]
|
||||
async fn secrets_update(
|
||||
&self,
|
||||
@@ -514,10 +562,7 @@ impl SecretsService {
|
||||
&user_key,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_update", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_update", Some(user_id), e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_update",
|
||||
@@ -534,7 +579,8 @@ impl SecretsService {
|
||||
|
||||
#[tool(
|
||||
description = "Delete one entry (specify namespace+kind+name) or bulk delete all \
|
||||
entries matching namespace+kind. Use dry_run=true to preview."
|
||||
entries matching namespace+kind. Use dry_run=true to preview.",
|
||||
annotations(title = "Delete Secret Entry", destructive_hint = true)
|
||||
)]
|
||||
async fn secrets_delete(
|
||||
&self,
|
||||
@@ -564,10 +610,7 @@ impl SecretsService {
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_delete", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_delete", user_id, e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_delete",
|
||||
@@ -582,7 +625,12 @@ impl SecretsService {
|
||||
|
||||
#[tool(
|
||||
description = "View change history for an entry. Returns a list of versions with \
|
||||
actions and timestamps."
|
||||
actions and timestamps.",
|
||||
annotations(
|
||||
title = "View Secret History",
|
||||
read_only_hint = true,
|
||||
idempotent_hint = true
|
||||
)
|
||||
)]
|
||||
async fn secrets_history(
|
||||
&self,
|
||||
@@ -609,10 +657,7 @@ impl SecretsService {
|
||||
user_id,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_history", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_history", user_id, e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_history",
|
||||
@@ -626,7 +671,8 @@ impl SecretsService {
|
||||
|
||||
#[tool(
|
||||
description = "Rollback an entry to a previous version. Requires X-Encryption-Key header. \
|
||||
Omit to_version to restore the most recent snapshot."
|
||||
Omit to_version to restore the most recent snapshot.",
|
||||
annotations(title = "Rollback Secret Entry", destructive_hint = true)
|
||||
)]
|
||||
async fn secrets_rollback(
|
||||
&self,
|
||||
@@ -655,10 +701,7 @@ impl SecretsService {
|
||||
Some(user_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_rollback", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_rollback", Some(user_id), e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_rollback",
|
||||
@@ -672,7 +715,12 @@ impl SecretsService {
|
||||
|
||||
#[tool(
|
||||
description = "Export matching entries with decrypted secrets as JSON/TOML/YAML string. \
|
||||
Requires X-Encryption-Key header. Useful for backup or data migration."
|
||||
Requires X-Encryption-Key header. Useful for backup or data migration.",
|
||||
annotations(
|
||||
title = "Export Secrets",
|
||||
read_only_hint = true,
|
||||
idempotent_hint = true
|
||||
)
|
||||
)]
|
||||
async fn secrets_export(
|
||||
&self,
|
||||
@@ -706,15 +754,23 @@ impl SecretsService {
|
||||
Some(&user_key),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_export", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_export", Some(user_id), e))?;
|
||||
|
||||
let serialized = format
|
||||
.parse::<secrets_core::models::ExportFormat>()
|
||||
.and_then(|fmt| fmt.serialize(&data))
|
||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
||||
let fmt = format.parse::<ExportFormat>().map_err(|e| {
|
||||
tracing::warn!(
|
||||
tool = "secrets_export",
|
||||
?user_id,
|
||||
error = %e,
|
||||
"invalid export format"
|
||||
);
|
||||
rmcp::ErrorData::invalid_request(
|
||||
"Invalid export format. Use json, toml, or yaml.",
|
||||
None,
|
||||
)
|
||||
})?;
|
||||
let serialized = fmt
|
||||
.serialize(&data)
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_export", Some(user_id), e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_export",
|
||||
@@ -729,7 +785,8 @@ impl SecretsService {
|
||||
#[tool(
|
||||
description = "Build the environment variable map from entry secrets with decrypted \
|
||||
plaintext values. Requires X-Encryption-Key header. \
|
||||
Returns a JSON object of VAR_NAME -> plaintext_value ready for injection."
|
||||
Returns a JSON object of VAR_NAME -> plaintext_value ready for injection.",
|
||||
annotations(title = "Build Env Map", read_only_hint = true, idempotent_hint = true)
|
||||
)]
|
||||
async fn secrets_env_map(
|
||||
&self,
|
||||
@@ -761,10 +818,7 @@ impl SecretsService {
|
||||
Some(user_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(tool = "secrets_env_map", ?user_id, error = %e, "tool call failed");
|
||||
rmcp::ErrorData::internal_error(e.to_string(), None)
|
||||
})?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_env_map", Some(user_id), e))?;
|
||||
|
||||
let entry_count = env_map.len();
|
||||
tracing::info!(
|
||||
@@ -785,13 +839,17 @@ impl SecretsService {
|
||||
impl ServerHandler for SecretsService {
|
||||
fn get_info(&self) -> InitializeResult {
|
||||
let mut info = InitializeResult::new(ServerCapabilities::builder().enable_tools().build());
|
||||
info.server_info = Implementation::new("secrets-mcp", env!("CARGO_PKG_VERSION"));
|
||||
info.protocol_version = ProtocolVersion::V_2025_03_26;
|
||||
info.server_info = Implementation::new("secrets-mcp", env!("CARGO_PKG_VERSION"))
|
||||
.with_title("Secrets MCP")
|
||||
.with_description(
|
||||
"Secure cross-device secrets and configuration management with encrypted secret fields.",
|
||||
);
|
||||
info.protocol_version = ProtocolVersion::V_2025_06_18;
|
||||
info.instructions = Some(
|
||||
"Manage cross-device secrets and configuration securely. \
|
||||
Data is encrypted with your passphrase-derived key. \
|
||||
Include your 64-char hex key in the X-Encryption-Key header for all read/write operations. \
|
||||
Use secrets_search to discover entries (no key needed), \
|
||||
Use secrets_search to discover entries (Bearer token required; encryption key not needed), \
|
||||
secrets_get to decrypt secret values, \
|
||||
and secrets_add/secrets_update to write encrypted secrets."
|
||||
.to_string(),
|
||||
|
||||
@@ -39,6 +39,15 @@ const SESSION_LOGIN_PROVIDER: &str = "login_provider";
|
||||
#[template(path = "login.html")]
|
||||
struct LoginTemplate {
|
||||
has_google: bool,
|
||||
base_url: String,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "home.html")]
|
||||
struct HomeTemplate {
|
||||
is_logged_in: bool,
|
||||
base_url: String,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
@@ -76,12 +85,22 @@ fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
||||
}
|
||||
|
||||
async fn current_user_id(session: &Session) -> Option<Uuid> {
|
||||
session
|
||||
.get::<String>(SESSION_USER_ID)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|s| Uuid::parse_str(&s).ok())
|
||||
match session.get::<String>(SESSION_USER_ID).await {
|
||||
Ok(opt) => match opt {
|
||||
Some(s) => match Uuid::parse_str(&s) {
|
||||
Ok(id) => Some(id),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, user_id_str = %s, "invalid user_id UUID in session");
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to read user_id from session");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request_client_ip(headers: &HeaderMap, connect_info: ConnectInfo<SocketAddr>) -> Option<String> {
|
||||
@@ -112,6 +131,9 @@ fn request_user_agent(headers: &HeaderMap) -> Option<String> {
|
||||
|
||||
pub fn web_router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/robots.txt", get(robots_txt))
|
||||
.route("/llms.txt", get(llms_txt))
|
||||
.route("/ai.txt", get(ai_txt))
|
||||
.route("/favicon.svg", get(favicon_svg))
|
||||
.route(
|
||||
"/favicon.ico",
|
||||
@@ -121,7 +143,8 @@ pub fn web_router() -> Router<AppState> {
|
||||
"/.well-known/oauth-protected-resource",
|
||||
get(oauth_protected_resource_metadata),
|
||||
)
|
||||
.route("/", get(login_page))
|
||||
.route("/", get(home_page))
|
||||
.route("/login", get(login_page))
|
||||
.route("/auth/google", get(auth_google))
|
||||
.route("/auth/google/callback", get(auth_google_callback))
|
||||
.route("/auth/logout", post(auth_logout))
|
||||
@@ -139,6 +162,33 @@ pub fn web_router() -> Router<AppState> {
|
||||
.route("/api/apikey/regenerate", post(api_apikey_regenerate))
|
||||
}
|
||||
|
||||
fn text_asset_response(content: &'static str, content_type: &'static str) -> Response {
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, content_type)
|
||||
.header(header::CACHE_CONTROL, "public, max-age=86400")
|
||||
.body(Body::from(content))
|
||||
.expect("text asset response")
|
||||
}
|
||||
|
||||
async fn robots_txt() -> Response {
|
||||
text_asset_response(
|
||||
include_str!("../static/robots.txt"),
|
||||
"text/plain; charset=utf-8",
|
||||
)
|
||||
}
|
||||
|
||||
async fn llms_txt() -> Response {
|
||||
text_asset_response(
|
||||
include_str!("../static/llms.txt"),
|
||||
"text/markdown; charset=utf-8",
|
||||
)
|
||||
}
|
||||
|
||||
async fn ai_txt() -> Response {
|
||||
llms_txt().await
|
||||
}
|
||||
|
||||
async fn favicon_svg() -> Response {
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
@@ -148,6 +198,21 @@ async fn favicon_svg() -> Response {
|
||||
.expect("favicon response")
|
||||
}
|
||||
|
||||
// ── Home page (public) ───────────────────────────────────────────────────────
|
||||
|
||||
async fn home_page(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let is_logged_in = current_user_id(&session).await.is_some();
|
||||
let tmpl = HomeTemplate {
|
||||
is_logged_in,
|
||||
base_url: state.base_url.clone(),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
render_template(tmpl)
|
||||
}
|
||||
|
||||
// ── Login page ────────────────────────────────────────────────────────────────
|
||||
|
||||
async fn login_page(
|
||||
@@ -160,6 +225,7 @@ async fn login_page(
|
||||
|
||||
let tmpl = LoginTemplate {
|
||||
has_google: state.google_config.is_some(),
|
||||
base_url: state.base_url.clone(),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
render_template(tmpl)
|
||||
@@ -177,7 +243,10 @@ async fn auth_google(
|
||||
session
|
||||
.insert(SESSION_OAUTH_STATE, &oauth_state)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to insert oauth_state into session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let url = google_auth_url(config, &oauth_state);
|
||||
Ok(Redirect::to(&url).into_response())
|
||||
@@ -239,31 +308,33 @@ where
|
||||
{
|
||||
if let Some(err) = params.error {
|
||||
tracing::warn!(provider, error = %err, "OAuth error");
|
||||
return Ok(Redirect::to("/?error=oauth_error").into_response());
|
||||
return Ok(Redirect::to("/login?error=oauth_error").into_response());
|
||||
}
|
||||
|
||||
let Some(code) = params.code else {
|
||||
tracing::warn!(provider, "OAuth callback missing code");
|
||||
return Ok(Redirect::to("/?error=oauth_missing_code").into_response());
|
||||
return Ok(Redirect::to("/login?error=oauth_missing_code").into_response());
|
||||
};
|
||||
let Some(returned_state) = params.state.as_deref() else {
|
||||
tracing::warn!(provider, "OAuth callback missing state");
|
||||
return Ok(Redirect::to("/?error=oauth_missing_state").into_response());
|
||||
return Ok(Redirect::to("/login?error=oauth_missing_state").into_response());
|
||||
};
|
||||
|
||||
let expected_state: Option<String> = session
|
||||
.get(SESSION_OAUTH_STATE)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let expected_state: Option<String> = session.get(SESSION_OAUTH_STATE).await.map_err(|e| {
|
||||
tracing::error!(provider, error = %e, "failed to read oauth_state from session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
if expected_state.as_deref() != Some(returned_state) {
|
||||
tracing::warn!(
|
||||
provider,
|
||||
expected_present = expected_state.is_some(),
|
||||
"OAuth state mismatch (empty session often means SameSite=Strict or server restart)"
|
||||
);
|
||||
return Ok(Redirect::to("/?error=oauth_state").into_response());
|
||||
return Ok(Redirect::to("/login?error=oauth_state").into_response());
|
||||
}
|
||||
if let Err(e) = session.remove::<String>(SESSION_OAUTH_STATE).await {
|
||||
tracing::warn!(provider, error = %e, "failed to remove oauth_state from session");
|
||||
}
|
||||
session.remove::<String>(SESSION_OAUTH_STATE).await.ok();
|
||||
|
||||
let config = match provider {
|
||||
"google" => state
|
||||
@@ -280,17 +351,25 @@ where
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let bind_mode: bool = session
|
||||
.get(SESSION_OAUTH_BIND_MODE)
|
||||
.await
|
||||
.unwrap_or(None)
|
||||
.unwrap_or(false);
|
||||
let bind_mode: bool = match session.get::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||
Ok(v) => v.unwrap_or(false),
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
provider,
|
||||
error = %e,
|
||||
"failed to read oauth_bind_mode from session"
|
||||
);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
if bind_mode {
|
||||
let user_id = current_user_id(session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await.ok();
|
||||
if let Err(e) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||
tracing::warn!(provider, error = %e, "failed to remove oauth_bind_mode from session after bind");
|
||||
}
|
||||
|
||||
let profile = OAuthProfile {
|
||||
provider: user_info.provider,
|
||||
@@ -328,11 +407,25 @@ where
|
||||
session
|
||||
.insert(SESSION_USER_ID, user.id.to_string())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(
|
||||
error = %e,
|
||||
user_id = %user.id,
|
||||
"failed to insert user_id into session after OAuth"
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
session
|
||||
.insert(SESSION_LOGIN_PROVIDER, &provider)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(
|
||||
provider,
|
||||
error = %e,
|
||||
"failed to insert login_provider into session after OAuth"
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
log_login(
|
||||
&state.pool,
|
||||
@@ -350,7 +443,9 @@ where
|
||||
// ── Logout ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async fn auth_logout(session: Session) -> impl IntoResponse {
|
||||
session.flush().await.ok();
|
||||
if let Err(e) = session.flush().await {
|
||||
tracing::warn!(error = %e, "failed to flush session on logout");
|
||||
}
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
||||
@@ -361,15 +456,15 @@ async fn dashboard(
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let Some(user_id) = current_user_id(&session).await else {
|
||||
return Ok(Redirect::to("/").into_response());
|
||||
return Ok(Redirect::to("/login").into_response());
|
||||
};
|
||||
|
||||
let user = match get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
{
|
||||
let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for dashboard");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})? {
|
||||
Some(u) => u,
|
||||
None => return Ok(Redirect::to("/").into_response()),
|
||||
None => return Ok(Redirect::to("/login").into_response()),
|
||||
};
|
||||
|
||||
let tmpl = DashboardTemplate {
|
||||
@@ -388,15 +483,15 @@ async fn audit_page(
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let Some(user_id) = current_user_id(&session).await else {
|
||||
return Ok(Redirect::to("/").into_response());
|
||||
return Ok(Redirect::to("/login").into_response());
|
||||
};
|
||||
|
||||
let user = match get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
{
|
||||
let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for audit page");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})? {
|
||||
Some(u) => u,
|
||||
None => return Ok(Redirect::to("/").into_response()),
|
||||
None => return Ok(Redirect::to("/login").into_response()),
|
||||
};
|
||||
|
||||
let rows = list_for_user(&state.pool, user_id, 100)
|
||||
@@ -439,7 +534,10 @@ async fn account_bind_google(
|
||||
session
|
||||
.insert(SESSION_OAUTH_BIND_MODE, true)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to insert oauth_bind_mode into session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let redirect_uri = format!("{}/account/bind/google/callback", state.base_url);
|
||||
let mut cfg = state
|
||||
@@ -448,7 +546,13 @@ async fn account_bind_google(
|
||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
cfg.redirect_uri = redirect_uri;
|
||||
let st = random_state();
|
||||
session.insert(SESSION_OAUTH_STATE, &st).await.ok();
|
||||
if let Err(e) = session.insert(SESSION_OAUTH_STATE, &st).await {
|
||||
tracing::error!(error = %e, "failed to insert oauth_state for account bind flow");
|
||||
if let Err(rm) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||
tracing::warn!(error = %rm, "failed to roll back oauth_bind_mode after oauth_state insert failure");
|
||||
}
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
Ok(Redirect::to(&google_auth_url(&cfg, &st)).into_response())
|
||||
}
|
||||
@@ -492,7 +596,10 @@ async fn account_unbind(
|
||||
let current_login_provider = session
|
||||
.get::<String>(SESSION_LOGIN_PROVIDER)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to read login_provider from session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
unbind_oauth_account(
|
||||
&state.pool,
|
||||
@@ -532,7 +639,10 @@ async fn api_key_salt(
|
||||
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for key-salt API");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
if user.key_salt.is_none() {
|
||||
@@ -576,10 +686,17 @@ async fn api_key_setup(
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let salt = hex::decode_hex(&body.salt).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let key_check = hex::decode_hex(&body.key_check).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let salt = hex::decode_hex(&body.salt).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-setup salt");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
let key_check = hex::decode_hex(&body.key_check).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-setup key_check");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
if salt.len() != 32 {
|
||||
tracing::warn!(salt_len = salt.len(), "key-setup salt must be 32 bytes");
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
@@ -608,9 +725,10 @@ async fn api_apikey_get(
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let api_key = ensure_api_key(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let api_key = ensure_api_key(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "ensure_api_key failed");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
Ok(Json(ApiKeyResponse { api_key }))
|
||||
}
|
||||
@@ -625,7 +743,10 @@ async fn api_apikey_regenerate(
|
||||
|
||||
let api_key = regenerate_api_key(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "regenerate_api_key failed");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
Ok(Json(ApiKeyResponse { api_key }))
|
||||
}
|
||||
|
||||
28
crates/secrets-mcp/static/llms.txt
Normal file
28
crates/secrets-mcp/static/llms.txt
Normal file
@@ -0,0 +1,28 @@
|
||||
# Secrets MCP
|
||||
|
||||
> 给 AI 与自动化工具的简要说明。本站是 **secrets-mcp**:Streamable HTTP **MCP**(Model Context Protocol)与 **Web 控制台** 的组合,用于在多租户场景下存储条目元数据与加密后的秘密字段;持久化在 PostgreSQL。用户通过 OAuth(如已配置)登录 Web;MCP 调用使用 API Key 与加密相关请求头。
|
||||
|
||||
## 公开页面
|
||||
|
||||
- **`/`**:公开首页,说明安全架构(客户端密钥派生、密文存储、多租户与审计等),无需登录。
|
||||
|
||||
## 不应抓取或索引的内容
|
||||
|
||||
- **`/mcp`**:MCP 流式 HTTP 端点(JSON-RPC 等),**不是** HTML 文档,也不适合作为公开知识库来源。
|
||||
- **`/api/*`**:会话或 API Key 相关的 HTTP API。
|
||||
- **`/login`**:登录入口页(`noindex` / robots 通常 disallow)。
|
||||
- **`/dashboard`、`/audit`、`/auth/*`、`/account/*`**:需浏览器会话,属于用户私有界面与 OAuth 流程。
|
||||
|
||||
## 给 AI 助手的实用提示
|
||||
|
||||
- 向用户说明连接方式时:MCP 基址为 `{BASE_URL}/mcp`(`BASE_URL` 由部署方设置),通常需要 `Authorization: Bearer <api_key>`;读写加密秘密时还需按部署文档传递 `X-Encryption-Key` 等头(与客户端模式有关)。
|
||||
- **不要编造**本实例的数据库 URL、OAuth 密钥、回调地址或任何凭据;一律以用户环境变量与运维文档为准。
|
||||
- Web 端在浏览器内用密码短语派生密钥完成端到端加密;MCP 路径下服务端可能在请求周期内临时使用客户端提供的密钥处理密文(架构细节见项目 README「加密架构」)。
|
||||
|
||||
## 延伸阅读
|
||||
|
||||
- 源码仓库:<https://gitea.refining.dev/refining/secrets>(`README.md`、`AGENTS.md` 含环境变量、表结构与运维约定)。
|
||||
|
||||
## 关于本文件
|
||||
|
||||
- 遵循常见的 **`/llms.txt`** 约定,便于人类与 LLM 快速了解站点性质与抓取边界;同文可在 **`/ai.txt`** 获取。
|
||||
31
crates/secrets-mcp/static/robots.txt
Normal file
31
crates/secrets-mcp/static/robots.txt
Normal file
@@ -0,0 +1,31 @@
|
||||
# Secrets MCP — robots.txt
|
||||
# 本站为需登录的私密控制台与 MCP API;以下路径请勿抓取,以免浪费配额并避免误索引敏感端点。
|
||||
# This host serves an authenticated dashboard and machine APIs; please skip crawling the paths below.
|
||||
|
||||
User-agent: *
|
||||
Disallow: /mcp
|
||||
Disallow: /api/
|
||||
Disallow: /dashboard
|
||||
Disallow: /audit
|
||||
Disallow: /auth/
|
||||
Disallow: /login
|
||||
Disallow: /account/
|
||||
|
||||
# 首页 `/` 为公开安全说明页,允许抓取。
|
||||
|
||||
# 面向 AI / LLM 的机器可读站点说明(Markdown):/llms.txt
|
||||
# Human & AI-readable site summary: /llms.txt (also /ai.txt)
|
||||
|
||||
User-agent: GPTBot
|
||||
User-agent: Google-Extended
|
||||
User-agent: anthropic-ai
|
||||
User-agent: Claude-Web
|
||||
User-agent: PerplexityBot
|
||||
User-agent: Bytespider
|
||||
Disallow: /mcp
|
||||
Disallow: /api/
|
||||
Disallow: /dashboard
|
||||
Disallow: /audit
|
||||
Disallow: /auth/
|
||||
Disallow: /login
|
||||
Disallow: /account/
|
||||
269
crates/secrets-mcp/templates/home.html
Normal file
269
crates/secrets-mcp/templates/home.html
Normal file
@@ -0,0 +1,269 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="description" content="Secrets MCP:基于 Model Context Protocol 的密钥与配置管理。密码短语在浏览器本地 PBKDF2 派生,密文 AES-GCM 存储,完整审计与历史版本。">
|
||||
<meta name="keywords" content="secrets management,MCP,Model Context Protocol,end-to-end encryption,AES-GCM,PBKDF2,API key,密钥管理">
|
||||
<meta name="robots" content="index, follow">
|
||||
<link rel="canonical" href="{{ base_url }}/">
|
||||
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||
<title>Secrets MCP — 端到端加密的密钥管理</title>
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="{{ base_url }}/">
|
||||
<meta property="og:title" content="Secrets MCP — 端到端加密的密钥管理">
|
||||
<meta property="og:description" content="密码短语客户端派生,密文存储;MCP API 与 Web 控制台,多租户与审计。">
|
||||
<meta name="twitter:card" content="summary">
|
||||
<meta name="twitter:title" content="Secrets MCP — 端到端加密的密钥管理">
|
||||
<meta name="twitter:description" content="密码短语客户端派生,密文存储;MCP API 与 Web 控制台,多租户与审计。">
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500;600&family=Inter:wght@400;500;600&display=swap');
|
||||
:root {
|
||||
--bg: #0d1117;
|
||||
--surface: #161b22;
|
||||
--surface2: #21262d;
|
||||
--border: #30363d;
|
||||
--text: #e6edf3;
|
||||
--text-muted: #8b949e;
|
||||
--accent: #58a6ff;
|
||||
--accent-hover: #79b8ff;
|
||||
}
|
||||
html, body { height: 100%; overflow: hidden; }
|
||||
@supports (height: 100dvh) {
|
||||
html, body { height: 100dvh; }
|
||||
}
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: 'Inter', sans-serif;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.nav {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 24px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
}
|
||||
.brand {
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
}
|
||||
.brand span { color: var(--accent); }
|
||||
.nav-right { display: flex; align-items: center; gap: 14px; }
|
||||
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; }
|
||||
.lang-btn {
|
||||
padding: 4px 10px; border: none; background: none; color: var(--text-muted);
|
||||
font-size: 12px; cursor: pointer; border-radius: 4px;
|
||||
}
|
||||
.lang-btn.active { background: var(--border); color: var(--text); }
|
||||
.cta {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
padding: 8px 18px; border-radius: 8px; font-size: 13px; font-weight: 600;
|
||||
text-decoration: none; border: 1px solid var(--accent);
|
||||
background: rgba(88, 166, 255, 0.12); color: var(--accent);
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.cta:hover { background: var(--accent); color: var(--bg); }
|
||||
.main {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 16px 24px 12px;
|
||||
gap: 20px;
|
||||
}
|
||||
.hero { text-align: center; max-width: 720px; }
|
||||
.hero h1 { font-size: clamp(20px, 4vw, 28px); font-weight: 600; margin-bottom: 8px; line-height: 1.25; }
|
||||
.hero .tagline { color: var(--text-muted); font-size: clamp(13px, 2vw, 15px); line-height: 1.5; }
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
max-width: 900px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.grid { grid-template-columns: repeat(2, 1fr); }
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
.grid { grid-template-columns: 1fr; gap: 8px; }
|
||||
.main { justify-content: flex-start; padding-top: 12px; }
|
||||
}
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 14px 14px 12px;
|
||||
min-height: 0;
|
||||
}
|
||||
.card-icon {
|
||||
width: 32px; height: 32px; border-radius: 8px;
|
||||
background: var(--surface2);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
margin-bottom: 10px; color: var(--accent);
|
||||
}
|
||||
.card-icon svg { width: 18px; height: 18px; }
|
||||
.card h2 { font-size: 13px; font-weight: 600; margin-bottom: 6px; line-height: 1.3; }
|
||||
.card p { font-size: 12px; color: var(--text-muted); line-height: 1.45; }
|
||||
.foot {
|
||||
flex-shrink: 0;
|
||||
text-align: center;
|
||||
padding: 8px 16px 12px;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
}
|
||||
.foot a { color: var(--accent); text-decoration: none; }
|
||||
.foot a:hover { text-decoration: underline; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="nav">
|
||||
<a class="brand" href="/">secrets<span>-mcp</span></a>
|
||||
<div class="nav-right">
|
||||
<div class="lang-bar">
|
||||
<button type="button" class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('en')">EN</button>
|
||||
</div>
|
||||
{% if is_logged_in %}
|
||||
<a class="cta" href="/dashboard" data-i18n="ctaDashboard">进入控制台</a>
|
||||
{% else %}
|
||||
<a class="cta" href="/login" data-i18n="ctaLogin">登录</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</header>
|
||||
<main class="main">
|
||||
<div class="hero">
|
||||
<h1 data-i18n="heroTitle">端到端加密的密钥与配置管理</h1>
|
||||
<p class="tagline" data-i18n="heroTagline">Streamable HTTP MCP 与 Web 控制台:元数据与密文分库存储,密钥永不离开你的客户端逻辑。</p>
|
||||
</div>
|
||||
<div class="grid">
|
||||
<article class="card">
|
||||
<div class="card-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 11c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v3c0 1.66 1.34 3 3 3z"/><path d="M19 10v1a7 7 0 01-14 0v-1"/><path d="M12 14v7M9 18h6"/></svg>
|
||||
</div>
|
||||
<h2 data-i18n="c1t">客户端密钥派生</h2>
|
||||
<p data-i18n="c1d">PBKDF2-SHA256(约 60 万次)在浏览器本地从密码短语派生密钥;服务端仅保存盐与校验值,不持有密码或明文主密钥。</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="card-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
|
||||
</div>
|
||||
<h2 data-i18n="c2t">AES-256-GCM 加密</h2>
|
||||
<p data-i18n="c2d">敏感字段以 AES-GCM 密文落库;Web 端在本地加解密,明文默认不经过服务端持久化。</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="card-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/></svg>
|
||||
</div>
|
||||
<h2 data-i18n="c3t">审计与历史</h2>
|
||||
<p data-i18n="c3d">操作写入审计日志;条目与密文保留历史版本,支持按版本查看与恢复。</p>
|
||||
</article>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="foot">
|
||||
<span data-i18n="versionLabel">版本</span> {{ version }} ·
|
||||
<a href="/llms.txt">llms.txt</a>
|
||||
<span data-i18n="sep"> · </span>
|
||||
<a href="https://gitea.refining.dev/refining/secrets" target="_blank" rel="noopener noreferrer" data-i18n="footRepo">源码仓库</a>
|
||||
{% if !is_logged_in %}
|
||||
<span data-i18n="sep"> · </span>
|
||||
<a href="/login" data-i18n="footLogin">登录</a>
|
||||
{% endif %}
|
||||
</footer>
|
||||
<script>
|
||||
const T = {
|
||||
'zh-CN': {
|
||||
docTitle: 'Secrets MCP — 端到端加密的密钥管理',
|
||||
ctaDashboard: '进入控制台',
|
||||
ctaLogin: '登录',
|
||||
heroTitle: '端到端加密的密钥与配置管理',
|
||||
heroTagline: 'Streamable HTTP MCP 与 Web 控制台:元数据与密文分库存储,密钥永不离开你的客户端逻辑。',
|
||||
c1t: '客户端密钥派生',
|
||||
c1d: 'PBKDF2-SHA256(约 60 万次)在浏览器本地从密码短语派生密钥;服务端仅保存盐与校验值,不持有密码或明文主密钥。',
|
||||
c2t: 'AES-256-GCM 加密',
|
||||
c2d: '敏感字段以 AES-GCM 密文落库;Web 端在本地加解密,明文默认不经过服务端持久化。',
|
||||
c3t: '审计与历史',
|
||||
c3d: '操作写入审计日志;条目与密文保留历史版本,支持按版本查看与恢复。',
|
||||
versionLabel: '版本',
|
||||
sep: ' · ',
|
||||
footRepo: '源码仓库',
|
||||
footLogin: '登录',
|
||||
},
|
||||
'zh-TW': {
|
||||
docTitle: 'Secrets MCP — 端到端加密的金鑰管理',
|
||||
ctaDashboard: '進入控制台',
|
||||
ctaLogin: '登入',
|
||||
heroTitle: '端到端加密的金鑰與設定管理',
|
||||
heroTagline: 'Streamable HTTP MCP 與 Web 控制台:中繼資料與密文分庫儲存,金鑰不離開你的用戶端邏輯。',
|
||||
c1t: '用戶端金鑰派生',
|
||||
c1d: 'PBKDF2-SHA256(約 60 萬次)在瀏覽器本地從密碼片語派生金鑰;伺服端僅保存鹽與校驗值,不持有密碼或明文主金鑰。',
|
||||
c2t: 'AES-256-GCM 加密',
|
||||
c2d: '敏感欄位以 AES-GCM 密文落庫;Web 端在本地加解密,明文預設不經伺服端持久化。',
|
||||
c3t: '稽核與歷史',
|
||||
c3d: '操作寫入稽核日誌;條目與密文保留歷史版本,支援依版本檢視與還原。',
|
||||
versionLabel: '版本',
|
||||
sep: ' · ',
|
||||
footRepo: '原始碼倉庫',
|
||||
footLogin: '登入',
|
||||
},
|
||||
'en': {
|
||||
docTitle: 'Secrets MCP — End-to-end encrypted secrets',
|
||||
ctaDashboard: 'Open dashboard',
|
||||
ctaLogin: 'Sign in',
|
||||
heroTitle: 'End-to-end encrypted secrets and configuration',
|
||||
heroTagline: 'Streamable HTTP MCP plus web console: metadata and ciphertext stored separately; keys stay on your client.',
|
||||
c1t: 'Client-side key derivation',
|
||||
c1d: 'PBKDF2-SHA256 (~600k iterations) derives keys from your passphrase in the browser; the server stores only salt and a verification blob, never your password or raw master key.',
|
||||
c2t: 'AES-256-GCM',
|
||||
c2d: 'Secret fields are stored as AES-GCM ciphertext; the web UI encrypts and decrypts locally so plaintext is not persisted server-side by default.',
|
||||
c3t: 'Audit and history',
|
||||
c3d: 'Operations are audited; entries and secrets keep version history for review and rollback.',
|
||||
versionLabel: 'Version',
|
||||
sep: ' · ',
|
||||
footRepo: 'Source repository',
|
||||
footLogin: 'Sign in',
|
||||
}
|
||||
};
|
||||
|
||||
let currentLang = localStorage.getItem('lang') || 'zh-CN';
|
||||
|
||||
function t(key) {
|
||||
return (T[currentLang] && T[currentLang][key]) || T['en'][key] || key;
|
||||
}
|
||||
|
||||
function applyLang() {
|
||||
document.documentElement.lang = currentLang;
|
||||
document.title = t('docTitle');
|
||||
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n');
|
||||
el.textContent = t(key);
|
||||
});
|
||||
document.querySelectorAll('.lang-btn').forEach(btn => {
|
||||
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
||||
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||
});
|
||||
}
|
||||
|
||||
function setLang(lang) {
|
||||
currentLang = lang;
|
||||
localStorage.setItem('lang', lang);
|
||||
applyLang();
|
||||
}
|
||||
|
||||
applyLang();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -3,8 +3,19 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="robots" content="noindex, follow">
|
||||
<meta name="description" content="登录 Secrets MCP Web 控制台,安全管理跨设备加密 secrets。">
|
||||
<meta name="keywords" content="Secrets MCP,登录,OAuth,密钥管理">
|
||||
<link rel="canonical" href="{{ base_url }}/login">
|
||||
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||
<title>Secrets — Sign In</title>
|
||||
<title>登录 — Secrets MCP</title>
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="{{ base_url }}/login">
|
||||
<meta property="og:title" content="登录 — Secrets MCP">
|
||||
<meta property="og:description" content="登录 Web 控制台,管理加密存储的密钥与配置。">
|
||||
<meta name="twitter:card" content="summary">
|
||||
<meta name="twitter:title" content="登录 — Secrets MCP">
|
||||
<meta name="twitter:description" content="登录 Web 控制台,管理加密存储的密钥与配置。">
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
|
||||
@@ -17,6 +28,7 @@
|
||||
--accent: #58a6ff;
|
||||
--accent-hover: #79b8ff;
|
||||
--google: #4285f4;
|
||||
--danger: #f85149;
|
||||
}
|
||||
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif;
|
||||
min-height: 100vh; display: flex; align-items: center; justify-content: center; }
|
||||
@@ -25,11 +37,24 @@
|
||||
padding: 48px 40px; width: 100%; max-width: 400px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
|
||||
}
|
||||
.topbar { display: flex; justify-content: flex-end; margin-bottom: 20px; }
|
||||
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; }
|
||||
.topbar { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px; gap: 12px; }
|
||||
.back-home {
|
||||
font-size: 13px; color: var(--accent); text-decoration: none; white-space: nowrap;
|
||||
}
|
||||
.back-home:hover { text-decoration: underline; }
|
||||
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; flex-shrink: 0; }
|
||||
.lang-btn { padding: 3px 9px; border: none; background: none; color: var(--text-muted);
|
||||
font-size: 12px; cursor: pointer; border-radius: 4px; }
|
||||
.lang-btn.active { background: var(--border); color: var(--text); }
|
||||
.oauth-alert {
|
||||
display: none;
|
||||
margin-bottom: 16px; padding: 10px 12px; border-radius: 8px;
|
||||
font-size: 13px; line-height: 1.4;
|
||||
background: rgba(248, 81, 73, 0.12);
|
||||
border: 1px solid rgba(248, 81, 73, 0.35);
|
||||
color: #ffa198;
|
||||
}
|
||||
.oauth-alert.visible { display: block; }
|
||||
h1 { font-size: 22px; font-weight: 600; margin-bottom: 8px; }
|
||||
.subtitle { color: var(--text-muted); font-size: 14px; margin-bottom: 32px; }
|
||||
.btn {
|
||||
@@ -48,12 +73,14 @@
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="topbar">
|
||||
<a class="back-home" href="/" data-i18n="backHome">返回首页</a>
|
||||
<div class="lang-bar">
|
||||
<button class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||
<button class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||
<button class="lang-btn" onclick="setLang('en')">EN</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('en')">EN</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="oauth-alert" class="oauth-alert" role="alert"></div>
|
||||
<h1 data-i18n="title">登录</h1>
|
||||
<p class="subtitle" data-i18n="subtitle">安全管理你的跨设备 secrets。</p>
|
||||
|
||||
@@ -78,22 +105,40 @@
|
||||
<script>
|
||||
const T = {
|
||||
'zh-CN': {
|
||||
docTitle: '登录 — Secrets MCP',
|
||||
backHome: '返回首页',
|
||||
title: '登录',
|
||||
subtitle: '安全管理你的跨设备 secrets。',
|
||||
google: '使用 Google 登录',
|
||||
noProviders: '未配置登录方式,请联系管理员。',
|
||||
err_oauth_error: '登录失败:授权提供方返回错误,请重试。',
|
||||
err_oauth_missing_code: '登录失败:未收到授权码,请重试。',
|
||||
err_oauth_missing_state: '登录失败:缺少安全校验参数,请重试。',
|
||||
err_oauth_state: '登录失败:会话校验不匹配(可能因 Cookie 策略或服务器重启)。请返回首页再试。',
|
||||
},
|
||||
'zh-TW': {
|
||||
docTitle: '登入 — Secrets MCP',
|
||||
backHome: '返回首頁',
|
||||
title: '登入',
|
||||
subtitle: '安全管理你的跨裝置 secrets。',
|
||||
google: '使用 Google 登入',
|
||||
noProviders: '尚未設定登入方式,請聯絡管理員。',
|
||||
err_oauth_error: '登入失敗:授權方回傳錯誤,請再試一次。',
|
||||
err_oauth_missing_code: '登入失敗:未取得授權碼,請再試一次。',
|
||||
err_oauth_missing_state: '登入失敗:缺少安全校驗參數,請再試一次。',
|
||||
err_oauth_state: '登入失敗:工作階段校驗不符(可能與 Cookie 政策或伺服器重啟有關)。請回到首頁再試。',
|
||||
},
|
||||
'en': {
|
||||
docTitle: 'Sign in — Secrets MCP',
|
||||
backHome: 'Back to home',
|
||||
title: 'Sign in',
|
||||
subtitle: 'Manage your cross-device secrets securely.',
|
||||
google: 'Continue with Google',
|
||||
noProviders: 'No login providers configured. Please contact your administrator.',
|
||||
err_oauth_error: 'Sign-in failed: the identity provider returned an error. Please try again.',
|
||||
err_oauth_missing_code: 'Sign-in failed: no authorization code was returned. Please try again.',
|
||||
err_oauth_missing_state: 'Sign-in failed: missing security state. Please try again.',
|
||||
err_oauth_state: 'Sign-in failed: session state mismatch (often cookies or server restart). Open the home page and try again.',
|
||||
}
|
||||
};
|
||||
|
||||
@@ -101,8 +146,23 @@
|
||||
|
||||
function t(key) { return T[currentLang][key] || T['en'][key] || key; }
|
||||
|
||||
function showOAuthError() {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const code = params.get('error');
|
||||
const el = document.getElementById('oauth-alert');
|
||||
if (!code || !code.startsWith('oauth_')) {
|
||||
el.classList.remove('visible');
|
||||
el.textContent = '';
|
||||
return;
|
||||
}
|
||||
const key = 'err_' + code;
|
||||
el.textContent = t(key) || t('err_oauth_error');
|
||||
el.classList.add('visible');
|
||||
}
|
||||
|
||||
function applyLang() {
|
||||
document.documentElement.lang = currentLang;
|
||||
document.title = t('docTitle');
|
||||
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n');
|
||||
el.textContent = t(key);
|
||||
@@ -111,6 +171,7 @@
|
||||
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
||||
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||
});
|
||||
showOAuthError();
|
||||
}
|
||||
|
||||
function setLang(lang) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# 复制此文件为 .env 并填写真实值
|
||||
|
||||
# ─── 数据库 ───────────────────────────────────────────────────────────
|
||||
# Web 会话(tower-sessions)与业务数据共用此库;启动时会自动 migrate 会话表,无需额外环境变量。
|
||||
SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@HOST:PORT/secrets-mcp
|
||||
|
||||
# ─── 服务地址 ─────────────────────────────────────────────────────────
|
||||
@@ -21,6 +22,9 @@ GOOGLE_CLIENT_SECRET=
|
||||
# WECHAT_APP_CLIENT_ID=
|
||||
# WECHAT_APP_CLIENT_SECRET=
|
||||
|
||||
# ─── 日志(可选)──────────────────────────────────────────────────────
|
||||
# RUST_LOG=secrets_mcp=debug
|
||||
|
||||
# ─── 注意 ─────────────────────────────────────────────────────────────
|
||||
# SERVER_MASTER_KEY 已不再需要。
|
||||
# 新架构(E2EE)中,加密密钥由用户密码短语在客户端本地派生,服务端不持有原始密钥。
|
||||
|
||||
22
scripts/cleanup-orphan-user-ids.sql
Normal file
22
scripts/cleanup-orphan-user-ids.sql
Normal file
@@ -0,0 +1,22 @@
|
||||
-- Run against prod BEFORE deploying secrets-mcp with FK migration.
|
||||
-- Requires: write access to SECRETS_DATABASE_URL.
|
||||
-- Example: psql "$SECRETS_DATABASE_URL" -v ON_ERROR_STOP=1 -f scripts/cleanup-orphan-user-ids.sql
|
||||
|
||||
BEGIN;
|
||||
|
||||
UPDATE entries
|
||||
SET user_id = NULL
|
||||
WHERE user_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = entries.user_id);
|
||||
|
||||
UPDATE entries_history
|
||||
SET user_id = NULL
|
||||
WHERE user_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = entries_history.user_id);
|
||||
|
||||
UPDATE audit_log
|
||||
SET user_id = NULL
|
||||
WHERE user_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = audit_log.user_id);
|
||||
|
||||
COMMIT;
|
||||
Reference in New Issue
Block a user