Compare commits
2 Commits
secrets-mc
...
secrets-mc
| Author | SHA1 | Date | |
|---|---|---|---|
| c3c536200e | |||
| 7909f7102d |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -1968,7 +1968,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "secrets-mcp"
|
name = "secrets-mcp"
|
||||||
version = "0.3.4"
|
version = "0.3.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"askama",
|
"askama",
|
||||||
|
|||||||
@@ -51,6 +51,34 @@ pub struct EntryRow {
|
|||||||
pub notes: String,
|
pub notes: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Entry row including `name` (used for id-scoped web / service updates).
|
||||||
|
#[derive(Debug, sqlx::FromRow)]
|
||||||
|
pub struct EntryWriteRow {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub version: i64,
|
||||||
|
pub folder: String,
|
||||||
|
#[sqlx(rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
|
pub name: String,
|
||||||
|
pub tags: Vec<String>,
|
||||||
|
pub metadata: Value,
|
||||||
|
pub notes: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&EntryWriteRow> for EntryRow {
|
||||||
|
fn from(r: &EntryWriteRow) -> Self {
|
||||||
|
EntryRow {
|
||||||
|
id: r.id,
|
||||||
|
version: r.version,
|
||||||
|
folder: r.folder.clone(),
|
||||||
|
entry_type: r.entry_type.clone(),
|
||||||
|
tags: r.tags.clone(),
|
||||||
|
metadata: r.metadata.clone(),
|
||||||
|
notes: r.notes.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Minimal secret field row fetched before snapshots or cascade deletes.
|
/// Minimal secret field row fetched before snapshots or cascade deletes.
|
||||||
#[derive(Debug, sqlx::FromRow)]
|
#[derive(Debug, sqlx::FromRow)]
|
||||||
pub struct SecretFieldRow {
|
pub struct SecretFieldRow {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use sqlx::PgPool;
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::db;
|
use crate::db;
|
||||||
use crate::models::{EntryRow, SecretFieldRow};
|
use crate::models::{EntryRow, EntryWriteRow, SecretFieldRow};
|
||||||
|
|
||||||
#[derive(Debug, serde::Serialize)]
|
#[derive(Debug, serde::Serialize)]
|
||||||
pub struct DeletedEntry {
|
pub struct DeletedEntry {
|
||||||
@@ -31,6 +31,62 @@ pub struct DeleteParams<'a> {
|
|||||||
pub user_id: Option<Uuid>,
|
pub user_id: Option<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Delete a single entry by id (multi-tenant: `user_id` must match). Cascades `secrets` via FK.
|
||||||
|
pub async fn delete_by_id(pool: &PgPool, entry_id: Uuid, user_id: Uuid) -> Result<DeleteResult> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
let row: Option<EntryWriteRow> = sqlx::query_as(
|
||||||
|
"SELECT id, version, folder, type, name, tags, metadata, notes FROM entries \
|
||||||
|
WHERE id = $1 AND user_id = $2 FOR UPDATE",
|
||||||
|
)
|
||||||
|
.bind(entry_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let row = match row {
|
||||||
|
Some(r) => r,
|
||||||
|
None => {
|
||||||
|
tx.rollback().await?;
|
||||||
|
anyhow::bail!("Entry not found");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let folder = row.folder.clone();
|
||||||
|
let entry_type = row.entry_type.clone();
|
||||||
|
let name = row.name.clone();
|
||||||
|
let entry_row: EntryRow = (&row).into();
|
||||||
|
|
||||||
|
snapshot_and_delete(
|
||||||
|
&mut tx,
|
||||||
|
&folder,
|
||||||
|
&entry_type,
|
||||||
|
&name,
|
||||||
|
&entry_row,
|
||||||
|
Some(user_id),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
crate::audit::log_tx(
|
||||||
|
&mut tx,
|
||||||
|
Some(user_id),
|
||||||
|
"delete",
|
||||||
|
&folder,
|
||||||
|
&entry_type,
|
||||||
|
&name,
|
||||||
|
json!({ "source": "web", "entry_id": entry_id }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
|
Ok(DeleteResult {
|
||||||
|
deleted: vec![DeletedEntry {
|
||||||
|
name,
|
||||||
|
folder,
|
||||||
|
entry_type,
|
||||||
|
}],
|
||||||
|
dry_run: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn run(pool: &PgPool, params: DeleteParams<'_>) -> Result<DeleteResult> {
|
pub async fn run(pool: &PgPool, params: DeleteParams<'_>) -> Result<DeleteResult> {
|
||||||
match params.name {
|
match params.name {
|
||||||
Some(name) => delete_one(pool, name, params.folder, params.dry_run, params.user_id).await,
|
Some(name) => delete_one(pool, name, params.folder, params.dry_run, params.user_id).await,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use crate::crypto;
|
use crate::crypto;
|
||||||
use crate::db;
|
use crate::db;
|
||||||
use crate::models::EntryRow;
|
use crate::models::{EntryRow, EntryWriteRow};
|
||||||
use crate::service::add::{
|
use crate::service::add::{
|
||||||
collect_field_paths, collect_key_paths, flatten_json_fields, insert_path, parse_key_path,
|
collect_field_paths, collect_key_paths, flatten_json_fields, insert_path, parse_key_path,
|
||||||
parse_kv, remove_path,
|
parse_kv, remove_path,
|
||||||
@@ -306,3 +306,118 @@ pub async fn run(
|
|||||||
remove_secrets: remove_secret_keys,
|
remove_secrets: remove_secret_keys,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Update non-sensitive entry columns by primary key (multi-tenant: `user_id` must match).
|
||||||
|
/// Does not read or modify `secrets` rows.
|
||||||
|
pub struct UpdateEntryFieldsByIdParams<'a> {
|
||||||
|
pub folder: &'a str,
|
||||||
|
pub entry_type: &'a str,
|
||||||
|
pub name: &'a str,
|
||||||
|
pub notes: &'a str,
|
||||||
|
pub tags: &'a [String],
|
||||||
|
pub metadata: &'a serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_fields_by_id(
|
||||||
|
pool: &PgPool,
|
||||||
|
entry_id: Uuid,
|
||||||
|
user_id: Uuid,
|
||||||
|
params: UpdateEntryFieldsByIdParams<'_>,
|
||||||
|
) -> Result<()> {
|
||||||
|
if params.folder.len() > 128 {
|
||||||
|
anyhow::bail!("folder must be at most 128 characters");
|
||||||
|
}
|
||||||
|
if params.entry_type.len() > 64 {
|
||||||
|
anyhow::bail!("type must be at most 64 characters");
|
||||||
|
}
|
||||||
|
if params.name.len() > 256 {
|
||||||
|
anyhow::bail!("name must be at most 256 characters");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
|
let row: Option<EntryWriteRow> = sqlx::query_as(
|
||||||
|
"SELECT id, version, folder, type, name, tags, metadata, notes FROM entries \
|
||||||
|
WHERE id = $1 AND user_id = $2 FOR UPDATE",
|
||||||
|
)
|
||||||
|
.bind(entry_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let row = match row {
|
||||||
|
Some(r) => r,
|
||||||
|
None => {
|
||||||
|
tx.rollback().await?;
|
||||||
|
anyhow::bail!("Entry not found");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(e) = db::snapshot_entry_history(
|
||||||
|
&mut tx,
|
||||||
|
db::EntrySnapshotParams {
|
||||||
|
entry_id: row.id,
|
||||||
|
user_id: Some(user_id),
|
||||||
|
folder: &row.folder,
|
||||||
|
entry_type: &row.entry_type,
|
||||||
|
name: &row.name,
|
||||||
|
version: row.version,
|
||||||
|
action: "update",
|
||||||
|
tags: &row.tags,
|
||||||
|
metadata: &row.metadata,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(error = %e, "failed to snapshot entry history before web update");
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = sqlx::query(
|
||||||
|
"UPDATE entries SET folder = $1, type = $2, name = $3, notes = $4, tags = $5, metadata = $6, \
|
||||||
|
version = version + 1, updated_at = NOW() \
|
||||||
|
WHERE id = $7 AND version = $8",
|
||||||
|
)
|
||||||
|
.bind(params.folder)
|
||||||
|
.bind(params.entry_type)
|
||||||
|
.bind(params.name)
|
||||||
|
.bind(params.notes)
|
||||||
|
.bind(params.tags)
|
||||||
|
.bind(params.metadata)
|
||||||
|
.bind(row.id)
|
||||||
|
.bind(row.version)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
if let sqlx::Error::Database(ref d) = e
|
||||||
|
&& d.code().as_deref() == Some("23505")
|
||||||
|
{
|
||||||
|
return anyhow::anyhow!(
|
||||||
|
"An entry with this folder and name already exists for your account."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
e.into()
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if res.rows_affected() == 0 {
|
||||||
|
tx.rollback().await?;
|
||||||
|
anyhow::bail!("Concurrent modification detected. Please refresh and try again.");
|
||||||
|
}
|
||||||
|
|
||||||
|
crate::audit::log_tx(
|
||||||
|
&mut tx,
|
||||||
|
Some(user_id),
|
||||||
|
"update",
|
||||||
|
params.folder,
|
||||||
|
params.entry_type,
|
||||||
|
params.name,
|
||||||
|
serde_json::json!({
|
||||||
|
"source": "web",
|
||||||
|
"entry_id": entry_id,
|
||||||
|
"fields": ["folder", "type", "name", "notes", "tags", "metadata"],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "secrets-mcp"
|
name = "secrets-mcp"
|
||||||
version = "0.3.4"
|
version = "0.3.6"
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
|
|||||||
@@ -8,9 +8,10 @@ use axum::{
|
|||||||
extract::{ConnectInfo, Path, Query, State},
|
extract::{ConnectInfo, Path, Query, State},
|
||||||
http::{HeaderMap, StatusCode, header},
|
http::{HeaderMap, StatusCode, header},
|
||||||
response::{Html, IntoResponse, Redirect, Response},
|
response::{Html, IntoResponse, Redirect, Response},
|
||||||
routing::{get, post},
|
routing::{get, patch, post},
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::json;
|
||||||
use tower_sessions::Session;
|
use tower_sessions::Session;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
@@ -19,7 +20,9 @@ use secrets_core::crypto::hex;
|
|||||||
use secrets_core::service::{
|
use secrets_core::service::{
|
||||||
api_key::{ensure_api_key, regenerate_api_key},
|
api_key::{ensure_api_key, regenerate_api_key},
|
||||||
audit_log::list_for_user,
|
audit_log::list_for_user,
|
||||||
|
delete::delete_by_id,
|
||||||
search::{SearchParams, count_entries, list_entries},
|
search::{SearchParams, count_entries, list_entries},
|
||||||
|
update::{UpdateEntryFieldsByIdParams, update_fields_by_id},
|
||||||
user::{
|
user::{
|
||||||
OAuthProfile, bind_oauth_account, find_or_create_user, get_user_by_id,
|
OAuthProfile, bind_oauth_account, find_or_create_user, get_user_by_id,
|
||||||
unbind_oauth_account, update_user_key_setup,
|
unbind_oauth_account, update_user_key_setup,
|
||||||
@@ -88,11 +91,14 @@ struct EntriesPageTemplate {
|
|||||||
total_count: i64,
|
total_count: i64,
|
||||||
shown_count: usize,
|
shown_count: usize,
|
||||||
limit: u32,
|
limit: u32,
|
||||||
|
filter_folder: String,
|
||||||
|
filter_type: String,
|
||||||
version: &'static str,
|
version: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Non-sensitive fields only (no `secrets` / ciphertext).
|
/// Non-sensitive fields only (no `secrets` / ciphertext).
|
||||||
struct EntryListItemView {
|
struct EntryListItemView {
|
||||||
|
id: String,
|
||||||
folder: String,
|
folder: String,
|
||||||
entry_type: String,
|
entry_type: String,
|
||||||
name: String,
|
name: String,
|
||||||
@@ -106,6 +112,14 @@ struct EntryListItemView {
|
|||||||
/// Cap for HTML list (avoids loading unbounded rows into memory).
|
/// Cap for HTML list (avoids loading unbounded rows into memory).
|
||||||
const ENTRIES_PAGE_LIMIT: u32 = 5_000;
|
const ENTRIES_PAGE_LIMIT: u32 = 5_000;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct EntriesQuery {
|
||||||
|
folder: Option<String>,
|
||||||
|
/// URL query key is `type` (maps to DB column `entries.type`).
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
entry_type: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
// ── App state helpers ─────────────────────────────────────────────────────────
|
// ── App state helpers ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
||||||
@@ -189,6 +203,10 @@ pub fn web_router() -> Router<AppState> {
|
|||||||
.route("/api/key-setup", post(api_key_setup))
|
.route("/api/key-setup", post(api_key_setup))
|
||||||
.route("/api/apikey", get(api_apikey_get))
|
.route("/api/apikey", get(api_apikey_get))
|
||||||
.route("/api/apikey/regenerate", post(api_apikey_regenerate))
|
.route("/api/apikey/regenerate", post(api_apikey_regenerate))
|
||||||
|
.route(
|
||||||
|
"/api/entries/{id}",
|
||||||
|
patch(api_entry_patch).delete(api_entry_delete),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn text_asset_response(content: &'static str, content_type: &'static str) -> Response {
|
fn text_asset_response(content: &'static str, content_type: &'static str) -> Response {
|
||||||
@@ -510,6 +528,7 @@ async fn dashboard(
|
|||||||
async fn entries_page(
|
async fn entries_page(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
session: Session,
|
session: Session,
|
||||||
|
Query(q): Query<EntriesQuery>,
|
||||||
) -> Result<Response, StatusCode> {
|
) -> Result<Response, StatusCode> {
|
||||||
let Some(user_id) = current_user_id(&session).await else {
|
let Some(user_id) = current_user_id(&session).await else {
|
||||||
return Ok(Redirect::to("/login").into_response());
|
return Ok(Redirect::to("/login").into_response());
|
||||||
@@ -523,9 +542,22 @@ async fn entries_page(
|
|||||||
None => return Ok(Redirect::to("/login").into_response()),
|
None => return Ok(Redirect::to("/login").into_response()),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let folder_filter = q
|
||||||
|
.folder
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.trim())
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
let type_filter = q
|
||||||
|
.entry_type
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.trim())
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
|
||||||
let params = SearchParams {
|
let params = SearchParams {
|
||||||
folder: None,
|
folder: folder_filter.as_deref(),
|
||||||
entry_type: None,
|
entry_type: type_filter.as_deref(),
|
||||||
name: None,
|
name: None,
|
||||||
tags: &[],
|
tags: &[],
|
||||||
query: None,
|
query: None,
|
||||||
@@ -549,6 +581,7 @@ async fn entries_page(
|
|||||||
let entries = rows
|
let entries = rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|e| EntryListItemView {
|
.map(|e| EntryListItemView {
|
||||||
|
id: e.id.to_string(),
|
||||||
folder: e.folder,
|
folder: e.folder,
|
||||||
entry_type: e.entry_type,
|
entry_type: e.entry_type,
|
||||||
name: e.name,
|
name: e.name,
|
||||||
@@ -567,6 +600,8 @@ async fn entries_page(
|
|||||||
total_count,
|
total_count,
|
||||||
shown_count,
|
shown_count,
|
||||||
limit: ENTRIES_PAGE_LIMIT,
|
limit: ENTRIES_PAGE_LIMIT,
|
||||||
|
filter_folder: folder_filter.unwrap_or_default(),
|
||||||
|
filter_type: type_filter.unwrap_or_default(),
|
||||||
version: env!("CARGO_PKG_VERSION"),
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -846,6 +881,122 @@ async fn api_apikey_regenerate(
|
|||||||
Ok(Json(ApiKeyResponse { api_key }))
|
Ok(Json(ApiKeyResponse { api_key }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Entry management (Web UI, non-sensitive fields only) ───────────────────────
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct EntryPatchBody {
|
||||||
|
folder: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
entry_type: String,
|
||||||
|
name: String,
|
||||||
|
notes: String,
|
||||||
|
tags: Vec<String>,
|
||||||
|
metadata: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
type EntryApiError = (StatusCode, Json<serde_json::Value>);
|
||||||
|
|
||||||
|
fn map_entry_mutation_err(e: anyhow::Error) -> EntryApiError {
|
||||||
|
let msg = e.to_string();
|
||||||
|
if msg.contains("Entry not found") {
|
||||||
|
return (
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
Json(json!({ "error": "条目不存在或无权访问" })),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if msg.contains("already exists") {
|
||||||
|
return (
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
Json(json!({ "error": "该账号下已存在相同 folder + name 的条目" })),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if msg.contains("Concurrent modification") {
|
||||||
|
return (
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
Json(json!({ "error": "条目已被修改,请刷新后重试" })),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if msg.contains("must be at most") {
|
||||||
|
return (StatusCode::BAD_REQUEST, Json(json!({ "error": msg })));
|
||||||
|
}
|
||||||
|
tracing::error!(error = %e, "entry mutation failed");
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Json(json!({ "error": "操作失败,请稍后重试" })),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn api_entry_patch(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
session: Session,
|
||||||
|
Path(entry_id): Path<Uuid>,
|
||||||
|
Json(body): Json<EntryPatchBody>,
|
||||||
|
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||||
|
let user_id = current_user_id(&session)
|
||||||
|
.await
|
||||||
|
.ok_or((StatusCode::UNAUTHORIZED, Json(json!({ "error": "未登录" }))))?;
|
||||||
|
|
||||||
|
let folder = body.folder.trim();
|
||||||
|
let entry_type = body.entry_type.trim();
|
||||||
|
let name = body.name.trim();
|
||||||
|
let notes = body.notes.trim();
|
||||||
|
|
||||||
|
if name.is_empty() {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
Json(json!({ "error": "name 不能为空" })),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let tags: Vec<String> = body
|
||||||
|
.tags
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| t.trim().to_string())
|
||||||
|
.filter(|t| !t.is_empty())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if !body.metadata.is_object() {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
Json(json!({ "error": "metadata 必须是 JSON 对象" })),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
update_fields_by_id(
|
||||||
|
&state.pool,
|
||||||
|
entry_id,
|
||||||
|
user_id,
|
||||||
|
UpdateEntryFieldsByIdParams {
|
||||||
|
folder,
|
||||||
|
entry_type,
|
||||||
|
name,
|
||||||
|
notes,
|
||||||
|
tags: &tags,
|
||||||
|
metadata: &body.metadata,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(map_entry_mutation_err)?;
|
||||||
|
|
||||||
|
Ok(Json(json!({ "ok": true })))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn api_entry_delete(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
session: Session,
|
||||||
|
Path(entry_id): Path<Uuid>,
|
||||||
|
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||||
|
let user_id = current_user_id(&session)
|
||||||
|
.await
|
||||||
|
.ok_or((StatusCode::UNAUTHORIZED, Json(json!({ "error": "未登录" }))))?;
|
||||||
|
|
||||||
|
delete_by_id(&state.pool, entry_id, user_id)
|
||||||
|
.await
|
||||||
|
.map_err(map_entry_mutation_err)?;
|
||||||
|
|
||||||
|
Ok(Json(json!({ "ok": true })))
|
||||||
|
}
|
||||||
|
|
||||||
// ── OAuth / Well-known ────────────────────────────────────────────────────────
|
// ── OAuth / Well-known ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/// RFC 9728 — OAuth 2.0 Protected Resource Metadata.
|
/// RFC 9728 — OAuth 2.0 Protected Resource Metadata.
|
||||||
|
|||||||
@@ -48,6 +48,30 @@
|
|||||||
padding: 24px; width: 100%; max-width: 1280px; margin: 0 auto; }
|
padding: 24px; width: 100%; max-width: 1280px; margin: 0 auto; }
|
||||||
.card-title { font-size: 20px; font-weight: 600; margin-bottom: 8px; }
|
.card-title { font-size: 20px; font-weight: 600; margin-bottom: 8px; }
|
||||||
.card-subtitle { color: var(--text-muted); font-size: 13px; margin-bottom: 20px; }
|
.card-subtitle { color: var(--text-muted); font-size: 13px; margin-bottom: 20px; }
|
||||||
|
.filter-bar {
|
||||||
|
display: flex; flex-wrap: wrap; align-items: flex-end; gap: 12px 16px;
|
||||||
|
margin-bottom: 20px; padding: 16px; background: var(--bg); border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
.filter-field { display: flex; flex-direction: column; gap: 6px; min-width: 140px; flex: 1; }
|
||||||
|
.filter-field label { font-size: 12px; color: var(--text-muted); font-weight: 500; }
|
||||||
|
.filter-field input {
|
||||||
|
background: var(--surface); border: 1px solid var(--border); border-radius: 6px;
|
||||||
|
color: var(--text); padding: 8px 10px; font-size: 13px; font-family: 'JetBrains Mono', monospace;
|
||||||
|
outline: none; width: 100%;
|
||||||
|
}
|
||||||
|
.filter-field input:focus { border-color: var(--accent); }
|
||||||
|
.filter-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||||
|
.btn-filter {
|
||||||
|
padding: 8px 16px; border-radius: 6px; border: none; background: var(--accent); color: #0d1117;
|
||||||
|
font-size: 13px; font-weight: 600; cursor: pointer;
|
||||||
|
}
|
||||||
|
.btn-filter:hover { background: var(--accent-hover); }
|
||||||
|
.btn-clear {
|
||||||
|
padding: 8px 14px; border-radius: 6px; border: 1px solid var(--border); background: transparent;
|
||||||
|
color: var(--text-muted); font-size: 13px; text-decoration: none; cursor: pointer;
|
||||||
|
}
|
||||||
|
.btn-clear:hover { background: var(--surface2); color: var(--text); }
|
||||||
.empty { color: var(--text-muted); font-size: 14px; padding: 20px 0; }
|
.empty { color: var(--text-muted); font-size: 14px; padding: 20px 0; }
|
||||||
.table-wrap { overflow-x: auto; }
|
.table-wrap { overflow-x: auto; }
|
||||||
table { width: 100%; border-collapse: collapse; min-width: 720px; }
|
table { width: 100%; border-collapse: collapse; min-width: 720px; }
|
||||||
@@ -58,11 +82,58 @@
|
|||||||
.cell-notes, .cell-meta {
|
.cell-notes, .cell-meta {
|
||||||
max-width: 280px; word-break: break-word;
|
max-width: 280px; word-break: break-word;
|
||||||
}
|
}
|
||||||
|
.notes-scroll {
|
||||||
|
max-height: 160px;
|
||||||
|
overflow: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
padding: 8px;
|
||||||
|
background: var(--bg);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
.detail {
|
.detail {
|
||||||
background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
|
background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
|
||||||
padding: 10px; white-space: pre-wrap; word-break: break-word; font-size: 12px;
|
padding: 10px; white-space: pre-wrap; word-break: break-word; font-size: 12px;
|
||||||
max-width: 320px; max-height: 160px; overflow: auto;
|
max-width: 320px; max-height: 160px; overflow: auto;
|
||||||
}
|
}
|
||||||
|
.col-actions { white-space: nowrap; }
|
||||||
|
.row-actions { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
.btn-row {
|
||||||
|
padding: 4px 10px; border-radius: 6px; font-size: 12px; cursor: pointer;
|
||||||
|
border: 1px solid var(--border); background: var(--surface2); color: var(--text-muted);
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
.btn-row:hover { color: var(--text); border-color: var(--text-muted); }
|
||||||
|
.btn-row.danger:hover { border-color: #f85149; color: #f85149; }
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed; inset: 0; background: rgba(1, 4, 9, 0.65); z-index: 200;
|
||||||
|
display: flex; align-items: center; justify-content: center; padding: 16px;
|
||||||
|
}
|
||||||
|
.modal-overlay[hidden] { display: none !important; }
|
||||||
|
.modal {
|
||||||
|
background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
|
||||||
|
padding: 22px; width: 100%; max-width: 520px; max-height: 90vh; overflow: auto;
|
||||||
|
box-shadow: 0 16px 48px rgba(0,0,0,0.45);
|
||||||
|
}
|
||||||
|
.modal-title { font-size: 16px; font-weight: 600; margin-bottom: 14px; }
|
||||||
|
.modal-field { margin-bottom: 12px; }
|
||||||
|
.modal-field label { display: block; font-size: 12px; color: var(--text-muted); margin-bottom: 5px; }
|
||||||
|
.modal-field input, .modal-field textarea {
|
||||||
|
width: 100%; background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
|
||||||
|
color: var(--text); padding: 8px 10px; font-size: 13px; font-family: 'JetBrains Mono', monospace;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.modal-field textarea { min-height: 72px; resize: vertical; }
|
||||||
|
.modal-field textarea.metadata-edit { min-height: 140px; }
|
||||||
|
.modal-error { color: #f85149; font-size: 12px; margin-bottom: 10px; display: none; }
|
||||||
|
.modal-error.visible { display: block; }
|
||||||
|
.modal-footer { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; margin-top: 16px; }
|
||||||
|
.btn-modal { padding: 8px 16px; border-radius: 6px; font-size: 13px; cursor: pointer; font-family: inherit; border: 1px solid var(--border); background: transparent; color: var(--text); }
|
||||||
|
.btn-modal.primary { background: var(--accent); color: #0d1117; border-color: transparent; font-weight: 600; }
|
||||||
|
.btn-modal.primary:hover { background: var(--accent-hover); }
|
||||||
|
.btn-modal.danger { border-color: #f85149; color: #f85149; }
|
||||||
@media (max-width: 900px) {
|
@media (max-width: 900px) {
|
||||||
.layout { flex-direction: column; }
|
.layout { flex-direction: column; }
|
||||||
.sidebar {
|
.sidebar {
|
||||||
@@ -89,7 +160,9 @@
|
|||||||
td.col-notes::before { content: "Notes"; }
|
td.col-notes::before { content: "Notes"; }
|
||||||
td.col-tags::before { content: "Tags"; }
|
td.col-tags::before { content: "Tags"; }
|
||||||
td.col-meta::before { content: "Metadata"; }
|
td.col-meta::before { content: "Metadata"; }
|
||||||
|
td.col-actions::before { content: "操作"; }
|
||||||
.detail { max-width: none; }
|
.detail { max-width: none; }
|
||||||
|
.notes-scroll { max-width: none; }
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
@@ -116,7 +189,22 @@
|
|||||||
<main class="main">
|
<main class="main">
|
||||||
<section class="card">
|
<section class="card">
|
||||||
<div class="card-title">我的条目</div>
|
<div class="card-title">我的条目</div>
|
||||||
<div class="card-subtitle">共 <strong>{{ total_count }}</strong> 条记录;当前列表显示 <strong>{{ shown_count }}</strong> 条(按更新时间降序,单页最多 {{ limit }} 条)。不含密文字段。时间为浏览器本地时区。</div>
|
<div class="card-subtitle">在当前筛选条件下,共 <strong>{{ total_count }}</strong> 条记录;本页显示 <strong>{{ shown_count }}</strong> 条(按更新时间降序,单页最多 {{ limit }} 条)。不含密文字段。时间为浏览器本地时区。</div>
|
||||||
|
|
||||||
|
<form class="filter-bar" method="get" action="/entries">
|
||||||
|
<div class="filter-field">
|
||||||
|
<label for="filter-folder">Folder(精确匹配)</label>
|
||||||
|
<input id="filter-folder" name="folder" type="text" value="{{ filter_folder }}" placeholder="例如 refining" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<div class="filter-field">
|
||||||
|
<label for="filter-type">Type(精确匹配)</label>
|
||||||
|
<input id="filter-type" name="type" type="text" value="{{ filter_type }}" placeholder="例如 server" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<div class="filter-actions">
|
||||||
|
<button type="submit" class="btn-filter">筛选</button>
|
||||||
|
<a href="/entries" class="btn-clear">清空</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
{% if entries.is_empty() %}
|
{% if entries.is_empty() %}
|
||||||
<div class="empty">暂无条目。</div>
|
<div class="empty">暂无条目。</div>
|
||||||
@@ -132,18 +220,25 @@
|
|||||||
<th>Notes</th>
|
<th>Notes</th>
|
||||||
<th>Tags</th>
|
<th>Tags</th>
|
||||||
<th>Metadata</th>
|
<th>Metadata</th>
|
||||||
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for entry in entries %}
|
{% for entry in entries %}
|
||||||
<tr>
|
<tr data-entry-id="{{ entry.id }}">
|
||||||
<td class="col-updated mono"><time class="entry-local-time" datetime="{{ entry.updated_at_iso }}">{{ entry.updated_at_iso }}</time></td>
|
<td class="col-updated mono"><time class="entry-local-time" datetime="{{ entry.updated_at_iso }}">{{ entry.updated_at_iso }}</time></td>
|
||||||
<td class="col-folder mono">{{ entry.folder }}</td>
|
<td class="col-folder mono cell-folder">{{ entry.folder }}</td>
|
||||||
<td class="col-type mono">{{ entry.entry_type }}</td>
|
<td class="col-type mono cell-type">{{ entry.entry_type }}</td>
|
||||||
<td class="col-name mono">{{ entry.name }}</td>
|
<td class="col-name mono cell-name">{{ entry.name }}</td>
|
||||||
<td class="col-notes cell-notes">{{ entry.notes }}</td>
|
<td class="col-notes cell-notes">{% if !entry.notes.is_empty() %}<div class="notes-scroll cell-notes-val">{{ entry.notes }}</div>{% endif %}</td>
|
||||||
<td class="col-tags mono">{{ entry.tags }}</td>
|
<td class="col-tags mono cell-tags-val">{{ entry.tags }}</td>
|
||||||
<td class="col-meta cell-meta"><pre class="detail">{{ entry.metadata }}</pre></td>
|
<td class="col-meta cell-meta"><pre class="detail cell-meta-val">{{ entry.metadata }}</pre></td>
|
||||||
|
<td class="col-actions">
|
||||||
|
<div class="row-actions">
|
||||||
|
<button type="button" class="btn-row btn-edit">编辑</button>
|
||||||
|
<button type="button" class="btn-row danger btn-del">删除</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -154,6 +249,23 @@
|
|||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div id="edit-overlay" class="modal-overlay" hidden>
|
||||||
|
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="edit-title">
|
||||||
|
<div class="modal-title" id="edit-title">编辑条目</div>
|
||||||
|
<div id="edit-error" class="modal-error"></div>
|
||||||
|
<div class="modal-field"><label for="edit-folder">Folder</label><input id="edit-folder" type="text" autocomplete="off"></div>
|
||||||
|
<div class="modal-field"><label for="edit-type">Type</label><input id="edit-type" type="text" autocomplete="off"></div>
|
||||||
|
<div class="modal-field"><label for="edit-name">Name</label><input id="edit-name" type="text" autocomplete="off"></div>
|
||||||
|
<div class="modal-field"><label for="edit-notes">Notes</label><textarea id="edit-notes"></textarea></div>
|
||||||
|
<div class="modal-field"><label for="edit-tags">Tags(逗号分隔)</label><input id="edit-tags" type="text" autocomplete="off"></div>
|
||||||
|
<div class="modal-field"><label for="edit-metadata">Metadata(JSON 对象)</label><textarea id="edit-metadata" class="metadata-edit"></textarea></div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn-modal" id="edit-cancel">取消</button>
|
||||||
|
<button type="button" class="btn-modal primary" id="edit-save">保存</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
document.querySelectorAll('time.entry-local-time[datetime]').forEach(function (el) {
|
document.querySelectorAll('time.entry-local-time[datetime]').forEach(function (el) {
|
||||||
@@ -164,6 +276,109 @@
|
|||||||
el.title = raw + ' (UTC)';
|
el.title = raw + ' (UTC)';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
var editOverlay = document.getElementById('edit-overlay');
|
||||||
|
var editError = document.getElementById('edit-error');
|
||||||
|
var editFolder = document.getElementById('edit-folder');
|
||||||
|
var editType = document.getElementById('edit-type');
|
||||||
|
var editName = document.getElementById('edit-name');
|
||||||
|
var editNotes = document.getElementById('edit-notes');
|
||||||
|
var editTags = document.getElementById('edit-tags');
|
||||||
|
var editMetadata = document.getElementById('edit-metadata');
|
||||||
|
var currentEntryId = null;
|
||||||
|
|
||||||
|
function showEditErr(msg) {
|
||||||
|
editError.textContent = msg || '';
|
||||||
|
editError.classList.toggle('visible', !!msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(tr) {
|
||||||
|
var id = tr.getAttribute('data-entry-id');
|
||||||
|
if (!id) return;
|
||||||
|
currentEntryId = id;
|
||||||
|
showEditErr('');
|
||||||
|
editFolder.value = tr.querySelector('.cell-folder') ? tr.querySelector('.cell-folder').textContent.trim() : '';
|
||||||
|
editType.value = tr.querySelector('.cell-type') ? tr.querySelector('.cell-type').textContent.trim() : '';
|
||||||
|
editName.value = tr.querySelector('.cell-name') ? tr.querySelector('.cell-name').textContent.trim() : '';
|
||||||
|
editNotes.value = tr.querySelector('.cell-notes-val') ? tr.querySelector('.cell-notes-val').textContent : '';
|
||||||
|
var tagsText = tr.querySelector('.cell-tags-val') ? tr.querySelector('.cell-tags-val').textContent.trim() : '';
|
||||||
|
editTags.value = tagsText;
|
||||||
|
var metaPre = tr.querySelector('.cell-meta-val');
|
||||||
|
editMetadata.value = metaPre ? metaPre.textContent : '{}';
|
||||||
|
editOverlay.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeEdit() {
|
||||||
|
editOverlay.hidden = true;
|
||||||
|
currentEntryId = null;
|
||||||
|
showEditErr('');
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('edit-cancel').addEventListener('click', closeEdit);
|
||||||
|
editOverlay.addEventListener('click', function (e) {
|
||||||
|
if (e.target === editOverlay) closeEdit();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('edit-save').addEventListener('click', function () {
|
||||||
|
if (!currentEntryId) return;
|
||||||
|
var meta;
|
||||||
|
try {
|
||||||
|
meta = JSON.parse(editMetadata.value);
|
||||||
|
} catch (err) {
|
||||||
|
showEditErr('Metadata 不是合法 JSON');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) {
|
||||||
|
showEditErr('Metadata 必须是 JSON 对象');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var tags = editTags.value.split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
||||||
|
var body = {
|
||||||
|
folder: editFolder.value,
|
||||||
|
type: editType.value,
|
||||||
|
name: editName.value.trim(),
|
||||||
|
notes: editNotes.value,
|
||||||
|
tags: tags,
|
||||||
|
metadata: meta
|
||||||
|
};
|
||||||
|
showEditErr('');
|
||||||
|
fetch('/api/entries/' + encodeURIComponent(currentEntryId), {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
credentials: 'same-origin',
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
}).then(function (r) {
|
||||||
|
return r.json().then(function (data) {
|
||||||
|
if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status));
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
}).then(function () {
|
||||||
|
closeEdit();
|
||||||
|
window.location.reload();
|
||||||
|
}).catch(function (e) {
|
||||||
|
showEditErr(e.message || String(e));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll('tr[data-entry-id]').forEach(function (tr) {
|
||||||
|
tr.querySelector('.btn-edit').addEventListener('click', function () { openEdit(tr); });
|
||||||
|
tr.querySelector('.btn-del').addEventListener('click', function () {
|
||||||
|
var id = tr.getAttribute('data-entry-id');
|
||||||
|
var nameEl = tr.querySelector('.cell-name');
|
||||||
|
var name = nameEl ? nameEl.textContent.trim() : '';
|
||||||
|
if (!id) return;
|
||||||
|
if (!confirm('确定删除条目「' + name + '」?关联的密文字段将一并删除。')) return;
|
||||||
|
fetch('/api/entries/' + encodeURIComponent(id), { method: 'DELETE', credentials: 'same-origin' })
|
||||||
|
.then(function (r) {
|
||||||
|
return r.json().then(function (data) {
|
||||||
|
if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status));
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function () { window.location.reload(); })
|
||||||
|
.catch(function (e) { alert(e.message || String(e)); });
|
||||||
|
});
|
||||||
|
});
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
Reference in New Issue
Block a user