@leiyi-works/dsh-session-tmpdir 0.9.7 → 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +15 -1
  2. package/index.js +147 -37
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -224,4 +224,18 @@ v0.9.5 变更(2026-11-16):**复制/移动类命令不再判源路径**。`
224
224
 
225
225
  v0.9.6 变更(2026-11-16):**`Start-Process` 不再默认算写命令**。它只是启动外部程序,参数里的路径通常是程序要打开的文件(读)。现在只有带 `-RedirectStandardOutput` / `-RedirectStandardError`(真正写文件)时才参与路径判定;`Start-Process notepad C:\缺失.txt` 这类不再误拦。
226
226
 
227
- v0.9.7 变更(2026-11-16):**白名单按机器分文件,修复跨机同步互相清空的问题**。此前白名单固定存 `~\.dsh\data\session-tmpdir-approvals.json`,该文件随云端同步:A 机批准的路径 B 机没有 → B 机刷新面板时按"目标不存在"回收条目 → 删减随同步回传,把 A 机的批准也删掉。现在每台机器用自己的文件 `session-tmpdir-approvals-<机器名>.json`(机器名取 `os.hostname()` 并做文件名安全化),互不覆盖;旧的无机器名文件只作为**只读迁移来源**(新文件不存在时读取一次,之后写入本机文件)。
227
+ v0.9.7 变更(2026-11-16):白名单曾改为按机器名分文件(`session-tmpdir-approvals-<机器名>.json`),意图是避免跨机同步互相覆盖。**该前提判断有误**,见 0.9.8。
228
+
229
+ v0.9.8 变更(2026-11-16):**白名单恢复通用文件名**。核对云端同步源码(`sync.js`:`data/session-tmpdir-*` 直接跳过)后确认:白名单文件本来就**不参与云端同步**,因此不会跨机覆盖、也不会每台机器多出别的机器的文件。改回固定路径 `<DSH_HOME>/data/session-tmpdir-approvals.json`(每台机器只有这一个文件);0.9.7 的按机器名文件只作为**读取回退**,写入统一回到通用文件。白名单语义:本机有效、同机重启后保留、跨机不共享(本来也不同步)。
230
+
231
+ v0.9.9 变更(2026-11-16):**白名单改为跨机同步(用户要求)**。
232
+
233
+ 1. **存储位置**:`<DSH_HOME>/data/tmpdir-guard/approvals.json`。该路径**不在**云端同步的排除名单里(排除的是 `data/session-tmpdir-*`),所以会随 `~/.dsh` 一起同步到其他机器。旧的两个本机文件(通用名 / 0.9.7 按机器名)只作为**读取迁移来源**。
234
+ 2. **条目带来源机器** `originMachine`;每台机器只自动回收**自己创建**的条目:
235
+ - 本机条目:目标文件曾存在、后来消失 → 回收;刚批准还没写入的(<30 分钟)保留;
236
+ - 其他机器的条目:本机看不到路径是正常的,**不会误删**;只有「从未被任何机器见过 + 超过 7 天」才回收。
237
+ 3. **合并与墓碑**:保存时先读文件再合并(按 `id` 取较新 `approvedAt`),删除写墓碑(30 天过期),所以:
238
+ - 一台机新增的批准会同步到其他机器(面板可见,带机器标记);
239
+ - 一台机删除的批准不会被另一台机同步“复活”;
240
+ - 云端落在“加载之后、保存之前”也不会覆盖掉另一台机的条目。
241
+ 4. 面板显示每条来源机器;移除任何机器的条目都写墓碑,其他机器同步后会一起消失。
package/index.js CHANGED
@@ -1302,14 +1302,19 @@ export function resolveDshHome() { const fromEnv = process.env.DSH_HOME && proc
1302
1302
  return fromEnv || join(homedir(), '.dsh')
1303
1303
  }
1304
1304
 
1305
- /** v0.9: persisted long-term whitelist file (exact files + directory prefixes). */
1305
+ /** Legacy (machine-local) whitelist file name. */
1306
1306
  const APPROVALS_FILE = 'session-tmpdir-approvals.json'
1307
-
1308
1307
  /**
1309
- * v0.9.7: 白名单按机器分文件,避免云端同步把别的机器的条目带过来后又因"目标不存在"被回收,
1310
- * 进而通过同步回传把原机器的批准也删掉(两台机互相清空)。
1308
+ * v0.9.9: 白名单改为**跨机同步**:存放在 `data/tmpdir-guard/approvals.json`,
1309
+ * 该路径不在云端同步的排除名单(`data/session-tmpdir-*`)里,因此会随云端一起同步。
1311
1310
  */
1312
- function approvalsFileSuffix() {
1311
+ const APPROVALS_SYNC_DIR = 'tmpdir-guard'
1312
+ const APPROVALS_SYNC_FILE = 'approvals.json'
1313
+ /** v0.9.9: 删除墓碑 30 天后过期(防止已删除条目被其他机器同步“复活”)。 */
1314
+ const APPROVALS_TOMBSTONE_TTL = 30 * 24 * 3600 * 1000
1315
+
1316
+ /** Sanitized machine id (hostname) used to tag approvals and guard pruning. */
1317
+ export function machineId() {
1313
1318
  let raw = ''
1314
1319
  try {
1315
1320
  raw = String(hostname() ?? '')
@@ -1324,44 +1329,110 @@ function approvalsFileSuffix() {
1324
1329
  return safe || 'machine'
1325
1330
  }
1326
1331
 
1327
- /** Absolute path of this machine's whitelist store (`<DSH_HOME>/data/session-tmpdir-approvals-<machine>.json`). */
1332
+ /** Absolute path of the synced whitelist store (`<DSH_HOME>/data/tmpdir-guard/approvals.json`). */
1328
1333
  export function approvalsFilePath() {
1329
- return join(resolveDshHome(), 'data', `session-tmpdir-approvals-${approvalsFileSuffix()}.json`)
1334
+ return join(resolveDshHome(), 'data', APPROVALS_SYNC_DIR, APPROVALS_SYNC_FILE)
1335
+ }
1336
+
1337
+ /** v0.9.9: legacy machine-local files, read-only migration sources. */
1338
+ export function legacyApprovalsFilePaths() {
1339
+ const dataDir = join(resolveDshHome(), 'data')
1340
+ return [join(dataDir, APPROVALS_FILE), join(dataDir, `session-tmpdir-approvals-${machineId()}.json`)]
1330
1341
  }
1331
1342
 
1332
- /** Pre-0.9.7 machine-agnostic filename: read fallback only, never written. */
1343
+ /** Kept for compatibility: the first legacy path. */
1333
1344
  export function legacyApprovalsFilePath() {
1334
- return join(resolveDshHome(), 'data', APPROVALS_FILE)
1345
+ return legacyApprovalsFilePaths()[0]
1346
+ }
1347
+
1348
+ /** Normalize one stored approval (old files may miss id/originMachine). */
1349
+ function normalizeApprovalEntry(entry, fallbackMachine) {
1350
+ if (!entry || typeof entry.path !== 'string' || !entry.path.trim() || typeof entry.sessionId !== 'string') return undefined
1351
+ return {
1352
+ id: typeof entry.id === 'string' && entry.id ? entry.id : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
1353
+ sessionId: entry.sessionId,
1354
+ path: entry.path,
1355
+ kind: entry.kind === 'dir' ? 'dir' : 'file',
1356
+ reason: typeof entry.reason === 'string' ? entry.reason : '',
1357
+ basis: typeof entry.basis === 'string' ? entry.basis : 'user_confirmed',
1358
+ approvedAt: Number(entry.approvedAt) || Date.now(),
1359
+ originMachine: typeof entry.originMachine === 'string' && entry.originMachine ? entry.originMachine : fallbackMachine,
1360
+ lastSeenAt: Number(entry.lastSeenAt) || 0,
1361
+ }
1335
1362
  }
1336
1363
 
1337
- /** Load the whitelist; a missing or corrupt file means an empty whitelist. */
1364
+ /**
1365
+ * Merge two whitelist states (v0.9.9): union by `id` with the newest `approvedAt` winning;
1366
+ * a tombstone removes entries approved before it. Used on every save (read-merge-write) so a
1367
+ * cloud sync landing between load and save cannot wipe another machine's entries.
1368
+ */
1369
+ export function mergeApprovalsStates(base, other) {
1370
+ const entries = new Map()
1371
+ for (const raw of [...(base?.entries ?? []), ...(other?.entries ?? [])]) {
1372
+ const entry = normalizeApprovalEntry(raw, 'legacy')
1373
+ if (!entry) continue
1374
+ const prev = entries.get(entry.id)
1375
+ if (!prev || entry.approvedAt >= prev.approvedAt) entries.set(entry.id, entry)
1376
+ }
1377
+ const tombstones = new Map()
1378
+ for (const raw of [...(base?.tombstones ?? []), ...(other?.tombstones ?? [])]) {
1379
+ if (!raw || typeof raw.id !== 'string' || !raw.id) continue
1380
+ const at = Number(raw.at) || 0
1381
+ const prev = tombstones.get(raw.id)
1382
+ if (!prev || at > prev.at) tombstones.set(raw.id, { id: raw.id, at })
1383
+ }
1384
+ const kept = [...entries.values()].filter((entry) => {
1385
+ const stone = tombstones.get(entry.id)
1386
+ return !stone || stone.at <= entry.approvedAt
1387
+ })
1388
+ return { version: 2, entries: kept, tombstones: [...tombstones.values()] }
1389
+ }
1390
+
1391
+ /** Load the whitelist: synced file first, then legacy machine-local files (migration sources). */
1338
1392
  export function loadApprovalsState() {
1339
- for (const file of [approvalsFilePath(), legacyApprovalsFilePath()]) {
1393
+ const primary = approvalsFilePath()
1394
+ for (const file of [primary, ...legacyApprovalsFilePaths()]) {
1340
1395
  try {
1341
1396
  const parsed = JSON.parse(readFileSync(file, 'utf8'))
1342
- const entries = Array.isArray(parsed?.entries)
1343
- ? parsed.entries.filter(
1344
- (entry) => entry && typeof entry.path === 'string' && entry.path.trim() && typeof entry.sessionId === 'string',
1345
- )
1346
- : []
1347
- return { version: 1, entries }
1397
+ const fallbackMachine = file === primary ? 'legacy' : machineId()
1398
+ const entries = []
1399
+ for (const raw of Array.isArray(parsed?.entries) ? parsed.entries : []) {
1400
+ const entry = normalizeApprovalEntry(raw, fallbackMachine)
1401
+ if (entry) entries.push(entry)
1402
+ }
1403
+ const tombstones = (Array.isArray(parsed?.tombstones) ? parsed.tombstones : [])
1404
+ .filter((stone) => stone && typeof stone.id === 'string')
1405
+ .map((stone) => ({ id: stone.id, at: Number(stone.at) || 0 }))
1406
+ return { version: 2, entries, tombstones }
1348
1407
  } catch {
1349
1408
  // try the next candidate
1350
1409
  }
1351
1410
  }
1352
- return { version: 1, entries: [] }
1411
+ return { version: 2, entries: [], tombstones: [] }
1353
1412
  }
1354
1413
 
1355
- /** Persist the whitelist; a failure only warns (the in-memory copy still works). */
1414
+ /** Persist the whitelist with a read-merge-write pass; returns the merged state. */
1356
1415
  export function saveApprovalsState(state) {
1357
1416
  try {
1358
1417
  const file = approvalsFilePath()
1418
+ let merged = state
1419
+ try {
1420
+ merged = mergeApprovalsStates(JSON.parse(readFileSync(file, 'utf8')), state)
1421
+ } catch {
1422
+ // first write (or corrupt file): keep the in-memory state
1423
+ }
1424
+ const now = Date.now()
1425
+ merged.tombstones = (merged.tombstones ?? []).filter((stone) => now - (Number(stone.at) || 0) < APPROVALS_TOMBSTONE_TTL)
1359
1426
  mkdirSync(dirname(file), { recursive: true })
1360
- writeFileSync(file, `${JSON.stringify({ version: 1, entries: state.entries ?? [] }, null, 2)}\n`, 'utf8')
1361
- return true
1427
+ writeFileSync(
1428
+ file,
1429
+ `${JSON.stringify({ version: 2, entries: merged.entries ?? [], tombstones: merged.tombstones }, null, 2)}\n`,
1430
+ 'utf8',
1431
+ )
1432
+ return merged
1362
1433
  } catch (error) {
1363
1434
  console.warn('[session-task-tmpdir] save approvals failed:', error?.message ?? error)
1364
- return false
1435
+ return undefined
1365
1436
  }
1366
1437
  }
1367
1438
 
@@ -1604,11 +1675,18 @@ export function apply(ctx, config) {
1604
1675
  }
1605
1676
  }
1606
1677
 
1607
- /** Persisted whitelist: `{ version, entries: [{ id, sessionId, path, kind, reason, basis, approvedAt }] }`. */
1608
- const approvalState = loadApprovalsState()
1678
+ /**
1679
+ * v0.9.9:白名单跨机同步 —— `{ version:2, entries, tombstones }`。
1680
+ * 每条带 `originMachine`;保存时读-合并-写(按 id 取较新 approvedAt,墓碑优先),
1681
+ * 避免云端同步后别的机器的条目被覆盖或误删。
1682
+ */
1683
+ let approvalState = loadApprovalsState()
1684
+ const THIS_MACHINE = machineId()
1609
1685
 
1610
1686
  function saveApprovalsNow() {
1611
- return saveApprovalsState(approvalState)
1687
+ const merged = saveApprovalsState(approvalState)
1688
+ if (merged) approvalState = merged
1689
+ return merged
1612
1690
  }
1613
1691
 
1614
1692
  /** Whitelist entries that apply to this session (exact files + directory prefixes). */
@@ -1620,7 +1698,7 @@ export function apply(ctx, config) {
1620
1698
  .map((entry) => ({ path: entry.path, kind: entry.kind === 'dir' ? 'dir' : 'file' }))
1621
1699
  }
1622
1700
 
1623
- /** All whitelist entries for the panel (this session and older ones). */
1701
+ /** All whitelist entries for the panel (all machines; `local` marks entries of this machine). */
1624
1702
  function approvalEntriesForPanel() {
1625
1703
  return approvalState.entries.map((entry) => ({
1626
1704
  id: entry.id,
@@ -1630,6 +1708,8 @@ export function apply(ctx, config) {
1630
1708
  reason: entry.reason ?? '',
1631
1709
  basis: entry.basis ?? '',
1632
1710
  approvedAt: entry.approvedAt ?? 0,
1711
+ originMachine: entry.originMachine ?? '',
1712
+ local: (entry.originMachine ?? '') === THIS_MACHINE,
1633
1713
  exists: (() => {
1634
1714
  try {
1635
1715
  return existsSync(entry.path)
@@ -1640,10 +1720,20 @@ export function apply(ctx, config) {
1640
1720
  }))
1641
1721
  }
1642
1722
 
1723
+ /** Add a tombstone so a removal stays removed after the next cross-machine merge. */
1724
+ function addTombstone(entryId) {
1725
+ const now = Date.now()
1726
+ const list = approvalState.tombstones ?? (approvalState.tombstones = [])
1727
+ const existing = list.find((stone) => stone.id === entryId)
1728
+ if (existing) existing.at = Math.max(Number(existing.at) || 0, now)
1729
+ else list.push({ id: entryId, at: now })
1730
+ }
1731
+
1643
1732
  /**
1644
- * v0.9.3:目标已不存在的白名单条目自动回收。
1645
- * 保护:刚批准、还没写入的条目(从未见过存在,且批准不到 30 分钟)不删,避免误删;
1646
- * 一旦见过目标存在(lastSeenAt>0),之后目标消失 → 下次刷新即删。
1733
+ * v0.9.3 + v0.9.9:目标已不存在的条目自动回收(跨机安全版)。
1734
+ * - 本机条目:见过目标存在后消失 → 回收;刚批准还没写入的(<30 分钟)保留。
1735
+ * - 其他机器的条目:本机看不到路径是正常的,只有"从未被任何机器见过 + 超过 7 天"才回收。
1736
+ * - 每次回收写墓碑,避免同步回来后又被“复活”。
1647
1737
  */
1648
1738
  function pruneMissingApprovals() {
1649
1739
  const now = Date.now()
@@ -1666,7 +1756,12 @@ export function apply(ctx, config) {
1666
1756
  }
1667
1757
  const approvedAt = Number(entry.approvedAt) || 0
1668
1758
  const seen = Number(entry.lastSeenAt) || 0
1669
- if (seen > 0 || (approvedAt > 0 && now - approvedAt > 30 * 60_000)) {
1759
+ const mine = (entry.originMachine ?? '') === THIS_MACHINE
1760
+ const due = mine
1761
+ ? seen > 0 || (approvedAt > 0 && now - approvedAt > 30 * 60_000)
1762
+ : !seen && approvedAt > 0 && now - approvedAt > 7 * 24 * 3600 * 1000
1763
+ if (due) {
1764
+ addTombstone(entry.id)
1670
1765
  changed = true
1671
1766
  continue
1672
1767
  }
@@ -1698,18 +1793,21 @@ export function apply(ctx, config) {
1698
1793
  reason: reason ?? '',
1699
1794
  basis: basis ?? 'user_confirmed',
1700
1795
  approvedAt: Date.now(),
1796
+ originMachine: THIS_MACHINE,
1797
+ lastSeenAt: 0,
1701
1798
  })
1702
1799
  saveApprovalsNow()
1703
- console.info(`[session-task-tmpdir] longterm approved (${entryKind}) ${normalized} (session ${id})`)
1800
+ console.info(`[session-task-tmpdir] longterm approved (${entryKind}) ${normalized} (session ${id}, machine ${THIS_MACHINE})`)
1704
1801
  }
1705
1802
  return approvalState.entries.filter((entry) => entry.sessionId === id)
1706
1803
  }
1707
1804
 
1708
- /** Remove one whitelist entry (the panel's only mutation). */
1805
+ /** Remove one whitelist entry (panel mutation); the tombstone keeps it removed across machines. */
1709
1806
  function revokeApproval(entryId) {
1710
1807
  const before = approvalState.entries.length
1711
1808
  approvalState.entries = approvalState.entries.filter((entry) => entry.id !== entryId)
1712
1809
  if (approvalState.entries.length === before) return false
1810
+ addTombstone(entryId)
1713
1811
  saveApprovalsNow()
1714
1812
  return true
1715
1813
  }
@@ -2130,12 +2228,24 @@ export function apply(ctx, config) {
2130
2228
  /* registry unavailable this tick */
2131
2229
  }
2132
2230
  const existingSessionIds = await collectPersistedSessionIds()
2133
- // v0.9:回收"会话已被删除"的白名单条目(live 与 persisted 会话都保留)。
2231
+ // v0.9/v0.9.9:回收"会话已被删除"的白名单条目(只删本机条目;其他机器的会话可能还没同步过来)。
2134
2232
  try {
2135
2233
  const aliveIds = new Set([...liveSessionIds, ...existingSessionIds].map((id) => String(id)))
2136
- const before = approvalState.entries.length
2137
- approvalState.entries = approvalState.entries.filter((entry) => aliveIds.has(entry.sessionId))
2138
- if (approvalState.entries.length !== before) saveApprovalsNow()
2234
+ const keep = []
2235
+ let changed = false
2236
+ for (const entry of approvalState.entries) {
2237
+ const mine = (entry.originMachine ?? '') === THIS_MACHINE
2238
+ if (mine && !aliveIds.has(entry.sessionId)) {
2239
+ addTombstone(entry.id)
2240
+ changed = true
2241
+ continue
2242
+ }
2243
+ keep.push(entry)
2244
+ }
2245
+ if (changed) {
2246
+ approvalState.entries = keep
2247
+ saveApprovalsNow()
2248
+ }
2139
2249
  } catch {
2140
2250
  // pruning the whitelist is best-effort
2141
2251
  }
@@ -2224,7 +2334,7 @@ export function apply(ctx, config) {
2224
2334
  '',
2225
2335
  '### Whitelist panel',
2226
2336
  '',
2227
- `Every approval is stored in this machine's own file \`<DSH_HOME>/data/session-tmpdir-approvals-<machine>.json\` (one file per machine, so cloud sync can never overwrite another machine's approvals) and shown in the left sidebar panel 「临时目录」 (display + remove only). Approvals survive a restart of the same session; entries whose session was deleted are pruned by the cleanup tick, and entries whose target no longer exists are pruned when the panel refreshes.`,
2337
+ `Every approval is stored in the **cloud-synced** file \`<DSH_HOME>/data/tmpdir-guard/approvals.json\` (outside cloud-sync's \`data/session-tmpdir-*\` exclusions) and shown in the left sidebar panel 「临时目录」 (display + remove only). Entries carry their origin machine and are merged by id (with tombstones for removals), so a whitelist entry approved on one machine appears on the others after the next sync; each machine only auto-prunes entries it created, and entries whose target no longer exists are pruned when the panel refreshes (foreign-machine entries are kept unless never seen anywhere for 7 days).`,
2228
2338
  ].join('\n'),
2229
2339
  }),
2230
2340
  )
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-session-tmpdir",
3
- "version": "0.9.7",
3
+ "version": "0.9.9",
4
4
  "type": "module",
5
5
  "description": "Per-session task temp folder with a long-term write guard. v0.9 (方案3): creating a new file outside _tmp requires the user's approval (per file by default, per directory with mode=dir), overwriting an existing file is allowed without asking, every write channel is guarded (write/edit, shell including ffmpeg/pandoc/Export-*/IO APIs, publish copies, code runtimes, unknown tools), and the persisted whitelist is shown in a left-sidebar panel「临时目录」 where entries can be removed. Every session also gets _tmp/<session title>/ in its working directory, cleaned 7 days after the session is deleted; the same tick reclaims the attachment store.",
6
6
  "exports": {