@leiyi-works/dsh-session-tmpdir 0.9.8 → 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 +12 -0
  2. package/index.js +153 -45
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -227,3 +227,15 @@ v0.9.6 变更(2026-11-16):**`Start-Process` 不再默认算写命令**。
227
227
  v0.9.7 变更(2026-11-16):白名单曾改为按机器名分文件(`session-tmpdir-approvals-<机器名>.json`),意图是避免跨机同步互相覆盖。**该前提判断有误**,见 0.9.8。
228
228
 
229
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,68 +1302,137 @@ 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
- * 白名单是本机文件:云端同步的排除名单包含 `data/session-tmpdir-*`
1310
- * (cloud-sync: `rel.slice(5).startsWith('session-tmpdir-')` 直接跳过),
1311
- * 因此固定用通用文件名即可,不会跨机同步、不会按机器产生多份文件。
1308
+ * v0.9.9: 白名单改为**跨机同步**:存放在 `data/tmpdir-guard/approvals.json`,
1309
+ * 该路径不在云端同步的排除名单(`data/session-tmpdir-*`)里,因此会随云端一起同步。
1312
1310
  */
1313
- function machineApprovalsPathV097() {
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() {
1314
1318
  let raw = ''
1315
1319
  try {
1316
1320
  raw = String(hostname() ?? '')
1317
1321
  } catch {
1318
1322
  raw = ''
1319
1323
  }
1320
- const safe =
1321
- raw
1322
- .toLowerCase()
1323
- .replace(/[^a-z0-9._-]+/g, '-')
1324
- .replace(/^-+|-+$/g, '')
1325
- .slice(0, 40) || 'machine'
1326
- return join(resolveDshHome(), 'data', `session-tmpdir-approvals-${safe}.json`)
1324
+ const safe = raw
1325
+ .toLowerCase()
1326
+ .replace(/[^a-z0-9._-]+/g, '-')
1327
+ .replace(/^-+|-+$/g, '')
1328
+ .slice(0, 40)
1329
+ return safe || 'machine'
1327
1330
  }
1328
1331
 
1329
- /** Absolute path of the whitelist store (machine-local; never cloud-synced). */
1332
+ /** Absolute path of the synced whitelist store (`<DSH_HOME>/data/tmpdir-guard/approvals.json`). */
1330
1333
  export function approvalsFilePath() {
1331
- return join(resolveDshHome(), 'data', APPROVALS_FILE)
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`)]
1332
1341
  }
1333
1342
 
1334
- /** v0.9.8: 0.9.7 曾按机器名分文件;仅作读取回退,写入统一回到通用文件。 */
1343
+ /** Kept for compatibility: the first legacy path. */
1335
1344
  export function legacyApprovalsFilePath() {
1336
- return machineApprovalsPathV097()
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
+ }
1337
1362
  }
1338
1363
 
1339
- /** 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). */
1340
1392
  export function loadApprovalsState() {
1341
- for (const file of [approvalsFilePath(), legacyApprovalsFilePath()]) {
1393
+ const primary = approvalsFilePath()
1394
+ for (const file of [primary, ...legacyApprovalsFilePaths()]) {
1342
1395
  try {
1343
1396
  const parsed = JSON.parse(readFileSync(file, 'utf8'))
1344
- const entries = Array.isArray(parsed?.entries)
1345
- ? parsed.entries.filter(
1346
- (entry) => entry && typeof entry.path === 'string' && entry.path.trim() && typeof entry.sessionId === 'string',
1347
- )
1348
- : []
1349
- 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 }
1350
1407
  } catch {
1351
1408
  // try the next candidate
1352
1409
  }
1353
1410
  }
1354
- return { version: 1, entries: [] }
1411
+ return { version: 2, entries: [], tombstones: [] }
1355
1412
  }
1356
1413
 
1357
- /** 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. */
1358
1415
  export function saveApprovalsState(state) {
1359
1416
  try {
1360
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)
1361
1426
  mkdirSync(dirname(file), { recursive: true })
1362
- writeFileSync(file, `${JSON.stringify({ version: 1, entries: state.entries ?? [] }, null, 2)}\n`, 'utf8')
1363
- 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
1364
1433
  } catch (error) {
1365
1434
  console.warn('[session-task-tmpdir] save approvals failed:', error?.message ?? error)
1366
- return false
1435
+ return undefined
1367
1436
  }
1368
1437
  }
1369
1438
 
@@ -1606,11 +1675,18 @@ export function apply(ctx, config) {
1606
1675
  }
1607
1676
  }
1608
1677
 
1609
- /** Persisted whitelist: `{ version, entries: [{ id, sessionId, path, kind, reason, basis, approvedAt }] }`. */
1610
- 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()
1611
1685
 
1612
1686
  function saveApprovalsNow() {
1613
- return saveApprovalsState(approvalState)
1687
+ const merged = saveApprovalsState(approvalState)
1688
+ if (merged) approvalState = merged
1689
+ return merged
1614
1690
  }
1615
1691
 
1616
1692
  /** Whitelist entries that apply to this session (exact files + directory prefixes). */
@@ -1622,7 +1698,7 @@ export function apply(ctx, config) {
1622
1698
  .map((entry) => ({ path: entry.path, kind: entry.kind === 'dir' ? 'dir' : 'file' }))
1623
1699
  }
1624
1700
 
1625
- /** 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). */
1626
1702
  function approvalEntriesForPanel() {
1627
1703
  return approvalState.entries.map((entry) => ({
1628
1704
  id: entry.id,
@@ -1632,6 +1708,8 @@ export function apply(ctx, config) {
1632
1708
  reason: entry.reason ?? '',
1633
1709
  basis: entry.basis ?? '',
1634
1710
  approvedAt: entry.approvedAt ?? 0,
1711
+ originMachine: entry.originMachine ?? '',
1712
+ local: (entry.originMachine ?? '') === THIS_MACHINE,
1635
1713
  exists: (() => {
1636
1714
  try {
1637
1715
  return existsSync(entry.path)
@@ -1642,10 +1720,20 @@ export function apply(ctx, config) {
1642
1720
  }))
1643
1721
  }
1644
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
+
1645
1732
  /**
1646
- * v0.9.3:目标已不存在的白名单条目自动回收。
1647
- * 保护:刚批准、还没写入的条目(从未见过存在,且批准不到 30 分钟)不删,避免误删;
1648
- * 一旦见过目标存在(lastSeenAt>0),之后目标消失 → 下次刷新即删。
1733
+ * v0.9.3 + v0.9.9:目标已不存在的条目自动回收(跨机安全版)。
1734
+ * - 本机条目:见过目标存在后消失 → 回收;刚批准还没写入的(<30 分钟)保留。
1735
+ * - 其他机器的条目:本机看不到路径是正常的,只有"从未被任何机器见过 + 超过 7 天"才回收。
1736
+ * - 每次回收写墓碑,避免同步回来后又被“复活”。
1649
1737
  */
1650
1738
  function pruneMissingApprovals() {
1651
1739
  const now = Date.now()
@@ -1668,7 +1756,12 @@ export function apply(ctx, config) {
1668
1756
  }
1669
1757
  const approvedAt = Number(entry.approvedAt) || 0
1670
1758
  const seen = Number(entry.lastSeenAt) || 0
1671
- 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)
1672
1765
  changed = true
1673
1766
  continue
1674
1767
  }
@@ -1700,18 +1793,21 @@ export function apply(ctx, config) {
1700
1793
  reason: reason ?? '',
1701
1794
  basis: basis ?? 'user_confirmed',
1702
1795
  approvedAt: Date.now(),
1796
+ originMachine: THIS_MACHINE,
1797
+ lastSeenAt: 0,
1703
1798
  })
1704
1799
  saveApprovalsNow()
1705
- 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})`)
1706
1801
  }
