Files
memoryweave/go/internal/api/routes/obsidian.go
T
小唯 e91ca91367 fix(security): 写入侧凭证过滤 — 密钥不再进记忆/图谱/Obsidian 镜像
背景(2026-09-10 mc P0 事故):某轮蒸馏把含真 Tailscale 预授权 key 的原始对话
当事实入库 → 知识图谱按其文本建实体 → ObsidianSyncer 用实体标题当文件名/正文,
把 tskey-auth-… 落成可读镜像文件,又被 git 跟踪并推送 Gitea。
本提交在三个写入边界统一加脱敏。

新增 internal/redact(唯一真源):
- SecretPattern 覆盖 sk- / tskey- / github_pat_ / ghp_ / nvapi- / AKIA
- Go RE2 不支持 lookbehind,故"前一字符是否属于更长标识符"手工判定(isTokenByte)
- sk- 段只吃 [A-Za-z0-9],避免误伤 URL 里的 task-driven 片段(事故中的假阳性来源)
- RedactSecrets 幂等;ContainsSecret 供"直接丢弃"场景用

四处接入:
- distill/quality.go       IsQualityFact 判定前脱敏 + FilterQualityFacts 返回值脱敏
- governance/graph_auto.go cleanEntityName 命中→空串;UpdateFromDistill 只对有效实体
                           建节点/建边;extractEntitiesFromText 过滤;含凭证的 fact 不建节点
- api/routes/obsidian.go   sanitizeFilename 入参脱敏 + PushToObsidian 镜像正文脱敏
- api/server.go            蒸馏直写记忆库路径(绕过 FilterQualityFacts 的那条)同步脱敏

测试:13 条新用例(redact 5 / distill 3 / governance 4 / routes 1),
含 URL 假阳性回归与幂等性断言。全部使用构造的假密钥,不含任何真实凭证。
证据:go build ./... OK;
go test -count=1 ./internal/redact/ ./internal/distill/ ./internal/governance/ ./internal/api/routes/ 全绿。

顺带修既有 test 腐化(否则 governance 包根本无法编译测试,非本任务引入):
governance_test.go isContradiction→IsContradiction、Navigate 补 relFilter 参数;
bench_test.go 同。仅测试文件,无生产行为改动。
2026-09-11 00:41:59 +08:00

