dsh-config-manager 0.4.0 → 0.4.2
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.
- package/lib/cli/actions.js +2 -3
- package/lib/cli/import-source.js +2 -6
- package/lib/cli/index.js +2 -3
- package/lib/client.d.ts +21 -7
- package/lib/client.js +26122 -25799
- package/lib/core/exporter.js +2 -4
- package/lib/core/host-schedulers/cache-cleanup.d.ts +41 -0
- package/lib/core/host-schedulers/cache-cleanup.js +45 -0
- package/lib/core/host-schedulers/lifecycle-hooks.d.ts +51 -0
- package/lib/core/host-schedulers/lifecycle-hooks.js +78 -0
- package/lib/core/host-schedulers/market-cache.d.ts +40 -0
- package/lib/core/host-schedulers/market-cache.js +92 -0
- package/lib/core/messages-core.d.ts +1 -0
- package/lib/core/messages-core.js +2 -0
- package/lib/core/migration-history.d.ts +18 -2
- package/lib/core/migration-history.js +19 -3
- package/lib/core/model-tools.js +2 -6
- package/lib/core/restore.d.ts +0 -2
- package/lib/core/restore.js +16 -18
- package/lib/core/verify-recovery.js +4 -7
- package/lib/index.d.ts +3 -22
- package/lib/index.js +71 -327
- package/lib/profiles/dsh-profile-manager.d.ts +23 -1
- package/lib/profiles/dsh-profile-manager.js +70 -2
- package/lib/routes/kit.d.ts +21 -0
- package/lib/routes/kit.js +29 -0
- package/lib/routes/prefs.js +6 -6
- package/lib/routes/recovery.js +25 -41
- package/lib/routes/route-support.d.ts +23 -1
- package/lib/routes/route-support.js +185 -0
- package/lib/routes/snapshots.js +4 -11
- package/lib/routes/sync.js +5 -7
- package/lib/security/redaction.d.ts +5 -1
- package/lib/security/redaction.js +26 -23
- package/lib/sync/autosync-scheduler.js +6 -2
- package/lib/sync/backup-scheduler.js +2 -6
- package/lib/sync/baseline-heal.d.ts +35 -0
- package/lib/sync/baseline-heal.js +39 -0
- package/lib/sync/push-precheck.d.ts +35 -0
- package/lib/sync/push-precheck.js +58 -0
- package/lib/sync/sync-engine.d.ts +9 -12
- package/lib/sync/sync-engine.js +24 -43
- package/lib/ui/backup-inspect.d.ts +1 -1
- package/lib/ui/dsh-profiles-view.d.ts +0 -10
- package/lib/ui/dsh-profiles-view.js +3 -7
- package/lib/ui/history-model.js +3 -2
- package/lib/ui/overview-view.d.ts +3 -3
- package/lib/ui/overview-view.js +9 -1
- package/lib/ui/snapshots-view.d.ts +0 -14
- package/lib/ui/snapshots-view.js +16 -2
- package/lib/utils/paths.d.ts +20 -4
- package/lib/utils/paths.js +22 -6
- package/lib/utils/time.d.ts +31 -0
- package/lib/utils/time.js +54 -0
- package/package.json +1 -1
- package/src/cli/actions.ts +2 -3
- package/src/cli/import-source.ts +2 -7
- package/src/cli/index.ts +2 -3
- package/src/client/about/AboutPanel.tsx +1 -1
- package/src/client/about/ReleaseBody.tsx +22 -52
- package/src/client/about/ReleaseNotesDialog.tsx +15 -69
- package/src/client/about/release-notes-view.ts +4 -11
- package/src/client/common/info-hint-guard.test.ts +11 -5
- package/src/client/common/ui.tsx +23 -0
- package/src/client/config-manager.module.css +201 -32
- package/src/client/css-token-guard.test.ts +135 -1
- package/src/client/history/history-locales.ts +2 -0
- package/src/client/home/HomePanel.tsx +9 -3
- package/src/client/import/ConflictList.tsx +3 -3
- package/src/client/import/ImportWizardView.tsx +1 -1
- package/src/client/library/ArtifactRow.tsx +2 -2
- package/src/client/library/RestorePlanView.tsx +21 -9
- package/src/client/library/report-dismiss.test.ts +5 -3
- package/src/client/locales/about.ts +97 -0
- package/src/client/locales/backup.ts +141 -0
- package/src/client/locales/common.ts +113 -0
- package/src/client/locales/export.ts +184 -0
- package/src/client/locales/foreign.ts +184 -0
- package/src/client/locales/import-compat.ts +32 -0
- package/src/client/locales/import.ts +192 -0
- package/src/client/locales/next-steps.ts +25 -0
- package/src/client/locales/overview-control.ts +32 -0
- package/src/client/locales/overview.ts +145 -0
- package/src/client/locales/profiles.ts +263 -0
- package/src/client/locales/report.ts +17 -0
- package/src/client/locales/restore.ts +132 -0
- package/src/client/locales/sessions.ts +257 -0
- package/src/client/locales/shell.ts +149 -0
- package/src/client/locales.ts +49 -1781
- package/src/client/market/MarketImportReview.tsx +2 -2
- package/src/client/market/MarketPanel.tsx +1 -1
- package/src/client/market/market-view.ts +3 -5
- package/src/client/recovery/RecoveryPanel.tsx +62 -1054
- package/src/client/recovery/SessionHealthCard.tsx +134 -0
- package/src/client/recovery/SessionHealthDialog.tsx +665 -0
- package/src/client/recovery/SessionLayoutSection.tsx +284 -0
- package/src/client/recovery/recovery-api.ts +10 -1
- package/src/client/recovery/recovery-panel-layout.test.ts +20 -5
- package/src/client/recovery/session-dialog-mount.test.ts +16 -9
- package/src/client/recovery/use-recovery-write.test.ts +90 -0
- package/src/client/recovery/use-recovery-write.ts +53 -0
- package/src/client/run-store.ts +57 -2
- package/src/client/sync/PushPreviewCard.tsx +2 -2
- package/src/client/sync/SyncConfirmView.tsx +5 -5
- package/src/client/sync/SyncLogList.tsx +2 -2
- package/src/client/sync/history-model.ts +7 -5
- package/src/client/sync/sync-locales.ts +2 -0
- package/src/client/sync/sync-view.ts +3 -4
- package/src/core/exporter.ts +2 -4
- package/src/core/host-schedulers/cache-cleanup.test.ts +84 -0
- package/src/core/host-schedulers/cache-cleanup.ts +74 -0
- package/src/core/host-schedulers/lifecycle-hooks.test.ts +111 -0
- package/src/core/host-schedulers/lifecycle-hooks.ts +118 -0
- package/src/core/host-schedulers/market-cache.test.ts +93 -0
- package/src/core/host-schedulers/market-cache.ts +116 -0
- package/src/core/messages-core.ts +2 -0
- package/src/core/migration-history.test.ts +19 -0
- package/src/core/migration-history.ts +28 -5
- package/src/core/model-tools.ts +2 -7
- package/src/core/restore-failure-state.test.ts +210 -0
- package/src/core/restore.ts +16 -18
- package/src/core/verify-recovery.ts +4 -7
- package/src/index.ts +78 -332
- package/src/profiles/dsh-profile-copy-rollback.test.ts +156 -0
- package/src/profiles/dsh-profile-manager.ts +71 -3
- package/src/routes/kit.ts +37 -0
- package/src/routes/prefs.ts +6 -6
- package/src/routes/recovery.ts +25 -42
- package/src/routes/route-support.ts +208 -1
- package/src/routes/snapshots.ts +4 -9
- package/src/routes/sync.ts +4 -7
- package/src/security/redaction.ts +29 -23
- package/src/sync/autosync-scheduler.test.ts +23 -0
- package/src/sync/autosync-scheduler.ts +6 -2
- package/src/sync/backup-scheduler.ts +3 -6
- package/src/sync/baseline-heal.ts +74 -0
- package/src/sync/push-precheck.ts +75 -0
- package/src/sync/sync-config.test.ts +24 -13
- package/src/sync/sync-engine.test.ts +88 -0
- package/src/sync/sync-engine.ts +33 -43
- package/src/ui/backup-inspect.ts +1 -1
- package/src/ui/dsh-profiles-view.ts +3 -5
- package/src/ui/history-model.test.ts +2 -1
- package/src/ui/history-model.ts +3 -2
- package/src/ui/i18n.test.ts +8 -3
- package/src/ui/overview-view.test.ts +12 -0
- package/src/ui/overview-view.ts +12 -4
- package/src/ui/snapshots-view.ts +2 -2
- package/src/utils/paths.test.ts +36 -1
- package/src/utils/paths.ts +30 -6
- package/src/utils/time.test.ts +46 -0
- package/src/utils/time.ts +55 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 市场缓存目录布局与暂存 zip 懒 GC(tech-debt #23 下沉)。
|
|
3
|
+
*
|
|
4
|
+
* 这些逻辑原本长在 src/index.ts 的 makeRoutes() 里,只有「装上宿主 + 真的拉过一次市场」
|
|
5
|
+
* 才能验证;抽出来之后目录哈希、条目完整性判定、保留期回收都是可单测的纯行为。
|
|
6
|
+
*
|
|
7
|
+
* 边界:src/core/host-schedulers/* 只能 import 'node:' 与同目录(core 层是 allow 白名单、
|
|
8
|
+
* 按**原始 spec 前缀**判定,'../../utils/hash.ts' 不在白名单里)——
|
|
9
|
+
* 所以 sha256 在这里用 node:crypto 本地算,别去 import utils。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { createHash } from 'node:crypto'
|
|
13
|
+
import { access, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
|
|
14
|
+
import { join } from 'node:path'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 暂存 zip 的保留期:market/download 每次暂存新 zip 前做懒 GC,
|
|
18
|
+
* 保留这段时间内的(供刚下载后立即执行的 /execute 消费),更旧的清掉。
|
|
19
|
+
*/
|
|
20
|
+
export const MARKET_TMP_RETENTION_MS = 10 * 60 * 1000
|
|
21
|
+
|
|
22
|
+
export interface MarketCacheLayout {
|
|
23
|
+
/** <marketDir>/cache */
|
|
24
|
+
cacheRoot: string
|
|
25
|
+
/** <marketDir>/work */
|
|
26
|
+
workRoot: string
|
|
27
|
+
/** 缓存的 index.json(结构校验由调用方做,这里只给路径) */
|
|
28
|
+
cacheIndex(url: string): string
|
|
29
|
+
/** 条目缓存目录(manifest.json + config.zip) */
|
|
30
|
+
itemDir(url: string): string
|
|
31
|
+
/** 该仓库的只读 git 工作副本目录(--depth 1,无凭据) */
|
|
32
|
+
workDir(url: string): string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 仓库 URL → 32 hex 稳定哈希(只作目录名,不作安全边界)。 */
|
|
36
|
+
function urlHash(url: string): string {
|
|
37
|
+
return createHash('sha256').update(url, 'utf8').digest('hex').slice(0, 32)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function createMarketCacheLayout(marketDir: string): MarketCacheLayout {
|
|
41
|
+
const cacheRoot = join(marketDir, 'cache')
|
|
42
|
+
const workRoot = join(marketDir, 'work')
|
|
43
|
+
return {
|
|
44
|
+
cacheRoot,
|
|
45
|
+
workRoot,
|
|
46
|
+
cacheIndex: (url: string) => join(cacheRoot, urlHash(url), 'index.json'),
|
|
47
|
+
itemDir: (url: string) => join(cacheRoot, urlHash(url), 'items'),
|
|
48
|
+
workDir: (url: string) => join(workRoot, urlHash(url)),
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 读缓存的 index.json 原始文本(不存在/读不出 → null;解析与结构校验归调用方)。 */
|
|
53
|
+
export async function readMarketCacheIndexText(layout: MarketCacheLayout, url: string): Promise<string | null> {
|
|
54
|
+
try {
|
|
55
|
+
return await readFile(layout.cacheIndex(url), 'utf8')
|
|
56
|
+
} catch {
|
|
57
|
+
return null
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 条目是否已有完整缓存(manifest.json + config.zip 都在才算)。 */
|
|
62
|
+
export async function marketItemCached(layout: MarketCacheLayout, url: string, itemId: string): Promise<boolean> {
|
|
63
|
+
try {
|
|
64
|
+
await access(join(layout.itemDir(url), itemId, 'config.zip'))
|
|
65
|
+
await access(join(layout.itemDir(url), itemId, 'manifest.json'))
|
|
66
|
+
return true
|
|
67
|
+
} catch {
|
|
68
|
+
return false
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 写条目缓存(manifest + config.zip)供离线重复查看。内容始终视为不可信。 */
|
|
73
|
+
export async function writeMarketItemCache(
|
|
74
|
+
layout: MarketCacheLayout,
|
|
75
|
+
url: string,
|
|
76
|
+
itemId: string,
|
|
77
|
+
manifestRaw: string,
|
|
78
|
+
zipBytes: Uint8Array,
|
|
79
|
+
): Promise<void> {
|
|
80
|
+
const dir = join(layout.itemDir(url), itemId)
|
|
81
|
+
await mkdir(dir, { recursive: true })
|
|
82
|
+
await writeFile(join(dir, 'manifest.json'), manifestRaw, 'utf8')
|
|
83
|
+
await writeFile(join(dir, 'config.zip'), zipBytes)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 清理滞留在 tmpDir 的过期市场暂存 zip(market-*.zip 与发布向导的 publish-*.zip)。
|
|
88
|
+
* 一次性尽力而为:任何读取/删除失败都只跳过,不影响主流程。
|
|
89
|
+
* 返回被删掉的文件名(便于单测与诊断;生产调用方可忽略)。
|
|
90
|
+
*/
|
|
91
|
+
export async function pruneStagedMarketZips(
|
|
92
|
+
tmpDir: string,
|
|
93
|
+
retentionMs: number = MARKET_TMP_RETENTION_MS,
|
|
94
|
+
now: number = Date.now(),
|
|
95
|
+
): Promise<string[]> {
|
|
96
|
+
const removed: string[] = []
|
|
97
|
+
let names: string[]
|
|
98
|
+
try {
|
|
99
|
+
names = await readdir(tmpDir)
|
|
100
|
+
} catch {
|
|
101
|
+
return removed // tmpDir 读不出 → 跳过
|
|
102
|
+
}
|
|
103
|
+
for (const name of names) {
|
|
104
|
+
if ((!name.startsWith('market-') && !name.startsWith('publish-')) || !name.endsWith('.zip')) continue
|
|
105
|
+
const p = join(tmpDir, name)
|
|
106
|
+
try {
|
|
107
|
+
const st = await stat(p)
|
|
108
|
+
if (now - st.mtimeMs <= retentionMs) continue
|
|
109
|
+
await rm(p, { force: true, recursive: true })
|
|
110
|
+
removed.push(name)
|
|
111
|
+
} catch {
|
|
112
|
+
// 单文件 stat/删除失败 → 跳过(尽力而为)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return removed
|
|
116
|
+
}
|
|
@@ -91,6 +91,7 @@ export const zh = {
|
|
|
91
91
|
'core.migrationHistory.resultSuccess': '成功',
|
|
92
92
|
'core.migrationHistory.resultFailed': '失败',
|
|
93
93
|
'core.migrationHistory.resultSkipped': '跳过',
|
|
94
|
+
'core.migrationHistory.resultPending': '待裁决',
|
|
94
95
|
|
|
95
96
|
// ---------- local-plugin-pack ----------
|
|
96
97
|
'core.localPluginPack.dirCreateFailed': '本地插件打包目录创建失败,已跳过全部本地插件: {reason}',
|
|
@@ -405,6 +406,7 @@ export const en: Record<keyof typeof zh, string> = {
|
|
|
405
406
|
'core.migrationHistory.resultSuccess': 'success',
|
|
406
407
|
'core.migrationHistory.resultFailed': 'failed',
|
|
407
408
|
'core.migrationHistory.resultSkipped': 'skipped',
|
|
409
|
+
'core.migrationHistory.resultPending': 'needs decision',
|
|
408
410
|
|
|
409
411
|
// ---------- local-plugin-pack ----------
|
|
410
412
|
'core.localPluginPack.dirCreateFailed': 'Failed to create the local plugin packing directory; skipped all local plugins: {reason}',
|
|
@@ -334,6 +334,25 @@ test('QUERYABLE:parseHistoryQuery 解析过滤参数并丢弃非法 kind', ()
|
|
|
334
334
|
assert.deepEqual(q.sections, ['plugins']);
|
|
335
335
|
});
|
|
336
336
|
|
|
337
|
+
test('0.4.1 待裁决:result=pending 可落盘读回、可被查询过滤、导出写人话而非裸枚举', async (t) => {
|
|
338
|
+
const dir = tmp(t);
|
|
339
|
+
const appended = await mkStore(dir).append(makeRaw({ kind: 'autosync', result: 'pending', summary: '自动同步有 1 个分区待裁决' }));
|
|
340
|
+
assert.equal(appended.ok, true);
|
|
341
|
+
|
|
342
|
+
const read = await mkStore(dir).read();
|
|
343
|
+
assert.deepEqual(read.corrupted, [], 'pending 是合法结果 —— 不得被当成篡改条目静默丢弃');
|
|
344
|
+
assert.equal(read.entries.length, 1);
|
|
345
|
+
assert.equal(read.entries[0]!.result, 'pending', '读回必须保留 pending(否则「待裁决」在刷新后消失)');
|
|
346
|
+
|
|
347
|
+
assert.deepEqual(parseHistoryQuery({ result: 'pending,failed' }).result, ['pending', 'failed'], '过滤白名单必须认 pending');
|
|
348
|
+
assert.equal(queryHistory(read.entries, { result: ['pending'] }).length, 1);
|
|
349
|
+
assert.equal(queryHistory(read.entries, { result: ['failed'] }).length, 0, 'pending 不得被当成 failed 命中');
|
|
350
|
+
|
|
351
|
+
const md = renderExport(read.entries, 'markdown', 'zh');
|
|
352
|
+
assert.match(md, /待裁决/, '导出要写人话');
|
|
353
|
+
assert.ok(!md.includes('| pending |'), '原文列绝不出现裸枚举值');
|
|
354
|
+
});
|
|
355
|
+
|
|
337
356
|
test('EXPORTABLE:renderExport json 输出合法 JSON + 统计', () => {
|
|
338
357
|
const entries = [sanitizeEntry(makeRaw()), sanitizeEntry(makeRaw({ kind: 'restore', result: 'failed' }))];
|
|
339
358
|
const json = renderExport(entries, 'json');
|
|
@@ -79,8 +79,29 @@ const MIGRATION_KINDS = [
|
|
|
79
79
|
/** §5 覆盖的操作 kind(COMPLETE 不变量;常量枚举,天然非敏感)。 */
|
|
80
80
|
export type MigrationKind = (typeof MIGRATION_KINDS)[number];
|
|
81
81
|
|
|
82
|
-
/**
|
|
83
|
-
|
|
82
|
+
/**
|
|
83
|
+
* 操作结果。
|
|
84
|
+
*
|
|
85
|
+
* 'pending'(0.4.1):操作**跑完了但仍有待裁决项**(自动同步上传成功、下行冲突未裁决;
|
|
86
|
+
* 合并已应用一部分)。它不是 failed —— 网络/凭据/repo 都是好的;也不是 skipped ——
|
|
87
|
+
* 那一轮确实做了事。旧实现把 partial 直接折成 'failed',用户看到「自动同步 失败」而
|
|
88
|
+
* 实际只需要在同步页确认一次冲突。读侧(parseEntry / query 解析)必须接受该值,
|
|
89
|
+
* 否则含 pending 的历史条目会被整条丢弃。
|
|
90
|
+
*/
|
|
91
|
+
export type MigrationResult = 'success' | 'failed' | 'skipped' | 'pending';
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 自动同步一轮的状态 → 历史 result(宿主 appendHistoryFn 的唯一映射,0.4.1)。
|
|
95
|
+
*
|
|
96
|
+
* 关键一条:`partial`(跑完了但仍有待裁决分区)**不是** failed —— 通道与凭据都正常,
|
|
97
|
+
* 只是需要用户在同步页确认一次冲突。落成 failed 会让首页红字报「同步失败」,
|
|
98
|
+
* 用户据此去查网络/凭据,方向完全错。
|
|
99
|
+
*/
|
|
100
|
+
export function historyResultFromAutosyncStatus(status: 'success' | 'skipped' | 'partial' | 'failed'): MigrationResult {
|
|
101
|
+
if (status === 'success') return 'success';
|
|
102
|
+
if (status === 'skipped') return 'skipped';
|
|
103
|
+
return status === 'partial' ? 'pending' : 'failed';
|
|
104
|
+
}
|
|
84
105
|
|
|
85
106
|
/** 触发来源(常量)。 */
|
|
86
107
|
export type MigrationSource = 'api' | 'autosync' | 'backup-scheduler' | 'recovery' | 'cli' | 'internal';
|
|
@@ -308,7 +329,7 @@ function parseEntry(text: string): StoredMigrationHistoryEntry | null {
|
|
|
308
329
|
if (p.schemaVersion !== MIGRATION_HISTORY_SCHEMA_VERSION) return null;
|
|
309
330
|
if (!isValidMigrationKind(p.kind)) return null;
|
|
310
331
|
if (typeof p.at !== 'string' || p.at === '') return null;
|
|
311
|
-
if (!['success', 'failed', 'skipped'].includes(p.result)) return null;
|
|
332
|
+
if (!['success', 'failed', 'skipped', 'pending'].includes(p.result)) return null;
|
|
312
333
|
if (typeof p.source !== 'string') return null;
|
|
313
334
|
if (typeof p.summary !== 'string') return null;
|
|
314
335
|
// 可选字段校验
|
|
@@ -479,7 +500,9 @@ export function renderExport(entries: StoredMigrationHistoryEntry[], format: Exp
|
|
|
479
500
|
? T('core.migrationHistory.resultSuccess')
|
|
480
501
|
: r === 'failed'
|
|
481
502
|
? T('core.migrationHistory.resultFailed')
|
|
482
|
-
:
|
|
503
|
+
: r === 'pending'
|
|
504
|
+
? T('core.migrationHistory.resultPending')
|
|
505
|
+
: T('core.migrationHistory.resultSkipped');
|
|
483
506
|
|
|
484
507
|
if (format === 'json') {
|
|
485
508
|
const stats = summarizeHistory(entries);
|
|
@@ -506,7 +529,7 @@ export function parseHistoryQuery(raw: Record<string, unknown>): MigrationQuery
|
|
|
506
529
|
const kinds = parseList(raw['kind']);
|
|
507
530
|
if (kinds.length > 0) q.kinds = kinds.filter(isValidMigrationKind);
|
|
508
531
|
const results = parseList(raw['result']);
|
|
509
|
-
if (results.length > 0) q.result = results.filter((r): r is MigrationResult => r === 'success' || r === 'failed' || r === 'skipped');
|
|
532
|
+
if (results.length > 0) q.result = results.filter((r): r is MigrationResult => r === 'success' || r === 'failed' || r === 'skipped' || r === 'pending');
|
|
510
533
|
const sections = parseList(raw['sections']);
|
|
511
534
|
if (sections.length > 0) q.sections = sections;
|
|
512
535
|
const from = parseNum(raw['from']);
|
package/src/core/model-tools.ts
CHANGED
|
@@ -40,6 +40,7 @@ import { parseSyncChannel, readFullSyncConfig, readSyncConfigFor, SYNC_CHANNELS
|
|
|
40
40
|
import type { SyncConfig, SyncConfigIssue, SyncTransportType } from '../sync/sync-config.ts'
|
|
41
41
|
import type { ConfigAdapter, HostContext, SecretScanner } from './types.ts'
|
|
42
42
|
import { runWithMutationLock } from '../utils/env-lock.ts'
|
|
43
|
+
import { formatDateStamp } from '../utils/time.ts'
|
|
43
44
|
|
|
44
45
|
/* ------------------------------------------------------------ 依赖与类型 */
|
|
45
46
|
|
|
@@ -81,12 +82,6 @@ async function snapshotDirExists(deps: ModelToolsDeps, snapshotId: string): Prom
|
|
|
81
82
|
return metas.some((m) => m.id === snapshotId)
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
/** 导出文件时间戳(YYYYMMDD-HHmmss),与 host 路由 dateStamp 同构。 */
|
|
85
|
-
function dateStamp(d: Date = new Date()): string {
|
|
86
|
-
const p = (n: number): string => String(n).padStart(2, '0')
|
|
87
|
-
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`
|
|
88
|
-
}
|
|
89
|
-
|
|
90
85
|
/** SECTION_IDS 白名单过滤(未知/非法分区 id 丢弃,与 host 路由语义一致)。 */
|
|
91
86
|
function filterSectionIds(ids: readonly string[]): SectionId[] {
|
|
92
87
|
return ids.filter((id): id is SectionId => (SECTION_IDS as readonly string[]).includes(id))
|
|
@@ -137,7 +132,7 @@ export function createModelTools(deps: ModelToolsDeps) {
|
|
|
137
132
|
// P2-C(Phase 8):config_backup 接入 GLOBAL mutation lock,与导入/恢复/同步/定时备份等
|
|
138
133
|
// destructive 操作互斥(写 exports 产物期间确保 live config 不被并发改动,产物一致)。
|
|
139
134
|
// 无锁环境(测试/mock)→ 不锁定直接执行;锁被占用 → 抛 EnvironmentLockUnavailableError。
|
|
140
|
-
const outPath = join(deps.exportsDir, `dsh-config-${
|
|
135
|
+
const outPath = join(deps.exportsDir, `dsh-config-${formatDateStamp()}-${randomBytes(3).toString('hex')}.zip`)
|
|
141
136
|
return runWithMutationLock(
|
|
142
137
|
deps.host.mutationLock,
|
|
143
138
|
{ op: 'model-backup', target: 'exports', isBlocked: () => deps.host.safeModeIsBlocked?.() ?? false },
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* task-1/D(tech-debt #4):恢复**单步失败**的可见性与可续跑判定(只加测试,不改引擎)。
|
|
3
|
+
*
|
|
4
|
+
* 回归锚点(tech-debt「恢复没有整笔回滚;先补崩溃回归测试」的对偶面):
|
|
5
|
+
* 崩溃(restore-crash-injection.test.ts)验的是「进程没了之后 journal 怎么说」;
|
|
6
|
+
* 这里验的是**进程活着、某一步真失败**之后三件事是否仍然诚实:
|
|
7
|
+
* 1. 失败进 report.failed(不是静默吞掉),且原因非空;
|
|
8
|
+
* 2. 该步在 journal 里的 WAL status = 'attention'(绝不记 done,否则 reconcile 会把半成品判成完成);
|
|
9
|
+
* 3. **后续动作继续执行**(单步失败不退化成整笔中止):另两个文件仍收敛到快照态;
|
|
10
|
+
* 4. 反悔副本(report.preRestoreDir)真实存在且可读 —— 失败现场可人工回退;
|
|
11
|
+
* 5. 续跑判定 judgeRestoreResume 见 attention 步 ⇒ 拒绝(code='step-attention'),
|
|
12
|
+
* 绝不把「有一步没做成」的 journal 当成可静默续跑。
|
|
13
|
+
*
|
|
14
|
+
* 制造「计划期通过、执行期必然失败」的失败点:目标 'blocked/x.yaml' 的中间段 `<home>/blocked`
|
|
15
|
+
* 是**普通文件**。计划期目标安全闸(assertPlanTargetsSafe)只解析「最近存在祖先」的真实落点,
|
|
16
|
+
* 该祖先仍在 home 内 ⇒ 通过;执行期 atomicCopyFile 的 mkdir(dirname) 撞上普通文件 ⇒ 抛错。
|
|
17
|
+
*/
|
|
18
|
+
import test from 'node:test';
|
|
19
|
+
import assert from 'node:assert/strict';
|
|
20
|
+
import fssync from 'node:fs';
|
|
21
|
+
import fs from 'node:fs/promises';
|
|
22
|
+
import os from 'node:os';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
|
|
25
|
+
import { ABSENT_FINGERPRINT, JournalStore, createJournalEntry, generateOperationId } from './journal.ts';
|
|
26
|
+
import { planRestore, restore } from './restore.ts';
|
|
27
|
+
import type { RestoreJournalPort } from './restore-wal.ts';
|
|
28
|
+
import { judgeRestoreResume } from './restore-resume.ts';
|
|
29
|
+
import type { Snapshot } from './types.ts';
|
|
30
|
+
|
|
31
|
+
const SNAP_ID = 'snap-restore-step-fail';
|
|
32
|
+
const FP = 'fp-restore-step-fail';
|
|
33
|
+
|
|
34
|
+
interface Fixture {
|
|
35
|
+
workDir: string;
|
|
36
|
+
homeDir: string;
|
|
37
|
+
snapshotDir: string;
|
|
38
|
+
transactionsDir: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function workdir(t: test.TestContext): string {
|
|
42
|
+
const dir = fssync.mkdtempSync(path.join(os.tmpdir(), 'dsh-cm-restore-fail-'));
|
|
43
|
+
t.after(() => fssync.rmSync(dir, { recursive: true, force: true }));
|
|
44
|
+
return dir;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const CURRENT: Record<string, string> = {
|
|
48
|
+
'a-settings.yaml': 'CURRENT-a',
|
|
49
|
+
'z-extra.yaml': 'CURRENT-z',
|
|
50
|
+
};
|
|
51
|
+
const SNAPSHOT: Record<string, string> = {
|
|
52
|
+
'a-settings.yaml': 'SNAP-a',
|
|
53
|
+
'blocked/x.yaml': 'SNAP-x',
|
|
54
|
+
'z-extra.yaml': 'SNAP-z',
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** home 三样:两个正常文件 + 一个占住路径的普通文件 `blocked`;快照三个 hostFileBackups。 */
|
|
58
|
+
async function makeFixture(workDir: string): Promise<Fixture> {
|
|
59
|
+
const homeDir = path.join(workDir, 'home');
|
|
60
|
+
const snapshotDir = path.join(workDir, 'data', 'snapshots', SNAP_ID);
|
|
61
|
+
await fs.mkdir(path.join(snapshotDir, 'blobs', 'host'), { recursive: true });
|
|
62
|
+
await fs.mkdir(homeDir, { recursive: true });
|
|
63
|
+
for (const [rel, body] of Object.entries(CURRENT)) {
|
|
64
|
+
await fs.writeFile(path.join(homeDir, rel), body, 'utf8');
|
|
65
|
+
}
|
|
66
|
+
// 计划期必须是干净的:这一层先建成**真目录**,`blocked/x.yaml` 只是「快照里有、本机没有」。
|
|
67
|
+
// 计划期目标安全闸只解析「最近存在祖先」的真实落点,普通文件当中间段在 POSIX 上会被它直接判越界
|
|
68
|
+
// (Linux 实测:assertPlanTargetsSafe 抛「路径越界: blocked/x.yaml」),那样就测不到执行期失败。
|
|
69
|
+
await fs.mkdir(path.join(homeDir, 'blocked'), { recursive: true });
|
|
70
|
+
const snapshot: Snapshot = {
|
|
71
|
+
id: SNAP_ID,
|
|
72
|
+
createdAt: '2026-10-22T00:00:00.000Z',
|
|
73
|
+
sourceZip: 'audit.zip',
|
|
74
|
+
entries: [],
|
|
75
|
+
status: 'done',
|
|
76
|
+
beforePlugins: [],
|
|
77
|
+
hostFileBackups: [
|
|
78
|
+
{ relPath: 'a-settings.yaml', blobPath: 'blobs/host/a', existed: true },
|
|
79
|
+
{ relPath: 'blocked/x.yaml', blobPath: 'blobs/host/x', existed: true },
|
|
80
|
+
{ relPath: 'z-extra.yaml', blobPath: 'blobs/host/z', existed: true },
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
await fs.writeFile(path.join(snapshotDir, 'snapshot.json'), JSON.stringify(snapshot, null, 2), 'utf8');
|
|
84
|
+
await fs.writeFile(path.join(snapshotDir, 'blobs', 'host', 'a'), SNAPSHOT['a-settings.yaml']!, 'utf8');
|
|
85
|
+
await fs.writeFile(path.join(snapshotDir, 'blobs', 'host', 'x'), SNAPSHOT['blocked/x.yaml']!, 'utf8');
|
|
86
|
+
await fs.writeFile(path.join(snapshotDir, 'blobs', 'host', 'z'), SNAPSHOT['z-extra.yaml']!, 'utf8');
|
|
87
|
+
return { workDir, homeDir, snapshotDir, transactionsDir: path.join(workDir, 'data', 'transactions') };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 与 phase3-host 的 JournalRunContext 同形的端口:WAL step 直接落进**真** JournalStore。 */
|
|
91
|
+
function makePort(store: JournalStore, opId: string): RestoreJournalPort {
|
|
92
|
+
return {
|
|
93
|
+
bindSnapshot: async (snapshotId) => {
|
|
94
|
+
await store.update(opId, (j) => ({ ...j, snapshotId }));
|
|
95
|
+
},
|
|
96
|
+
markApplying: async () => undefined,
|
|
97
|
+
recordStep: async (rec) => {
|
|
98
|
+
await store.update(opId, (j) => {
|
|
99
|
+
const plannedSteps = j.plannedSteps.includes(rec.id) ? j.plannedSteps : [...j.plannedSteps, rec.id];
|
|
100
|
+
return {
|
|
101
|
+
...j,
|
|
102
|
+
plannedSteps,
|
|
103
|
+
steps: {
|
|
104
|
+
...j.steps,
|
|
105
|
+
[rec.id]: {
|
|
106
|
+
adapter: rec.adapter,
|
|
107
|
+
ref: rec.ref,
|
|
108
|
+
kind: rec.kind,
|
|
109
|
+
external: rec.external === true,
|
|
110
|
+
beforeFp: rec.beforeFp ?? null,
|
|
111
|
+
afterFp: rec.afterFp ?? null,
|
|
112
|
+
status: rec.status ?? 'planned',
|
|
113
|
+
appliedAt: new Date().toISOString(),
|
|
114
|
+
message: rec.message ?? null,
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
});
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
test('core-F1 单步失败:report.failed 可见、该步 WAL=attention、后续动作继续执行、反悔副本可读、续跑判定拒绝', async (t) => {
|
|
124
|
+
const f = await makeFixture(workdir(t));
|
|
125
|
+
const store = new JournalStore({ transactionsDir: f.transactionsDir });
|
|
126
|
+
await store.ensureDirs();
|
|
127
|
+
const opId = generateOperationId();
|
|
128
|
+
await store.create(createJournalEntry('cli-restore', {
|
|
129
|
+
operationId: opId,
|
|
130
|
+
ownerInstanceId: 'restore-step-fail-owner',
|
|
131
|
+
lockId: 'restore-step-fail-owner',
|
|
132
|
+
packageVersion: '0.1.79',
|
|
133
|
+
environmentFingerprint: FP,
|
|
134
|
+
}, new Date().toISOString()));
|
|
135
|
+
await store.transition(opId, 'APPLYING');
|
|
136
|
+
|
|
137
|
+
// 续跑判定要的是「本次重新规划的动作」,所以先自己规划一份留下(计划期已过目标安全闸)。
|
|
138
|
+
const plan = await planRestore({ snapshotDir: f.snapshotDir, homeDir: f.homeDir, profile: 'web' });
|
|
139
|
+
const failAbs = path.join(f.homeDir, 'blocked', 'x.yaml');
|
|
140
|
+
assert.deepEqual(
|
|
141
|
+
plan.actions.filter((a) => a.kind !== 'skip').map((a) => a.kind),
|
|
142
|
+
['hostFileRestore', 'hostFileRestore', 'hostFileRestore'],
|
|
143
|
+
'夹具里三个动盘动作都应是整文件还原(含那个必然失败的)',
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
// 计划已过闸,此刻把该动作的**源 blob** 换成目录:目标侧路径依旧合法(计划期与执行期的目标安全闸都不受
|
|
147
|
+
// 影响),但执行期 atomicCopyFile 的 copyFile(源=目录, 临时文件) 必然抛错(POSIX EISDIR / Windows EPERM)。
|
|
148
|
+
// 早先的写法是「目标父路径换成普通文件」,在 POSIX 上会被计划期目标安全闸先判越界(lstat 目标抛 ENOTDIR ⇒
|
|
149
|
+
// target-unreadable),于是测到的是计划期拒绝而不是执行期失败 —— 那是平台相关的假失败。
|
|
150
|
+
const brokenBlob = path.join(f.snapshotDir, 'blobs', 'host', 'x');
|
|
151
|
+
await fs.rm(brokenBlob, { force: true });
|
|
152
|
+
await fs.mkdir(brokenBlob, { recursive: true });
|
|
153
|
+
|
|
154
|
+
const report = await restore({
|
|
155
|
+
snapshotDir: f.snapshotDir,
|
|
156
|
+
homeDir: f.homeDir,
|
|
157
|
+
profile: 'web',
|
|
158
|
+
journal: makePort(store, opId),
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// ① 失败可见:item 是被写的目标,reason 非空(绝不静默吞)
|
|
162
|
+
assert.equal(report.failed.length, 1, '应恰有 1 个失败项');
|
|
163
|
+
assert.equal(report.failed[0]!.item, 'blocked/x.yaml');
|
|
164
|
+
assert.ok(report.failed[0]!.reason.length > 0, '失败原因不得为空串');
|
|
165
|
+
|
|
166
|
+
// ③ 单步失败不退化成整笔中止:先后两个文件都收敛到快照态
|
|
167
|
+
assert.deepEqual(report.restored.slice().sort(), ['a-settings.yaml', 'z-extra.yaml']);
|
|
168
|
+
assert.equal(await fs.readFile(path.join(f.homeDir, 'a-settings.yaml'), 'utf8'), 'SNAP-a');
|
|
169
|
+
assert.equal(await fs.readFile(path.join(f.homeDir, 'z-extra.yaml'), 'utf8'), 'SNAP-z');
|
|
170
|
+
// 失败目标一个字节都没写(父目录仍在、仍是空目录,未被清掉或替换)
|
|
171
|
+
assert.ok((await fs.stat(path.join(f.homeDir, 'blocked'))).isDirectory(), '父目录不该被替换');
|
|
172
|
+
assert.deepEqual(await fs.readdir(path.join(f.homeDir, 'blocked')), [], '失败目标不应留下任何产物');
|
|
173
|
+
await assert.rejects(fs.access(failAbs), '失败目标不应被创建');
|
|
174
|
+
|
|
175
|
+
// ② journal 逐动作终态:attention 而不是 done(否则 reconcile 会把半成品判成完成)
|
|
176
|
+
const active = await store.scanActive();
|
|
177
|
+
assert.equal(active.length, 1);
|
|
178
|
+
const journal = await store.loadActive(active[0]!);
|
|
179
|
+
assert.ok(journal, 'active journal 应可读');
|
|
180
|
+
assert.equal(journal.state, 'APPLYING', '恢复不写终态(终态由 runJournaled 尾操作写)');
|
|
181
|
+
assert.equal(Object.keys(journal.steps).length, 3, '三个动盘动作全部预登记(不是只登记已执行的)');
|
|
182
|
+
const byRef = new Map(Object.entries(journal.steps).map(([id, step]) => [step.ref, { id, step }]));
|
|
183
|
+
const failedStep = byRef.get(failAbs);
|
|
184
|
+
assert.ok(failedStep, '失败目标应有对应 WAL step');
|
|
185
|
+
assert.equal(failedStep!.step.status, 'attention', '失败步必须记 attention');
|
|
186
|
+
assert.ok((failedStep!.step.message ?? '').length > 0, 'attention 步要带原因');
|
|
187
|
+
assert.equal(failedStep!.step.afterFp, ABSENT_FINGERPRINT, '写入失败后目标仍是「可证明不存在」');
|
|
188
|
+
for (const rel of ['a-settings.yaml', 'z-extra.yaml']) {
|
|
189
|
+
const ok = byRef.get(path.join(f.homeDir, rel));
|
|
190
|
+
assert.equal(ok?.step.status, 'done', rel + ' 应记 done');
|
|
191
|
+
assert.notEqual(ok?.step.afterFp, null, rel + ' 的 done 步应带 afterFp(可被 reconcile 证明)');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// ④ 反悔副本真实存在且可读:失败现场能人工回退
|
|
195
|
+
assert.ok(report.preRestoreDir !== undefined, '有文件被覆盖 ⇒ 必须产出 attempt 目录');
|
|
196
|
+
const preFiles = (await fs.readdir(report.preRestoreDir!)).sort();
|
|
197
|
+
assert.deepEqual(preFiles, ['0001-a-settings.yaml', '0002-z-extra.yaml'], '只备份真正被覆盖的两份');
|
|
198
|
+
assert.equal(await fs.readFile(path.join(report.preRestoreDir!, '0001-a-settings.yaml'), 'utf8'), 'CURRENT-a');
|
|
199
|
+
assert.equal(await fs.readFile(path.join(report.preRestoreDir!, '0002-z-extra.yaml'), 'utf8'), 'CURRENT-z');
|
|
200
|
+
|
|
201
|
+
// ⑤ 有 attention 步 ⇒ 续跑判定拒绝(在指纹校验之前就拒,绝不静默续跑)
|
|
202
|
+
const verdict = await judgeRestoreResume({
|
|
203
|
+
journal: journal!,
|
|
204
|
+
actions: plan.actions,
|
|
205
|
+
snapshotId: SNAP_ID,
|
|
206
|
+
homeDir: f.homeDir,
|
|
207
|
+
});
|
|
208
|
+
assert.equal(verdict.ok, false, '含 attention 步的 journal 不得被判为可续跑');
|
|
209
|
+
assert.equal(verdict.ok === false ? verdict.code : '', 'step-attention');
|
|
210
|
+
});
|
package/src/core/restore.ts
CHANGED
|
@@ -39,6 +39,7 @@ import {
|
|
|
39
39
|
import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from './restore-wal.ts';
|
|
40
40
|
import type { RestoreResumeHint } from './restore-resume.ts';
|
|
41
41
|
import { parseJsonSafe } from '../utils/json.ts';
|
|
42
|
+
import { isPathInside } from '../utils/paths.ts';
|
|
42
43
|
import { atomicCopyFile, atomicWriteFile } from '../utils/atomic-write.ts';
|
|
43
44
|
import type { SectionId } from '../schema/types.ts';
|
|
44
45
|
import type { HostContext, Snapshot, SnapshotStatus } from './types.ts';
|
|
@@ -214,16 +215,17 @@ async function fileExists(p: string): Promise<boolean> {
|
|
|
214
215
|
}
|
|
215
216
|
}
|
|
216
217
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
218
|
+
/*
|
|
219
|
+
* 越界防御只有一份实现:`src/utils/paths.ts` 的 `isPathInside`。
|
|
220
|
+
* 这里曾自带 `isWithinHome`(`abs.startsWith(root + sep)`),`verify-recovery.ts` 又逐字复制了一份 ——
|
|
221
|
+
* 四份同义守卫分散在四个模块,其中三份用 `rel.startsWith('..')` 判越界,
|
|
222
|
+
* 会把名字真叫 `..foo` 的兄弟目录误判成逃逸(`path.relative('/a/b','/a/b/..foo') === '..foo'`)。
|
|
223
|
+
*/
|
|
222
224
|
|
|
223
225
|
/** homeDir 内绝对路径(越界抛错) */
|
|
224
226
|
export function homeAbs(homeDir: string, relPath: string, msg: MsgFunc): string {
|
|
225
227
|
const abs = path.resolve(homeDir, relPath);
|
|
226
|
-
if (!
|
|
228
|
+
if (!isPathInside(abs, homeDir)) throw new Error(msg('restore.pathEscape', { path: relPath }));
|
|
227
229
|
return abs;
|
|
228
230
|
}
|
|
229
231
|
|
|
@@ -243,20 +245,20 @@ export function resolveRestoreTargetAbs(homeDir: string, target: string): string
|
|
|
243
245
|
/** 快照目录内 blob 绝对路径(防 snapshot.json 里伪造 ../ 越界读) */
|
|
244
246
|
export function blobAbs(snapshotDir: string, blobPath: string, msg: MsgFunc): string {
|
|
245
247
|
const abs = path.resolve(snapshotDir, blobPath);
|
|
246
|
-
if (!
|
|
248
|
+
if (!isPathInside(abs, snapshotDir)) throw new Error(msg('restore.blobPathEscape', { path: blobPath }));
|
|
247
249
|
return abs;
|
|
248
250
|
}
|
|
249
251
|
|
|
250
252
|
/** 绝对路径 → 相对 $DSH_HOME(跨平台归一为 / 分隔;越界返回空串) */
|
|
251
253
|
function toRelPath(homeDir: string, abs: string): string {
|
|
252
|
-
if (!
|
|
254
|
+
if (!isPathInside(abs, homeDir)) return '';
|
|
253
255
|
return path.relative(homeDir, abs).split(path.sep).join('/');
|
|
254
256
|
}
|
|
255
257
|
|
|
256
258
|
/* ------------------------- 目标侧真实路径围栏(junction / symlink 防写穿,D4) */
|
|
257
259
|
|
|
258
260
|
/**
|
|
259
|
-
*
|
|
261
|
+
* 目标侧路径安全:纯字符串围栏(`isPathInside`)挡不住两类逃逸 ——
|
|
260
262
|
* 1. `$DSH_HOME` 内某个**目录**本身是链接(Windows junction / POSIX 目录 symlink):
|
|
261
263
|
* 字符串前缀成立,真实落点却在 home 之外;
|
|
262
264
|
* 2. **目标文件本身是 symlink**:`atomicCopyFile` 缺省 `symlink:'follow'`
|
|
@@ -291,11 +293,7 @@ function foldPathKey(p: string): string {
|
|
|
291
293
|
return process.platform === 'win32' ? p.toLowerCase() : p;
|
|
292
294
|
}
|
|
293
295
|
|
|
294
|
-
|
|
295
|
-
function isRealInside(root: string, child: string): boolean {
|
|
296
|
-
const rel = path.relative(foldPathKey(root), foldPathKey(child));
|
|
297
|
-
return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
|
|
298
|
-
}
|
|
296
|
+
/* child 是否位于 root 之内(两侧都应是已解析的真实路径)→ `isPathInside`(共享实现,Windows 折大小写)。 */
|
|
299
297
|
|
|
300
298
|
/**
|
|
301
299
|
* 生成「目标安全性」判定函数;返回 null = 安全,否则返回**机器码**(只作日志/诊断,
|
|
@@ -340,7 +338,7 @@ function createTargetSafetyChecker(homeDir: string): (absTarget: string) => stri
|
|
|
340
338
|
}
|
|
341
339
|
const parentReal = projectedParentReal(path.dirname(absTarget));
|
|
342
340
|
if (parentReal === null) return 'parent-unresolvable';
|
|
343
|
-
if (!
|
|
341
|
+
if (!isPathInside(parentReal, rootReal)) return 'parent-escape';
|
|
344
342
|
return null;
|
|
345
343
|
};
|
|
346
344
|
}
|
|
@@ -359,7 +357,7 @@ function assertPlanTargetsSafe(actions: RestoreAction[], homeDir: string, msg: M
|
|
|
359
357
|
for (const a of actions) {
|
|
360
358
|
if (a.target === undefined || !WRITE_TARGET_KINDS.has(a.kind)) continue;
|
|
361
359
|
const abs = path.resolve(homeDir, a.target);
|
|
362
|
-
if (!
|
|
360
|
+
if (!isPathInside(abs, homeDir)) continue;
|
|
363
361
|
const unsafe = check(abs);
|
|
364
362
|
if (unsafe !== null) {
|
|
365
363
|
// 复用既有「路径越界」语义与错误码:planRestore 顶层抛出 ⇒ restore() 一个字节都没写。
|
|
@@ -467,7 +465,7 @@ export interface RestoreSnapshotValidation {
|
|
|
467
465
|
/** 递归检查快照目录内关键文件非 symlink(F25:拒绝 symlink 化 metadata/blob 写穿)。 */
|
|
468
466
|
async function assertNoSnapshotSymlink(dir: string, rel: string): Promise<string | null> {
|
|
469
467
|
const p = path.join(dir, rel);
|
|
470
|
-
if (!
|
|
468
|
+
if (!isPathInside(p, dir)) return engineMsg('core.restore.pathEscaped', { rel });
|
|
471
469
|
try {
|
|
472
470
|
const st = await fs.lstat(p);
|
|
473
471
|
if (st.isSymbolicLink()) return engineMsg('core.restore.symlinkCriticalFile', { rel });
|
|
@@ -500,7 +498,7 @@ export async function validateSnapshotForRestore(
|
|
|
500
498
|
|
|
501
499
|
// 目录边界:snapshotDir 必须紧邻 snapshotsRoot 下的一层
|
|
502
500
|
const rel = path.relative(snapshotsRoot, snapshotDir).split(path.sep).join('/');
|
|
503
|
-
if (rel === '' || rel.includes('/') || !
|
|
501
|
+
if (rel === '' || rel.includes('/') || !isPathInside(snapshotDir, snapshotsRoot)) {
|
|
504
502
|
return { verdict: 'INVALID', reason: engineMsg('core.restore.snapshotDirOutOfBounds') };
|
|
505
503
|
}
|
|
506
504
|
|
|
@@ -34,6 +34,7 @@ import { validateSnapshotForRestore } from './restore.ts';
|
|
|
34
34
|
import type { RecoveryVerification, RecoveryVerificationVerdict } from './journal.ts';
|
|
35
35
|
import type { HostContext, Snapshot } from './types.ts';
|
|
36
36
|
import type { SectionId } from '../schema/types.ts';
|
|
37
|
+
import { isPathInside } from '../utils/paths.ts';
|
|
37
38
|
|
|
38
39
|
export interface VerifyRecoveryOptions {
|
|
39
40
|
/** 快照根目录(<snapshotsDir>,<snapshotDir> 的直接父级)。 */
|
|
@@ -44,22 +45,18 @@ export interface VerifyRecoveryOptions {
|
|
|
44
45
|
expectedOperationId?: string;
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
|
|
48
|
-
function isWithinHome(homeDir: string, abs: string): boolean {
|
|
49
|
-
const root = path.resolve(homeDir);
|
|
50
|
-
return abs === root || abs.startsWith(root + path.sep);
|
|
51
|
-
}
|
|
48
|
+
/* 越界防御只有一份实现:`src/utils/paths.ts` 的 `isPathInside`(此处原有逐字复制的一份)。 */
|
|
52
49
|
|
|
53
50
|
/** 绝对路径 → 相对 homeDir(跨平台归一为 / 分隔;越界返回空串) */
|
|
54
51
|
function toRelPath(homeDir: string, abs: string): string {
|
|
55
|
-
if (!
|
|
52
|
+
if (!isPathInside(abs, homeDir)) return '';
|
|
56
53
|
return path.relative(homeDir, abs).split(path.sep).join('/');
|
|
57
54
|
}
|
|
58
55
|
|
|
59
56
|
/** 快照目录内 blob 绝对路径(防 snapshot.json 里伪造 ../ 越界读) */
|
|
60
57
|
function blobAbs(snapshotDir: string, blobPath: string): string {
|
|
61
58
|
const abs = path.resolve(snapshotDir, blobPath);
|
|
62
|
-
if (!
|
|
59
|
+
if (!isPathInside(abs, snapshotDir)) throw new Error(engineMsg('core.verifyRecovery.blobPathEscaped', { path: blobPath }));
|
|
63
60
|
return abs;
|
|
64
61
|
}
|
|
65
62
|
|