DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): one-time heads-up for unignored sensitive files
yingtianlan655548c88e34
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts b/packages/dsh-tauri-turnrewind-ts/src/host/apply.tsindex 9da36dcb..89e9c8eb 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts@@ -38,12 +38,14 @@ import {getPendingPlanStatus,getTurn,hasNeedsRecoveryWorkspace,+ hasSensitiveNotice,insertTurn,listRecoveryWorkspaces,markPendingPlanApplied,markPendingPlanCancelled,openLedger,pruneConsumedNotices,+ queueSensitiveNotice,recordSkippedTurn,registerWorkspace,releasePendingPlanClaim,@@ -55,6 +57,7 @@ import {import { purgeWorkspace } from './service/maintenance'import { planDrift } from './service/planner'import { enforceRetention } from './service/retention'+import { findUnignoredSensitiveFiles } from './service/sensitive'import { applyUndo, buildPlanEntries, executeUndoRestore, parseUndoInput, turnRefsExist, workspaceForAgent, workspaceHasActiveTurn, workspaceIssue, workspaceKeyFor } from './service/undo'import { acquireWorkspaceLockSync, withWorkspaceLock, WorkspaceLockBusyError } from './service/workspace-lock'@@ -439,6 +442,18 @@ export function apply(ctx: HostApplyContext): void {settleDeferred(baseline, { ok: false, reason: 'turnrewind plugin disposed during baseline capture' })return}+ // 敏感文件一次性提醒(P2-5 隐私面):不持锁(扫描 + check-ignore 是+ // 纯读),每会话+工作区只扫一次——已有提醒的会话直接跳过扫描。+ if (!disposed && !runtime.disposed && !hasSensitiveNotice(ledger, sessionId, runtime.workspaceKey)) {+ try {+ const sensitive = await findUnignoredSensitiveFiles(runtime.workspaceDir)+ if (sensitive.length > 0)+ queueSensitiveNotice(ledger, sessionId, runtime.workspaceKey, sensitive)+ }+ catch (scanError) {+ log.warn(`turnrewind: sensitive-file scan failed (ignored): ${String(scanError)}`)+ }+ }settleDeferred(baseline, { ok: true })}catch (error) {diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.tsindex d9e3e5ad..eb19a129 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts@@ -357,6 +357,42 @@ export function listNeedsRecoveryWorkspaces(db: Ledger): string[] {`).all() as { workspace_key: string }[]).map(row => row.workspace_key)}+/**+ * 敏感文件提醒的去重查询:每会话+工作区只发一条(kind 'sensitive-files')。+ * 独立导出:baselineTask 用它避免每 turn 都跑扫描。+ */+export function hasSensitiveNotice(db: Ledger, sessionId: string, workspaceKey: string): boolean {+ return db.prepare(`+ SELECT 1 FROM rewind_notices+ WHERE session_id = ? AND workspace_key = ? AND kind = 'sensitive-files'+ LIMIT 1+ `).get(sessionId, workspaceKey) !== undefined+}++/** 写入敏感文件提醒(kind 'sensitive-files',reason 携带文件清单);重复为 no-op。 */+export function queueSensitiveNotice(db: Ledger, sessionId: string, workspaceKey: string, files: string[]): boolean {+ db.exec('BEGIN IMMEDIATE')+ try {+ if (hasSensitiveNotice(db, sessionId, workspaceKey)) {+ db.exec('COMMIT')+ return false+ }+ db.prepare(`+ INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, reason, status, created_at)+ VALUES (?, ?, ?, 'workspace-sensitive', '[]', ?, 'sensitive-files', ?, 'pending', ?)+ `).run(randomUUID(), sessionId, workspaceKey, JSON.stringify(capNoticePaths(files)), files.join('; '), new Date().toISOString())+ db.exec('COMMIT')+ return true+ }+ catch (error) {+ try {+ db.exec('ROLLBACK')+ }+ catch { /* no active transaction */ }+ throw error+ }+}+/** 恢复面板行:一个被围 workspace 的 needs-recovery 操作明细。 */export interface RecoveryWorkspace {workspace_key: stringdiff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/sensitive.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/sensitive.tsnew file mode 100644index 00000000..d8433811--- /dev/null+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/sensitive.ts@@ -0,0 +1,113 @@+/**+ * host/service/sensitive.ts — 秘密文件快照提醒(启发式,只提醒不改变语义)。+ *+ * Git 目录模式把快照面完全委托给源仓库 ignore 规则:未写进 ignore 的+ * .env/密钥类文件会被捕获进私有快照并可被 /undo 恢复(这是有意的取舍,+ * 见 README「快照范围与敏感文件」)。本模块在会话首次追踪某工作区时做一次+ * 浅层扫描(根 + 两层,上限 500 个文件,跳过 .git/node_modules 等噪音目录),+ * 命中启发式再经 `git check-ignore --stdin` 批量过滤掉已 ignore 的文件——+ * 剩下的就是"会被快照的疑似秘密",由调用方写成每会话/工作区一条的+ * heads-up notice。扫描/探测失败一律静默降级为"无发现":这是提醒,不是门禁。+ */++import { Buffer } from 'node:buffer'+import { spawn } from 'node:child_process'+import { readdirSync } from 'node:fs'+import process from 'node:process'+import { join } from 'pathe'+import { SYNC_GIT_TIMEOUT_MS } from '../constants'++/**+ * 基名启发式:.env*、证书/密钥扩展名、常见凭据文件名。宁可漏报不误报——+ * 提醒的措辞由调用方承担,这里只负责"看起来像秘密"。+ */+const SENSITIVE_NAME: RegExp[] = [+ /^\.env$/i,+ /^\.env\./i,+ /\.(pem|key|pfx|p12|keystore|jks)$/i,+ /^id_rsa/i,+ /^credentials/i,+ /^secrets?/i,+ /^\.npmrc$/i,+]++function isSensitiveName(name: string): boolean {+ return SENSITIVE_NAME.some(re => re.test(name))+}++const MAX_SCAN_FILES = 500+const MAX_SCAN_DEPTH = 2+const SKIP_DIRS = new Set(['.git', '.turnrewind', 'node_modules'])++function collectCandidates(root: string, rel: string, depth: number, out: string[]): void {+ if (out.length >= MAX_SCAN_FILES)+ return+ let entries: import('node:fs').Dirent[]+ try {+ entries = readdirSync(rel === '' ? root : join(root, rel), { withFileTypes: true })+ }+ catch {+ return+ }+ for (const entry of entries) {+ if (out.length >= MAX_SCAN_FILES)+ return+ const childRel = rel === '' ? entry.name : `${rel}/${entry.name}`+ if (entry.isDirectory()) {+ if (SKIP_DIRS.has(entry.name) || depth >= MAX_SCAN_DEPTH)+ continue+ collectCandidates(root, childRel, depth + 1, out)+ continue+ }+ if (entry.isFile() && isSensitiveName(entry.name))+ out.push(childRel)+ }+}++/**+ * `git check-ignore -z --stdin` 批量过滤:返回未被 ignore 的候选。+ * git 缺失/超时/异常路径一律返回全部候选(宁可多提醒一次)。+ */+function filterIgnored(workspaceDir: string, candidates: string[]): Promise<string[]> {+ if (candidates.length === 0)+ return Promise.resolve([])+ return new Promise((resolvePromise) => {+ const child = spawn('git', ['-c', 'core.quotepath=false', 'check-ignore', '-z', '--stdin'], {+ cwd: workspaceDir,+ env: { ...process.env },+ })+ const chunks: Buffer[] = []+ let settled = false+ let timeout: ReturnType<typeof setTimeout> | undefined+ const settle = (value: string[]): void => {+ if (settled)+ return+ settled = true+ if (timeout !== undefined)+ clearTimeout(timeout)+ resolvePromise(value)+ }+ timeout = setTimeout(() => {+ child.kill('SIGKILL')+ settle(candidates)+ }, SYNC_GIT_TIMEOUT_MS)+ child.stdout.on('data', (chunk: Buffer) => chunks.push(chunk))+ child.stdin.on('error', () => {})+ child.on('error', () => settle(candidates))+ child.on('close', (code) => {+ // 0 = 有被 ignore 的;1 = 全部未被 ignore;两者都是有效答案。+ if (code !== 0 && code !== 1)+ return settle(candidates)+ const ignored = new Set(Buffer.concat(chunks).toString('utf8').split('\0').filter(Boolean))+ settle(candidates.filter(file => !ignored.has(file)))+ })+ child.stdin.end(candidates.join('\0'))+ })+}++/** 未被 ignore 的疑似秘密文件(工作区相对、正斜杠路径)。 */+export async function findUnignoredSensitiveFiles(workspaceDir: string): Promise<string[]> {+ const candidates: string[] = []+ collectCandidates(workspaceDir, '', 0, candidates)+ return filterIgnored(workspaceDir, candidates)+}diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.tsindex 7f3a7c50..822f22a1 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts@@ -402,7 +402,7 @@ export interface NoticeMessage {source: {kind: 'plugin'plugin: string- form: 'rewind-notice' | 'undo-unavailable-notice'+ form: 'rewind-notice' | 'undo-unavailable-notice' | 'rewind-privacy-notice'sections: { name: string, text: string }[]}}@@ -428,6 +428,28 @@ function createRewindNoticeMessage(notice: { notice_id: string, kind?: string, t}}+function createSensitiveNoticeMessage(notice: { notice_id: string, paths: string[] }): NoticeMessage {+ const paths = notice.paths.map(path => `- ${path}`).join('\n')+ const text = [+ '[Turn rewind privacy notice]',+ 'These sensitive-looking files are NOT ignored by the repository\'s ignore rules, so they are captured into the private snapshot repo and restored by /undo:',+ paths,+ '',+ 'If that is not intended, add them to .gitignore or .git/info/exclude — the snapshot scope follows the repository\'s ignore rules on every capture.',+ ].join('\n')+ return {+ id: `turnrewind-notice-${notice.notice_id}`,+ role: 'user',+ content: [{ type: 'text', text }],+ source: {+ kind: 'plugin',+ plugin: PLUGIN_NAME,+ form: 'rewind-privacy-notice',+ sections: [{ name: PLUGIN_NAME, text }],+ },+ }+}+function createUnsupportedNoticeMessage(notice: { notice_id: string, reason: string | null }): NoticeMessage {const text = `[Turn rewind unavailable]\nUndo is disabled for this workspace.\nReason: ${notice.reason}\n\nTurns here still run normally, but their file changes are not recorded, so /undo cannot revert them. Move this session to a normal project directory if you want undoable turns.`return {@@ -444,6 +466,8 @@ function createUnsupportedNoticeMessage(notice: { notice_id: string, reason: str}export function createNoticeMessage(notice: { notice_id: string, kind?: string, reason?: string | null, turns?: string[], target_turn_id?: string | null, paths?: string[] }): NoticeMessage {+ if (notice.kind === 'sensitive-files')+ return createSensitiveNoticeMessage({ notice_id: notice.notice_id, paths: notice.paths ?? [] })if (notice.kind === 'unsupported')return createUnsupportedNoticeMessage({ notice_id: notice.notice_id, reason: notice.reason ?? '' })return createRewindNoticeMessage({diff --git a/packages/dsh-tauri-turnrewind-ts/test/sensitive.test.js b/packages/dsh-tauri-turnrewind-ts/test/sensitive.test.jsnew file mode 100644index 00000000..73ea2ba6--- /dev/null+++ b/packages/dsh-tauri-turnrewind-ts/test/sensitive.test.js@@ -0,0 +1,59 @@+import assert from 'node:assert/strict'+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'pathe'+import { it } from 'vitest'+import { claimRewindNotices, hasSensitiveNotice, openLedger, queueSensitiveNotice } from '../src/host/service/ledger'+import { findUnignoredSensitiveFiles } from '../src/host/service/sensitive'+import { createNoticeMessage } from '../src/host/service/undo'+import { initGitWorkspace, runGit } from './git-test-utils.js'++it('finds unignored sensitive files and filters gitignored ones', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-sensitive-'))+ const workspace = join(root, 'workspace')+ try {+ await initGitWorkspace(workspace)+ await writeFile(join(workspace, '.gitignore'), '/.env\n/creds/**\n')+ await writeFile(join(workspace, '.env'), 'SECRET=1\n')+ await writeFile(join(workspace, 'server.pem'), '-----BEGIN\n')+ await mkdir(join(workspace, 'sub'))+ await writeFile(join(workspace, 'sub', 'token.key'), 'k\n')+ await mkdir(join(workspace, 'creds'), { recursive: true })+ await writeFile(join(workspace, 'creds', 'id_rsa'), 'k\n')+ await runGit(workspace, ['add', '.gitignore'])++ const found = await findUnignoredSensitiveFiles(workspace)+ assert.deepEqual(found, ['server.pem', 'sub/token.key'])+ }+ finally {+ await rm(root, { recursive: true, force: true })+ }+})++it('queues one sensitive notice per session and workspace and builds its message', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-sensitive-notice-'))+ const db = openLedger(root)+ try {+ assert.equal(hasSensitiveNotice(db, 'session', 'ws'), false)+ assert.equal(queueSensitiveNotice(db, 'session', 'ws', ['.env', 'sub/token.key']), true)+ // Repeat (another process racing, another turn) is a no-op.+ assert.equal(queueSensitiveNotice(db, 'session', 'ws', ['.env']), false)+ assert.equal(hasSensitiveNotice(db, 'session', 'ws'), true)++ const notices = claimRewindNotices(db, 'session', 'ws')+ assert.equal(notices.length, 1)+ assert.equal(notices[0].kind, 'sensitive-files')+ assert.deepEqual(notices[0].paths, ['.env', 'sub/token.key'])++ const message = createNoticeMessage(notices[0])+ assert.match(message.source.form, /rewind-privacy-notice/u)+ assert.match(message.content[0].text, /\[Turn rewind privacy notice\]/u)+ assert.match(message.content[0].text, /- \.env/u)+ // Already consumed: no further notices.+ assert.deepEqual(claimRewindNotices(db, 'session', 'ws'), [])+ }+ finally {+ db.close()+ await rm(root, { recursive: true, force: true })+ }+})