1707
1802
  return approvalState.entries.filter((entry) => entry.sessionId === id)
1708
1803
  }
1709
1804
 
1710
- /** Remove one whitelist entry (the panel's only mutation). */
1805
+ /** Remove one whitelist entry (panel mutation); the tombstone keeps it removed across machines. */
1711
1806
  function revokeApproval(entryId) {
1712
1807
  const before = approvalState.entries.length
1713
1808
  approvalState.entries = approvalState.entries.filter((entry) => entry.id !== entryId)
1714
1809
  if (approvalState.entries.length === before) return false
1810
+ addTombstone(entryId)
1715
1811
  saveApprovalsNow()
1716
1812
  return true
1717
1813
  }
@@ -2132,12 +2228,24 @@ export function apply(ctx, config) {
2132
2228
  /* registry unavailable this tick */
2133
2229
  }
2134
2230
  const existingSessionIds = await collectPersistedSessionIds()
2135
- // v0.9:回收"会话已被删除"的白名单条目(live 与 persisted 会话都保留)。
2231
+ // v0.9/v0.9.9:回收"会话已被删除"的白名单条目(只删本机条目;其他机器的会话可能还没同步过来)。
2136
2232
  try {
2137
2233
  const aliveIds = new Set([...liveSessionIds, ...existingSessionIds].map((id) => String(id)))
2138
- const before = approvalState.entries.length
2139
- approvalState.entries = approvalState.entries.filter((entry) => aliveIds.has(entry.sessionId))
2140
- 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
+ }
2141
2249
  } catch {
2142
2250
  // pruning the whitelist is best-effort
2143
2251
  }
@@ -2226,7 +2334,7 @@ export function apply(ctx, config) {
2226
2334
  '',
2227
2335
  '### Whitelist panel',
2228
2336
  '',
2229
- `Every approval is stored in the machine-local file \`<DSH_HOME>/data/session-tmpdir-approvals.json\` (files under \`data/session-tmpdir-*\` are excluded from cloud sync, so nothing is shared across machines) 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).`,
2230
2338
  ].join('\n'),
2231
2339
  }),
2232
2340
  )
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-session-tmpdir",
3
- "version": "0.9.8",
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": {