Compare commits
8 Commits
secrets-mc
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f86d12b80e | ||
|
|
43d6164a15 | ||
|
|
1b2fbdae4d | ||
|
|
ab1e3329b9 | ||
|
|
c3b1a0df1a | ||
|
|
d772066210 | ||
|
|
2c7dbf890b | ||
|
|
8c49316923 |
25
AGENTS.md
25
AGENTS.md
@@ -42,7 +42,7 @@ secrets/
|
||||
Cargo.toml
|
||||
crates/
|
||||
secrets-core/ # db / crypto / models / audit / service
|
||||
secrets-mcp/ # rmcp tools、axum、OAuth、Dashboard
|
||||
secrets-mcp/ # rmcp tools、axum、OAuth、Dashboard;CHANGELOG.md → /changelog
|
||||
scripts/
|
||||
release-check.sh
|
||||
setup-gitea-actions.sh
|
||||
@@ -113,6 +113,7 @@ users (
|
||||
key_check BYTEA, -- 派生密钥加密已知常量,用于验证密码短语
|
||||
key_params JSONB, -- 算法参数,如 {"alg":"pbkdf2-sha256","iterations":600000}
|
||||
api_key TEXT UNIQUE, -- MCP Bearer token,明文存储(设计决策,见下方说明)
|
||||
key_version BIGINT NOT NULL DEFAULT 0, -- 密码短语变更时递增,用于使其它设备会话失效
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
@@ -165,6 +166,28 @@ oauth_accounts (
|
||||
| `secrets.type` | 密钥类型(调用方提供,默认 `text`) | `text`, `password`, `key` |
|
||||
| `secrets.encrypted` | 密文 | AES-GCM |
|
||||
|
||||
### Web 变更记录(`/changelog`)
|
||||
|
||||
`crates/secrets-mcp/CHANGELOG.md` 在构建时嵌入,服务端以 **Markdown** 渲染为 HTML(`pulldown-cmark`)。**首页**(`/`)页脚与 **Dashboard**(`/dashboard`,MCP 配置页)页脚均提供「变更记录」链接;发版时随 `secrets-mcp` 版本更新该文件即可。
|
||||
|
||||
### Google OAuth 出站 HTTP
|
||||
|
||||
换 token(`POST https://oauth2.googleapis.com/token`)与拉取 userinfo 使用工作区 **`reqwest`**。根目录 `Cargo.toml` 中为 `reqwest` 启用了 **`system-proxy`**(因 `default-features = false` 须显式打开),以便在 **macOS / Windows** 上读取**系统代理**,避免「浏览器能上 Google、服务端换 token 超时」这类代理不一致。若仅提供端口代理、系统代理未生效,可设 **`HTTPS_PROXY` / `NO_PROXY`**,见 `deploy/.env.example`。
|
||||
|
||||
### Web JSON API 与会话
|
||||
|
||||
除页面路由使用的 `require_valid_user`(未登录或 `key_version` 与库不一致时重定向 `/login`)外,JSON API(`/api/...`)使用等价校验:会话中的 `key_version` 须与 `users.key_version` 一致,否则返回 **401** JSON,避免仅校验 `user_id` 时与页面行为不一致。
|
||||
|
||||
### Web 条目页表格列(`/entries`)
|
||||
|
||||
列表仅展示非敏感字段;**名称**与**操作**列为固定列(不可在「显示列」中关闭)。**文件夹**(对应 `entries.folder`)、类型、备注、标签、关联、密文等为**可选列**,由用户在「显示列」面板中勾选;可见性保存在浏览器 `localStorage`,键为 **`entries_col_vis`**。新增列会并入默认:若用户曾保存过旧版配置,缺失的列键会按当前默认补齐。**文件夹**列默认**显示**,便于在「全部」等跨 folder 视图下区分条目所属隔离空间。
|
||||
|
||||
筛选栏支持查询参数 **`tags`**(逗号分隔,多标签 **AND**,语义同 `SearchParams.tags` / `tags @> ARRAY[...]`);分页与 folder 标签计数与当前筛选一致。
|
||||
|
||||
### 导出 / 导入文件
|
||||
|
||||
JSON/TOML/YAML 导出可在每条目上包含 `secret_types`(secret 名 → `text` / `password` / `key` 等),导入时写回 `secrets.type`;**旧版导出无该字段**时导入仍成功,类型按 **`text`** 默认。
|
||||
|
||||
### 共享密钥(N:N 关联)
|
||||
|
||||
多个 entry 可共享同一 secret 字段,通过 `entry_secrets` 中间表关联。
|
||||
|
||||
87
Cargo.lock
generated
87
Cargo.lock
generated
@@ -356,6 +356,16 @@ dependencies = [
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
@@ -740,6 +750,15 @@ dependencies = [
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getopts"
|
||||
version = "0.2.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
|
||||
dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
@@ -1016,9 +1035,11 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"system-configuration",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1578,6 +1599,25 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark"
|
||||
version = "0.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c3a14896dfa883796f1cb410461aef38810ea05f2b2c33c5aded3649095fdad"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"getopts",
|
||||
"memchr",
|
||||
"pulldown-cmark-escape",
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark-escape"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
|
||||
|
||||
[[package]]
|
||||
name = "quanta"
|
||||
version = "0.12.6"
|
||||
@@ -2065,7 +2105,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "secrets-mcp"
|
||||
version = "0.5.18"
|
||||
version = "0.5.27"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
@@ -2075,6 +2115,7 @@ dependencies = [
|
||||
"dotenvy",
|
||||
"governor",
|
||||
"http",
|
||||
"pulldown-cmark",
|
||||
"rand 0.10.0",
|
||||
"reqwest",
|
||||
"rmcp",
|
||||
@@ -2582,6 +2623,27 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-configuration"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"core-foundation",
|
||||
"system-configuration-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-configuration-sys"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -2985,6 +3047,12 @@ version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.18"
|
||||
@@ -3012,6 +3080,12 @@ version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.6"
|
||||
@@ -3337,6 +3411,17 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-registry"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
|
||||
@@ -36,4 +36,5 @@ tracing-subscriber = { version = "^0.3", features = ["env-filter"] }
|
||||
dotenvy = "^0.15"
|
||||
|
||||
# HTTP
|
||||
reqwest = { version = "^0.12", default-features = false, features = ["rustls-tls", "json"] }
|
||||
# system-proxy:与浏览器一致,读取 macOS/Windows 系统代理(禁用 default 后须显式开启,否则 OAuth 出站不走 Clash 等)
|
||||
reqwest = { version = "^0.12", default-features = false, features = ["rustls-tls", "json", "system-proxy"] }
|
||||
|
||||
11
README.md
11
README.md
@@ -23,7 +23,8 @@ cargo build --release -p secrets-mcp
|
||||
| `SECRETS_ENV` | 可选。设为 `prod` / `production` 时会拒绝弱 PostgreSQL TLS 模式(`prefer`、`disable`、`allow`、`require`)。 |
|
||||
| `BASE_URL` | 对外访问基址;OAuth 回调为 `{BASE_URL}/auth/google/callback`。默认 `http://localhost: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、勿打入二进制。 |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;不配置则无 Google 登录入口。运行时从环境读取,勿写入 CI、勿打入二进制。换 token 须访问 `oauth2.googleapis.com`:工作区 **`reqwest` 已启用 `system-proxy`**,与浏览器一致可走 macOS/Windows **系统代理**(如 Clash 系统代理模式)。 |
|
||||
| `HTTPS_PROXY` / `NO_PROXY` | 可选。仅当系统代理未被进程识别、又需走本地端口代理时设置;示例见 [`deploy/.env.example`](deploy/.env.example)。 |
|
||||
| `RUST_LOG` | 可选;日志级别,如 `secrets_mcp=debug`。 |
|
||||
| `SECRETS_DATABASE_POOL_SIZE` | 可选。连接池最大连接数,默认 `10`。 |
|
||||
| `SECRETS_DATABASE_ACQUIRE_TIMEOUT` | 可选。获取连接超时秒数,默认 `5`。 |
|
||||
@@ -46,7 +47,7 @@ SECRETS_DATABASE_SSL_ROOT_CERT=/etc/secrets/pg-ca.crt
|
||||
SECRETS_ENV=production
|
||||
```
|
||||
|
||||
- **Web**:`BASE_URL`(登录、Dashboard、设置密码短语、创建 API Key)。
|
||||
- **Web**:`BASE_URL`(登录、Dashboard、设置密码短语、创建 API Key)。**变更记录**页 **`/changelog`**:内容来自 `crates/secrets-mcp/CHANGELOG.md`(构建时嵌入并以 Markdown 渲染);首页页脚与 Dashboard(MCP)页脚均提供入口。**条目**页 `/entries` 支持 folder 标签与条件筛选(含 **`tags`** 逗号分隔、多标签同时匹配);表格列可在「显示列」中开关(名称与操作固定),**文件夹**列为可选列且默认显示。列可见性持久化见 [AGENTS.md](AGENTS.md)「Web 条目页表格列」。
|
||||
- **MCP**:Streamable HTTP 基址 `{BASE_URL}/mcp`,需 `Authorization: Bearer <api_key>` + `X-Encryption-Key: <hex>` 请求头(读密文工具须带密钥)。
|
||||
|
||||
## PostgreSQL TLS 加固
|
||||
@@ -72,9 +73,9 @@ SECRETS_ENV=production
|
||||
| `secrets_update` | 是 | 更新条目,支持 `id` 或 `name`+`folder` 定位 |
|
||||
| `secrets_delete` | 否 | 删除条目,支持 `id` 或 `name`+`folder` 定位;`dry_run=true` 预览删除 |
|
||||
| `secrets_history` | 否 | 查看条目历史,支持 `id` 或 `name`+`folder` 定位 |
|
||||
| `secrets_rollback` | 是 | 回滚条目到指定历史版本,支持 `id` 或 `name`+`folder` 定位 |
|
||||
| `secrets_rollback` | 否 | 回滚条目到指定历史版本(服务端按历史快照恢复元数据与密文关联),支持 `id`;仅需 **Bearer**,不要求 `X-Encryption-Key` |
|
||||
| `secrets_export` | 是 | 导出条目(含解密明文),支持 JSON/TOML/YAML 格式 |
|
||||
| `secrets_env_map` | 是 | 将 secrets 转换为环境变量映射(`UPPER(entry)_UPPER(field)` 格式),支持 `prefix` |
|
||||
| `secrets_env_map` | 是 | 将 secrets 转为环境变量映射:`PREFIX_ENTRYNAME_FIELDNAME`(字段名中 `.`→`__`、`-`→`_` 再转大写,避免与纯下划线字段名碰撞),支持 `prefix` |
|
||||
| `secrets_overview` | 否 | 返回各 folder 和 type 的 entry 计数概览 |
|
||||
|
||||
### 消歧规则
|
||||
@@ -226,7 +227,7 @@ crates/secrets-core/ # db / crypto / models / audit / service
|
||||
src/
|
||||
taxonomy.rs # SECRET_TYPE_OPTIONS(secret 字段类型下拉选项)
|
||||
service/ # 业务逻辑(add, search, update, delete, export, env_map 等)
|
||||
crates/secrets-mcp/ # MCP HTTP、Web、OAuth、API Key
|
||||
crates/secrets-mcp/ # MCP HTTP、Web、OAuth、API Key;CHANGELOG.md 嵌入 /changelog
|
||||
scripts/
|
||||
release-check.sh # 发版前 fmt / clippy / test
|
||||
setup-gitea-actions.sh
|
||||
|
||||
@@ -184,6 +184,9 @@ pub struct ExportEntry {
|
||||
/// Decrypted secret fields. None means no secrets in this export (--no-secrets).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub secrets: Option<BTreeMap<String, Value>>,
|
||||
/// Per-secret types (`text`, `password`, `key`, …). Omitted in legacy exports; importers default to `"text"`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub secret_types: Option<BTreeMap<String, String>>,
|
||||
}
|
||||
|
||||
// ── Multi-user models ──────────────────────────────────────────────────────────
|
||||
@@ -311,3 +314,44 @@ pub fn toml_to_json_value(v: &toml::Value) -> Value {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod export_entry_tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn export_entry_roundtrip_includes_secret_types() {
|
||||
let mut secrets = BTreeMap::new();
|
||||
secrets.insert("k".to_string(), serde_json::json!("v"));
|
||||
let mut types = BTreeMap::new();
|
||||
types.insert("k".to_string(), "password".to_string());
|
||||
let e = ExportEntry {
|
||||
name: "n".to_string(),
|
||||
folder: "f".to_string(),
|
||||
entry_type: "t".to_string(),
|
||||
notes: "".to_string(),
|
||||
tags: vec![],
|
||||
metadata: serde_json::json!({}),
|
||||
secrets: Some(secrets),
|
||||
secret_types: Some(types),
|
||||
};
|
||||
let json = serde_json::to_string(&e).unwrap();
|
||||
let back: ExportEntry = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(
|
||||
back.secret_types
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.get("k")
|
||||
.map(String::as_str),
|
||||
Some("password")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_entry_legacy_json_without_secret_types_deserializes() {
|
||||
let json = r#"{"name":"a","folder":"","type":"","notes":"","tags":[],"metadata":{},"secrets":{"x":"y"}}"#;
|
||||
let e: ExportEntry = serde_json::from_str(json).unwrap();
|
||||
assert!(e.secret_types.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +161,7 @@ pub fn flatten_json_fields(prefix: &str, value: &Value) -> Vec<(String, Value)>
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct AddResult {
|
||||
pub entry_id: Uuid,
|
||||
pub name: String,
|
||||
pub folder: String,
|
||||
#[serde(rename = "type")]
|
||||
@@ -477,6 +478,7 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(AddResult {
|
||||
entry_id,
|
||||
name: params.name.to_string(),
|
||||
folder: params.folder.to_string(),
|
||||
entry_type: entry_type.to_string(),
|
||||
|
||||
@@ -47,11 +47,14 @@ pub async fn ensure_api_key(pool: &PgPool, user_id: Uuid) -> Result<String> {
|
||||
/// Generate a fresh API key for the user, replacing the old one.
|
||||
pub async fn regenerate_api_key(pool: &PgPool, user_id: Uuid) -> Result<String> {
|
||||
let new_key = generate_api_key();
|
||||
sqlx::query("UPDATE users SET api_key = $1 WHERE id = $2")
|
||||
let res = sqlx::query("UPDATE users SET api_key = $1 WHERE id = $2")
|
||||
.bind(&new_key)
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
if res.rows_affected() == 0 {
|
||||
return Err(AppError::NotFoundUser.into());
|
||||
}
|
||||
Ok(new_key)
|
||||
}
|
||||
|
||||
@@ -63,3 +66,30 @@ pub async fn validate_api_key(pool: &PgPool, raw_key: &str) -> Result<Option<Uui
|
||||
.await?;
|
||||
Ok(row.map(|(id,)| id))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use sqlx::PgPool;
|
||||
|
||||
use super::regenerate_api_key;
|
||||
use crate::error::AppError;
|
||||
|
||||
#[tokio::test]
|
||||
async fn regenerate_api_key_unknown_user_returns_not_found() {
|
||||
let Ok(url) = std::env::var("SECRETS_DATABASE_URL") else {
|
||||
return;
|
||||
};
|
||||
let Ok(pool) = PgPool::connect(&url).await else {
|
||||
return;
|
||||
};
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let err = regenerate_api_key(&pool, id)
|
||||
.await
|
||||
.err()
|
||||
.expect("expected error");
|
||||
assert!(matches!(
|
||||
err.downcast_ref::<AppError>(),
|
||||
Some(AppError::NotFoundUser)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,18 +45,27 @@ pub async fn build_env_map(
|
||||
|
||||
for f in fields {
|
||||
let decrypted = crypto::decrypt_json(master_key, &f.encrypted)?;
|
||||
let key = format!(
|
||||
"{}_{}",
|
||||
effective_prefix,
|
||||
f.name.to_uppercase().replace(['-', '.'], "_")
|
||||
);
|
||||
combined.insert(key, json_to_env_string(&decrypted));
|
||||
let seg = secret_name_to_env_segment(&f.name);
|
||||
let key = format!("{}_{}", effective_prefix, seg);
|
||||
if let Some(_old) = combined.insert(key.clone(), json_to_env_string(&decrypted)) {
|
||||
anyhow::bail!(
|
||||
"environment variable name collision after normalization: '{}' (secret '{}')",
|
||||
key,
|
||||
f.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(combined)
|
||||
}
|
||||
|
||||
/// Map a secret field name to an env key segment: `.` → `__`, `-` → `_`, then uppercase.
|
||||
/// Avoids collisions between e.g. `db.password` and `db_password`.
|
||||
fn secret_name_to_env_segment(name: &str) -> String {
|
||||
name.replace('.', "__").replace('-', "_").to_uppercase()
|
||||
}
|
||||
|
||||
fn env_prefix(entry: &crate::models::Entry, prefix: &str) -> String {
|
||||
let name_part = entry.name.to_uppercase().replace(['-', '.', ' '], "_");
|
||||
if prefix.is_empty() {
|
||||
@@ -75,3 +84,39 @@ fn json_to_env_string(v: &Value) -> String {
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{env_prefix, secret_name_to_env_segment};
|
||||
use crate::models::Entry;
|
||||
|
||||
#[test]
|
||||
fn secret_name_env_segment_disambiguates_dot_from_underscore() {
|
||||
assert_eq!(secret_name_to_env_segment("db.password"), "DB__PASSWORD");
|
||||
assert_eq!(secret_name_to_env_segment("db_password"), "DB_PASSWORD");
|
||||
assert_eq!(secret_name_to_env_segment("api-key"), "API_KEY");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_prefix_with_and_without_prefix() {
|
||||
let entry = Entry {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
user_id: None,
|
||||
folder: "test".into(),
|
||||
entry_type: "server".into(),
|
||||
name: "my-server".into(),
|
||||
notes: String::new(),
|
||||
tags: vec![],
|
||||
metadata: Value::Null,
|
||||
version: 1,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
deleted_at: None,
|
||||
};
|
||||
assert_eq!(env_prefix(&entry, ""), "MY_SERVER");
|
||||
assert_eq!(env_prefix(&entry, "ALIYUN"), "ALIYUN_MY_SERVER");
|
||||
assert_eq!(env_prefix(&entry, "aliyun_"), "ALIYUN_MY_SERVER");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,21 +44,23 @@ pub async fn export(
|
||||
|
||||
let mut export_entries: Vec<ExportEntry> = Vec::with_capacity(entries.len());
|
||||
for entry in &entries {
|
||||
let secrets = if params.no_secrets {
|
||||
None
|
||||
let (secrets, secret_types) = if params.no_secrets {
|
||||
(None, None)
|
||||
} else {
|
||||
let fields = secrets_map.get(&entry.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
if fields.is_empty() {
|
||||
Some(BTreeMap::new())
|
||||
(Some(BTreeMap::new()), Some(BTreeMap::new()))
|
||||
} else {
|
||||
let mk = master_key
|
||||
.ok_or_else(|| anyhow::anyhow!("master key required to decrypt secrets"))?;
|
||||
let mut map = BTreeMap::new();
|
||||
let mut type_map = BTreeMap::new();
|
||||
for f in fields {
|
||||
let decrypted = crypto::decrypt_json(mk, &f.encrypted)?;
|
||||
map.insert(f.name.clone(), decrypted);
|
||||
type_map.insert(f.name.clone(), f.secret_type.clone());
|
||||
}
|
||||
Some(map)
|
||||
(Some(map), Some(type_map))
|
||||
}
|
||||
};
|
||||
|
||||
@@ -70,6 +72,7 @@ pub async fn export(
|
||||
tags: entry.tags.clone(),
|
||||
metadata: entry.metadata.clone(),
|
||||
secrets,
|
||||
secret_types,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use anyhow::Result;
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::ExportFormat;
|
||||
@@ -80,6 +81,11 @@ pub async fn run(
|
||||
|
||||
let secret_entries = build_secret_entries(entry.secrets.as_ref());
|
||||
let meta_entries = build_meta_entries(&entry.metadata);
|
||||
let secret_types_map: HashMap<String, String> = entry
|
||||
.secret_types
|
||||
.as_ref()
|
||||
.map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
match add_run(
|
||||
pool,
|
||||
@@ -91,7 +97,7 @@ pub async fn run(
|
||||
tags: &entry.tags,
|
||||
meta_entries: &meta_entries,
|
||||
secret_entries: &secret_entries,
|
||||
secret_types: &Default::default(),
|
||||
secret_types: &secret_types_map,
|
||||
link_secret_names: &[],
|
||||
user_id: params.user_id,
|
||||
},
|
||||
@@ -125,3 +131,50 @@ pub async fn run(
|
||||
dry_run: params.dry_run,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use crate::models::ExportEntry;
|
||||
|
||||
/// Mirrors the map built in `run` before `AddParams` (legacy files omit `secret_types`).
|
||||
fn secret_types_for_add(entry: &ExportEntry) -> HashMap<String, String> {
|
||||
entry
|
||||
.secret_types
|
||||
.as_ref()
|
||||
.map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_types_three_kinds_round_trip_for_add_params() {
|
||||
let mut types = BTreeMap::new();
|
||||
types.insert("p".into(), "password".into());
|
||||
types.insert("k".into(), "key".into());
|
||||
types.insert("t".into(), "text".into());
|
||||
let entry = ExportEntry {
|
||||
name: "n".into(),
|
||||
folder: "f".into(),
|
||||
entry_type: "ty".into(),
|
||||
notes: "".into(),
|
||||
tags: vec![],
|
||||
metadata: serde_json::json!({}),
|
||||
secrets: Some(BTreeMap::new()),
|
||||
secret_types: Some(types),
|
||||
};
|
||||
let m = secret_types_for_add(&entry);
|
||||
assert_eq!(m.get("p").map(String::as_str), Some("password"));
|
||||
assert_eq!(m.get("k").map(String::as_str), Some("key"));
|
||||
assert_eq!(m.get("t").map(String::as_str), Some("text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_types_absent_defaults_to_empty_map_like_legacy_export() {
|
||||
let json =
|
||||
r#"{"name":"a","folder":"","type":"","notes":"","tags":[],"metadata":{},"secrets":{}}"#;
|
||||
let entry: ExportEntry = serde_json::from_str(json).unwrap();
|
||||
assert!(entry.secret_types.is_none());
|
||||
assert!(secret_types_for_add(&entry).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,58 +30,61 @@ pub async fn run(
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
name: String,
|
||||
version: i64,
|
||||
action: String,
|
||||
tags: Vec<String>,
|
||||
metadata: Value,
|
||||
}
|
||||
|
||||
let live_entry: Option<EntryWriteRow> = if let Some(uid) = user_id {
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let live: Option<EntryWriteRow> = if let Some(uid) = user_id {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, folder, type, name, tags, metadata, notes, deleted_at FROM entries \
|
||||
WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL",
|
||||
WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL FOR UPDATE",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(uid)
|
||||
.fetch_optional(pool)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, folder, type, name, tags, metadata, notes, deleted_at FROM entries \
|
||||
WHERE id = $1 AND user_id IS NULL AND deleted_at IS NULL",
|
||||
WHERE id = $1 AND user_id IS NULL AND deleted_at IS NULL FOR UPDATE",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_optional(pool)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
let live_entry = live_entry.ok_or(AppError::NotFoundEntry)?;
|
||||
let lr = live.ok_or(AppError::NotFoundEntry)?;
|
||||
|
||||
let snap: Option<EntryHistoryRow> = if let Some(ver) = to_version {
|
||||
sqlx::query_as(
|
||||
"SELECT folder, type, version, action, tags, metadata \
|
||||
"SELECT folder, type, name, version, action, tags, metadata \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 AND version = $2 ORDER BY id ASC LIMIT 1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(ver)
|
||||
.fetch_optional(pool)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT folder, type, version, action, tags, metadata \
|
||||
"SELECT folder, type, name, version, action, tags, metadata \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 ORDER BY id DESC LIMIT 1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_optional(pool)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
let snap = snap.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"No history found for entry '{}'{}.",
|
||||
live_entry.name,
|
||||
lr.name,
|
||||
to_version
|
||||
.map(|v| format!(" at version {}", v))
|
||||
.unwrap_or_default()
|
||||
@@ -91,17 +94,7 @@ pub async fn run(
|
||||
let snap_secret_snapshot = db::entry_secret_snapshot_from_metadata(&snap.metadata);
|
||||
let snap_metadata = db::strip_secret_snapshot_from_metadata(&snap.metadata);
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let live: Option<EntryWriteRow> = sqlx::query_as(
|
||||
"SELECT id, version, folder, type, name, tags, metadata, notes, deleted_at FROM entries \
|
||||
WHERE id = $1 AND deleted_at IS NULL FOR UPDATE",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let live_entry_id = if let Some(ref lr) = live {
|
||||
let live_entry_id = {
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, lr.id, &lr.metadata).await {
|
||||
Ok(v) => v,
|
||||
@@ -168,8 +161,8 @@ pub async fn run(
|
||||
)
|
||||
.bind(&snap.folder)
|
||||
.bind(&snap.entry_type)
|
||||
.bind(&live_entry.name)
|
||||
.bind(&live_entry.notes)
|
||||
.bind(&snap.name)
|
||||
.bind(&lr.notes)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap_metadata)
|
||||
.bind(lr.id)
|
||||
@@ -177,8 +170,6 @@ pub async fn run(
|
||||
.await?;
|
||||
|
||||
lr.id
|
||||
} else {
|
||||
return Err(AppError::NotFoundEntry.into());
|
||||
};
|
||||
|
||||
if let Some(secret_snapshot) = snap_secret_snapshot {
|
||||
@@ -191,7 +182,7 @@ pub async fn run(
|
||||
"rollback",
|
||||
&snap.folder,
|
||||
&snap.entry_type,
|
||||
&live_entry.name,
|
||||
&snap.name,
|
||||
serde_json::json!({
|
||||
"entry_id": entry_id,
|
||||
"restored_version": snap.version,
|
||||
@@ -203,7 +194,7 @@ pub async fn run(
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(RollbackResult {
|
||||
name: live_entry.name,
|
||||
name: snap.name,
|
||||
folder: snap.folder,
|
||||
entry_type: snap.entry_type,
|
||||
restored_version: snap.version,
|
||||
|
||||
38
crates/secrets-mcp/CHANGELOG.md
Normal file
38
crates/secrets-mcp/CHANGELOG.md
Normal file
@@ -0,0 +1,38 @@
|
||||
本文档在构建时嵌入 Web 的 `/changelog` 页面,并由服务端渲染为 HTML。
|
||||
|
||||
## [0.5.27] - 2026-04-11
|
||||
|
||||
### Added
|
||||
|
||||
- Web **`/entries`**:按 **tags** 筛选(逗号分隔、trim、多标签 **AND** 语义,与 `SearchParams` / MCP 一致);folder 标签计数、分页与筛选栏状态同步保留 `tags`。
|
||||
|
||||
## [0.5.26] - 2026-04-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Google OAuth**:工作区 `reqwest` 此前关闭默认特性且未启用 **`system-proxy`**,进程不读取 macOS/Windows 系统代理,易出现与浏览器不一致(本机可上 Google 但换 token 超时)。已显式启用 `system-proxy`。
|
||||
|
||||
## [0.5.25] - 2026-04-11
|
||||
|
||||
### Changed
|
||||
|
||||
- Google OAuth:token / userinfo 请求单独 **45s** 超时(避免仅触达默认客户端 15s);失败时区分超时、连接错误,并在非 2xx 时记录/返回 Google 响应体片段(如 `invalid_grant`、`redirect_uri_mismatch`)。
|
||||
|
||||
## [0.5.24] - 2026-04-11
|
||||
|
||||
### Changed
|
||||
|
||||
- 首页页脚将原「登录」入口改为「变更记录」(`/changelog`);顶部导航仍保留登录 / 进入控制台。
|
||||
|
||||
## [0.5.23] - 2026-04-11
|
||||
|
||||
### Added
|
||||
|
||||
- Changelog 页使用 **Markdown** 渲染(`pulldown-cmark`:表格、~~删除线~~、任务列表等)。
|
||||
|
||||
## [0.5.22] - 2026-04-11
|
||||
|
||||
### Added
|
||||
|
||||
- Dashboard(MCP)页脚版本旁增加「变更记录」链接,打开本变更说明页。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "secrets-mcp"
|
||||
version = "0.5.18"
|
||||
version = "0.5.27"
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
@@ -45,3 +45,4 @@ urlencoding = "2"
|
||||
schemars = "1"
|
||||
http = "1"
|
||||
url = "2"
|
||||
pulldown-cmark = "0.13.3"
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{OAuthConfig, OAuthUserInfo};
|
||||
|
||||
/// OAuth token / userinfo calls can be slow on poor routes; keep above client default if needed.
|
||||
const OAUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(45);
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TokenResponse {
|
||||
access_token: String,
|
||||
@@ -20,14 +25,28 @@ struct UserInfo {
|
||||
picture: Option<String>,
|
||||
}
|
||||
|
||||
fn map_reqwest_send_err(e: reqwest::Error) -> anyhow::Error {
|
||||
if e.is_timeout() {
|
||||
anyhow::anyhow!(
|
||||
"timeout reaching Google OAuth ({}s); ensure outbound HTTPS to oauth2.googleapis.com works (firewall/proxy/VPN if Google is unreachable)",
|
||||
OAUTH_HTTP_TIMEOUT.as_secs()
|
||||
)
|
||||
} else if e.is_connect() {
|
||||
anyhow::anyhow!("connection error to Google OAuth: {e}")
|
||||
} else {
|
||||
anyhow::Error::new(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Exchange authorization code for tokens and fetch user profile.
|
||||
pub async fn exchange_code(
|
||||
client: &reqwest::Client,
|
||||
config: &OAuthConfig,
|
||||
code: &str,
|
||||
) -> Result<OAuthUserInfo> {
|
||||
let token_resp: TokenResponse = client
|
||||
let token_http = client
|
||||
.post("https://oauth2.googleapis.com/token")
|
||||
.timeout(OAUTH_HTTP_TIMEOUT)
|
||||
.form(&[
|
||||
("code", code),
|
||||
("client_id", &config.client_id),
|
||||
@@ -37,24 +56,55 @@ pub async fn exchange_code(
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.context("failed to exchange Google code")?
|
||||
.error_for_status()
|
||||
.context("Google token endpoint error")?
|
||||
.json()
|
||||
.await
|
||||
.context("failed to parse Google token response")?;
|
||||
.map_err(map_reqwest_send_err)
|
||||
.context("Google token HTTP request failed")?;
|
||||
|
||||
let user: UserInfo = client
|
||||
let status = token_http.status();
|
||||
let body_bytes = token_http
|
||||
.bytes()
|
||||
.await
|
||||
.context("read Google token response body")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let body_lossy = String::from_utf8_lossy(&body_bytes);
|
||||
tracing::warn!(%status, body = %body_lossy, "Google token endpoint error");
|
||||
anyhow::bail!(
|
||||
"Google token error {}: {}",
|
||||
status,
|
||||
body_lossy.chars().take(512).collect::<String>()
|
||||
);
|
||||
}
|
||||
|
||||
let token_resp: TokenResponse =
|
||||
serde_json::from_slice(&body_bytes).context("failed to parse Google token JSON")?;
|
||||
|
||||
let user_http = client
|
||||
.get("https://openidconnect.googleapis.com/v1/userinfo")
|
||||
.timeout(OAUTH_HTTP_TIMEOUT)
|
||||
.bearer_auth(&token_resp.access_token)
|
||||
.send()
|
||||
.await
|
||||
.context("failed to fetch Google userinfo")?
|
||||
.error_for_status()
|
||||
.context("Google userinfo endpoint error")?
|
||||
.json()
|
||||
.map_err(map_reqwest_send_err)
|
||||
.context("Google userinfo HTTP request failed")?;
|
||||
|
||||
let status = user_http.status();
|
||||
let body_bytes = user_http
|
||||
.bytes()
|
||||
.await
|
||||
.context("failed to parse Google userinfo")?;
|
||||
.context("read Google userinfo body")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let body_lossy = String::from_utf8_lossy(&body_bytes);
|
||||
tracing::warn!(%status, body = %body_lossy, "Google userinfo endpoint error");
|
||||
anyhow::bail!(
|
||||
"Google userinfo error {}: {}",
|
||||
status,
|
||||
body_lossy.chars().take(512).collect::<String>()
|
||||
);
|
||||
}
|
||||
|
||||
let user: UserInfo =
|
||||
serde_json::from_slice(&body_bytes).context("failed to parse Google userinfo JSON")?;
|
||||
|
||||
Ok(OAuthUserInfo {
|
||||
provider: "google".to_string(),
|
||||
|
||||
@@ -345,15 +345,6 @@ impl SecretsService {
|
||||
Self::extract_enc_key(ctx)
|
||||
}
|
||||
|
||||
/// Require both user_id and encryption key (header only, no arg fallback).
|
||||
fn require_user_and_key(
|
||||
ctx: &RequestContext<RoleServer>,
|
||||
) -> Result<(Uuid, [u8; 32]), rmcp::ErrorData> {
|
||||
let user_id = Self::require_user_id(ctx)?;
|
||||
let key = Self::extract_enc_key(ctx)?;
|
||||
Ok((user_id, key))
|
||||
}
|
||||
|
||||
/// Require both user_id and encryption key, preferring an explicit argument
|
||||
/// value over the X-Encryption-Key header.
|
||||
fn require_user_and_key_or_arg(
|
||||
@@ -801,10 +792,7 @@ impl SecretsService {
|
||||
|
||||
let total_count = secrets_core::service::search::count_entries(&self.pool, &count_params)
|
||||
.await
|
||||
.inspect_err(
|
||||
|e| tracing::warn!(tool = "secrets_find", error = %e, "count_entries failed"),
|
||||
)
|
||||
.unwrap_or(0);
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_find", Some(user_id), e))?;
|
||||
let relation_map = get_relations_for_entries(
|
||||
&self.pool,
|
||||
&result
|
||||
@@ -1135,11 +1123,8 @@ impl SecretsService {
|
||||
.await
|
||||
.map_err(|e| mcp_err_from_anyhow("secrets_add", Some(user_id), e))?;
|
||||
|
||||
let created_entry = resolve_entry(&self.pool, &input.name, Some(folder), Some(user_id))
|
||||
.await
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_add", Some(user_id), e))?;
|
||||
for parent_id in parent_ids {
|
||||
add_parent_relation(&self.pool, parent_id, created_entry.id, Some(user_id))
|
||||
add_parent_relation(&self.pool, parent_id, result.entry_id, Some(user_id))
|
||||
.await
|
||||
.map_err(|e| mcp_err_from_anyhow("secrets_add", Some(user_id), e))?;
|
||||
}
|
||||
@@ -1420,7 +1405,7 @@ impl SecretsService {
|
||||
}
|
||||
|
||||
#[tool(
|
||||
description = "Rollback an entry to a previous version. Requires X-Encryption-Key header. \
|
||||
description = "Rollback an entry to a previous version. Requires Bearer API key only (no encryption key). \
|
||||
Omit to_version to restore the most recent snapshot. \
|
||||
Optionally pass 'id' (from secrets_find) to target directly.",
|
||||
annotations(title = "Rollback Secret Entry", destructive_hint = true)
|
||||
@@ -1431,7 +1416,7 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let (user_id, _user_key) = Self::require_user_and_key(&ctx)?;
|
||||
let user_id = Self::require_user_id(&ctx)?;
|
||||
tracing::info!(
|
||||
tool = "secrets_rollback",
|
||||
?user_id,
|
||||
|
||||
@@ -11,7 +11,7 @@ use secrets_core::service::{
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
use super::{SESSION_KEY_VERSION, current_user_id, render_template, require_valid_user};
|
||||
use super::{SESSION_KEY_VERSION, load_session_user_strict, render_template, require_valid_user};
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "dashboard.html")]
|
||||
@@ -92,17 +92,11 @@ pub(super) async fn api_key_salt(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Json<KeySaltResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.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)?;
|
||||
let user = match load_session_user_strict(&state.pool, &session).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => return Err(StatusCode::UNAUTHORIZED),
|
||||
Err(()) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
};
|
||||
|
||||
if user.key_salt.is_none() {
|
||||
return Ok(Json(KeySaltResponse {
|
||||
@@ -126,19 +120,14 @@ pub(super) async fn api_key_setup(
|
||||
session: Session,
|
||||
Json(body): Json<KeySetupRequest>,
|
||||
) -> Result<Json<KeySetupResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let user = match load_session_user_strict(&state.pool, &session).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => return Err(StatusCode::UNAUTHORIZED),
|
||||
Err(()) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
};
|
||||
let user_id = user.id;
|
||||
|
||||
// Guard: if a passphrase is already configured, reject and direct to /api/key-change
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for key-setup guard");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
if user.key_salt.is_some() {
|
||||
tracing::warn!(%user_id, "key-setup called but passphrase already configured; use /api/key-change");
|
||||
return Err(StatusCode::CONFLICT);
|
||||
@@ -175,17 +164,12 @@ pub(super) async fn api_key_change(
|
||||
session: Session,
|
||||
Json(body): Json<KeyChangeRequest>,
|
||||
) -> Result<Json<KeySetupResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for key-change");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let user = match load_session_user_strict(&state.pool, &session).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => return Err(StatusCode::UNAUTHORIZED),
|
||||
Err(()) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
};
|
||||
let user_id = user.id;
|
||||
|
||||
// Must have an existing passphrase to change
|
||||
let existing_key_check = user.key_check.ok_or_else(|| {
|
||||
@@ -276,9 +260,12 @@ pub(super) async fn api_apikey_get(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Json<ApiKeyResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let user = match load_session_user_strict(&state.pool, &session).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => return Err(StatusCode::UNAUTHORIZED),
|
||||
Err(()) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
};
|
||||
let user_id = user.id;
|
||||
|
||||
let api_key = ensure_api_key(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "ensure_api_key failed");
|
||||
@@ -292,9 +279,12 @@ pub(super) async fn api_apikey_regenerate(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Json<ApiKeyResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let user = match load_session_user_strict(&state.pool, &session).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => return Err(StatusCode::UNAUTHORIZED),
|
||||
Err(()) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
};
|
||||
let user_id = user.id;
|
||||
|
||||
let api_key = regenerate_api_key(&state.pool, user_id)
|
||||
.await
|
||||
|
||||
48
crates/secrets-mcp/src/web/changelog.rs
Normal file
48
crates/secrets-mcp/src/web/changelog.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use askama::Template;
|
||||
use axum::{extract::State, http::StatusCode, response::Response};
|
||||
use pulldown_cmark::{Options, Parser, html};
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
use super::render_template;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "changelog.html")]
|
||||
pub(super) struct ChangelogTemplate {
|
||||
pub base_url: String,
|
||||
pub version: &'static str,
|
||||
pub changelog_html: String,
|
||||
}
|
||||
|
||||
fn markdown_to_html(md: &str) -> String {
|
||||
let mut opts = Options::empty();
|
||||
opts.insert(Options::ENABLE_TABLES);
|
||||
opts.insert(Options::ENABLE_STRIKETHROUGH);
|
||||
opts.insert(Options::ENABLE_TASKLISTS);
|
||||
let parser = Parser::new_ext(md, opts);
|
||||
let mut out = String::new();
|
||||
html::push_html(&mut out, parser);
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) async fn changelog_page(State(state): State<AppState>) -> Result<Response, StatusCode> {
|
||||
let md = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/CHANGELOG.md"));
|
||||
render_template(ChangelogTemplate {
|
||||
base_url: state.base_url.clone(),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
changelog_html: markdown_to_html(md),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::markdown_to_html;
|
||||
|
||||
#[test]
|
||||
fn markdown_renders_heading_and_list() {
|
||||
let html = markdown_to_html("# Title\n\n- a\n");
|
||||
assert!(html.contains("<h1"));
|
||||
assert!(html.contains("Title"));
|
||||
assert!(html.contains("<ul") || html.contains("<li"));
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,8 @@ use secrets_core::service::{
|
||||
use crate::AppState;
|
||||
|
||||
use super::{
|
||||
ENTRIES_PAGE_LIMIT, UiLang, current_user_id, paginate, render_template, request_ui_lang,
|
||||
require_valid_user, tr,
|
||||
ENTRIES_PAGE_LIMIT, UiLang, paginate, render_template, request_ui_lang, require_valid_user,
|
||||
require_valid_user_json, tr,
|
||||
};
|
||||
|
||||
// ── Template types ────────────────────────────────────────────────────────────
|
||||
@@ -45,6 +45,7 @@ struct EntriesPageTemplate {
|
||||
filter_folder: String,
|
||||
filter_name: String,
|
||||
filter_metadata_query: String,
|
||||
filter_tags: String,
|
||||
filter_type: String,
|
||||
current_page: u32,
|
||||
total_pages: u32,
|
||||
@@ -125,6 +126,8 @@ pub(super) struct EntriesQuery {
|
||||
/// URL query key is `type` (maps to DB column `entries.type`).
|
||||
#[serde(rename = "type")]
|
||||
entry_type: Option<String>,
|
||||
/// Comma-separated tags (AND semantics); matches `SearchParams.tags`.
|
||||
tags: Option<String>,
|
||||
page: Option<u32>,
|
||||
}
|
||||
|
||||
@@ -252,6 +255,18 @@ fn relation_views(items: &[RelationEntrySummary]) -> Vec<RelationSummaryView> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Parse Web `tags` query: comma-separated, trim, drop empties (AND semantics via `SearchParams`).
|
||||
fn parse_tags_filter(raw: Option<&str>) -> Vec<String> {
|
||||
let Some(s) = raw else {
|
||||
return Vec::new();
|
||||
};
|
||||
s.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
.map(std::string::ToString::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ── Handlers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
pub(super) async fn entries_page(
|
||||
@@ -289,13 +304,15 @@ pub(super) async fn entries_page(
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
let filter_tags = q.tags.clone().unwrap_or_default();
|
||||
let tag_vec = parse_tags_filter(q.tags.as_deref());
|
||||
let page = q.page.unwrap_or(1).max(1);
|
||||
let count_params = SearchParams {
|
||||
folder: folder_filter.as_deref(),
|
||||
entry_type: type_filter.as_deref(),
|
||||
name: None,
|
||||
name_query: name_filter.as_deref(),
|
||||
tags: &[],
|
||||
tags: tag_vec.as_slice(),
|
||||
query: None,
|
||||
metadata_query: metadata_query_filter.as_deref(),
|
||||
sort: "updated",
|
||||
@@ -328,6 +345,16 @@ pub(super) async fn entries_page(
|
||||
));
|
||||
bind_idx += 1;
|
||||
}
|
||||
if !tag_vec.is_empty() {
|
||||
let placeholders: Vec<String> = (0..tag_vec.len())
|
||||
.map(|i| format!("${}", bind_idx + i as i32))
|
||||
.collect();
|
||||
folder_sql.push_str(&format!(
|
||||
" AND tags @> ARRAY[{}]::text[]",
|
||||
placeholders.join(", ")
|
||||
));
|
||||
bind_idx += tag_vec.len() as i32;
|
||||
}
|
||||
let _ = bind_idx;
|
||||
folder_sql.push_str(" GROUP BY folder ORDER BY folder");
|
||||
let mut folder_query = sqlx::query_as::<_, FolderCountRow>(&folder_sql).bind(user_id);
|
||||
@@ -340,6 +367,9 @@ pub(super) async fn entries_page(
|
||||
if let Some(v) = metadata_query_filter.as_deref() {
|
||||
folder_query = folder_query.bind(ilike_pattern(v));
|
||||
}
|
||||
for t in &tag_vec {
|
||||
folder_query = folder_query.bind(t);
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct TypeOptionRow {
|
||||
@@ -414,6 +444,7 @@ pub(super) async fn entries_page(
|
||||
entry_type: Option<&str>,
|
||||
name: Option<&str>,
|
||||
metadata_query: Option<&str>,
|
||||
tags: Option<&str>,
|
||||
page: Option<u32>,
|
||||
) -> String {
|
||||
let mut pairs: Vec<String> = Vec::new();
|
||||
@@ -437,6 +468,11 @@ pub(super) async fn entries_page(
|
||||
{
|
||||
pairs.push(format!("metadata_query={}", urlencoding::encode(v)));
|
||||
}
|
||||
if let Some(tg) = tags
|
||||
&& !tg.is_empty()
|
||||
{
|
||||
pairs.push(format!("tags={}", urlencoding::encode(tg)));
|
||||
}
|
||||
if let Some(p) = page {
|
||||
pairs.push(format!("page={}", p));
|
||||
}
|
||||
@@ -447,6 +483,7 @@ pub(super) async fn entries_page(
|
||||
}
|
||||
}
|
||||
|
||||
let tags_for_href = (!filter_tags.is_empty()).then_some(filter_tags.as_str());
|
||||
let all_count: i64 = folder_rows.iter().map(|r| r.count).sum();
|
||||
let mut folder_tabs: Vec<FolderTabView> = Vec::with_capacity(folder_rows.len() + 1);
|
||||
folder_tabs.push(FolderTabView {
|
||||
@@ -457,6 +494,7 @@ pub(super) async fn entries_page(
|
||||
type_filter.as_deref(),
|
||||
name_filter.as_deref(),
|
||||
metadata_query_filter.as_deref(),
|
||||
tags_for_href,
|
||||
Some(1),
|
||||
),
|
||||
active: folder_filter.is_none(),
|
||||
@@ -469,6 +507,7 @@ pub(super) async fn entries_page(
|
||||
type_filter.as_deref(),
|
||||
name_filter.as_deref(),
|
||||
metadata_query_filter.as_deref(),
|
||||
tags_for_href,
|
||||
Some(1),
|
||||
),
|
||||
active: folder_filter.as_deref() == Some(name.as_str()),
|
||||
@@ -534,6 +573,7 @@ pub(super) async fn entries_page(
|
||||
filter_folder: folder_filter.unwrap_or_default(),
|
||||
filter_name: name_filter.unwrap_or_default(),
|
||||
filter_metadata_query: metadata_query_filter.unwrap_or_default(),
|
||||
filter_tags,
|
||||
filter_type: type_filter.unwrap_or_default(),
|
||||
current_page,
|
||||
total_pages,
|
||||
@@ -616,10 +656,8 @@ pub(super) async fn api_entry_patch(
|
||||
Json(body): Json<EntryPatchBody>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
let folder = body.folder.trim();
|
||||
let entry_type = body.entry_type.trim();
|
||||
@@ -635,6 +673,71 @@ pub(super) async fn api_entry_patch(
|
||||
));
|
||||
}
|
||||
|
||||
if folder.chars().count() > crate::validation::MAX_FOLDER_LENGTH {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "error": format!(
|
||||
"{} {} {}",
|
||||
tr(
|
||||
lang,
|
||||
"folder 长度不能超过",
|
||||
"folder 長度不能超過",
|
||||
"folder must be at most"
|
||||
),
|
||||
crate::validation::MAX_FOLDER_LENGTH,
|
||||
tr(lang, " 个字符", " 個字元", " characters")
|
||||
) })),
|
||||
));
|
||||
}
|
||||
if entry_type.chars().count() > crate::validation::MAX_ENTRY_TYPE_LENGTH {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "error": format!(
|
||||
"{} {} {}",
|
||||
tr(
|
||||
lang,
|
||||
"type 长度不能超过",
|
||||
"type 長度不能超過",
|
||||
"type must be at most"
|
||||
),
|
||||
crate::validation::MAX_ENTRY_TYPE_LENGTH,
|
||||
tr(lang, " 个字符", " 個字元", " characters")
|
||||
) })),
|
||||
));
|
||||
}
|
||||
if name.chars().count() > crate::validation::MAX_NAME_LENGTH {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "error": format!(
|
||||
"{} {} {}",
|
||||
tr(
|
||||
lang,
|
||||
"name 长度不能超过",
|
||||
"name 長度不能超過",
|
||||
"name must be at most"
|
||||
),
|
||||
crate::validation::MAX_NAME_LENGTH,
|
||||
tr(lang, " 个字符", " 個字元", " characters")
|
||||
) })),
|
||||
));
|
||||
}
|
||||
if notes.chars().count() > crate::validation::MAX_NOTES_LENGTH {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "error": format!(
|
||||
"{} {} {}",
|
||||
tr(
|
||||
lang,
|
||||
"notes 长度不能超过",
|
||||
"notes 長度不能超過",
|
||||
"notes must be at most"
|
||||
),
|
||||
crate::validation::MAX_NOTES_LENGTH,
|
||||
tr(lang, " 个字符", " 個字元", " characters")
|
||||
) })),
|
||||
));
|
||||
}
|
||||
|
||||
let tags: Vec<String> = body
|
||||
.tags
|
||||
.into_iter()
|
||||
@@ -683,10 +786,8 @@ pub(super) async fn api_entry_options(
|
||||
Query(q): Query<EntryOptionQuery>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
let query =
|
||||
q.q.as_deref()
|
||||
@@ -738,10 +839,8 @@ pub(super) async fn api_entry_delete(
|
||||
Path(entry_id): Path<Uuid>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
delete_by_id(&state.pool, entry_id, user_id)
|
||||
.await
|
||||
@@ -760,10 +859,8 @@ pub(super) async fn api_trash_restore(
|
||||
Path(entry_id): Path<Uuid>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
restore_deleted_by_id(&state.pool, entry_id, user_id)
|
||||
.await
|
||||
@@ -782,10 +879,8 @@ pub(super) async fn api_trash_purge(
|
||||
Path(entry_id): Path<Uuid>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
purge_deleted_by_id(&state.pool, entry_id, user_id)
|
||||
.await
|
||||
@@ -818,10 +913,8 @@ pub(super) async fn api_secret_check_name(
|
||||
Query(params): Query<SecretCheckNameQuery>,
|
||||
) -> Result<Json<SecretCheckNameResponse>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
let name = params.name.trim();
|
||||
if name.is_empty() {
|
||||
@@ -914,10 +1007,8 @@ pub(super) async fn api_secret_patch(
|
||||
}
|
||||
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
let name = body.name.as_ref().map(|s| s.trim());
|
||||
let secret_type = body.secret_type.as_ref().map(|s| s.trim());
|
||||
@@ -1123,10 +1214,8 @@ pub(super) async fn api_entry_secret_unlink(
|
||||
}
|
||||
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
let mut tx = state
|
||||
.pool
|
||||
@@ -1216,10 +1305,8 @@ pub(super) async fn api_entry_secrets_decrypt(
|
||||
Path(entry_id): Path<Uuid>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
let user = require_valid_user_json(&state.pool, &session, lang).await?;
|
||||
let user_id = user.id;
|
||||
|
||||
let master_key = require_encryption_key(&headers, lang)?;
|
||||
|
||||
@@ -1255,3 +1342,19 @@ pub(super) async fn api_entry_secrets_decrypt(
|
||||
|
||||
Ok(Json(json!({ "ok": true, "secrets": secrets })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tags_filter_tests {
|
||||
use super::parse_tags_filter;
|
||||
|
||||
#[test]
|
||||
fn parse_tags_comma_trim_skip_empty() {
|
||||
let v = parse_tags_filter(Some(" prod , aliyun ,, "));
|
||||
assert_eq!(v, vec!["prod".to_string(), "aliyun".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_tags_none_empty() {
|
||||
assert!(parse_tags_filter(None).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use askama::Template;
|
||||
use axum::{
|
||||
Router,
|
||||
Json, Router,
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::{Html, IntoResponse, Redirect, Response},
|
||||
routing::{get, patch, post},
|
||||
};
|
||||
use serde_json::json;
|
||||
use tower_sessions::Session;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -15,6 +16,7 @@ mod account;
|
||||
mod assets;
|
||||
mod audit;
|
||||
mod auth;
|
||||
mod changelog;
|
||||
mod entries;
|
||||
|
||||
// ── Session keys ──────────────────────────────────────────────────────────────
|
||||
@@ -34,7 +36,7 @@ const AUDIT_PAGE_LIMIT: i64 = 10;
|
||||
// ── UI language ───────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum UiLang {
|
||||
pub(super) enum UiLang {
|
||||
ZhCn,
|
||||
ZhTw,
|
||||
En,
|
||||
@@ -143,6 +145,71 @@ async fn require_valid_user(
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
/// `Ok(None)` — unauthenticated or session invalidated (including `key_version` mismatch).
|
||||
/// `Err(())` — database error loading the user.
|
||||
pub(super) async fn load_session_user_strict(
|
||||
pool: &sqlx::PgPool,
|
||||
session: &Session,
|
||||
) -> Result<Option<secrets_core::models::User>, ()> {
|
||||
let Some(user_id) = current_user_id(session).await else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let user = match secrets_core::service::user::get_user_by_id(pool, user_id).await {
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, %user_id, "load_session_user_strict: failed to load user");
|
||||
return Err(());
|
||||
}
|
||||
Ok(None) => {
|
||||
if let Err(e) = session.flush().await {
|
||||
tracing::warn!(error = %e, "failed to flush stale session");
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(u)) => u,
|
||||
};
|
||||
|
||||
let session_kv: Option<i64> = match session.get::<i64>(SESSION_KEY_VERSION).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to read key_version from session; treating as missing");
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(kv) = session_kv
|
||||
&& kv != user.key_version
|
||||
{
|
||||
tracing::info!(%user_id, session_kv = kv, db_kv = user.key_version, "key_version mismatch; invalidating session (API)");
|
||||
if let Err(e) = session.flush().await {
|
||||
tracing::warn!(error = %e, "failed to flush outdated session");
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(Some(user))
|
||||
}
|
||||
|
||||
/// JSON API equivalent of [`require_valid_user`]: returns `401` with a JSON body instead of redirecting.
|
||||
pub(super) async fn require_valid_user_json(
|
||||
pool: &sqlx::PgPool,
|
||||
session: &Session,
|
||||
lang: UiLang,
|
||||
) -> Result<secrets_core::models::User, (StatusCode, Json<serde_json::Value>)> {
|
||||
match load_session_user_strict(pool, session).await {
|
||||
Ok(Some(user)) => Ok(user),
|
||||
Ok(None) => Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
)),
|
||||
Err(()) => Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "操作失败,请稍后重试", "操作失敗,請稍後重試", "Operation failed, please try again later") }),
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn request_user_agent(headers: &HeaderMap) -> Option<String> {
|
||||
headers
|
||||
.get(header::USER_AGENT)
|
||||
@@ -187,6 +254,7 @@ pub fn web_router() -> Router<AppState> {
|
||||
get(assets::oauth_protected_resource_metadata),
|
||||
)
|
||||
.route("/", get(auth::home_page))
|
||||
.route("/changelog", get(changelog::changelog_page))
|
||||
.route("/login", get(auth::login_page))
|
||||
.route("/auth/google", get(auth::auth_google))
|
||||
.route("/auth/google/callback", get(auth::auth_google_callback))
|
||||
|
||||
185
crates/secrets-mcp/templates/changelog.html
Normal file
185
crates/secrets-mcp/templates/changelog.html
Normal file
@@ -0,0 +1,185 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="canonical" href="{{ base_url }}/changelog">
|
||||
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||
<title data-i18n="docTitle">变更记录 — Secrets</title>
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Inter:wght@400;500;600&display=swap');
|
||||
:root {
|
||||
--bg: #0d1117; --surface: #161b22;
|
||||
--border: #30363d; --text: #e6edf3; --text-muted: #8b949e;
|
||||
--accent: #58a6ff; --accent-hover: #79b8ff;
|
||||
}
|
||||
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif; min-height: 100vh; }
|
||||
.wrap { max-width: 880px; margin: 0 auto; padding: 24px 20px 48px; }
|
||||
.top {
|
||||
display: flex; align-items: center; flex-wrap: wrap; gap: 12px 16px;
|
||||
margin-bottom: 24px; padding-bottom: 16px;
|
||||
border-bottom: 1px solid rgba(240,246,252,0.08);
|
||||
}
|
||||
.brand {
|
||||
font-size: 18px; font-weight: 700; color: #fff; text-decoration: none;
|
||||
}
|
||||
.brand:hover { color: var(--accent); }
|
||||
.top-actions { margin-left: auto; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.lang-bar { display: flex; gap: 2px; background: rgba(240,246,252,0.06); border-radius: 8px; padding: 2px; }
|
||||
.lang-btn { padding: 4px 10px; border: none; background: none; color: #8b949e;
|
||||
font-size: 12px; cursor: pointer; border-radius: 6px; }
|
||||
.lang-btn.active { background: rgba(240,246,252,0.1); color: #fff; }
|
||||
.link-dash {
|
||||
font-size: 13px; color: var(--accent); text-decoration: none;
|
||||
}
|
||||
.link-dash:hover { text-decoration: underline; }
|
||||
h1 { font-size: 22px; font-weight: 700; margin-bottom: 16px; color: #fff; }
|
||||
.card {
|
||||
background: #111827; border: 1px solid rgba(240,246,252,0.08); border-radius: 18px;
|
||||
padding: 20px 22px;
|
||||
}
|
||||
/* Rendered Markdown (pulldown-cmark) */
|
||||
.changelog-md {
|
||||
font-size: 14px;
|
||||
line-height: 1.65;
|
||||
color: #c9d1d9;
|
||||
}
|
||||
.changelog-md > :first-child { margin-top: 0; }
|
||||
.changelog-md > :last-child { margin-bottom: 0; }
|
||||
.changelog-md h1 {
|
||||
font-size: 1.5rem; font-weight: 700; color: #fff;
|
||||
margin: 1.25em 0 0.5em; padding-bottom: 0.35em;
|
||||
border-bottom: 1px solid rgba(240,246,252,0.1);
|
||||
}
|
||||
.changelog-md h2 {
|
||||
font-size: 1.2rem; font-weight: 650; color: #f0f6fc;
|
||||
margin: 1.35em 0 0.5em;
|
||||
}
|
||||
.changelog-md h3 { font-size: 1.05rem; font-weight: 600; color: #e6edf3; margin: 1.1em 0 0.45em; }
|
||||
.changelog-md h4, .changelog-md h5, .changelog-md h6 { font-size: 1rem; font-weight: 600; color: #e6edf3; margin: 1em 0 0.4em; }
|
||||
.changelog-md p { margin: 0.65em 0; }
|
||||
.changelog-md ul, .changelog-md ol { margin: 0.65em 0; padding-left: 1.35em; }
|
||||
.changelog-md li { margin: 0.3em 0; }
|
||||
.changelog-md li > p { margin: 0.35em 0; }
|
||||
.changelog-md a { color: var(--accent); text-decoration: none; }
|
||||
.changelog-md a:hover { text-decoration: underline; }
|
||||
.changelog-md code {
|
||||
font-family: 'JetBrains Mono', ui-monospace, monospace;
|
||||
font-size: 0.88em;
|
||||
background: rgba(240,246,252,0.08);
|
||||
padding: 0.12em 0.4em;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.changelog-md pre {
|
||||
margin: 0.85em 0;
|
||||
padding: 12px 14px;
|
||||
overflow-x: auto;
|
||||
background: #0d1117;
|
||||
border: 1px solid rgba(240,246,252,0.1);
|
||||
border-radius: 10px;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.changelog-md pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
font-size: inherit;
|
||||
border-radius: 0;
|
||||
}
|
||||
.changelog-md blockquote {
|
||||
margin: 0.75em 0;
|
||||
padding-left: 1em;
|
||||
border-left: 3px solid rgba(56,139,253,0.45);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.changelog-md hr {
|
||||
margin: 1.25em 0;
|
||||
border: none;
|
||||
border-top: 1px solid rgba(240,246,252,0.1);
|
||||
}
|
||||
.changelog-md table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 0.85em 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.changelog-md th, .changelog-md td {
|
||||
border: 1px solid var(--border);
|
||||
padding: 8px 10px;
|
||||
text-align: left;
|
||||
}
|
||||
.changelog-md th { background: rgba(240,246,252,0.06); color: #f0f6fc; }
|
||||
.changelog-md input[type="checkbox"] { margin-right: 0.35em; vertical-align: middle; }
|
||||
.foot {
|
||||
margin-top: 28px; text-align: center; font-size: 11px; color: var(--text-muted);
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
.foot a { color: var(--accent); text-decoration: none; }
|
||||
.foot a:hover { text-decoration: underline; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header class="top">
|
||||
<a href="/" class="brand">secrets</a>
|
||||
<div class="top-actions">
|
||||
<a href="/dashboard" class="link-dash" data-i18n="backDash">控制台</a>
|
||||
<div class="lang-bar" role="group" aria-label="Language">
|
||||
<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>
|
||||
</header>
|
||||
<h1 data-i18n="pageTitle">变更记录</h1>
|
||||
<div class="card changelog-md">
|
||||
{{ changelog_html|safe }}
|
||||
</div>
|
||||
<footer class="foot">
|
||||
<span data-i18n="versionLabel">版本</span> {{ version }}
|
||||
</footer>
|
||||
</div>
|
||||
<script>
|
||||
const T = {
|
||||
'zh-CN': {
|
||||
docTitle: '变更记录 — Secrets',
|
||||
pageTitle: '变更记录',
|
||||
backDash: '控制台',
|
||||
versionLabel: '版本',
|
||||
},
|
||||
'zh-TW': {
|
||||
docTitle: '變更記錄 — Secrets',
|
||||
pageTitle: '變更記錄',
|
||||
backDash: '控制台',
|
||||
versionLabel: '版本',
|
||||
},
|
||||
'en': {
|
||||
docTitle: 'Changelog — Secrets',
|
||||
pageTitle: 'Changelog',
|
||||
backDash: 'Dashboard',
|
||||
versionLabel: 'Version',
|
||||
}
|
||||
};
|
||||
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 => {
|
||||
el.textContent = t(el.getAttribute('data-i18n'));
|
||||
});
|
||||
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>
|
||||
@@ -57,6 +57,8 @@
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
margin-top: auto;
|
||||
}
|
||||
.app-footer a { color: var(--accent); text-decoration: none; }
|
||||
.app-footer a:hover { text-decoration: underline; }
|
||||
.card { background: #111827; border: 1px solid rgba(240,246,252,0.08); border-radius: 18px;
|
||||
padding: 20px; width: 100%; }
|
||||
.card-title { font-size: 22px; font-weight: 700; margin-bottom: 24px; color: #fff; }
|
||||
@@ -288,7 +290,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<footer class="app-footer">{{ version }}</footer>
|
||||
<footer class="app-footer">{{ version }} · <a href="/changelog" data-i18n="changelogLink">变更记录</a></footer>
|
||||
</div><!-- /main -->
|
||||
</div><!-- /content-shell -->
|
||||
</div><!-- /layout -->
|
||||
@@ -379,6 +381,7 @@ const T = {
|
||||
regenFailed: '重置失败,请刷新页面重试。',
|
||||
ariaShowPw: '显示密码',
|
||||
ariaHidePw: '隐藏密码',
|
||||
changelogLink: '变更记录',
|
||||
},
|
||||
'zh-TW': {
|
||||
navMcp: 'MCP', navEntries: '條目', navTrash: '回收站', navAudit: '審計',
|
||||
@@ -417,6 +420,7 @@ const T = {
|
||||
regenFailed: '重置失敗,請重新整理頁面再試。',
|
||||
ariaShowPw: '顯示密碼',
|
||||
ariaHidePw: '隱藏密碼',
|
||||
changelogLink: '變更記錄',
|
||||
},
|
||||
'en': {
|
||||
navMcp: 'MCP', navEntries: 'Entries', navTrash: 'Trash', navAudit: 'Audit',
|
||||
@@ -455,6 +459,7 @@ const T = {
|
||||
regenFailed: 'Reset failed. Please refresh and try again.',
|
||||
ariaShowPw: 'Show password',
|
||||
ariaHidePw: 'Hide password',
|
||||
changelogLink: 'Changelog',
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -145,12 +145,13 @@
|
||||
}
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 1100px;
|
||||
min-width: 1240px;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
table-layout: fixed;
|
||||
}
|
||||
col[data-col="name"] { width: 220px; }
|
||||
col[data-col="folder"] { width: 140px; }
|
||||
col[data-col="type"] { width: 120px; }
|
||||
col[data-col="notes"] { width: 320px; }
|
||||
col[data-col="tags"] { width: 220px; }
|
||||
@@ -172,8 +173,8 @@
|
||||
}
|
||||
td { font-size: 13px; line-height: 1.45; color: #c9d1d9; }
|
||||
tbody tr:nth-child(2n) td { background: rgba(255, 255, 255, 0.01); }
|
||||
tbody tr:nth-child(2n) td.col-name { background: #0f1620; }
|
||||
.mono { font-family: 'JetBrains Mono', monospace; }
|
||||
.col-folder { text-align: center; vertical-align: middle; }
|
||||
.col-type { text-align: center; vertical-align: middle; }
|
||||
.col-secrets { vertical-align: middle; }
|
||||
.col-secrets .secret-list { max-height: 120px; overflow: auto; }
|
||||
@@ -542,6 +543,10 @@
|
||||
<label for="filter-name" data-i18n="filterNameLabel">名称</label>
|
||||
<input id="filter-name" name="name" type="text" value="{{ filter_name }}" data-i18n-ph="filterNamePlaceholder" placeholder="输入关键字" autocomplete="off">
|
||||
</div>
|
||||
<div class="filter-field">
|
||||
<label for="filter-tags" data-i18n="filterTagsLabel">标签</label>
|
||||
<input id="filter-tags" name="tags" type="text" value="{{ filter_tags }}" data-i18n-ph="filterTagsPlaceholder" placeholder="多个标签用逗号分隔" autocomplete="off">
|
||||
</div>
|
||||
<div class="filter-field">
|
||||
<label for="filter-metadata-query" data-i18n="filterMetadataLabel">元数据值</label>
|
||||
<input id="filter-metadata-query" name="metadata_query" type="text" value="{{ filter_metadata_query }}" data-i18n-ph="filterMetadataPlaceholder" placeholder="搜索元数据值" autocomplete="off">
|
||||
@@ -557,7 +562,7 @@
|
||||
</div>
|
||||
<div class="filter-actions">
|
||||
<button type="submit" class="btn-filter" data-i18n="filterSubmit">筛选</button>
|
||||
<a href="/entries" class="btn-clear" data-i18n="filterClear">清空</a>
|
||||
<a href="/entries" class="btn-clear" data-i18n="filterClear">重置</a>
|
||||
<div class="col-menu">
|
||||
<button type="button" class="btn-col-toggle" id="col-toggle-btn" data-i18n-title="columnSettings" title="显示列">▥</button>
|
||||
<div class="col-panel" id="col-panel"></div>
|
||||
@@ -572,6 +577,7 @@
|
||||
<table>
|
||||
<colgroup>
|
||||
<col data-col="name">
|
||||
<col data-col="folder">
|
||||
<col data-col="type">
|
||||
<col data-col="notes">
|
||||
<col data-col="tags">
|
||||
@@ -582,6 +588,7 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-col="name" data-i18n="colName">名称</th>
|
||||
<th data-col="folder" data-i18n="colFolder">文件夹</th>
|
||||
<th data-col="type" data-i18n="colType">类型</th>
|
||||
<th data-col="notes" data-i18n="colNotes">备注</th>
|
||||
<th data-col="tags" data-i18n="colTags">标签</th>
|
||||
@@ -594,6 +601,7 @@
|
||||
{% for entry in entries %}
|
||||
<tr data-entry-id="{{ entry.id }}" data-entry-folder="{{ entry.folder }}" data-entry-metadata="{{ entry.metadata_json }}" data-entry-secrets="{{ entry.secrets_json }}" data-entry-parents="{{ entry.parents_json }}" data-updated-at="{{ entry.updated_at_iso }}">
|
||||
<td class="col-name mono cell-name" data-col="name" data-label="名称">{{ entry.name }}</td>
|
||||
<td class="col-folder mono cell-folder" data-col="folder" data-label="文件夹">{{ entry.folder }}</td>
|
||||
<td class="col-type mono cell-type" data-col="type" data-label="类型">{{ entry.entry_type }}</td>
|
||||
<td class="col-notes cell-notes" data-col="notes" data-label="备注">{% if !entry.notes.is_empty() %}<div class="notes-scroll cell-notes-val">{{ entry.notes }}</div>{% endif %}</td>
|
||||
<td class="col-tags mono cell-tags-val" data-col="tags" data-label="标签">{{ entry.tags }}</td>
|
||||
@@ -639,13 +647,13 @@
|
||||
{% if total_count > 0 %}
|
||||
<div class="pagination">
|
||||
{% if current_page > 1 %}
|
||||
<a href="?{% if !filter_folder.is_empty() %}folder={{ filter_folder | urlencode }}&{% endif %}{% if !filter_type.is_empty() %}type={{ filter_type | urlencode }}&{% endif %}{% if !filter_name.is_empty() %}name={{ filter_name | urlencode }}&{% endif %}{% if !filter_metadata_query.is_empty() %}metadata_query={{ filter_metadata_query | urlencode }}&{% endif %}page={{ current_page - 1 }}" class="page-btn" data-i18n="prevPage">上一页</a>
|
||||
<a href="?{% if !filter_folder.is_empty() %}folder={{ filter_folder | urlencode }}&{% endif %}{% if !filter_type.is_empty() %}type={{ filter_type | urlencode }}&{% endif %}{% if !filter_name.is_empty() %}name={{ filter_name | urlencode }}&{% endif %}{% if !filter_tags.is_empty() %}tags={{ filter_tags | urlencode }}&{% endif %}{% if !filter_metadata_query.is_empty() %}metadata_query={{ filter_metadata_query | urlencode }}&{% endif %}page={{ current_page - 1 }}" class="page-btn" data-i18n="prevPage">上一页</a>
|
||||
{% else %}
|
||||
<span class="page-btn page-btn-disabled" data-i18n="prevPage">上一页</span>
|
||||
{% endif %}
|
||||
<span class="page-info">{{ current_page }} / {{ total_pages }}</span>
|
||||
{% if current_page < total_pages %}
|
||||
<a href="?{% if !filter_folder.is_empty() %}folder={{ filter_folder | urlencode }}&{% endif %}{% if !filter_type.is_empty() %}type={{ filter_type | urlencode }}&{% endif %}{% if !filter_name.is_empty() %}name={{ filter_name | urlencode }}&{% endif %}{% if !filter_metadata_query.is_empty() %}metadata_query={{ filter_metadata_query | urlencode }}&{% endif %}page={{ current_page + 1 }}" class="page-btn" data-i18n="nextPage">下一页</a>
|
||||
<a href="?{% if !filter_folder.is_empty() %}folder={{ filter_folder | urlencode }}&{% endif %}{% if !filter_type.is_empty() %}type={{ filter_type | urlencode }}&{% endif %}{% if !filter_name.is_empty() %}name={{ filter_name | urlencode }}&{% endif %}{% if !filter_tags.is_empty() %}tags={{ filter_tags | urlencode }}&{% endif %}{% if !filter_metadata_query.is_empty() %}metadata_query={{ filter_metadata_query | urlencode }}&{% endif %}page={{ current_page + 1 }}" class="page-btn" data-i18n="nextPage">下一页</a>
|
||||
{% else %}
|
||||
<span class="page-btn page-btn-disabled" data-i18n="nextPage">下一页</span>
|
||||
{% endif %}
|
||||
@@ -709,14 +717,17 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
allTab: '全部',
|
||||
filterNameLabel: '名称',
|
||||
filterNamePlaceholder: '输入关键字',
|
||||
filterTagsLabel: '标签',
|
||||
filterTagsPlaceholder: '多个标签用逗号分隔',
|
||||
filterMetadataLabel: '元数据值',
|
||||
filterMetadataPlaceholder: '搜索元数据值',
|
||||
filterTypeLabel: '类型',
|
||||
filterTypeAll: '全部',
|
||||
filterSubmit: '筛选',
|
||||
filterClear: '清空',
|
||||
filterClear: '重置',
|
||||
emptyEntries: '暂无条目。',
|
||||
colName: '名称',
|
||||
colFolder: '文件夹',
|
||||
colType: '类型',
|
||||
colNotes: '备注',
|
||||
colTags: '标签',
|
||||
@@ -740,6 +751,7 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
modalCancel: '取消',
|
||||
modalSave: '保存',
|
||||
mobileLabelName: '名称',
|
||||
mobileLabelFolder: '文件夹',
|
||||
mobileLabelType: '类型',
|
||||
mobileLabelNotes: '备注',
|
||||
mobileLabelTags: '标签',
|
||||
@@ -793,14 +805,17 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
allTab: '全部',
|
||||
filterNameLabel: '名稱',
|
||||
filterNamePlaceholder: '輸入關鍵字',
|
||||
filterTagsLabel: '標籤',
|
||||
filterTagsPlaceholder: '多個標籤用逗號分隔',
|
||||
filterMetadataLabel: '中繼資料值',
|
||||
filterMetadataPlaceholder: '搜尋中繼資料值',
|
||||
filterTypeLabel: '類型',
|
||||
filterTypeAll: '全部',
|
||||
filterSubmit: '篩選',
|
||||
filterClear: '清除',
|
||||
filterClear: '重置',
|
||||
emptyEntries: '暫無條目。',
|
||||
colName: '名稱',
|
||||
colFolder: '資料夾',
|
||||
colType: '類型',
|
||||
colNotes: '備註',
|
||||
colTags: '標籤',
|
||||
@@ -824,6 +839,7 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
modalCancel: '取消',
|
||||
modalSave: '儲存',
|
||||
mobileLabelName: '名稱',
|
||||
mobileLabelFolder: '資料夾',
|
||||
mobileLabelType: '類型',
|
||||
mobileLabelNotes: '備註',
|
||||
mobileLabelTags: '標籤',
|
||||
@@ -877,14 +893,17 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
allTab: 'All',
|
||||
filterNameLabel: 'Name',
|
||||
filterNamePlaceholder: 'Enter keywords',
|
||||
filterTagsLabel: 'Tags',
|
||||
filterTagsPlaceholder: 'Comma-separated tags',
|
||||
filterMetadataLabel: 'Metadata value',
|
||||
filterMetadataPlaceholder: 'Search metadata values',
|
||||
filterTypeLabel: 'Type',
|
||||
filterTypeAll: 'All',
|
||||
filterSubmit: 'Filter',
|
||||
filterClear: 'Clear',
|
||||
filterClear: 'Reset',
|
||||
emptyEntries: 'No entries.',
|
||||
colName: 'Name',
|
||||
colFolder: 'Folder',
|
||||
colType: 'Type',
|
||||
colNotes: 'Notes',
|
||||
colTags: 'Tags',
|
||||
@@ -908,6 +927,7 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
modalCancel: 'Cancel',
|
||||
modalSave: 'Save',
|
||||
mobileLabelName: 'Name',
|
||||
mobileLabelFolder: 'Folder',
|
||||
mobileLabelType: 'Type',
|
||||
mobileLabelNotes: 'Notes',
|
||||
mobileLabelTags: 'Tags',
|
||||
@@ -962,6 +982,7 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
document.querySelectorAll('tr[data-entry-id]').forEach(function (tr) {
|
||||
var map = {
|
||||
'.col-name': 'mobileLabelName',
|
||||
'.col-folder': 'mobileLabelFolder',
|
||||
'.col-type': 'mobileLabelType',
|
||||
'.col-notes': 'mobileLabelNotes',
|
||||
'.col-tags': 'mobileLabelTags',
|
||||
@@ -977,9 +998,9 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
rebuildColPanel();
|
||||
};
|
||||
|
||||
var COL_ORDER = ['name', 'type', 'notes', 'tags', 'relations', 'secrets', 'actions'];
|
||||
var COL_ORDER = ['name', 'folder', 'type', 'notes', 'tags', 'relations', 'secrets', 'actions'];
|
||||
var COL_ALWAYS_ON = { name: true, actions: true };
|
||||
var COL_DEFAULTS = { name: true, type: true, notes: false, tags: true, relations: true, secrets: false, actions: true };
|
||||
var COL_DEFAULTS = { name: true, folder: true, type: true, notes: false, tags: true, relations: true, secrets: false, actions: true };
|
||||
var COL_STORAGE_KEY = 'entries_col_vis';
|
||||
var colPanel = document.getElementById('col-panel');
|
||||
var colToggleBtn = document.getElementById('col-toggle-btn');
|
||||
@@ -987,7 +1008,16 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
function getColVis() {
|
||||
try {
|
||||
var saved = localStorage.getItem(COL_STORAGE_KEY);
|
||||
if (saved) { var parsed = JSON.parse(saved); if (parsed && typeof parsed === 'object') return parsed; }
|
||||
if (saved) {
|
||||
var parsed = JSON.parse(saved);
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
var merged = {};
|
||||
COL_ORDER.forEach(function (col) {
|
||||
merged[col] = parsed[col] !== undefined ? parsed[col] : COL_DEFAULTS[col];
|
||||
});
|
||||
return merged;
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
var defaults = {};
|
||||
COL_ORDER.forEach(function (col) { defaults[col] = COL_DEFAULTS[col]; });
|
||||
|
||||
@@ -178,10 +178,8 @@
|
||||
<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 %}
|
||||
<a href="/changelog" data-i18n="footChangelog">变更记录</a>
|
||||
</footer>
|
||||
<script>
|
||||
const T = {
|
||||
@@ -200,7 +198,7 @@
|
||||
versionLabel: '版本',
|
||||
sep: ' · ',
|
||||
footRepo: '源码仓库',
|
||||
footLogin: '登录',
|
||||
footChangelog: '变更记录',
|
||||
},
|
||||
'zh-TW': {
|
||||
docTitle: 'Secrets MCP — 端到端加密的金鑰管理',
|
||||
@@ -217,7 +215,7 @@
|
||||
versionLabel: '版本',
|
||||
sep: ' · ',
|
||||
footRepo: '原始碼倉庫',
|
||||
footLogin: '登入',
|
||||
footChangelog: '變更記錄',
|
||||
},
|
||||
'en': {
|
||||
docTitle: 'Secrets MCP — End-to-end encrypted secrets',
|
||||
@@ -234,7 +232,7 @@
|
||||
versionLabel: 'Version',
|
||||
sep: ' · ',
|
||||
footRepo: 'Source repository',
|
||||
footLogin: 'Sign in',
|
||||
footChangelog: 'Changelog',
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -20,9 +20,14 @@ BASE_URL=https://secrets.example.com
|
||||
|
||||
# ─── Google OAuth ─────────────────────────────────────────────────────
|
||||
# Google Cloud Console → APIs & Services → Credentials
|
||||
# 授权回调 URI 须配置为:${BASE_URL}/auth/google/callback
|
||||
# 授权回调 URI 须与 BASE_URL 完全一致:${BASE_URL}/auth/google/callback(含 http/https、主机名、端口)
|
||||
# 运行 secrets-mcp 的机器须能访问 Google(oauth2.googleapis.com)。若本机用 Clash/Surge「系统代理」上网:
|
||||
# 构建时已启用 reqwest 的 system-proxy,进程会跟随系统代理;仍失败时可设 HTTPS_PROXY(见下方)。
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
# 若仍无法换 token(仅提供端口代理、无系统代理):可取消注释并改为本机代理地址
|
||||
# HTTPS_PROXY=http://127.0.0.1:7890
|
||||
# NO_PROXY=localhost,127.0.0.1
|
||||
|
||||
# ─── 微信登录(暂未开放,预留)───────────────────────────────────────
|
||||
# WECHAT_APP_CLIENT_ID=
|
||||
|
||||
201
plans/code-review-fixes-2026-04-11.md
Normal file
201
plans/code-review-fixes-2026-04-11.md
Normal file
@@ -0,0 +1,201 @@
|
||||
# Code Review 修复计划
|
||||
|
||||
**日期**: 2026-04-11
|
||||
**来源**: 三份 code review 报告提炼合并
|
||||
**范围**: 7 项修复 + 1 项风险提示(不纳入本次修复)
|
||||
|
||||
---
|
||||
|
||||
## 1. `secrets-core` 导入/导出链路
|
||||
|
||||
**目标**: 修复"导入丢失 secret type"。
|
||||
|
||||
**涉及文件**:
|
||||
- `crates/secrets-core/src/models.rs`
|
||||
- `crates/secrets-core/src/service/export.rs`
|
||||
- `crates/secrets-core/src/service/import.rs`
|
||||
|
||||
**实施项**:
|
||||
1. 在 `ExportEntry` 增加可选字段 `secret_types: Option<BTreeMap<String, String>>`,键为 secret 名,值为 type。
|
||||
2. 修改导出逻辑,除了导出 `secrets` 的值,也把每个 secret 的 `type` 一并导出。
|
||||
3. 修改导入逻辑,把 `entry.secret_types` 传给 `AddParams.secret_types`,不再用 `&Default::default()`。
|
||||
4. 明确兼容旧导出文件:`secret_types` 缺失时继续默认 `"text"`。
|
||||
|
||||
**验证**:
|
||||
1. 新增 round-trip 测试:带 `password` / `key` / `text` 三种类型的导出再导入,类型保持不变。
|
||||
2. 新增向后兼容测试:旧格式导入时仍成功,默认回落到 `"text"`。
|
||||
|
||||
---
|
||||
|
||||
## 2. `secrets-core` env map
|
||||
|
||||
**目标**: 修复环境变量名碰撞。
|
||||
|
||||
**涉及文件**:
|
||||
- `crates/secrets-core/src/service/env_map.rs`
|
||||
|
||||
**实施项**:
|
||||
1. 统一分隔符策略:把字段名里的 `.` 替换成 `__`(双下划线),保留原始 `_` 为单下划线,避免 `db.password` 和 `db_password` 碰撞。
|
||||
2. 如仍发生碰撞,显式返回错误,而不是 `HashMap::insert` 静默覆盖。
|
||||
|
||||
**验证**:
|
||||
1. 添加测试覆盖:
|
||||
- `db.password` vs `db_password`
|
||||
- 带 `prefix` 的情况
|
||||
- 多 entry 合并时碰撞
|
||||
2. 确认输出变量名文档与实现一致。
|
||||
|
||||
---
|
||||
|
||||
## 3. `secrets-core` rollback
|
||||
|
||||
**目标**: 修复回滚路径中的 TOCTOU 和"使用旧 live 值"问题。
|
||||
|
||||
**涉及文件**:
|
||||
- `crates/secrets-core/src/service/rollback.rs`
|
||||
|
||||
**实施项**:
|
||||
1. 把首次读取 live entry 的逻辑移入事务内,并与 `FOR UPDATE` 合并,避免在加锁前基于过期数据做决策。
|
||||
2. 在拿到加锁后的 live row 后,再决定错误消息、审计字段和更新语句输入。
|
||||
3. 明确回滚语义:
|
||||
- 若产品希望"完全回到快照",则 `name/notes` 也从快照恢复。
|
||||
- 若希望保留当前标识,则代码和文档都要显式说明此设计决策。
|
||||
4. 避免混用事务前的 `live_entry` 与事务内的 `lr`。
|
||||
|
||||
**验证**:
|
||||
1. 新增测试覆盖:
|
||||
- 回滚时恢复字段是否符合预期
|
||||
- 并发更新 + 回滚场景不再依赖过期值
|
||||
|
||||
---
|
||||
|
||||
## 4. `secrets-core` API key
|
||||
|
||||
**目标**: 修复 `regenerate_api_key` 返回未持久化 key。
|
||||
|
||||
**涉及文件**:
|
||||
- `crates/secrets-core/src/service/api_key.rs`
|
||||
|
||||
**实施项**:
|
||||
1. 检查 `UPDATE` 的 `rows_affected()`。
|
||||
2. 若为 `0`,返回 `NotFoundUser` 或等价业务错误。
|
||||
3. 可选:改成 `UPDATE ... RETURNING api_key`,减少"先生成后判断"的分支。
|
||||
|
||||
**验证**:
|
||||
1. 新增测试:
|
||||
- 正常用户可返回新 key
|
||||
- 不存在用户时返回错误,而不是返回伪成功 key
|
||||
|
||||
---
|
||||
|
||||
## 5. `secrets-mcp` tools
|
||||
|
||||
**目标**: 修复 MCP 层三个问题:
|
||||
- `secrets_add` 提交后再回查 entry 的竞态
|
||||
- `secrets_find` 计数失败被吞成 0
|
||||
- `secrets_rollback` 冗余要求 encryption key
|
||||
|
||||
**涉及文件**:
|
||||
- `crates/secrets-mcp/src/tools.rs`
|
||||
- 可能连带 `crates/secrets-core/src/service/add.rs` 的返回结构
|
||||
|
||||
**实施项**:
|
||||
1. 让 `svc_add` 直接返回 `entry_id`,MCP 不再在提交后用 `name+folder+user_id` 二次 `resolve_entry`。
|
||||
2. `secrets_find` 中移除 `.unwrap_or(0)`:
|
||||
- 要么把计数错误向上传播
|
||||
- 要么返回 `total_count: null` / `count_unavailable: true`
|
||||
3. `secrets_rollback` 改为只要求用户身份,不要求 encryption key。
|
||||
4. 同步修正工具描述文案,避免 schema 与实际行为不一致。
|
||||
|
||||
**验证**:
|
||||
1. `secrets_add`:父子关系新增时直接使用返回的 `entry_id`。
|
||||
2. `secrets_find`:模拟 count 失败时,结果不再伪装成 `0`。
|
||||
3. `secrets_rollback`:无 key 时可执行,工具描述与行为一致。
|
||||
|
||||
---
|
||||
|
||||
## 6. `secrets-mcp` Web 会话校验
|
||||
|
||||
**目标**: 让 JSON API 与页面路由的 `key_version` 校验对齐。
|
||||
|
||||
**涉及文件**:
|
||||
- `crates/secrets-mcp/src/web/mod.rs`
|
||||
- `crates/secrets-mcp/src/web/entries.rs`
|
||||
- `crates/secrets-mcp/src/web/account.rs`
|
||||
- 其他仅使用 `current_user_id()` 的 JSON handler
|
||||
|
||||
**实施项**:
|
||||
1. 抽一个适用于 JSON API 的用户校验辅助函数。
|
||||
2. 该函数应同时完成:
|
||||
- session 取 `user_id`
|
||||
- 加载用户
|
||||
- 比对 `SESSION_KEY_VERSION` 与 DB `key_version`
|
||||
3. 页面路由继续保留 `require_valid_user`,JSON 路由统一改用等价校验。
|
||||
4. 统一失败语义:
|
||||
- HTML 路由:重定向 `/login`
|
||||
- JSON 路由:返回 `401`
|
||||
|
||||
**验证**:
|
||||
1. 新增测试覆盖:
|
||||
- `key_version` 一致时 JSON API 正常
|
||||
- `key_version` 不一致时 JSON API 返回 `401`
|
||||
- 用户删除/会话损坏时返回正确错误
|
||||
|
||||
---
|
||||
|
||||
## 7. Web API 输入校验
|
||||
|
||||
**目标**: 补齐 Web JSON API 的长度校验,避免 DB 约束错误落成 500。
|
||||
|
||||
**涉及文件**:
|
||||
- `crates/secrets-mcp/src/web/entries.rs`
|
||||
- 如有需要,抽公共 helper 到 `web/mod.rs` 或单独模块
|
||||
|
||||
**实施项**:
|
||||
1. 在 `api_entry_patch` 对齐 MCP 的长度规则:
|
||||
- `folder <= 128`
|
||||
- `type <= 64`
|
||||
- `name <= 256`
|
||||
- `notes <= 10000`
|
||||
2. 视情况复用 `validation` 常量,避免 Web/MCP 两套上限漂移。
|
||||
3. 保持错误返回为 `400`,而不是依赖数据库报错。
|
||||
|
||||
**验证**:
|
||||
1. 为超长 `folder/type/name/notes` 分别补测试。
|
||||
2. 确认错误文案和现有本地化风格一致。
|
||||
|
||||
---
|
||||
|
||||
## 8. 暂不纳入本次修复(风险提示)
|
||||
|
||||
- 调试日志记录加密密钥片段(`extract_enc_key_or_arg` 在 debug 级别记录 key 前后缀)
|
||||
- `encryption_key` 作为工具参数带来的日志/对话暴露面
|
||||
|
||||
**处理方式**: 记录为"接口安全风险提示",待后续单独决定是否收紧 debug 日志、调整工具描述或限制参数传 key 的路径。
|
||||
|
||||
---
|
||||
|
||||
## 实施顺序
|
||||
|
||||
1. `secrets-core` 导入/导出链路
|
||||
2. `secrets-core` env map
|
||||
3. `secrets-core` rollback
|
||||
4. `secrets-core` API key
|
||||
5. `secrets-mcp` tools
|
||||
6. `secrets-mcp` Web 会话校验
|
||||
7. `secrets-mcp` Web 输入校验
|
||||
|
||||
**原因**: 先修 core 语义和返回结构,再修上层接入。`svc_add` 返回结构、rollback 语义、export/import 格式都属于底层契约,适合先稳定。
|
||||
|
||||
---
|
||||
|
||||
## 验证与收尾
|
||||
|
||||
1. 先跑相关单元/集成测试。
|
||||
2. 再跑全量:
|
||||
```bash
|
||||
cargo fmt -- --check
|
||||
cargo clippy --locked -- -D warnings
|
||||
cargo test --locked
|
||||
```
|
||||
3. 若涉及 `crates/**` 的实际改动,按 `AGENTS.md` 约定检查版本/tag,并执行 `./scripts/release-check.sh`。
|
||||
141
plans/merge-code-review-fixes-2026-04-11.md
Normal file
141
plans/merge-code-review-fixes-2026-04-11.md
Normal file
@@ -0,0 +1,141 @@
|
||||
# Code Review 修复方案合并计划
|
||||
|
||||
**日期**: 2026-04-11
|
||||
**来源**: 两个 AI 实现对比评估
|
||||
**比较对象**:
|
||||
|
||||
- `d7720662` (`/Users/voson/work/refining/secrets-cr-fixes-ws`)
|
||||
- `9f8a68cd` (`/Users/voson/work/refining/secrets/plan-impl`)
|
||||
|
||||
---
|
||||
|
||||
## 结论
|
||||
|
||||
以 `**d7720662`** 为主线采纳。
|
||||
|
||||
**原因**:
|
||||
|
||||
1. `rollback` 的 live row 加锁与 snapshot 读取都在事务内完成,更符合原计划里对 TOCTOU 的修复要求。
|
||||
2. Web JSON API 的 session 校验保留了按 `UiLang` 返回错误信息的行为,没有把错误消息退化成固定英文。
|
||||
3. `svc_add` 返回 `entry_id`,MCP 层直接使用返回值建立 parent relation,和计划第 5 项更一致。
|
||||
|
||||
---
|
||||
|
||||
## 采纳策略
|
||||
|
||||
### 1. 主线保留 `d7720662`
|
||||
|
||||
保留以下实现,不从另一份实现回退:
|
||||
|
||||
- `crates/secrets-core/src/service/rollback.rs`
|
||||
- `crates/secrets-mcp/src/web/mod.rs`
|
||||
- `crates/secrets-core/src/service/add.rs`
|
||||
- `crates/secrets-mcp/src/tools.rs`
|
||||
|
||||
### 2. 从 `9f8a68cd` 手动吸收的小改动
|
||||
|
||||
仅吸收下面两处,手动改写,不直接整文件 cherry-pick:
|
||||
|
||||
1. `crates/secrets-mcp/src/web/entries.rs`
|
||||
- 把长度校验报错文案改成基于 `crate::validation::`* 常量拼接,避免上限数字硬编码在文案里。
|
||||
2. `crates/secrets-core/src/service/env_map.rs`
|
||||
- 补 `env_prefix_with_and_without_prefix` 单测。
|
||||
|
||||
---
|
||||
|
||||
## 明确不采纳的实现
|
||||
|
||||
### 不采纳 `9f8a68cd` 的 `rollback.rs`
|
||||
|
||||
原因:
|
||||
|
||||
- 它仍然先在事务外读取 `entries_history`,再开启事务并锁 live row。
|
||||
- 对“回滚到最近快照”的路径仍存在先读后锁的时间窗口。
|
||||
|
||||
### 不采纳 `9f8a68cd` 的 `web/mod.rs`
|
||||
|
||||
原因:
|
||||
|
||||
- `load_session_user_strict()` / `require_valid_user_json()` 返回固定英文 JSON 错误。
|
||||
- 会丢失现有多语言错误语义。
|
||||
|
||||
### 不采纳 `9f8a68cd` 的 `AddResult.id`
|
||||
|
||||
原因:
|
||||
|
||||
- 本轮计划里明确要求 `svc_add` 返回 `entry_id`。
|
||||
- `d7720662` 的字段命名与 MCP 使用方式更贴近计划要求。
|
||||
|
||||
---
|
||||
|
||||
## 与原计划的覆盖情况
|
||||
|
||||
两份实现都完成了大部分代码修改,但验证项整体没有补齐,当前更像“代码已改,测试仍不足”。
|
||||
|
||||
### 已基本完成
|
||||
|
||||
1. 导入/导出链路补 `secret_types`
|
||||
2. env map `.` -> `__`,并在冲突时返回错误
|
||||
3. API key `rows_affected()` 检查
|
||||
4. MCP `secrets_add` 避免提交后二次回查竞态
|
||||
5. MCP `secrets_find` 不再把 count 错误吞成 `0`
|
||||
6. MCP `secrets_rollback` 不再要求 encryption key
|
||||
7. Web JSON API 引入 `key_version` 严格校验
|
||||
8. Web PATCH 补长度校验
|
||||
|
||||
### 尚需补齐的验证
|
||||
|
||||
1. export/import round-trip 测试
|
||||
- `password` / `key` / `text` 三种类型导出再导入后保持不变
|
||||
2. legacy import 测试
|
||||
- 老格式缺失 `secret_types` 时默认回落到 `text`
|
||||
3. env map 测试
|
||||
- `db.password` vs `db_password`
|
||||
- 带 `prefix`
|
||||
- 多 entry 合并冲突
|
||||
4. rollback 测试
|
||||
- 恢复字段是否符合预期
|
||||
- 并发更新 + 回滚不依赖过期值
|
||||
5. `regenerate_api_key` 测试
|
||||
- 正常用户返回新 key
|
||||
- 不存在用户返回错误
|
||||
6. MCP tool 测试
|
||||
- `secrets_find` count 失败路径
|
||||
- `secrets_rollback` 无 encryption key 也可执行
|
||||
7. Web session / validation 测试
|
||||
- `key_version` mismatch -> `401`
|
||||
- 用户不存在 / session 损坏 -> 正确错误
|
||||
- `folder/type/name/notes` 超长 -> `400`
|
||||
|
||||
---
|
||||
|
||||
## 执行步骤
|
||||
|
||||
1. 以 `d7720662` 对应实现为合并基线。
|
||||
2. 手动吸收 `9f8a68cd` 中 `web/entries.rs` 的常量化长度报错文案。
|
||||
3. 手动吸收 `9f8a68cd` 中 `env_map.rs` 的 `env_prefix_with_and_without_prefix` 测试。
|
||||
4. 不引入 `9f8a68cd` 的 `rollback.rs`、`web/mod.rs`、`AddResult.id` 方案。
|
||||
5. 针对原计划缺失的验证项补测试。
|
||||
6. 跑质量门禁:
|
||||
|
||||
```bash
|
||||
cargo fmt -- --check
|
||||
cargo clippy --locked -- -D warnings
|
||||
cargo test --locked
|
||||
```
|
||||
|
||||
1. 跑发布前检查:
|
||||
|
||||
```bash
|
||||
./scripts/release-check.sh
|
||||
```
|
||||
|
||||
1. 确认版本和 tag:
|
||||
- `crates/secrets-mcp/Cargo.toml` 已 bump(合并执行时为 `0.5.21`,因 `crates/**` 有变更)
|
||||
- `jj tag list`
|
||||
|
||||
---
|
||||
|
||||
## 备注
|
||||
|
||||
如果后续要做最终合并,建议以 `d7720662` 为基础继续补测试,而不是尝试把两份实现整合成第三套逻辑。这样改动面最小,风险也最低。
|
||||
@@ -23,7 +23,7 @@ Add a new `metadata_query` filter to `SearchParams` that uses PostgreSQL `jsonb_
|
||||
|
||||
#### secrets-core
|
||||
|
||||
**`crates/secrets-core/src/service/search.rs`**
|
||||
`**crates/secrets-core/src/service/search.rs`**
|
||||
|
||||
- Add `metadata_query: Option<&'a str>` field to `SearchParams`
|
||||
- In `entry_where_clause_and_next_idx`, when `metadata_query` is set, add:
|
||||
@@ -42,7 +42,7 @@ EXISTS (
|
||||
|
||||
#### secrets-mcp (MCP tools)
|
||||
|
||||
**`crates/secrets-mcp/src/tools.rs`**
|
||||
`**crates/secrets-mcp/src/tools.rs**`
|
||||
|
||||
- Add `metadata_query` field to `FindInput`:
|
||||
|
||||
@@ -56,7 +56,7 @@ metadata_query: Option<String>,
|
||||
|
||||
#### secrets-mcp (Web)
|
||||
|
||||
**`crates/secrets-mcp/src/web/entries.rs`**
|
||||
`**crates/secrets-mcp/src/web/entries.rs**`
|
||||
|
||||
- Add `metadata_query: Option<String>` to `EntriesQuery`
|
||||
- Thread it into all `SearchParams` usages (count, list, folder counts)
|
||||
@@ -64,17 +64,19 @@ metadata_query: Option<String>,
|
||||
- Add `metadata_query` to `EntriesPageTemplate` and filter form hidden fields
|
||||
- Include `metadata_query` in pagination `href` links
|
||||
|
||||
**`crates/secrets-mcp/templates/entries.html`**
|
||||
`**crates/secrets-mcp/templates/entries.html**`
|
||||
|
||||
- Add a "metadata 值" text input to the filter bar (after name, before type)
|
||||
- Preserve value in the input on re-render
|
||||
|
||||
### i18n Keys
|
||||
|
||||
| Key | zh | zh-Hant | en |
|
||||
|-----|-----|---------|-----|
|
||||
| `filterMetaLabel` | 元数据值 | 元数据值 | Metadata value |
|
||||
| `filterMetaPlaceholder` | 搜索元数据值 | 搜尋元資料值 | Search metadata values |
|
||||
|
||||
| Key | zh | zh-Hant | en |
|
||||
| ----------------------- | ------ | ------- | ---------------------- |
|
||||
| `filterMetaLabel` | 元数据值 | 元数据值 | Metadata value |
|
||||
| `filterMetaPlaceholder` | 搜索元数据值 | 搜尋元資料值 | Search metadata values |
|
||||
|
||||
|
||||
### Performance Notes
|
||||
|
||||
@@ -191,81 +193,76 @@ pub async fn get_relations_for_entries(
|
||||
) -> Result<HashMap<Uuid, Vec<RelationSummary>>>
|
||||
```
|
||||
|
||||
**`crates/secrets-core/src/service/mod.rs`** — add `pub mod relations;`
|
||||
`**crates/secrets-core/src/service/mod.rs**` — add `pub mod relations;`
|
||||
|
||||
**`crates/secrets-core/src/db.rs`** — add entry_relations table creation in `migrate()`
|
||||
`**crates/secrets-core/src/db.rs**` — add entry_relations table creation in `migrate()`
|
||||
|
||||
**`crates/secrets-core/src/error.rs`** — no new error variant needed; use `AppError::Validation { message }` for cycle detection and permission errors
|
||||
`**crates/secrets-core/src/error.rs**` — no new error variant needed; use `AppError::Validation { message }` for cycle detection and permission errors
|
||||
|
||||
### MCP Tool Changes
|
||||
|
||||
**`crates/secrets-mcp/src/tools.rs`**
|
||||
`**crates/secrets-mcp/src/tools.rs**`
|
||||
|
||||
1. **`secrets_add`** (`AddInput`): add optional `parent_ids: Option<Vec<String>>` field
|
||||
- Description: "UUIDs of parent entries to link. Creates parent→child relations."
|
||||
- After creating the entry, call `relations::add_relation` for each parent
|
||||
|
||||
2. **`secrets_update`** (`UpdateInput`): add two fields:
|
||||
- `add_parent_ids: Option<Vec<String>>` — "UUIDs of parent entries to link"
|
||||
- `remove_parent_ids: Option<Vec<String>>` — "UUIDs of parent entries to unlink"
|
||||
|
||||
3. **`secrets_find`** and `secrets_search` output: add `parents` and `children` arrays to each entry result:
|
||||
```json
|
||||
1. `**secrets_add**` (`AddInput`): add optional `parent_ids: Option<Vec<String>>` field
|
||||
- Description: "UUIDs of parent entries to link. Creates parent→child relations."
|
||||
- After creating the entry, call `relations::add_relation` for each parent
|
||||
2. `**secrets_update**` (`UpdateInput`): add two fields:
|
||||
- `add_parent_ids: Option<Vec<String>>` — "UUIDs of parent entries to link"
|
||||
- `remove_parent_ids: Option<Vec<String>>` — "UUIDs of parent entries to unlink"
|
||||
3. `**secrets_find**` and `secrets_search` output: add `parents` and `children` arrays to each entry result:
|
||||
```json
|
||||
{
|
||||
"id": "...",
|
||||
"name": "...",
|
||||
"parents": [{"id": "...", "name": "...", "folder": "...", "type": "..."}],
|
||||
"children": [{"id": "...", "name": "...", "folder": "...", "type": "..."}]
|
||||
}
|
||||
```
|
||||
- Fetch relations for all returned entry IDs in a single batch query
|
||||
```
|
||||
- Fetch relations for all returned entry IDs in a single batch query
|
||||
|
||||
### Web Changes
|
||||
|
||||
**`crates/secrets-mcp/src/web/entries.rs`**
|
||||
`**crates/secrets-mcp/src/web/entries.rs**`
|
||||
|
||||
1. **New API endpoints:**
|
||||
|
||||
- `POST /api/entries/{id}/relations` — add parent relation
|
||||
- Body: `{ "parent_id": "uuid" }`
|
||||
- Validates same-user ownership and cycle detection
|
||||
|
||||
- `DELETE /api/entries/{id}/relations/{parent_id}` — remove parent relation
|
||||
|
||||
- `GET /api/entries/options?q=xxx` — lightweight search for parent selection modal
|
||||
- Returns `[{ "id": "...", "name": "...", "folder": "...", "type": "..." }]`
|
||||
- Used by the edit dialog's parent selection autocomplete
|
||||
|
||||
- `POST /api/entries/{id}/relations` — add parent relation
|
||||
- Body: `{ "parent_id": "uuid" }`
|
||||
- Validates same-user ownership and cycle detection
|
||||
- `DELETE /api/entries/{id}/relations/{parent_id}` — remove parent relation
|
||||
- `GET /api/entries/options?q=xxx` — lightweight search for parent selection modal
|
||||
- Returns `[{ "id": "...", "name": "...", "folder": "...", "type": "..." }]`
|
||||
- Used by the edit dialog's parent selection autocomplete
|
||||
2. **Entry list template data** — include parent/child counts per entry row
|
||||
3. `**api_entry_patch`** — extend `EntryPatchBody` with optional `parent_ids: Option<Vec<Uuid>>`
|
||||
- When present, replace all parent relations for this entry with the given list
|
||||
- This is simpler than incremental add/remove in the Web UI context
|
||||
|
||||
3. **`api_entry_patch`** — extend `EntryPatchBody` with optional `parent_ids: Option<Vec<Uuid>>`
|
||||
- When present, replace all parent relations for this entry with the given list
|
||||
- This is simpler than incremental add/remove in the Web UI context
|
||||
|
||||
**`crates/secrets-mcp/templates/entries.html`**
|
||||
`**crates/secrets-mcp/templates/entries.html**`
|
||||
|
||||
1. **List table**: add a "关联" (relations) column showing parent/child counts as clickable chips
|
||||
2. **Edit dialog**: add "上级条目" (parent entries) section
|
||||
- Show current parents as removable chips
|
||||
- Add a search-as-you-type input that queries `/api/entries/options`
|
||||
- Click a search result to add it as parent
|
||||
- On save, send `parent_ids` in the PATCH body
|
||||
- Show current parents as removable chips
|
||||
- Add a search-as-you-type input that queries `/api/entries/options`
|
||||
- Click a search result to add it as parent
|
||||
- On save, send `parent_ids` in the PATCH body
|
||||
3. **View dialog / detail**: show "下级条目" (children) list with clickable links that navigate to the child entry
|
||||
4. **i18n**: add keys for all new UI elements
|
||||
|
||||
### i18n Keys (Entry Relations)
|
||||
|
||||
| Key | zh | zh-Hant | en |
|
||||
|-----|-----|---------|-----|
|
||||
| `colRelations` | 关联 | 關聯 | Relations |
|
||||
| `parentEntriesLabel` | 上级条目 | 上級條目 | Parent entries |
|
||||
| `childrenEntriesLabel` | 下级条目 | 下級條目 | Child entries |
|
||||
| `addParentLabel` | 添加上级 | 新增上級 | Add parent |
|
||||
| `removeParentLabel` | 移除上级 | 移除上級 | Remove parent |
|
||||
| `searchEntriesPlaceholder` | 搜索条目… | 搜尋條目… | Search entries… |
|
||||
| `noParents` | 无上级 | 無上級 | No parents |
|
||||
| `noChildren` | 无下级 | 無下級 | No children |
|
||||
| `relationCycleError` | 无法添加:会形成循环引用 | 無法新增:會形成循環引用 | Cannot add: would create a cycle |
|
||||
|
||||
| Key | zh | zh-Hant | en |
|
||||
| -------------------------- | ------------ | ------------ | -------------------------------- |
|
||||
| `colRelations` | 关联 | 關聯 | Relations |
|
||||
| `parentEntriesLabel` | 上级条目 | 上級條目 | Parent entries |
|
||||
| `childrenEntriesLabel` | 下级条目 | 下級條目 | Child entries |
|
||||
| `addParentLabel` | 添加上级 | 新增上級 | Add parent |
|
||||
| `removeParentLabel` | 移除上级 | 移除上級 | Remove parent |
|
||||
| `searchEntriesPlaceholder` | 搜索条目… | 搜尋條目… | Search entries… |
|
||||
| `noParents` | 无上级 | 無上級 | No parents |
|
||||
| `noChildren` | 无下级 | 無下級 | No children |
|
||||
| `relationCycleError` | 无法添加:会形成循环引用 | 無法新增:會形成循環引用 | Cannot add: would create a cycle |
|
||||
|
||||
|
||||
### Audit Logging
|
||||
|
||||
@@ -276,7 +273,7 @@ Log relation changes in the existing `audit::log_tx` system:
|
||||
|
||||
### Export / Import
|
||||
|
||||
**`ExportEntry`** — add optional `parents: Vec<ParentRef>` where:
|
||||
`**ExportEntry`** — add optional `parents: Vec<ParentRef>` where:
|
||||
|
||||
```rust
|
||||
pub struct ParentRef {
|
||||
@@ -368,25 +365,28 @@ This is idempotent (uses `IF NOT EXISTS`) and will run automatically on next sta
|
||||
## Testing Checklist
|
||||
|
||||
### Metadata Search
|
||||
- [ ] `metadata_query=1.2.3.4` matches entries where any metadata value contains "1.2.3.4"
|
||||
- [ ] `metadata_query=1.2.3.4` does NOT match entries where only the key contains "1.2.3.4"
|
||||
- [ ] `metadata_query` works with nested metadata (e.g. `{"server": {"ip": "1.2.3.4"}}`)
|
||||
- [ ] `metadata_query` combined with `folder`/`type`/`tags` filters works correctly
|
||||
- [ ] `metadata_query` with special characters (`%`, `_`) is properly escaped
|
||||
- [ ] Existing `query` parameter behavior is unchanged
|
||||
- [ ] Web filter bar preserves `metadata_query` across pagination and folder tab clicks
|
||||
|
||||
- `metadata_query=1.2.3.4` matches entries where any metadata value contains "1.2.3.4"
|
||||
- `metadata_query=1.2.3.4` does NOT match entries where only the key contains "1.2.3.4"
|
||||
- `metadata_query` works with nested metadata (e.g. `{"server": {"ip": "1.2.3.4"}}`)
|
||||
- `metadata_query` combined with `folder`/`type`/`tags` filters works correctly
|
||||
- `metadata_query` with special characters (`%`, `_`) is properly escaped
|
||||
- Existing `query` parameter behavior is unchanged
|
||||
- Web filter bar preserves `metadata_query` across pagination and folder tab clicks
|
||||
|
||||
### Entry Relations
|
||||
- [ ] Can add a parent→child relation between two entries
|
||||
- [ ] Can add multiple parents to a single entry
|
||||
- [ ] Cannot add self-referencing relation (CHECK constraint)
|
||||
- [ ] Cannot create a direct cycle (A→B→A)
|
||||
- [ ] Cannot create an indirect cycle (A→B→C→A)
|
||||
- [ ] Cannot link entries from different users
|
||||
- [ ] Deleting an entry removes all its relation edges but leaves related entries intact
|
||||
- [ ] MCP `secrets_add` with `parent_ids` creates relations
|
||||
- [ ] MCP `secrets_update` with `add_parent_ids`/`remove_parent_ids` modifies relations
|
||||
- [ ] MCP `secrets_find`/`secrets_search` output includes `parents` and `children`
|
||||
- [ ] Web entry list shows relation counts
|
||||
- [ ] Web edit dialog allows adding/removing parents
|
||||
- [ ] Web entry view shows children with navigation links
|
||||
|
||||
- Can add a parent→child relation between two entries
|
||||
- Can add multiple parents to a single entry
|
||||
- Cannot add self-referencing relation (CHECK constraint)
|
||||
- Cannot create a direct cycle (A→B→A)
|
||||
- Cannot create an indirect cycle (A→B→C→A)
|
||||
- Cannot link entries from different users
|
||||
- Deleting an entry removes all its relation edges but leaves related entries intact
|
||||
- MCP `secrets_add` with `parent_ids` creates relations
|
||||
- MCP `secrets_update` with `add_parent_ids`/`remove_parent_ids` modifies relations
|
||||
- MCP `secrets_find`/`secrets_search` output includes `parents` and `children`
|
||||
- Web entry list shows relation counts
|
||||
- Web edit dialog allows adding/removing parents
|
||||
- Web entry view shows children with navigation links
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
### 2. 查看密文弹窗 — 增加管理功能
|
||||
|
||||
在每个解密字段行中增加:
|
||||
|
||||
- **重命名输入框**(inline edit,带 debounce 校验)
|
||||
- **类型下拉选择**
|
||||
- **解绑按钮**
|
||||
|
||||
178
plans/web-tags-filter.md
Normal file
178
plans/web-tags-filter.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# Web 条目页 tags 筛选计划
|
||||
|
||||
## 目标
|
||||
|
||||
在 Web `/entries` 页面补齐 `tags` 筛选能力,使现有 `tags` 字段在 Web、MCP、数据层三者之间保持一致。
|
||||
|
||||
本次只做最小实现:支持用户在 Web 上输入 tags 条件并筛选条目,不改动数据库结构,不新增 MCP tool 参数,不改动条目编辑语义。
|
||||
|
||||
## 当前状态
|
||||
|
||||
- 数据层已支持 `tags` 过滤:`crates/secrets-core/src/service/search.rs`
|
||||
- MCP 已支持 `tags` 参数:`crates/secrets-mcp/src/tools.rs`
|
||||
- Web `/entries` 仅展示 tags 列与编辑字段,没有筛选入口:
|
||||
- 查询参数缺少 `tags`:`crates/secrets-mcp/src/web/entries.rs`
|
||||
- 模板筛选栏缺少 tags 输入:`crates/secrets-mcp/templates/entries.html`
|
||||
- Web 查询当前固定传 `tags: &[]`
|
||||
|
||||
## 范围
|
||||
|
||||
### 包含
|
||||
|
||||
- `/entries` 页面增加 tags 筛选输入
|
||||
- 后端将 tags 解析并传入 `SearchParams`
|
||||
- 分页、folder tabs、筛选重置后的 URL 状态保持一致
|
||||
- i18n 文案补齐
|
||||
|
||||
### 不包含
|
||||
|
||||
- MCP 工具改造
|
||||
- 数据库迁移或索引变更
|
||||
- `/trash` 页面筛选增强
|
||||
- 新增 tags 自动补全、标签选择器、标签管理页
|
||||
|
||||
## 交互定义
|
||||
|
||||
### 输入方式
|
||||
|
||||
- 在 `/entries` 筛选栏增加一个 `tags` 文本输入框
|
||||
- 输入格式采用逗号分隔,例如:`prod, aliyun`
|
||||
- 服务端按逗号拆分、`trim`、去掉空字符串
|
||||
|
||||
### 匹配语义
|
||||
|
||||
- 继续复用现有搜索层语义:`tags @> ARRAY[...]::text[]`
|
||||
- 即:用户输入多个 tags 时,要求条目同时包含这些 tags(AND 语义)
|
||||
|
||||
### 状态保持
|
||||
|
||||
- 筛选提交后,输入框保留原值
|
||||
- 分页上一页/下一页链接保留 `tags`
|
||||
- folder tabs 切换时保留 `tags`
|
||||
- `重置` 仍回到 `/entries`,清空所有筛选条件
|
||||
|
||||
## 实施步骤
|
||||
|
||||
### 1. 扩展 Web 查询参数与模板上下文
|
||||
|
||||
文件:`crates/secrets-mcp/src/web/entries.rs`
|
||||
|
||||
- 在 `EntriesQuery` 中增加 `tags: Option<String>`
|
||||
- 在 `EntriesPageTemplate` 中增加 `filter_tags: String`
|
||||
- 在 `entries_page` 中读取原始 tags 字符串,用于模板回填
|
||||
- 将原始字符串解析为 `Vec<String>`,供 `SearchParams.tags` 使用
|
||||
|
||||
建议新增一个局部辅助函数,职责仅限于:
|
||||
|
||||
- 接收 `Option<&str>`
|
||||
- 按逗号分割
|
||||
- `trim`
|
||||
- 过滤空值
|
||||
- 返回 `Vec<String>`
|
||||
|
||||
保持逻辑局部化,避免把 tags 解析散落到多个位置。
|
||||
|
||||
### 2. 将 tags 传入条目查询与计数
|
||||
|
||||
文件:`crates/secrets-mcp/src/web/entries.rs`
|
||||
|
||||
- 更新 `count_params`,不再使用 `tags: &[]`
|
||||
- 更新 `list_params`,复用相同 tags 切片
|
||||
- 确保总数统计、分页列表与实际筛选条件一致
|
||||
|
||||
## 3. 让 folder tabs 计数遵循相同 tags 条件
|
||||
|
||||
文件:`crates/secrets-mcp/src/web/entries.rs`
|
||||
|
||||
当前 folder tabs 使用手写 SQL 统计各 folder 数量,需要同步加入 tags 条件,否则会出现:
|
||||
|
||||
- 列表已按 tags 过滤
|
||||
- 但 folder tab 数量仍是未过滤结果
|
||||
|
||||
实现方式:
|
||||
|
||||
- 在构建 `folder_sql` 时,当 tags 非空,追加 `tags @> ARRAY[...]::text[]`
|
||||
- 对应补齐 bind 参数
|
||||
- 保持与 `SearchParams` 的过滤语义完全一致
|
||||
|
||||
## 4. 让 URL 生成函数保留 tags
|
||||
|
||||
文件:`crates/secrets-mcp/src/web/entries.rs`
|
||||
|
||||
- 扩展 `entries_href(...)` 参数,加入 `tags: Option<&str>`
|
||||
- 在 folder tabs 链接中传入当前 tags
|
||||
- 在需要保留筛选状态的地方一并传递 tags
|
||||
|
||||
## 5. 更新模板筛选栏与分页链接
|
||||
|
||||
文件:`crates/secrets-mcp/templates/entries.html`
|
||||
|
||||
- 在筛选表单中新增 tags 输入框
|
||||
- 输入框 value 绑定 `filter_tags`
|
||||
- 为 tags 输入框增加 i18n label / placeholder
|
||||
- 分页链接 `上一页/下一页` 补充 `tags` query 参数
|
||||
|
||||
建议放置位置:名称与元数据值之间或元数据值与类型之间,保持现有筛选栏布局最小改动。
|
||||
|
||||
## 6. 补齐前端文案
|
||||
|
||||
文件:`crates/secrets-mcp/templates/entries.html`
|
||||
|
||||
新增 i18n key:
|
||||
|
||||
- `filterTagsLabel`
|
||||
- `filterTagsPlaceholder`
|
||||
|
||||
建议文案:
|
||||
|
||||
- zh-CN: `标签` / `多个标签用逗号分隔`
|
||||
- zh-Hant: `標籤` / `多個標籤用逗號分隔`
|
||||
- en: `Tags` / `Comma-separated tags`
|
||||
|
||||
## 验收标准
|
||||
|
||||
### 功能验收
|
||||
|
||||
- 访问 `/entries?tags=prod` 时,只返回包含 `prod` 的条目
|
||||
- 访问 `/entries?tags=prod,aliyun` 时,只返回同时包含 `prod` 与 `aliyun` 的条目
|
||||
- tags 两侧空格不影响结果,例如 `prod, aliyun`
|
||||
- 空字符串、重复逗号不会报错,例如 `prod,,aliyun`
|
||||
- 分页后 `tags` 不丢失
|
||||
- 切换 folder tab 后 `tags` 不丢失
|
||||
- 重置后清空 `tags`
|
||||
|
||||
### 一致性验收
|
||||
|
||||
- 页面总数、列表内容、folder tab 数量使用同一组 tags 条件
|
||||
- Web 语义与 MCP / `SearchParams` 语义一致,均为 AND 匹配
|
||||
|
||||
## 风险与注意点
|
||||
|
||||
- folder tabs 计数 SQL 是手写的,最容易漏掉 tags 绑定顺序
|
||||
- `list_params` 基于 `count_params` 结构展开,注意借用生命周期不要引入临时值悬垂
|
||||
- 分页链接和 `entries_href` 若漏传 `tags`,用户会感觉筛选“偶尔失效”
|
||||
- 现阶段不做 tags 规范化;输入 `Prod` 与存储 `prod` 是否匹配,取决于数组元素本身是否完全一致
|
||||
|
||||
## 可选后续
|
||||
|
||||
如果上线后确认 `tags` 仍被频繁使用,可以继续做:
|
||||
|
||||
1. tags chip UI,而不是纯文本输入
|
||||
2. 常用 tags 自动补全
|
||||
3. 在 Web 过滤栏里明确提示“多个标签为同时匹配”
|
||||
4. 评估是否需要大小写规范化策略
|
||||
|
||||
## 验证建议
|
||||
|
||||
实现后至少执行:
|
||||
|
||||
```bash
|
||||
cargo fmt -- --check
|
||||
cargo test --locked
|
||||
```
|
||||
|
||||
如果本次提交涉及 `crates/**`,按仓库规则在提交前再执行:
|
||||
|
||||
```bash
|
||||
./scripts/release-check.sh
|
||||
```
|
||||
Reference in New Issue
Block a user