Skip to content

A full-featured download manager.

fix(legacy-import): enable native windows checkpoint activation (#2397)

Dr_rOot122bf3b244bd
diff --git a/docs/legacy-migration.md b/docs/legacy-migration.md
new file mode 100644
index 00000000..15a85d37
--- /dev/null
+++ b/docs/legacy-migration.md
@@ -0,0 +1,51 @@
+# Migrating legacy Motrix downloads
+
+The desktop Migration Assistant imports selected Motrix v1 records paused.
+Keep a backup of the old profile and downloads, close the old application, and
+review the selected tasks before importing. Importing records never starts a
+transfer or changes the original files.
+
+## Resuming BitTorrent downloads
+
+Supply the original torrent metadata when requested, confirm the original
+download directory, and explicitly activate the task. Motrix preserves the
+original file selection. The engine imports the `.aria2` checkpoint, creates a
+paused task with a durable authorized metadata backup, and verifies its binding
+before requesting resume. Existing pieces are checked before transfer.
+
+This requires the running engine to advertise `SQLite3-Persistence`,
+`LegacyCheckpointImportV1`, and `LegacyTorrentMetadataV1`. A custom or older
+engine without these capabilities cannot activate imported progress. Motrix does
+not fall back to a torrent upload that would lose the authorized metadata on
+restart.
+
+## Windows destinations
+
+Windows progress import requires a local fixed NTFS volume. Payloads and the
+metadata backup must be owned by the account running Motrix, with no write grant
+to other users apart from SYSTEM and Administrators. Motrix does not rewrite the
+permissions of your downloads. Close other programs writing to these files
+before activation.
+
+Unicode names and long paths are supported. Network shares, FAT/exFAT volumes,
+junctions, symbolic links, cloud reparse points, hard-linked files, alternate data
+streams and aliased paths are refused. Use the original canonical directory;
+relocating files or changing their identity requires a separate download.
+
+## HTTP and recovery
+
+Imported HTTP records download into a separate directory when explicitly
+activated. A historical checkpoint alone does not prove the remote object is
+unchanged, so the assistant does not reuse historical HTTP bytes in place.
+
+After a restart, authorized legacy BitTorrent tasks return paused. Check their
+state and explicitly resume. A replaced or modified payload or metadata backup
+invalidates recovery; putting an old file back does not revive an invalidated
+grant. If an activation response is lost, Motrix reconciles its saved token and
+GID instead of blindly creating a duplicate task.
+
+Retain the engine's `*.pre-schema5-*.db` backup when upgrading an old database.
+It contains the state before the schema upgrade. An older engine cannot open the
+newer schema; stop all engines and restore a verified backup to a separate path
+if a downgrade is necessary. Existing released engines and application packages
+are immutable; support depends on the engine bundled with the installed build.
diff --git a/docs/legacy-migration.zh-CN.md b/docs/legacy-migration.zh-CN.md
new file mode 100644
index 00000000..2aaa45e1
--- /dev/null
+++ b/docs/legacy-migration.zh-CN.md
@@ -0,0 +1,38 @@
+# 迁移旧版 Motrix 下载
+
+桌面端迁移助手会将选中的 Motrix v1 任务导入为暂停记录。请先备份旧配置和下载
+文件,关闭旧版应用,并核对待导入的任务。导入记录不会开始传输或修改原文件。
+
+## 恢复 BitTorrent 下载
+
+按提示提供原始 torrent 元数据,确认原下载目录,再明确激活任务。Motrix 会保留
+原始文件选择。引擎先导入 `.aria2` checkpoint,再使用已授权元数据的持久化备份
+创建暂停任务;应用验证绑定后才请求恢复下载。已有分片会在传输前经过校验。
+
+此功能要求运行中的引擎报告 `SQLite3-Persistence`、`LegacyCheckpointImportV1`
+和 `LegacyTorrentMetadataV1` 三项能力。缺少这些能力的旧版或自定义引擎不能激活
+已导入的进度。Motrix 不会回退到重启后可能丢失已授权元数据的普通 torrent 上传。
+
+## Windows 下载目录
+
+Windows 进度导入要求文件位于本地固定 NTFS 卷。下载文件和元数据备份必须归运行
+Motrix 的账户所有,且除 SYSTEM 和 Administrators 外,不能向其他用户授予写入
+权限。Motrix 不会改写下载文件的权限。激活前请关闭正在写入这些文件的其他程序。
+
+支持 Unicode 文件名和长路径。网络共享、FAT/exFAT 卷、junction、符号链接、云盘
+reparse point、硬链接文件、备用数据流和别名路径会被拒绝。请使用原始规范目录;
+移动文件或改变文件身份后,需要作为独立下载处理。
+
+## HTTP 下载与恢复
+
+导入的 HTTP 记录在明确激活后,会下载到独立目录。历史 checkpoint 本身无法证明
+远端对象没有变化,因此迁移助手不会在原位置复用历史 HTTP 数据。
+
+重启后,已授权的旧版 BitTorrent 任务仍以暂停状态恢复。请核对状态后明确恢复。
+下载文件或元数据备份被替换、修改时,恢复授权会失效;放回旧文件也不会重新激活
+已失效的授权。激活响应丢失时,Motrix 会核对已保存的 token 和 GID,避免盲目创建
+重复任务。
+
+升级旧数据库时,请保留引擎的 `*.pre-schema5-*.db` 备份。备份记录的是升级前状态。
+旧引擎无法打开新 schema;如需降级,请停止所有引擎,将经过验证的备份恢复到独立
+路径。已发布的引擎和应用安装包保持不变,功能支持取决于所安装版本捆绑的引擎。
diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.ts
index 0784f720..aa9fa588 100644
--- a/src/core/engine/aria2/aria2-adapter.ts
+++ b/src/core/engine/aria2/aria2-adapter.ts
@@ -42,6 +42,7 @@ import type {
} from '../engine-adapter'
import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine-adapter'
import { Aria2LegacyCheckpoint } from './aria2-legacy-checkpoint'
+import { legacyWirePath } from './aria2-legacy-path'
import type { Aria2RpcClient } from './aria2-rpc-client'
import { recommend } from './aria2-tuning'
import { isConnectionLimitRangeError, isNotFoundError } from './error-utils'
@@ -779,12 +780,12 @@ export class Aria2Adapter implements EngineAdapter {
files.every(
(file, index) =>
file.index === index &&
- file.path === input.files[index].path &&
+ file.path === legacyWirePath(input.files[index].path) &&
file.size === input.files[index].length &&
file.selected === selected.has(index)
) &&
options !== null &&
- options.dir === input.saveDir &&
+ options.dir === legacyWirePath(input.saveDir) &&
options['bt-seed-unverified'] === 'false' &&
options['bt-hash-check-seed'] === 'false' &&
Number(options['seed-time']) === 0 &&
@@ -973,10 +974,11 @@ export class Aria2Adapter implements EngineAdapter {
ErrorCode.EngineFeatureUnavailable,
'legacyImport.errors.checkpointUnavailable'
)
+ opts.dir = legacyWirePath(params.saveDir)
const input = {
token: context.token,
- targetPath: context.targetPath,
- metadataFile: reference.path,
+ targetPath: legacyWirePath(context.targetPath),
+ metadataFile: legacyWirePath(reference.path),
metadataDigest: reference.digest,
metadata: b64,
options: opts,
diff --git a/src/core/engine/aria2/aria2-legacy-checkpoint.integration.test.ts b/src/core/engine/aria2/aria2-legacy-checkpoint.integration.test.ts
index 5704d1ba..2d43ba72 100644
--- a/src/core/engine/aria2/aria2-legacy-checkpoint.integration.test.ts
+++ b/src/core/engine/aria2/aria2-legacy-checkpoint.integration.test.ts
@@ -1,8 +1,10 @@
// @vitest-environment node
// Opt in with MOTRIX_LEGACY_CHECKPOINT_ENGINE pointing to an engine that
// implements LegacyCheckpointImportV1. The ordinary bundled engine may not.
+import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import {
+ mkdir,
mkdtemp,
readFile,
realpath,
@@ -20,7 +22,8 @@ import {
connectAdapter,
spawnAria2ForTest,
} from '@test-utils/aria2'
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { legacyBtActivationFixture } from '@test-utils/legacy-bt-activation-fixture'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const binaryPath = process.env.MOTRIX_LEGACY_CHECKPOINT_ENGINE
const fixtures = path.resolve('tests/fixtures/legacy-v1/generated/downloads')
@@ -31,6 +34,34 @@ const payloadDigest =
const gid = '2222222222222222'
const token = 'real_v1_checkpoint_import_0001'
+function secureWindowsFixture(filename: string, directory = false): void {
+ if (process.platform !== 'win32') return
+ const sid = execFileSync(
+ 'powershell.exe',
+ [
+ '-NoProfile',
+ '-Command',
+ '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
+ ],
+ { encoding: 'utf8' }
+ ).trim()
+ if (directory)
+ execFileSync('icacls.exe', [
+ filename,
+ '/inheritance:r',
+ '/grant:r',
+ `*${sid}:(OI)(CI)F`,
+ '*S-1-5-18:(OI)(CI)F',
+ '*S-1-5-32-544:(OI)(CI)F',
+ ])
+ execFileSync('icacls.exe', [
+ filename,
+ '/setowner',
+ `*${sid}`,
+ ...(directory ? ['/T'] : []),
+ ])
+}
+
async function until<T>(read: () => Promise<T | false>): Promise<T> {
const deadline = Date.now() + 20000
while (Date.now() < deadline) {
@@ -83,6 +114,7 @@ describe.skipIf(!binaryPath)(
root = await realpath(
await mkdtemp(path.join(tmpdir(), 'motrix-v1-native-'))
)
+ secureWindowsFixture(root, true)
ranges.length = 0
targetPath = path.join(root, 'partial.bin')
const partial = gunzipSync(
@@ -90,6 +122,7 @@ describe.skipIf(!binaryPath)(
)
expect(partial.byteLength).toBe(completedBytes)
await writeFile(targetPath, partial)
+ secureWindowsFixture(targetPath)
const { adapter } = await startEngine()
const controlFile = await readFile(
path.join(fixtures, 'partial.bin.aria2')
@@ -208,7 +241,9 @@ describe.skipIf(!binaryPath)(
)
await adapter.createDownload({
uris: [`http://127.0.0.1:${address.port}/partial.bin`],
- saveDir: root,
+ // The native imported checkpoint key uses aria2's forward-slash form.
+ saveDir:
+ process.platform === 'win32' ? root.replaceAll('\\', '/') : root,
filename: 'partial.bin',
gid,
pause: true,
@@ -253,6 +288,135 @@ describe.skipIf(!binaryPath)(
expect(source).toEqual(original)
}, 45000)
+ it('activates a durable BT receipt paused and restores the same selection after termination', async () => {
+ const { adapter, rpc } = wired!
+ const target = path.join(root, 'fixture-bundle')
+ await mkdir(target)
+ const files: LegacyCheckpointImport['files'] = []
+ for (const [index, name] of ['first.bin', 'second.bin'].entries()) {
+ const filename = path.join(target, name)
+ await writeFile(filename, Buffer.alloc(16384, index + 1))
+ secureWindowsFixture(filename)
+ const identity = await stat(filename, { bigint: true })
+ files.push({
+ path: filename,
+ offset: index * 16384,
+ length: 16384,
+ identity: {
+ device: String(identity.dev),
+ inode: String(identity.ino),
+ size: String(identity.size),
+ mtimeNs: String(identity.mtimeNs),
+ ctimeNs: String(identity.ctimeNs),
+ },
+ })
+ }
+ const controlFile = await readFile(
+ path.join(fixtures, 'fixture-bundle.aria2')
+ )
+ const inspection = await adapter.inspectLegacyCheckpoint(controlFile)
+ const request: LegacyCheckpointImport = {
+ ...input,
+ targetPath: target,
+ controlFile,
+ sourceDigest: inspection.sourceDigest,
+ files,
+ expected: {
+ type: inspection.type,
+ totalBytes: inspection.totalBytes,
+ pieceBytes: inspection.pieceBytes,
+ infoHash: inspection.infoHash,
+ },
+ }
+ const receipt = await adapter.importLegacyCheckpoint(request)
+ const metadata = await readFile(
+ path.join(fixtures, 'a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent')
+ )
+ const metadataPath = path.join(root, 'authorized.torrent')
+ await writeFile(metadataPath, metadata)
+ secureWindowsFixture(metadataPath)
+ const before = await Promise.all(files.map((file) => readFile(file.path)))
+ expect(await adapter.supportsLegacyBtActivation()).toBe(true)
+ await adapter.addTorrent({
+ metadata,
+ gid,
+ saveDir: root,
+ pause: true,
+ selectedFiles: [1],
+ isPrivate: true,
+ legacyCheckpointActivation: { token, targetPath: target },
+ durableMetadata: {
+ path: metadataPath,
+ digest: createHash('sha256').update(metadata).digest('hex'),
+ },
+ })
+ expect((await rpc.tellStatus(gid)).status).toBe('paused')
+ // Terminate without saveSession: the add RPC must already be durable.
+ handle!.proc.kill('SIGKILL')
+ await stopEngine()
+ const restored = await startEngine()
+ const status = await restored.rpc.tellStatus(gid)
+ expect(status.status).toBe('paused')
+ expect(status.files.map((file) => file.selected)).toEqual([
+ 'true',
+ 'false',
+ ])
+ expect((await restored.rpc.tellWaiting(0, 10)).length).toBe(1)
+ expect(
+ await restored.adapter.reconcileLegacyCheckpoint({
+ token,
+ targetPath: target,
+ })
+ ).toEqual(receipt)
+ expect(
+ await Promise.all(files.map((file) => readFile(file.path)))
+ ).toEqual(before)
+ }, 45000)
+
+ it('runs the migration service from authorized v1 records through binding before unpause', async () => {
+ const { adapter, rpc } = wired!
+ const fixture = await legacyBtActivationFixture(adapter)
+ try {
+ secureWindowsFixture(fixture.root, true)
+ const original = await readFile(
+ path.join(fixture.downloads, 'fixture-bundle', 'first.bin')
+ )
+ const resume = adapter.resumeTask.bind(adapter)
+ const resumed = vi
+ .spyOn(adapter, 'resumeTask')
+ .mockImplementation(async (id) => {
+ expect((await rpc.tellStatus(id)).status).toBe('paused')
+ expect(
+ fixture.db.getTask(fixture.taskId)?.instances[0].payload
+ .legacyBtActivation
+ ).toMatchObject({
+ stage: 'bound',
+ engineTaskId: id,
+ })
+ await resume(id)
+ })
+ expect(
+ await fixture.service.activate(
+ fixture.taskId,
+ async () => fixture.downloads
+ )
+ ).toBe(true)
+ expect(resumed).toHaveBeenCalledOnce()
+ const state = fixture.db.getTask(fixture.taskId)?.instances[0].payload
+ .legacyBtActivation
+ expect(state).toMatchObject({ stage: 'active' })
+ expect(
+ await readFile(
+ path.join(fixture.downloads, 'fixture-bundle', 'first.bin')
+ )
+ ).toEqual(original)
+ resumed.mockRestore()
+ } finally {
+ await stopEngine()
+ await fixture.dispose()
+ }
+ }, 45000)
+
it('rejects changed file identities without creating a receipt or checkpoint', async () => {
const { adapter } = wired!
await writeFile(targetPath, Buffer.alloc(completedBytes, 17))
diff --git a/src/core/engine/aria2/aria2-legacy-checkpoint.ts b/src/core/engine/aria2/aria2-legacy-checkpoint.ts
index 7c809c73..b4e32359 100644
--- a/src/core/engine/aria2/aria2-legacy-checkpoint.ts
+++ b/src/core/engine/aria2/aria2-legacy-checkpoint.ts
@@ -1,5 +1,4 @@
import { createHash } from 'node:crypto'
-import path from 'node:path'
import { AppError, ErrorCode } from '@shared/errors'
import {
type LegacyCheckpointImport,
@@ -16,6 +15,7 @@ import {
} from '@shared/schemas/legacy-checkpoint'
import { FEATURE_SQLITE3_PERSISTENCE } from '@shared/types/engine'
import { z } from 'zod'
+import { legacyWirePath } from './aria2-legacy-path'
import type { Aria2RpcClient } from './aria2-rpc-client'
export const FEATURE_LEGACY_CHECKPOINT_IMPORT_V1 = 'LegacyCheckpointImportV1'
@@ -100,18 +100,6 @@ function parse<T>(
return value.data
}
-function checkPath(value: string): void {
- if (
- !path.isAbsolute(value) ||
- path.normalize(value) !== value ||
- Buffer.byteLength(value) > 4096
- )
- throw new AppError(
- ErrorCode.InvalidSelection,
- 'Invalid legacy checkpoint path'
- )
-}
-
function controlSnapshot(bytes: Uint8Array): {
controlFile: string
sourceDigest: string
@@ -138,11 +126,16 @@ function receipt(
expected: LegacyCheckpointReconcile
): LegacyCheckpointReceipt {
const wire = parse(wireReceipt, value)
+ if (wire.targetPath !== legacyWirePath(expected.targetPath))
+ throw new AppError(
+ ErrorCode.EngineProtocolError,
+ 'Legacy checkpoint receipt path mismatch'
+ )
const result = parse(legacyCheckpointReceiptSchema, {
status: wire.status,
token: wire.token,
engineTaskId: wire.gid,
- targetPath: wire.targetPath,
+ targetPath: expected.targetPath,
sourceDigest: wire.controlDigest,
})
if (
@@ -221,14 +214,14 @@ export class Aria2LegacyCheckpoint {
ErrorCode.InvalidSelection,
'Legacy checkpoint source changed'
)
- checkPath(request.targetPath)
- for (const file of request.files) checkPath(file.path)
+ legacyWirePath(request.targetPath)
+ for (const file of request.files) legacyWirePath(file.path)
const wire: Aria2LegacyCheckpointImport = {
token: request.token,
gid: request.engineTaskId,
controlFile: snapshot.controlFile,
controlDigest: snapshot.sourceDigest,
- targetPath: request.targetPath,
+ targetPath: legacyWirePath(request.targetPath),
expected: {
kind: request.expected.type === 'bt' ? 'bittorrent' : 'http',
totalLength: String(request.expected.totalBytes),
@@ -237,6 +230,7 @@ export class Aria2LegacyCheckpoint {
},
files: request.files.map((file) => ({
...file,
+ path: legacyWirePath(file.path),
offset: String(file.offset),
length: String(file.length),
})),
@@ -272,14 +266,17 @@ export class Aria2LegacyCheckpoint {
input,
ErrorCode.InvalidSelection
)
- checkPath(request.targetPath)
+ legacyWirePath(request.targetPath)
await this.requireSupport()
- const result = await this.rpc.reconcileLegacyCheckpointV1(request)
+ const result = await this.rpc.reconcileLegacyCheckpointV1({
+ ...request,
+ targetPath: legacyWirePath(request.targetPath),
+ })
const absent = wireAbsent.safeParse(result)
if (absent.success) {
if (
absent.data.token !== request.token ||
- absent.data.targetPath !== request.targetPath
+ absent.data.targetPath !== legacyWirePath(request.targetPath)
)
throw new AppError(
ErrorCode.EngineProtocolError,
diff --git a/src/core/engine/aria2/aria2-legacy-path.test.ts b/src/core/engine/aria2/aria2-legacy-path.test.ts
new file mode 100644
index 00000000..81efc2e6
--- /dev/null
+++ b/src/core/engine/aria2/aria2-legacy-path.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+import { legacyWirePath } from './aria2-legacy-path'
+
+describe('legacy native engine paths', () => {
+ it('keeps POSIX keys and converts canonical Windows Unicode paths', () => {
+ expect(legacyWirePath('/confirmed/下载/file.bin', 'darwin')).toBe(
+ '/confirmed/下载/file.bin'
+ )
+ expect(legacyWirePath('C:\\Users\\name\\下载\\file.bin', 'win32')).toBe(
+ 'C:/Users/name/下载/file.bin'
+ )
+ const long = `D:\\${'nested\\'.repeat(40)}file.bin`
+ expect(legacyWirePath(long, 'win32')).toBe(long.replaceAll('\\', '/'))
+ })
+
+ it.each([
+ 'C:relative.bin',
+ '\\\\server\\share\\file.bin',
+ '\\\\?\\C:\\file.bin',
+ 'C:\\dir\\..\\file.bin',
+ 'C:\\dir\\file.bin:stream',
+ 'C:\\dir\\file.bin.',
+ 'C:\\dir\\file.bin ',
+ 'C:\\dir\\CON.txt',
+ 'C:\\dir\\LPT1',
+ 'C:\\dir\\COM¹.txt',
+ 'C:\\dir\\CON .txt',
+ 'c:\\dir\\file.bin',
+ 'C:\\dir\\bad\u0000.bin',
+ ])('refuses ambiguous Windows identity %j', (value) => {
+ expect(() => legacyWirePath(value, 'win32')).toThrow()
+ })
+})
diff --git a/src/core/engine/aria2/aria2-legacy-path.ts b/src/core/engine/aria2/aria2-legacy-path.ts
new file mode 100644
index 00000000..b9a5f873
--- /dev/null
+++ b/src/core/engine/aria2/aria2-legacy-path.ts
@@ -0,0 +1,46 @@
+import path from 'node:path'
+import { AppError, ErrorCode } from '@shared/errors'
+
+/** Match aria2's persisted native path keys without changing app path identity. */
+export function legacyWirePath(
+ value: string,
+ platform: NodeJS.Platform = process.platform
+): string {
+ const paths = platform === 'win32' ? path.win32 : path.posix
+ if (
+ !paths.isAbsolute(value) ||
+ paths.normalize(value) !== value ||
+ Buffer.byteLength(value) > 4096 ||
+ [...value].some(
+ (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127
+ )
+ )
+ throw new AppError(
+ ErrorCode.InvalidSelection,
+ 'Invalid legacy checkpoint path'
+ )
+ if (platform !== 'win32') return value
+ // Local drive paths only. The engine verifies NTFS, exact on-disk casing,
+ // reparse points, file identity and ACLs through held read-only handles.
+ if (!/^[A-Z]:\\/.test(value))
+ throw new AppError(
+ ErrorCode.InvalidSelection,
+ 'Invalid legacy checkpoint drive'
+ )
+ const parts = value.slice(3).split('\\')
+ if (
+ parts.some(
+ (part) =>
+ !part ||
+ /[. ]$|[:<>"|?*]/.test(part) ||
+ /^(?:con|prn|aux|nul|conin\$|conout\$|clock\$|com[0-9¹²³]|lpt[0-9¹²³]) *(?:\.|$)/i.test(
+ part
+ )
+ )
+ )
+ throw new AppError(
+ ErrorCode.InvalidSelection,
+ 'Invalid legacy checkpoint component'
+ )
+ return value.replaceAll('\\', '/')
+}
diff --git a/src/core/legacy-import/bt-activation-service.ts b/src/core/legacy-import/bt-activation-service.ts
index 6a038a30..81d64af0 100644
--- a/src/core/legacy-import/bt-activation-service.ts
+++ b/src/core/legacy-import/bt-activation-service.ts
@@ -365,7 +365,9 @@ export class LegacyBtActivationService {
? !stat.isDirectory()
: !stat.isFile() ||
stat.nlink !== 1n ||
- (stat.mode & 0o022n) !== 0n ||
+ // Windows mode bits do not describe ACLs; the engine checks the
+ // owner/DACL through the same held handle used for import.
+ (process.platform !== 'win32' && (stat.mode & 0o022n) !== 0n) ||
(process.getuid && BigInt(process.getuid()) !== stat.uid)
)
throw failure('payloadUnsafe')
@@ -431,12 +433,19 @@ export class LegacyBtActivationService {
} finally {
await file.close()
}
- for (const name of [directory, source.root]) {
- const handle = await open(name, constants.O_RDONLY | constants.O_NOFOLLOW)
- try {
- await handle.sync()
- } finally {
- await handle.close()
+ // Node cannot open/sync directories on Windows. The snapshot file itself
+ // is flushed above; recovery revalidates its persisted digest before use.
+ if (process.platform !== 'win32') {
+ for (const name of [directory, source.root]) {
+ const handle = await open(
+ name,
+ constants.O_RDONLY | constants.O_NOFOLLOW
+ )
+ try {
+ await handle.sync()
+ } finally {
+ await handle.close()
+ }
}
}
return filename
diff --git a/src/core/legacy-import/session-parser.ts b/src/core/legacy-import/session-parser.ts
index fd14521f..6af7039f 100644
--- a/src/core/legacy-import/session-parser.ts
+++ b/src/core/legacy-import/session-parser.ts
@@ -131,7 +131,11 @@ export function safeLegacyComponent(value: string): boolean {
export function safeLegacyDirectory(dir: string): string | null {
if (!path.isAbsolute(dir) || dir.includes('\0') || dir.length > 4096)
return null
- const root = path.resolve(dir)
+ let root = path.resolve(dir)
+ // Drive-letter casing has no identity distinction, even in a case-sensitive
+ // NTFS directory. Keep persisted Windows paths aligned with realpath.
+ if (process.platform === 'win32' && /^[a-z]:\\/.test(root))
+ root = root[0].toUpperCase() + root.slice(1)
return root === path.parse(root).root ? null : root
}
diff --git a/src/core/legacy-import/session-parser.win32.test.ts b/src/core/legacy-import/session-parser.win32.test.ts
new file mode 100644
index 00000000..654a979c
--- /dev/null
+++ b/src/core/legacy-import/session-parser.win32.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest'
+import { safeLegacyDirectory, safeLegacyOutput } from './session-parser'
+
+describe.skipIf(process.platform !== 'win32')(
+ 'legacy Windows drive paths',
+ () => {
+ it('canonicalizes the drive letter without folding directory or filename case', () => {
+ expect(safeLegacyDirectory('c:\\Users\\Name\\下载')).toBe(
+ 'C:\\Users\\Name\\下载'
+ )
+ expect(safeLegacyOutput('d:\\Downloads', 'Original.Name')).toBe(
+ 'D:\\Downloads\\Original.Name'
+ )
+ })
+
+ it('refuses drive-relative paths and volume roots', () => {
+ expect(safeLegacyDirectory('C:Downloads')).toBeNull()
+ expect(safeLegacyDirectory('c:\\')).toBeNull()
+ })
+ }
+)
diff --git a/src/test-utils/legacy-bt-activation-fixture.ts b/src/test-utils/legacy-bt-activation-fixture.ts
index a4346b1d..0d68181a 100644
--- a/src/test-utils/legacy-bt-activation-fixture.ts
+++ b/src/test-utils/legacy-bt-activation-fixture.ts
@@ -1,3 +1,4 @@
+import { execFileSync } from 'node:child_process'
import {
cp,
mkdir,
@@ -16,6 +17,30 @@ import { MotrixDatabase } from '@core/session/motrix-database'
import { TaskManager } from '@core/task/task-manager'
import { vi } from 'vitest'
+function secureWindowsFixture(root: string): void {
+ if (process.platform !== 'win32') return
+ const sid = execFileSync(
+ 'powershell.exe',
+ [
+ '-NoProfile',
+ '-Command',
+ '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
+ ],
+ { encoding: 'utf8' }
+ ).trim()
+ execFileSync('icacls.exe', [
+ root,
+ '/inheritance:r',
+ '/grant:r',
+ `*${sid}:(OI)(CI)F`,
+ '*S-1-5-18:(OI)(CI)F',
+ '*S-1-5-32-544:(OI)(CI)F',
+ ])
+ // Hosted runners use an elevated token whose default owner may be Administrators.
+ // Production import checks ownership and never changes it; only fixtures do.
+ execFileSync('icacls.exe', [root, '/setowner', `*${sid}`, '/T'])
+}
+
/** Actual v1 metadata/control snapshots; deterministic payloads recreated from the recorded recipe. */
export async function legacyBtActivationFixture(adapter: EngineAdapter) {
const root = await realpath(
@@ -28,11 +53,13 @@ export async function legacyBtActivationFixture(adapter: EngineAdapter) {
const downloads = path.join(root, 'downloads')
for (const name of ['download.session', 'system.json']) {
const filename = path.join(profile, name)
+ const encodePath = (value: string) =>
+ name.endsWith('.json') ? JSON.stringify(value).slice(1, -1) : value
await writeFile(
filename,
(await readFile(filename, 'utf8'))
- .replaceAll('__FIXTURE_ROOT__', profile)
- .replaceAll('__FIXTURE_DOWNLOADS__', downloads)
+ .replaceAll('__FIXTURE_ROOT__', encodePath(profile))
+ .replaceAll('__FIXTURE_DOWNLOADS__', encodePath(downloads))
.replaceAll('__FIXTURE_HTTP_PORT__', '18080')
)
}
@@ -75,6 +102,7 @@ export async function legacyBtActivationFixture(adapter: EngineAdapter) {
if (importer.getRun(run.runId).stage !== 'completed')
throw new Error('Import pending')
}
+ secureWindowsFixture(root)
const taskId = db.getAllTasks()[0].task.motrixId
const publishTasks = vi.fn()
const deps = {