440 lines
11 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 MemoryWeave — Obsidian 双向同步
package routes
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unicode"
"github.com/xiaoxue/memoryweave/internal/redact"
"github.com/xiaoxue/memoryweave/internal/storage"
)
// ObsidianSyncer 双向同步织忆与 Obsidian 知识库
type ObsidianSyncer struct {
vaultPath string
ldb storage.LanceDB
mu sync.Mutex
lastSync time.Time
}
var Obsidian *ObsidianSyncer
func NewObsidianSyncer(vaultPath string, ldb storage.LanceDB) *ObsidianSyncer {
s := &ObsidianSyncer{
vaultPath: vaultPath,
ldb: ldb,
}
Obsidian = s
return s
}
// PushToObsidian 推送织忆记忆到 Obsidian(默认 vault)
func (s *ObsidianSyncer) PushToObsidian(memories []map[string]interface{}, folder string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.vaultPath == "" {
s.vaultPath = os.Getenv("OBSIDIAN_VAULT")
if s.vaultPath == "" {
s.vaultPath = fmt.Sprintf("/home/%s/mc/小唯", os.Getenv("USER"))
}
}
targetDir := filepath.Join(s.vaultPath, folder)
if err := os.MkdirAll(targetDir, 0755); err != nil {
return fmt.Errorf("mkdir %s: %w", targetDir, err)
}
count := 0
used := make(map[string]int, len(memories))
for _, mem := range memories {
content := strVal(mem["content"])
// 2026-09-10 P0:镜像正文同样脱敏——旧事故里正文与文件名都把
// tskey-auth-… 原样落盘(小唯/07-Wiki/织忆/未找到命令.md)。
content = redact.RedactSecrets(content)
if len(content) < 5 {
continue
}
// 2026-09-10 修复:旧实现 content[:30] 按字节切 + sanitizeFilename 把非 ASCII
// 全替换成 '_',中文标题直接变 ____123.md(07-Wiki/织忆 1628 个乱码文件名成因),
// 且不同记忆撞名会静默互相覆盖。改为 rune 级截断 + 保留 Unicode + 撞名加短哈希。
base := sanitizeFilename(truncateRunes(content, 30))
if base == "" {
base = "untitled"
}
if used[base] > 0 {
base = base + "-" + shortHash(content)
}
used[base]++
filename := base + ".md"
target := filepath.Join(targetDir, filename)
mdContent := fmt.Sprintf(`---
id: %s
category: %s
quality_score: %.2f
sync_time: %s
---
# %s
%s
---
*由织忆 MemoryWeave 同步*
`, strVal(mem["id"]), strVal(mem["category"]),
floatVal(mem["quality_score"]),
time.Now().Format(time.RFC3339),
truncate(content, 60),
content)
if err := os.WriteFile(target, []byte(mdContent), 0644); err != nil {
log.Printf("[obsidian] 写入失败 %s: %v", filename, err)
continue
}
count++
}
s.lastSync = time.Now()
log.Printf("[obsidian] 推送 %d 条记忆到 %s", count, targetDir)
return nil
}
// PullFromObsidian 从 Obsidian 拉取笔记并 commit 到织忆
func (s *ObsidianSyncer) PullFromObsidian(folder string) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.vaultPath == "" {
s.vaultPath = os.Getenv("OBSIDIAN_VAULT")
if s.vaultPath == "" {
s.vaultPath = fmt.Sprintf("/home/%s/mc/小唯", os.Getenv("USER"))
}
}
targetDir := filepath.Join(s.vaultPath, folder)
entries, err := os.ReadDir(targetDir)
if err != nil {
return 0, fmt.Errorf("readdir %s: %w", targetDir, err)
}
count := 0
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") {
continue
}
data, err := os.ReadFile(filepath.Join(targetDir, entry.Name()))
if err != nil {
continue
}
content := string(data)
// 跳过已经同步过的(检查 FRONT MATTER)
if strings.Contains(content, "*由织忆 MemoryWeave 同步*") {
continue
}
// 简单提取:去掉 YAML 头,取正文
body := content
if idx := strings.Index(content, "---\n"); idx >= 0 {
if endIdx := strings.Index(content[4:], "---\n"); endIdx >= 0 {
body = content[endIdx+8:]
}
}
s.ldb.InsertEpisode(
"obsidian-sync",
"shared",
strings.TrimSpace(body),
"obsidian_import",
)
count++
}
s.lastSync = time.Now()
log.Printf("[obsidian] 拉取 %d 条笔记", count)
return count, nil
}
// ─── API ──────────────────────────────────────────────────
// POST /api/v1/obsidian/push
func (s *ObsidianSyncer) PushHandler(w http.ResponseWriter, r *http.Request) {
var req struct {
Memories []map[string]interface{} `json:"memories"`
Folder string `json:"folder"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
return
}
if req.Folder == "" {
req.Folder = "02-Memory"
}
if err := s.PushToObsidian(req.Memories, req.Folder); err != nil {
respondError(w, 500, "push failed: "+err.Error())
return
}
respond(w, 200, map[string]interface{}{
"status": "pushed", "count": len(req.Memories),
})
}
// POST /api/v1/obsidian/pull
func (s *ObsidianSyncer) PullHandler(w http.ResponseWriter, r *http.Request) {
var req struct {
Folder string `json:"folder"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
return
}
if req.Folder == "" {
req.Folder = "02-Memory"
}
count, err := s.PullFromObsidian(req.Folder)
if err != nil {
respondError(w, 500, "pull failed: "+err.Error())
return
}
respond(w, 200, map[string]interface{}{
"status": "pulled", "count": count,
})
}
// GET /api/v1/obsidian/status
func (s *ObsidianSyncer) StatusHandler(w http.ResponseWriter, r *http.Request) {
respond(w, 200, map[string]interface{}{
"vault_path": s.vaultPath,
"last_sync": s.lastSync.Format(time.RFC3339),
"vault_exists": dirExists(s.vaultPath),
})
}
// ─── 辅助 ─────────────────────────────────────────────────
// sanitizeFilename 把标题转成文件系统安全的文件名片段,并保留 Unicode(中文)可读性。
//
// 2026-09-10 修复:旧实现把所有非 ASCII rune 逐个替换为 '_',于是中文标题全变成
// `____123.md`,在 Obsidian 里无法按名浏览(07-Wiki/织忆 1628 个 legacy 文件的成因)。
// 现在只替换文件系统非法字符(/ \ : * ? " < > | 控制符等),连续的非法字符折叠成一个 '_'。
// 返回空串表示内容里没有任何可用的安全字符,由调用方兜底。
func sanitizeFilename(s string) string {
// 2026-09-10 P0:入参先脱敏,防任何路径把凭证带进文件名
s = redact.RedactSecrets(s)
var b strings.Builder
prevIllegal := false
for _, r := range s {
if unicode.IsLetter(r) || unicode.IsDigit(r) ||
r == '-' || r == '_' || r == ' ' || r == '.' {
prevIllegal = false
b.WriteRune(r)
continue
}
// 文件系统非法字符(/ \ : * ? " < > | 控制符等)+ 其它符号 → 折叠成一个 '_'
if !prevIllegal {
b.WriteRune('_')
prevIllegal = true
}
}
return strings.Trim(b.String(), " ._-")
}
// shortHash 取内容摘要前 8 位十六进制,仅用于同名文件消歧,不做安全用途。
func shortHash(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:4])
}
// truncateRunes 按 rune(而非字节)截断,避免把多字节字符切掉一半产生乱码。
func truncateRunes(s string, maxRunes int) string {
if maxRunes <= 0 {
return ""
}
n := 0
for i := range s {
if n == maxRunes {
return s[:i]
}
n++
}
return s
}
// truncate 展示用截断,按 rune 计数(2026-09-10 从字节切改为 rune 切,避免乱码)。
func truncate(s string, maxLen int) string {
t := truncateRunes(s, maxLen)
if len(t) == len(s) {
return s
}
return t + "..."
}
func floatVal(v interface{}) float64 {
switch f := v.(type) {
case float64:
return f
case int:
return float64(f)
}
return 0
}
func dirExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// extractTitle 从 markdown 内容提取第一个 # 标题
func extractTitle(content string) string {
lines := strings.Split(content, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "# ") {
return strings.TrimPrefix(line, "# ")
}
}
return "无标题"
}
// extractSnippet 提取包含实体的片段(前后各60字)
func extractSnippet(content string, entities []string) string {
lowerContent := strings.ToLower(content)
bestPos := -1
for _, entity := range entities {
searchTerm := strings.TrimPrefix(entity, "n_")
pos := strings.Index(lowerContent, strings.ToLower(searchTerm))
if pos >= 0 && (bestPos < 0 || pos < bestPos) {
bestPos = pos
}
}
if bestPos < 0 {
bestPos = 0
}
start := bestPos - 60
if start < 0 {
start = 0
}
end := bestPos + 120
if end > len(content) {
end = len(content)
}
snippet := strings.TrimSpace(content[start:end])
if start > 0 {
snippet = "..." + snippet
}
if end < len(content) {
snippet = snippet + "..."
}
return snippet
}
// SearchNotesByEntities 在 Obsidian vault 中搜索包含指定实体的笔记
func (s *ObsidianSyncer) SearchNotesByEntities(entities []string, maxResults int) []map[string]interface{} {
if len(entities) == 0 || maxResults <= 0 {
return nil
}
vaultPath := s.vaultPath
if vaultPath == "" {
vaultPath = os.Getenv("OBSIDIAN_VAULT")
if vaultPath == "" {
vaultPath = fmt.Sprintf("/home/%s/mc/小唯", os.Getenv("USER"))
}
}
type noteMatch struct {
path string
title string
snippet string
entities []string
score float64
}
var matches []noteMatch
err := filepath.Walk(vaultPath, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
if !strings.HasSuffix(path, ".md") {
return nil
}
data, err := os.ReadFile(path)
if err != nil {
return nil
}
content := string(data)
if strings.Contains(content, "*由织忆 MemoryWeave 同步*") {
return nil
}
title := extractTitle(content)
hitEntities := []string{}
lowerContent := strings.ToLower(content)
for _, entity := range entities {
searchTerm := strings.TrimPrefix(entity, "n_")
if strings.Contains(lowerContent, strings.ToLower(searchTerm)) {
hitEntities = append(hitEntities, entity)
}
}
if len(hitEntities) > 0 {
snippet := extractSnippet(content, entities)
relPath, _ := filepath.Rel(vaultPath, path)
matches = append(matches, noteMatch{
path: relPath,
title: title,
snippet: snippet,
entities: hitEntities,
score: float64(len(hitEntities)),
})
}
return nil
})
if err != nil {
log.Printf("[obsidian] SearchNotes walk error: %v", err)
return nil
}
// 按分数排序
for i := 0; i < len(matches); i++ {
for j := i + 1; j < len(matches); j++ {
if matches[j].score > matches[i].score {
matches[i], matches[j] = matches[j], matches[i]
}
}
}
if len(matches) > maxResults {
matches = matches[:maxResults]
}
results := make([]map[string]interface{}, len(matches))
for i, m := range matches {
results[i] = map[string]interface{}{
"path": m.path,
"title": m.title,
"snippet": m.snippet,
"entities": m.entities,
"score": m.score,
}
}
return results
}