Skip to content

A full-featured download manager.

fix(migration): filter legacy options and use the current proxy (#2438)

Dr_rOot7eecee9a6138
diff --git a/e2e/legacy-http-activation.spec.ts b/e2e/legacy-http-activation.spec.ts
index b0f6d15b..b0edc9d5 100644
--- a/e2e/legacy-http-activation.spec.ts
+++ b/e2e/legacy-http-activation.spec.ts
@@ -4,6 +4,7 @@ import { createServer } from 'node:http'
import path from 'node:path'
import { gunzipSync } from 'node:zlib'
import type { Page } from '@playwright/test'
+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'
import { Commands } from '../src/shared/protocol/commands'
import { Queries } from '../src/shared/protocol/queries'
import type { DownloadTask } from '../src/shared/types/task'
@@ -48,9 +49,19 @@ for (const mismatch of [false, true]) {
for (let index = 0; index < total; index++) payload[index] = index % 251
if (mismatch) payload[completed - 1] ^= 255
const ranges: string[] = []
+ const proxyRanges: string[] = []
+ const authorization = `Basic ${Buffer.from('current-user:current-password').toString('base64')}`
const server = createServer((request, response) => {
const range = request.headers.range ?? ''
ranges.push(range)
+ if (
+ request.url !== 'http://legacy-http.invalid/partial.bin' ||
+ request.headers['proxy-authorization'] !== authorization
+ ) {
+ response.writeHead(407).end()
+ return
+ }
+ proxyRanges.push(range)
if (
request.headers.cookie !== 'session=e2e-fixture' ||
request.headers['accept-encoding'] !== 'identity'
@@ -73,6 +84,30 @@ for (const mismatch of [false, true]) {
const address = server.address()
if (!address || typeof address === 'string')
throw new Error('Missing local server')
+ await writeFile(
+ path.join(userDataDir, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: { language: 'en-US', autofillClipboardLinks: false },
+ onboarding: { disclaimerAccepted: true },
+ tracker: { autoSync: false },
+ proxy: {
+ enabled: true,
+ protocol: 'http',
+ host: '127.0.0.1',
+ port: address.port,
+ user: 'current-user',
+ password: 'current-password',
+ bypass: [],
+ scopes: {
+ download: true,
+ plugins: false,
+ updateApp: false,
+ updateTrackers: false,
+ },
+ },
+ })
+ )
const source = path.join(userDataDir, 'legacy-http-profile')
const downloads = path.join(userDataDir, 'original-downloads')
await mkdir(source)
@@ -95,11 +130,15 @@ for (const mismatch of [false, true]) {
)
await writeFile(
path.join(source, 'system.json'),
- JSON.stringify({ dir: downloads })
+ JSON.stringify({
+ dir: downloads,
+ 'all-proxy': 'http://old-user:[email protected]:1',
+ 'no-proxy': '*',
+ })
)
await writeFile(
path.join(source, 'download.session'),
- `http://127.0.0.1:${address.port}/partial.bin\n gid=1234567890abcdef\n out=partial.bin\n pause=true\n header=Cookie: session=e2e-fixture\n`
+ `http://legacy-http.invalid/partial.bin\n gid=1234567890abcdef\n out=partial.bin\n pause=true\n header=Cookie: session=e2e-fixture\n`
)
let app = await launchMotrix({
userDataDir,
@@ -162,6 +201,7 @@ for (const mismatch of [false, true]) {
downloadedBytes: total,
})
expect(ranges).toContain(`bytes=${completed}-${total - 1}`)
+ expect(proxyRanges).toContain(`bytes=${completed}-${total - 1}`)
expect(
createHash('sha256')
.update(await readFile(target))
@@ -204,6 +244,9 @@ for (const mismatch of [false, true]) {
expect(await invoke(restarted, Queries.ListTasks)).toEqual([])
expect((await readFile(target)).equals(payload)).toBe(true)
}
+ expect(proxyRanges.some((range) => range.startsWith('bytes=0-'))).toBe(
+ true
+ )
expect(await readFile(`${target}.aria2`)).toEqual(control)
} finally {
server.closeAllConnections()
diff --git a/e2e/legacy-import.spec.ts b/e2e/legacy-import.spec.ts
index e2b2f62d..566116d2 100644
--- a/e2e/legacy-import.spec.ts
+++ b/e2e/legacy-import.spec.ts
@@ -69,13 +69,13 @@ async function expandTaskGroups(page: Page) {
}
test.describe('v1 task import', () => {
- test('migrates paused HTTP tasks with request settings while preserving blocked records and original files', async ({
+ test('migrates paused HTTP tasks after stripping unsupported options while preserving malformed records and original files', async ({
userDataDir,
rpcPort,
}, testInfo) => {
const source = await legacyProfile(userDataDir)
const sessionPath = path.join(source, 'download.session')
- const session = `${await readFile(sessionPath, 'utf8')} header=Authorization: Bearer LEGACY_AUTH_SECRET\n header=Referer: https://example.invalid/private-page\nhttps://example.invalid/blocked.zip\n gid=2234567890abcdef\n out=blocked.zip\n on-download-complete=LEGACY_COMMAND_SECRET\n`
+ const session = `${await readFile(sessionPath, 'utf8')} header=Authorization: Bearer LEGACY_AUTH_SECRET\n header=Referer: https://example.invalid/private-page\nhttps://example.invalid/stripped.zip\n gid=2234567890abcdef\n out=stripped.zip\n on-download-complete=LEGACY_COMMAND_SECRET\nhttps://example.invalid/broken.zip\n gid=invalid\n out=broken.zip\n`
await writeFile(sessionPath, session)
await writeFile(
path.join(source, 'system.json'),
@@ -100,10 +100,16 @@ test.describe('v1 task import', () => {
await expect(archive).toBeEnabled()
await expect(archive).toBeChecked()
await expect(
- page.getByRole('checkbox', { name: 'blocked.zip', exact: true })
+ page.getByRole('checkbox', { name: 'stripped.zip', exact: true })
+ ).toBeChecked()
+ await expect(
+ page.locator('[data-import-task="gid:2234567890abcdef"]')
+ ).toContainText('on-download-complete')
+ await expect(
+ page.getByRole('checkbox', { name: 'broken.zip', exact: true })
).toBeDisabled()
await expect(page.locator('[data-import-group="http"]')).toBeVisible()
- const body = await page.locator('body').innerText()
+ const body = (await page.locator('body').textContent()) ?? ''
for (const secret of [
'LEGACY_AUTH_SECRET',
'LEGACY_PROXY_SECRET',
@@ -117,39 +123,62 @@ test.describe('v1 task import', () => {
await expect(
page
.getByLabel('Migration summary')
- .getByText('1 task', { exact: true })
+ .getByText('2 tasks', { exact: true })
.first()
).toBeVisible()
const tasks = (await invoke(page, Queries.ListTasks)) as Array<{
id: string
+ name: string
instances: Array<{
gid: string | null
payload: Record<string, unknown>
}>
}>
- expect(tasks).toEqual([
- expect.objectContaining({
- name: 'archive.zip',
- status: 'paused',
- engineTaskId: '',
- }),
- ])
- expect(tasks[0].instances[0].payload.legacyImport).toMatchObject({
+ expect(tasks).toHaveLength(2)
+ expect(tasks).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'archive.zip',
+ status: 'paused',
+ engineTaskId: '',
+ }),
+ expect.objectContaining({
+ name: 'stripped.zip',
+ status: 'paused',
+ engineTaskId: '',
+ }),
+ ])
+ )
+ const archiveTask = tasks.find((task) => task.name === 'archive.zip')
+ const strippedTask = tasks.find((task) => task.name === 'stripped.zip')
+ expect(archiveTask).toBeDefined()
+ expect(strippedTask).toBeDefined()
+ if (!archiveTask || !strippedTask)
+ throw new Error('Imported tasks are missing')
+ expect(strippedTask.instances[0].payload.legacyImport).toMatchObject({
+ activation: 'inactive',
+ ignoredOptions: expect.arrayContaining([
+ 'on-download-complete',
+ 'all-proxy',
+ ]),
+ })
+ expect(archiveTask.instances[0].payload.legacyImport).toMatchObject({
activation: 'inactive',
reason: 'request-settings-required',
- requestOptions: expect.arrayContaining(['header', 'all-proxy']),
+ requestOptions: ['header'],
})
await expect(
- invoke(page, Commands.ResumeTask, tasks[0].id)
+ invoke(page, Commands.ResumeTask, archiveTask.id)
).rejects.toThrow()
expect(JSON.stringify(tasks)).not.toContain('LEGACY_AUTH_SECRET')
expect(JSON.stringify(tasks)).not.toContain('LEGACY_PROXY_SECRET')
+ expect(JSON.stringify(tasks)).not.toContain('LEGACY_COMMAND_SECRET')
expect(await readFile(sessionPath, 'utf8')).toBe(session)
expect(
await readFile(path.join(source, 'downloads', 'archive.zip'), 'utf8')
).toBe('original v1 bytes')
await page.getByRole('button', { name: 'View downloads' }).click()
- await page.locator(`[data-task-id="${tasks[0].id}"]`).dblclick()
+ await page.locator(`[data-task-id="${archiveTask.id}"]`).dblclick()
await page
.getByRole('button', { name: 'Reconfigure and download…' })
.click()
@@ -177,7 +206,7 @@ test.describe('v1 task import', () => {
expect(addTask).toBeDefined()
if (!addTask) throw new Error('Add-task window did not open')
await expect(addTask.getByRole('alert')).toContainText(
- 'Saved request settings: header, all-proxy'
+ 'Saved request settings: header'
)
await expect(
addTask.getByRole('button', { name: 'Advanced', exact: true })
@@ -196,13 +225,104 @@ test.describe('v1 task import', () => {
path: testInfo.outputPath('request-settings-form.png'),
})
expect((await invoke(page, Queries.ListTasks)) as unknown[]).toHaveLength(
- 1
+ 2
)
} finally {
await app.close().catch(() => {})
}
})
+ test('migrates a named magnet after discarding old proxy and unsupported settings', async ({
+ userDataDir,
+ rpcPort,
+ }, testInfo) => {
+ const source = await legacyProfile(userDataDir)
+ const sessionPath = path.join(source, 'download.session')
+ const magnet = `magnet:?xt=urn:btih:${'a'.repeat(40)}&dn=Legacy-proxy-bundle`
+ const session = `${magnet}\n gid=3234567890abcdef\n pause=true\n header=Cookie: LEGACY_MAGNET_COOKIE_SECRET\n on-download-complete=LEGACY_MAGNET_COMMAND_SECRET\n`
+ await writeFile(sessionPath, session)
+ await writeFile(
+ path.join(source, 'system.json'),
+ JSON.stringify({
+ dir: path.join(source, 'downloads'),
+ 'all-proxy':
+ 'http://proxy-user:[email protected]:8080',
+ 'no-proxy': '.internal.example',
+ })
+ )
+ const app = await launchMotrix({
+ userDataDir,
+ rpcPort,
+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },
+ })
+ try {
+ const page = await firstPage(app)
+ await page.getByRole('button', { name: 'Continue', exact: true }).click()
+ await expandTaskGroups(page)
+ const checkbox = page.getByRole('checkbox', {
+ name: 'Legacy-proxy-bundle',
+ exact: true,
+ })
+ await expect(page.getByRole('note')).toContainText(
+ 'current download proxy settings'
+ )
+ await expect(checkbox).toBeEnabled()
+ await expect(checkbox).toBeChecked()
+ const row = page.locator('[data-import-task="gid:3234567890abcdef"]')
+ await expect(row).toContainText('header')
+ await expect(row).toContainText('on-download-complete')
+ const body = (await page.locator('body').textContent()) ?? ''
+ expect(body).not.toMatch(/LEGACY_MAGNET_|proxy-user|proxy\.example/)
+ await page.screenshot({
+ path: testInfo.outputPath('magnet-proxy-preview.png'),
+ })
+ await page.getByRole('button', { name: 'Migrate', exact: true }).click()
+ await expect(
+ page
+ .getByLabel('Migration summary')
+ .getByText('1 task', { exact: true })
+ .first()
+ ).toBeVisible()
+ const tasks = (await invoke(page, Queries.ListTasks)) as Array<{
+ id: string
+ instances: Array<{
+ gid: string | null
+ payload: Record<string, unknown>
+ }>
+ }>
+ expect(tasks).toHaveLength(1)
+ expect(tasks[0]).toMatchObject({
+ name: 'Legacy-proxy-bundle',
+ type: 'magnet',
+ status: 'paused',
+ engineTaskId: '',
+ })
+ expect(tasks[0].instances[0].gid).toBeNull()
+ expect(tasks[0].instances[0].payload.legacyImport).toMatchObject({
+ activation: 'inactive',
+ reason: 'metadata-required',
+ ignoredOptions: expect.arrayContaining([
+ 'all-proxy',
+ 'no-proxy',
+ 'header',
+ 'on-download-complete',
+ ]),
+ })
+ expect(JSON.stringify(tasks)).not.toMatch(
+ /LEGACY_MAGNET_|proxy-user|proxy\.example/
+ )
+ await expect(
+ invoke(page, Commands.ResumeTask, tasks[0].id)
+ ).rejects.toThrow()
+ expect(await readFile(sessionPath, 'utf8')).toBe(session)
+ expect(
+ await readFile(path.join(source, 'downloads', 'archive.zip'), 'utf8')
+ ).toBe('original v1 bytes')
+ } finally {
+ await app.close().catch(() => {})
+ }
+ })
+
test('retains invalid source paths and recovers through the native folder picker', async ({
userDataDir,
rpcPort,
diff --git a/src/core/legacy-import/http-activation-service.test.ts b/src/core/legacy-import/http-activation-service.test.ts
index 55d0389e..1b9421f5 100644
--- a/src/core/legacy-import/http-activation-service.test.ts
+++ b/src/core/legacy-import/http-activation-service.test.ts
@@ -305,6 +305,90 @@ describe('durable HTTP legacy activation', () => {
])
expect(serialized).not.toContain(secret)
})
+ it.each([true, false])(
+ 'uses the current download route for verification and continuation (proxy enabled: %s)',
+ async (enabled) => {
+ const f = await fixture({
+ system: {
+ 'all-proxy': 'http://old:[email protected]:8080',
+ 'no-proxy': '*',
+ },
+ })
+ const proxy = enabled ? 'http://current:[email protected]:7890' : ''
+ f.proxyPolicy.commit(
+ enabled ? { allProxy: proxy, noProxy: '.internal' } : null
+ )
+ await f.service.activate(f.taskId, async () => f.downloads)
+ const route = { proxy, noProxy: enabled ? '.internal' : '' }
+ expect(
+ f.verifier.verifyLegacyContent.mock.calls[0][0].options
+ ).toMatchObject(route)
+ expect(f.adapter.createDownload).toHaveBeenCalledWith(
+ expect.objectContaining(route)
+ )
+ expect(JSON.stringify(f.db.getTask(f.taskId))).not.toMatch(
+ /password|old\.invalid|secret/
+ )
+ }
+ )
+
+ it('fails closed if engine restart invalidates the route during verification', async () => {
+ const f = await fixture()
+ const verify = f.verifier.verifyLegacyContent.getMockImplementation()!
+ f.verifier.verifyLegacyContent.mockImplementationOnce(async (input) => {
+ const result = await verify(input)
+ f.proxyPolicy.markUnavailable()
+ return result
+ })
+ await expect(
+ f.service.activate(f.taskId, async () => f.downloads)
+ ).rejects.toThrow()
+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()
+ expect(f.adapter.createDownload).not.toHaveBeenCalled()
+ expect(await readFile(f.target)).toEqual(f.payload)
+ })
+
+ it('rechecks the source after native creation before unpausing', async () => {
+ const f = await fixture()
+ const create = vi.mocked(f.adapter.createDownload).getMockImplementation()!
+ vi.mocked(f.adapter.createDownload).mockImplementationOnce(
+ async (params) => {
+ const gid = await create(params)
+ await writeFile(path.join(f.profile, 'system.json'), '{}')
+ return gid
+ }
+ )
+ await expect(
+ f.service.activate(f.taskId, async () => f.downloads)
+ ).rejects.toThrow('legacyImport.errors.changedSource')
+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()
+ expect(await readFile(f.target)).toEqual(f.payload)
+ })
+
+ it('holds the applied route stable until verification and native dispatch finish', async () => {
+ const f = await fixture()
+ f.proxyPolicy.commit({ allProxy: 'http://current:8080', noProxy: '' })
+ let transition: Promise<unknown> | undefined
+ const apply = vi.fn(async () => ({
+ downloadProxy: 'applied' as const,
+ appliedProxy: null,
+ }))
+ const verify = f.verifier.verifyLegacyContent.getMockImplementation()!
+ f.verifier.verifyLegacyContent.mockImplementationOnce(async (input) => {
+ transition = f.proxyPolicy.applyTransition(apply)
+ await Promise.resolve()
+ expect(apply).not.toHaveBeenCalled()
+ return verify(input)
+ })
+ await f.service.activate(f.taskId, async () => f.downloads)
+ await transition
+ expect(apply).toHaveBeenCalledOnce()
+ expect(f.adapter.createDownload).toHaveBeenCalledWith(
+ expect.objectContaining({ proxy: 'http://current:8080' })
+ )
+ expect(f.proxyPolicy.snapshot()).toEqual({ noProxy: '' })
+ })
+
it('leaves originals and the engine untouched when remote bytes mismatch', async () => {
const f = await fixture()
f.verifier.verifyLegacyContent.mockRejectedValueOnce(
@@ -856,15 +940,21 @@ describe('durable HTTP legacy activation', () => {
false
)
})
- it('rejects unsupported request dependencies before any network or import', async () => {
+ it('discards unsupported cookie-file dependencies while retaining content verification', async () => {
const f = await fixture({
requestLines: ' load-cookies=/tmp/private-cookies\n',
})
await expect(
f.service.activate(f.taskId, async () => f.downloads)
- ).rejects.toThrow('httpRequestUnsupported')
- expect(f.verifier.verifyLegacyContent).not.toHaveBeenCalled()
- expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()
+ ).resolves.toBe(true)
+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledOnce()
+ expect(f.adapter.importLegacyCheckpoint).toHaveBeenCalledOnce()
+ expect(
+ JSON.stringify(f.verifier.verifyLegacyContent.mock.calls)
+ ).not.toContain('/tmp/private-cookies')
+ expect(
+ JSON.stringify(vi.mocked(f.adapter.createDownload).mock.calls)
+ ).not.toContain('/tmp/private-cookies')
})
it.each(['symlink', 'hardlink'] as const)(
'refuses a %s payload',
diff --git a/src/core/legacy-import/http-activation-service.ts b/src/core/legacy-import/http-activation-service.ts
index aa97d9b5..a3577338 100644
--- a/src/core/legacy-import/http-activation-service.ts
+++ b/src/core/legacy-import/http-activation-service.ts
@@ -4,6 +4,7 @@ import { lstat, mkdir, open, realpath } from 'node:fs/promises'
import path from 'node:path'
import type { EngineAdapter } from '@core/engine/engine-adapter'
import { newEngineTaskId } from '@core/lib/ids'
+import type { AppliedDownloadProxyPolicyReader } from '@core/proxy/applied-download-proxy-policy'
import type {
MotrixDatabase,
TaskWithInstances,
@@ -31,6 +32,7 @@ export interface LegacyHttpActivationDeps {
taskManager: TaskManager
adapter: EngineAdapter
backupRoot: string
+ proxyPolicy: AppliedDownloadProxyPolicyReader
isProcessRunning: (pid: number) => boolean | Promise<boolean>
publishTasks: () => void
runTaskMutation: <T>(
@@ -116,7 +118,15 @@ export class LegacyHttpActivationService {
const pair = this.requireTask(taskId)
const previous = pair.instances[0].payload.legacyHttpActivation
if (previous !== undefined) {
- await this.reconcile(pair, true, controller.signal)
+ await this.withCurrentProxy((assertCurrent) =>
+ this.reconcile(
+ pair,
+ true,
+ controller.signal,
+ undefined,
+ assertCurrent
+ )
+ )
return true
}
const available = await this.availability(taskId)
@@ -136,16 +146,20 @@ export class LegacyHttpActivationService {
if (!picked || this.stopping || controller.signal.aborted) return false
if (JSON.stringify(this.requireTask(taskId)) !== JSON.stringify(pair))
throw failure('changedSource')
- const prepared = await this.prepare(pair, picked, controller.signal)
- this.checkCancelled(controller.signal)
- this.deps.taskManager.reserveEngineTaskId(prepared.intent.engineTaskId)
- await this.persist(pair, prepared.intent, false)
- await this.reconcile(
- this.requireTask(taskId),
- true,
- controller.signal,
- prepared.context
- )
+ await this.withCurrentProxy(async (assertCurrent) => {
+ const prepared = await this.prepare(pair, picked, controller.signal)
+ this.checkCancelled(controller.signal)
+ assertCurrent()
+ this.deps.taskManager.reserveEngineTaskId(prepared.intent.engineTaskId)
+ await this.persist(pair, prepared.intent, false)
+ await this.reconcile(
+ this.requireTask(taskId),
+ true,
+ controller.signal,
+ prepared.context,
+ assertCurrent
+ )
+ })
return true
})
this.admission = operation
@@ -160,6 +174,15 @@ export class LegacyHttpActivationService {
return operation
}
+ private withCurrentProxy<T>(
+ operation: (assertCurrent: () => void) => Promise<T>
+ ): Promise<T> {
+ return this.deps.proxyPolicy.runWithSnapshot((snapshot, lease) => {
+ if (!snapshot) throw failure('httpRequestUnsupported')
+ return operation(() => lease.assertCurrent())
+ })
+ }
+
cancel(taskId: string): void {
if (this.currentTaskId !== taskId) return
this.controller?.abort()
@@ -301,13 +324,16 @@ export class LegacyHttpActivationService {
)
throw failure('running')
}
- return resolveLegacyHttpRequestContext({
+ const context = resolveLegacyHttpRequestContext({
session,
system,
itemKey: marker.itemKey,
uris: pair.instances[0].uris,
targetPath: pair.task.finalPath,
})
+ const route = this.deps.proxyPolicy.snapshot()
+ if (!route) throw failure('httpRequestUnsupported')
+ return { ...context, proxy: route.proxy ?? '', noProxy: route.noProxy }
}
private async prepare(
@@ -763,7 +789,8 @@ export class LegacyHttpActivationService {
pair: TaskWithInstances,
resume: boolean,
signal?: AbortSignal,
- verifiedContext?: LegacyHttpRequestContext
+ verifiedContext?: LegacyHttpRequestContext,
+ assertProxyCurrent?: () => void
): Promise<void> {
const intent = legacyHttpActivationSchema.parse(
pair.instances[0].payload.legacyHttpActivation
@@ -877,6 +904,7 @@ export class LegacyHttpActivationService {
}
this.checkCancelled(signal)
try {
+ assertProxyCurrent?.()
await this.deps.adapter.resumeTask(intent.engineTaskId)
this.checkCancelled(signal)
intent.stage = 'active'
@@ -954,6 +982,7 @@ export class LegacyHttpActivationService {
if (receipt.status === 'absent') {
if (intent.stage !== 'import-uncertain')
throw failure('activationUncertain')
+ assertProxyCurrent?.()
const imported = await this.deps.adapter.importLegacyCheckpoint?.({
token: intent.token,
engineTaskId: intent.engineTaskId,
@@ -990,6 +1019,7 @@ export class LegacyHttpActivationService {
!this.deps.taskManager.getByEngineTaskId(intent.engineTaskId)
)
this.deps.taskManager.reserveEngineTaskId(intent.engineTaskId)
+ assertProxyCurrent?.()
const gid = await this.deps.adapter.createDownload({
uris: [context.uri],
saveDir: intent.saveDir,
@@ -1019,7 +1049,9 @@ export class LegacyHttpActivationService {
await this.reconcile(
pair,
resume && !signal?.aborted && !this.stopping,
- signal
+ signal,
+ undefined,
+ assertProxyCurrent
)
this.checkCancelled(signal)
}
diff --git a/src/core/legacy-import/http-request-context.test.ts b/src/core/legacy-import/http-request-context.test.ts
index db34173d..993df756 100644
--- a/src/core/legacy-import/http-request-context.test.ts
+++ b/src/core/legacy-import/http-request-context.test.ts
@@ -1,6 +1,5 @@
// @vitest-environment node
import path from 'node:path'
-import { extractAria2ProxyCredentials } from '@core/proxy/aria2-proxy-routing'
import { describe, expect, it } from 'vitest'
import { resolveLegacyHttpRequestContext } from './http-request-context'
import { digestBytes, parseLegacySession } from './session-parser'
@@ -39,7 +38,7 @@ describe('legacy HTTP request context', () => {
}
)
- it('restores only verified headers, referer, user agent, basic auth, and the effective proxy', () => {
+ it('restores HTTP request fields while discarding old proxy settings', () => {
const context = resolve(
' header=Cookie: session=secret\n referer=https://example.com/list\n http-user=user\n http-passwd=secret\n',
{
@@ -57,91 +56,19 @@ describe('legacy HTTP request context', () => {
referer: 'https://example.com/list',
authorization: `Basic ${Buffer.from('user:secret').toString('base64')}`,
},
- proxy: 'http://proxy-user:[email protected]:8080/',
- noProxy: 'localhost',
+ proxy: '',
+ noProxy: '',
userAgent: 'Legacy Browser',
})
})
- it.each([
- ['proxy%40user', 'password%21'],
- ["代理@ user:/?#[]!$&'()*+,;=%", "密碼@ pass:/?#[]!$&'()*+,;=%"],
- ])(
- 'preserves raw dedicated proxy credential bytes: %s',
- (username, password) => {
- const context = resolve('', {
- 'all-proxy': 'http://proxy.example:8080',
- 'all-proxy-user': username,
- 'all-proxy-passwd': password,
- })
- expect(extractAria2ProxyCredentials(context.proxy)).toEqual({
- username,
- password,
- })
- expect(context.headers).toEqual({})
- }
- )
- it.each([
- {
- options: { 'all-proxy-user': 'new%40user' },
- expected: { username: 'new%40user', password: 'uri%21pass' },
- },
- {
- options: { 'all-proxy-passwd': 'new%21pass' },
- expected: { username: 'uri%40user', password: 'new%21pass' },
- },
- {
- options: { 'all-proxy-user': '' },
- expected: { username: '', password: '' },
- },
- {
- options: { 'all-proxy-passwd': '' },
- expected: { username: 'uri%40user', password: '' },
- },
- ])(
- 'overrides only defined URI credential fields: $options',
- ({ options, expected }) => {
- const context = resolve('', {
- 'all-proxy': 'http://uri%2540user:uri%[email protected]:8080',
- ...options,
- })
- expect(extractAria2ProxyCredentials(context.proxy)).toEqual(expected)
- }
- )
- it('honors an explicitly empty task password over inherited credentials', () => {
- const context = resolve(' all-proxy-passwd=\n', {
- 'all-proxy': 'http://uri-user:[email protected]:8080',
- 'all-proxy-user': 'global%40user',
- 'all-proxy-passwd': 'global-pass',
- })
- expect(extractAria2ProxyCredentials(context.proxy)).toEqual({
- username: 'global%40user',
- password: '',
- })
- })
- it('keeps reconstructed proxy credentials out of preview data', () => {
+ it('keeps discarded proxy credentials out of the context and preview', () => {
const options =
- ' all-proxy=http://proxy.example:8080\n all-proxy-user=private%40user\n all-proxy-passwd=private%21password\n'
- expect(extractAria2ProxyCredentials(resolve(options).proxy)).toEqual({
- username: 'private%40user',
- password: 'private%21password',
- })
- const preview = JSON.stringify(
- parseLegacySession(Buffer.from(`${uri}\n${options}`))
- )
- expect(preview).not.toContain('private')
+ ' all-proxy=http://private:[email protected]:8080\n all-proxy-passwd=private-password\n'
+ expect(resolve(options)).toMatchObject({ proxy: '', noProxy: '' })
+ expect(
+ JSON.stringify(parseLegacySession(Buffer.from(`${uri}\n${options}`)))
+ ).not.toMatch(/private|secret|proxy\.example/)
})
- it.each(['private\npassword', 'private\ud800password'])(
- 'rejects invalid credential text without exposing it',
- (password) => {
- expect(() =>
- resolve('', {
- 'all-proxy': 'http://proxy.example:8080',
- 'all-proxy-user': 'private-user',
- 'all-proxy-passwd': password,
- })
- ).toThrow(/^legacyImport\.errors\.httpRequestUnsupported$/)
- }
- )
it.each([
' load-cookies=/secret/cookies.txt\n',
' no-netrc=false\n',
@@ -149,8 +76,10 @@ describe('legacy HTTP request context', () => {
' header=Proxy-Authorization: private\n',
' http-proxy=http://proxy.example:8080\n',
' referer=*\n',
- ])('rejects request contexts that cannot be mirrored: %s', (options) => {
- expect(() => resolve(options)).toThrow('httpRequestUnsupported')
+ ' proxy-method=tunnel\n',
+ ' on-download-complete=private-script\n',
+ ])('discards unsupported settings before verification: %s', (options) => {
+ expect(resolve(options)).toMatchObject({ headers: {}, proxy: '' })
})
it('leaves range and representation conditions owned by verification', () => {
expect(
@@ -165,10 +94,26 @@ describe('legacy HTTP request context', () => {
.headers
).toEqual({ 'x-source': 'legacy', cookie: 'private' })
})
- it('rejects a conflicting global and per-task header collection', () => {
- expect(() =>
- resolve(' header=Cookie: changed\n', { header: ['Cookie: old'] })
- ).toThrow('httpRequestUnsupported')
+ it('discards a conflicting global and per-task header collection', () => {
+ expect(
+ resolve(' header=Cookie: changed\n', { header: ['Cookie: old'] }).headers
+ ).toEqual({})
+ })
+ it('discards both protocol-specific legacy routes', () => {
+ expect(
+ resolve('', {
+ 'http-proxy': 'http://plain.example:8080',
+ 'https-proxy': 'http://secure.example:8081',
+ }).proxy
+ ).toBe('')
+ })
+ it('honors last singleton settings and an explicitly cleared task proxy', () => {
+ expect(
+ resolve(
+ ' all-proxy=http://first.example:8080\n all-proxy=\n user-agent=first\n user-agent=last\n',
+ { 'all-proxy': 'http://global.example:8080' }
+ )
+ ).toMatchObject({ proxy: '', userAgent: 'last' })
})
it('uses the migration stable key when the original session has no GID', () => {
const context = resolveLegacyHttpRequestContext({
diff --git a/src/core/legacy-import/http-request-context.ts b/src/core/legacy-import/http-request-context.ts
index 110d5835..c79aebfa 100644
--- a/src/core/legacy-import/http-request-context.ts
+++ b/src/core/legacy-import/http-request-context.ts
@@ -1,10 +1,10 @@
import path from 'node:path'
-import { normalizeAria2TaskProxyUrl } from '@core/proxy/aria2-proxy-routing'
import type { DirectResourceRequestOptions } from '@core/task/direct-resource-validator'
import { AppError, ErrorCode } from '@shared/errors'
import {
digestBytes,
parseLegacySession,
+ resolveLegacyRequestSettings,
safeLegacyOutput,
} from './session-parser'
@@ -97,68 +97,11 @@ export function resolveLegacyHttpRequestContext(input: {
)
throw failure()
- // Use the parser's exact block digest to retrieve request values without
- // ever adding credentials to its preview/database-facing representation.
- const blocks: string[][] = []
- for (const line of new TextDecoder('utf-8', { fatal: true })
- .decode(input.session)
- .split(/\r?\n/)) {
- if (!line.trim() || line.startsWith('#')) continue
- if (!/^\s/.test(line)) blocks.push([line])
- else blocks.at(-1)?.push(line)
- }
- const block = blocks.find(
- (lines) => digestBytes(lines.join('\n')) === entry.digest
- )
- if (!block) throw changed()
- const task: Record<string, string[]> = Object.create(null)
- for (const line of block.slice(1)) {
- const match = /^\s+([a-z0-9-]+)=(.*)$/.exec(line)
- if (!match) throw failure()
- task[match[1]] ??= []
- task[match[1]].push(match[2])
- }
- const values = (key: string): string[] => {
- const raw = task[key] ?? system[key]
- if (raw === undefined || raw === null) return []
- const list = Array.isArray(raw) ? raw : [raw]
- if (
- list.some(
- (value) =>
- typeof value !== 'string' &&
- typeof value !== 'boolean' &&
- typeof value !== 'number'
- )
- )
- throw failure()
- return list.map(String)
- }
- const value = (key: string, fallback = ''): string => {
- const list = values(key)
- if (list.length > 1) throw failure()
- const result = list[0] ?? fallback
- if (
- [...result].some(
- (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127
- )
- )
- throw failure()
- return result
- }
- if (
- value('load-cookies') ||
- value('netrc-path') ||
- value('no-netrc') === 'false'
- )
- throw failure()
- for (const [key, baseline] of [
- ['http-accept-gzip', 'false'],
- ['http-auth-challenge', 'false'],
- ['http-no-cache', 'false'],
- ['conditional-get', 'false'],
- ['proxy-method', 'get'],
- ])
- if (value(key, baseline) !== baseline) throw failure()
+ // The same filtered, merged values drive preview and actual verification.
+ // Private values remain attached to the parsed entry, never its serialized DTO.
+ const { values } = resolveLegacyRequestSettings(entry, system, 'http')
+ const value = (key: string, fallback = ''): string =>
+ values[key]?.at(-1) ?? fallback
const headers: Record<string, string> = Object.create(null)
const putHeader = (name: string, content: string) => {
@@ -185,18 +128,7 @@ export function resolveLegacyHttpRequestContext(input: {
throw failure()
headers[key] = content
}
- const inheritedHeaders =
- system.header === undefined || system.header === null
- ? []
- : Array.isArray(system.header)
- ? system.header
- : [system.header]
- if (inheritedHeaders.some((value) => typeof value !== 'string'))
- throw failure()
- for (const line of [
- ...(inheritedHeaders as string[]),
- ...(task.header ?? []),
- ].filter((part) => part.trim())) {
+ for (const line of values.header ?? []) {
const colon = line.indexOf(':')
if (colon <= 0) throw failure()
putHeader(line.slice(0, colon), line.slice(colon + 1).trim())
@@ -216,41 +148,14 @@ export function resolveLegacyHttpRequestContext(input: {
)
}
const userAgent = headers['user-agent'] ?? value('user-agent', 'aria2/1.36.0')
- const proxyFor = (prefix: string) => {
- const raw = value(prefix)
- if (!raw) {
- if (value(`${prefix}-user`) || value(`${prefix}-passwd`)) throw failure()
- return ''
- }
- const proxy = normalizeAria2TaskProxyUrl(raw)
- if (!proxy) throw failure()
- const userKey = `${prefix}-user`
- const passKey = `${prefix}-passwd`
- const user = value(userKey)
- const pass = value(passKey)
- try {
- // Dedicated options are raw values and override each URI field only
- // when defined, including an explicitly empty value.
- if (values(userKey).length) proxy.username = encodeURIComponent(user)
- if (values(passKey).length) proxy.password = encodeURIComponent(pass)
- } catch {
- throw failure()
- }
- // aria2 omits userinfo entirely when the resulting username is empty.
- if (!proxy.username) proxy.password = ''
- return proxy.href
- }
- const allProxy = proxyFor('all-proxy')
- const httpProxy = proxyFor('http-proxy') || allProxy
- const httpsProxy = proxyFor('https-proxy') || allProxy
- // Redirects can change protocol. One explicit route must describe both.
- if (httpProxy !== httpsProxy) throw failure()
if (path.dirname(input.targetPath) === input.targetPath) throw changed()
return {
uri,
headers,
userAgent,
- proxy: httpProxy,
- noProxy: value('no-proxy'),
+ // The activation service supplies the currently applied download route.
+ // Legacy proxy endpoints and credentials are never replayed.
+ proxy: '',
+ noProxy: '',
}
}
diff --git a/src/core/legacy-import/import-service-adversarial.test.ts b/src/core/legacy-import/import-service-adversarial.test.ts
index 1ae8c996..fa37fc8e 100644
--- a/src/core/legacy-import/import-service-adversarial.test.ts
+++ b/src/core/legacy-import/import-service-adversarial.test.ts
@@ -424,6 +424,8 @@ describe('legacy import service adversarial acceptance', () => {
' pause=true',
' header=Authorization: Bearer LEGACY_AUTH_SECRET',
' header=Cookie: session=LEGACY_COOKIE_SECRET',
+ ' load-cookies=/private/LEGACY_COOKIE_FILE_SECRET',
+ ' on-download-complete=LEGACY_COMMAND_SECRET',
'',
].join('\n')
await writeFile(f.sessionPath, session)
@@ -439,7 +441,11 @@ describe('legacy import service adversarial acceptance', () => {
type: 'http',
selectable: true,
reason: 'request-settings-required',
- requestOptions: expect.arrayContaining(['header', 'all-proxy']),
+ requestOptions: ['header'],
+ ignoredOptions: expect.arrayContaining([
+ 'load-cookies',
+ 'on-download-complete',
+ ]),
})
const run = await f.service.commit({
previewId: preview.previewId,
@@ -454,7 +460,11 @@ describe('legacy import service adversarial acceptance', () => {
activation: 'inactive',
storagePolicy: 'legacy-read-only',
reason: 'request-settings-required',
- requestOptions: expect.arrayContaining(['header', 'all-proxy']),
+ requestOptions: ['header'],
+ ignoredOptions: expect.arrayContaining([
+ 'load-cookies',
+ 'on-download-complete',
+ ]),
})
const persisted = JSON.stringify({
tasks: f.db.getAllTasks(),
@@ -465,6 +475,8 @@ describe('legacy import service adversarial acceptance', () => {
'LEGACY_AUTH_SECRET',
'LEGACY_COOKIE_SECRET',
'LEGACY_PROXY_SECRET',
+ 'LEGACY_COOKIE_FILE_SECRET',
+ 'LEGACY_COMMAND_SECRET',
])
expect(persisted).not.toContain(secret)
expect(await readFile(f.sessionPath, 'utf8')).toBe(session)
@@ -485,6 +497,70 @@ describe('legacy import service adversarial acceptance', () => {
})
})
+ it('imports a proxy-dependent magnet inactive with stripped option names and no request secrets', async () => {
+ const f = await fixture()
+ const session = [
+ 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=bundle',
+ ' gid=0000000000000002',
+ ' all-proxy-user=LEGACY_PROXY_USER',
+ ' header=Cookie: LEGACY_BT_COOKIE_SECRET',
+ ' rpc-secret=LEGACY_RPC_SECRET',
+ '',
+ ].join('\n')
+ await writeFile(f.sessionPath, session)
+ await writeFile(
+ path.join(f.sourceRoot, 'system.json'),
+ JSON.stringify({
+ dir: f.downloads,
+ 'all-proxy': 'http://proxy.example:8080',
+ 'all-proxy-passwd': 'LEGACY_PROXY_PASSWORD',
+ })
+ )
+ const preview = await f.service.scan(f.source.sourceHandle)
+ expect(preview.items[0]).toMatchObject({
+ type: 'magnet',
+ name: 'bundle',
+ selectable: true,
+ reason: 'metadata-required',
+ ignoredOptions: expect.arrayContaining([
+ 'header',
+ 'rpc-secret',
+ 'all-proxy',
+ 'all-proxy-user',
+ 'all-proxy-passwd',
+ ]),
+ })
+ const run = await f.service.commit({
+ previewId: preview.previewId,
+ itemIds: [preview.items[0].itemId],
+ })
+ const report = await completed(f.service, run.runId)
+ expect(report.imported).toBe(1)
+ const [task] = f.taskManager.getAll()
+ expect(task.status).toBe(TaskStatus.Paused)
+ expect(task.instances[0].gid).toBeNull()
+ expect(task.instances[0].payload.legacyImport).toMatchObject({
+ activation: 'inactive',
+ storagePolicy: 'legacy-read-only',
+ ignoredOptions: expect.arrayContaining([
+ 'header',
+ 'rpc-secret',
+ 'all-proxy',
+ 'all-proxy-user',
+ 'all-proxy-passwd',
+ ]),
+ })
+ const persisted = JSON.stringify({
+ tasks: f.db.getAllTasks(),
+ preview,
+ report,
+ })
+ expect(persisted).not.toMatch(
+ /LEGACY_PROXY_USER|LEGACY_BT_COOKIE_SECRET|LEGACY_RPC_SECRET|LEGACY_PROXY_PASSWORD|proxy\.example/
+ )
+ expect(await readFile(f.sessionPath, 'utf8')).toBe(session)
+ })
+
it('rejects a stale preview before committing records', async () => {
const f = await fixture()
await writeFile(
diff --git a/src/core/legacy-import/import-service.ts b/src/core/legacy-import/import-service.ts
index e7b51aef..653c7bf4 100644
--- a/src/core/legacy-import/import-service.ts
+++ b/src/core/legacy-import/import-service.ts
@@ -806,6 +806,9 @@ export class LegacyImportService {
...(candidate.item.requestOptions?.length
? { requestOptions: candidate.item.requestOptions }
: {}),
+ ...(candidate.item.ignoredOptions?.length
+ ? { ignoredOptions: candidate.item.ignoredOptions }
+ : {}),
selectionKnown: candidate.selectionKnown,
selectedFiles: candidate.selectedFiles,
},
diff --git a/src/core/legacy-import/parser-adversarial.test.ts b/src/core/legacy-import/parser-adversarial.test.ts
index 92f8e908..246b3e0a 100644
--- a/src/core/legacy-import/parser-adversarial.test.ts
+++ b/src/core/legacy-import/parser-adversarial.test.ts
@@ -1,6 +1,11 @@
// @vitest-environment node
import { describe, expect, it } from 'vitest'
-import { parseLegacySession, validateLegacyBencode } from './session-parser'
+import {
+ getLegacyRequestValues,
+ parseLegacySession,
+ resolveLegacyRequestSettings,
+ validateLegacyBencode,
+} from './session-parser'
const encode = (value: string) => new TextEncoder().encode(value)
@@ -34,16 +39,13 @@ describe('legacy session adversarial parsing', () => {
const [entry] = parseLegacySession(
encode(`https://example.test/a\n no-netrc=${value}\n`)
)
- expect(entry.reason).toBe('unsupported-options')
+ expect(entry.reason).toBeNull()
}
)
it.each([
['header', 'Authorization: Bearer private-token'],
['referer', 'https://private.test/source'],
- ['all-proxy', 'http://private-user:[email protected]:8080'],
- ['load-cookies', '/private/cookies.txt'],
- ['no-netrc', 'false'],
])(
'keeps only the name of request option %s for reconfiguration',
(key, value) => {
@@ -69,7 +71,7 @@ describe('legacy session adversarial parsing', () => {
expect(JSON.stringify(entry)).not.toMatch(/private-cookie|private-token/)
})
- it('ignores empty known request options but rejects empty unknown options', () => {
+ it('ignores empty known request options and strips empty unknown options', () => {
const [empty, unknown] = parseLegacySession(
encode(
'https://example.test/a\n header=\n referer= \n all-proxy=\nhttps://example.test/b\n unsafe-option=\n'
@@ -77,19 +79,19 @@ describe('legacy session adversarial parsing', () => {
)
expect(empty.reason).toBeNull()
expect(empty.requestOptions).toEqual([])
- expect(unknown.reason).toBe('unsupported-options')
- expect(unknown.unsupportedOptions).toEqual(['unsafe-option'])
+ expect(unknown.reason).toBeNull()
+ expect(unknown.ignoredOptions).toEqual(['unsafe-option'])
})
- it('bounds safe diagnostic names while preserving unsupported rejection', () => {
+ it('bounds safe diagnostic names without retaining unsupported values', () => {
const [entry] = parseLegacySession(
encode(
`https://example.test/a\n ${'x'.repeat(65)}=private\n${Array.from({ length: 70 }, (_, index) => ` unknown-${index}=private`).join('\n')}\n`
)
)
- expect(entry.reason).toBe('unsupported-options')
- expect(entry.unsupportedOptions).toHaveLength(64)
- expect(entry.unsupportedOptions.every((key) => key.length <= 64)).toBe(true)
+ expect(entry.reason).toBeNull()
+ expect(entry.ignoredOptions).toHaveLength(64)
+ expect(entry.ignoredOptions.every((key) => key.length <= 64)).toBe(true)
expect(JSON.stringify(entry)).not.toContain('private')
})
@@ -137,17 +139,121 @@ describe('legacy session adversarial parsing', () => {
'input-file=/tmp/other',
'rpc-secret=private',
])(
- 'does not replay executable, remote-control or credential options: %s',
+ 'strips executable, remote-control or credential options: %s',
(option) => {
const [entry] = parseLegacySession(
encode(`https://example.test/a\n ${option}\n out=a.zip\n`)
)
- expect(entry.reason).toBe('unsupported-options')
- expect(entry.unsupportedOptions).toEqual([option.split('=')[0]])
+ expect(entry.reason).toBeNull()
+ expect(entry.ignoredOptions).toEqual([option.split('=')[0]])
expect(entry.options[option.split('=')[0]]).toBeUndefined()
}
)
+ it('keeps private request values out of serialization while resolving the final task singleton', () => {
+ const [entry] = parseLegacySession(
+ encode(
+ [
+ 'https://example.test/a',
+ ' all-proxy=http://obsolete-private.test:8080',
+ ' all-proxy=',
+ ' http-user=obsolete-user',
+ ' http-user=final-user',
+ ' header=X-Task: private-task',
+ '',
+ ].join('\n')
+ )
+ )
+ const resolved = resolveLegacyRequestSettings(
+ entry,
+ {
+ 'all-proxy': 'http://global-private.test:8080',
+ 'http-user': 'global-user',
+ header: ['X-Global: private-global'],
+ },
+ 'http'
+ )
+ expect(resolved.values).toMatchObject({
+ 'http-user': ['final-user'],
+ header: ['X-Global: private-global', 'X-Task: private-task'],
+ })
+ expect(resolved.requestOptions).toEqual(
+ expect.arrayContaining(['http-user', 'header'])
+ )
+ expect(resolved.requestOptions).not.toContain('all-proxy')
+ expect(getLegacyRequestValues(entry)['all-proxy']).toBeUndefined()
+ expect(JSON.stringify(entry)).not.toMatch(
+ /private|final-user|obsolete-user/
+ )
+ })
+
+ it('drops unsupported and conflicting headers while preserving independent valid headers', () => {
+ const [entry] = parseLegacySession(
+ encode(
+ [
+ 'https://example.test/a',
+ ' header=Authorization: private-task',
+ ' header=X-Valid: retained',
+ ' header=Range: bytes=0-1',
+ ' header=Host: unsafe.test',
+ ' header=invalid',
+ ' load-cookies=/private/cookies.txt',
+ ' netrc-path=/private/netrc',
+ ' no-netrc=false',
+ '',
+ ].join('\n')
+ )
+ )
+ const resolved = resolveLegacyRequestSettings(
+ entry,
+ { header: ['Authorization: private-global'] },
+ 'http'
+ )
+ expect(resolved.values.header).toEqual(['X-Valid: retained'])
+ expect(resolved.requestOptions).toEqual(['header'])
+ expect(resolved.ignoredOptions).toEqual(
+ expect.arrayContaining([
+ 'header',
+ 'load-cookies',
+ 'netrc-path',
+ 'no-netrc',
+ ])
+ )
+ expect(JSON.stringify(entry)).not.toMatch(/private|unsafe/)
+ })
+
+ it.each(['http', 'bt', 'magnet'] as const)(
+ 'discards legacy proxy values for %s while reporting only names',
+ (kind) => {
+ const prefixes = ['all-proxy', 'http-proxy', 'https-proxy', 'ftp-proxy']
+ const settings = Object.fromEntries(
+ prefixes.flatMap((key) => [
+ [key, 'http://private:[email protected]:8080'],
+ [`${key}-user`, 'private-user'],
+ [`${key}-passwd`, 'private-password'],
+ ])
+ )
+ Object.assign(settings, {
+ 'no-proxy': '.private.test',
+ 'proxy-method': 'tunnel',
+ })
+ const entry = parseLegacySession(
+ encode(
+ 'https://example.test/a\n' +
+ Object.entries(settings)
+ .map(([key, value]) => ` ${key}=${value}`)
+ .join('\n')
+ )
+ )[0]
+ const result = resolveLegacyRequestSettings(entry, settings, kind)
+ expect(result.values).toEqual({})
+ expect(result.requestOptions).toEqual([])
+ expect(result.ignoredOptions.sort()).toEqual(Object.keys(settings).sort())
+ expect(getLegacyRequestValues(entry)).toEqual({})
+ expect(JSON.stringify(entry)).not.toMatch(/private|secret|proxy\.test/)
+ }
+ )
+
it('rejects malformed UTF-8 instead of merging replacement characters into an identity', () => {
expect(() =>
parseLegacySession(new Uint8Array([0x68, 0xff, 0x0a]))
diff --git a/src/core/legacy-import/session-parser.ts b/src/core/legacy-import/session-parser.ts
index 367f38e6..80d50b39 100644
--- a/src/core/legacy-import/session-parser.ts
+++ b/src/core/legacy-import/session-parser.ts
@@ -26,12 +26,9 @@ const OPTIONS = new Set([
'allow-overwrite',
'auto-file-renaming',
'file-allocation',
- // Only explicit true is retained: it disables ambient netrc credentials.
- 'no-netrc',
// Declarative options emitted by the v1.8.19 bundled engine even when the
// user did not customize a task. None is applied during scan or import.
'pause-metadata',
- 'user-agent',
'follow-torrent',
'follow-metalink',
'enable-peer-exchange',
@@ -41,24 +38,198 @@ const OPTIONS = new Set([
'bt-tracker',
])
-/** Only names survive parsing; old credentials and request values are never replayed. */
+const PROXY_PREFIXES = ['all-proxy', 'http-proxy', 'https-proxy', 'ftp-proxy']
+const LEGACY_PROXY_OPTIONS = new Set([
+ ...PROXY_PREFIXES.flatMap((key) => [key, `${key}-user`, `${key}-passwd`]),
+ 'no-proxy',
+ 'proxy-method',
+])
+
+/** Values remain private to the parser; only filtered names enter public records. */
export const LEGACY_REQUEST_OPTIONS = new Set([
'header',
'referer',
- 'all-proxy',
- 'all-proxy-user',
- 'all-proxy-passwd',
- 'http-proxy',
- 'http-proxy-user',
- 'http-proxy-passwd',
- 'https-proxy',
- 'https-proxy-user',
- 'https-proxy-passwd',
'http-user',
'http-passwd',
- 'load-cookies',
+ 'user-agent',
+ 'no-netrc',
])
+type LegacyRequestValues = Readonly<Record<string, readonly string[]>>
+type LegacyRequestKind = 'http' | 'bt' | 'magnet' | 'unknown'
+const privateRequestValues = new WeakMap<
+ LegacySessionEntry,
+ LegacyRequestValues
+>()
+const privateIgnoredOptions = new WeakMap<
+ LegacySessionEntry,
+ readonly string[]
+>()
+const EMPTY_REQUEST_VALUES: LegacyRequestValues = Object.freeze(
+ Object.create(null)
+)
+
+export function getLegacyRequestValues(
+ entry: LegacySessionEntry
+): LegacyRequestValues {
+ return privateRequestValues.get(entry) ?? EMPTY_REQUEST_VALUES
+}
+
+function safeOptionName(name: string): boolean {
+ return name.length <= 64 && /^[a-z0-9-]+$/.test(name)
+}
+
+function validRequestText(value: unknown): value is string {
+ return (
+ typeof value === 'string' &&
+ value.length <= MAX_LINE &&
+ !Array.from(value).some((character) => {
+ const code = character.charCodeAt(0)
+ return code < 32 || code === 127
+ }) &&
+ !/[\ud800-\udfff]/u.test(value)
+ )
+}
+
+/** Resolve aria2 singleton precedence and cumulative headers once per entry. */
+export function resolveLegacyRequestSettings(
+ entry: LegacySessionEntry,
+ system: Readonly<Record<string, unknown>>,
+ kind: LegacyRequestKind
+): {
+ values: LegacyRequestValues
+ requestOptions: string[]
+ ignoredOptions: string[]
+} {
+ const task = getLegacyRequestValues(entry)
+ const values: Record<string, string[]> = Object.create(null)
+ const ignored = new Set(
+ privateIgnoredOptions.get(entry) ?? entry.ignoredOptions
+ )
+ const ignore = (key: string) => {
+ if (safeOptionName(key) && ignored.size < 64) ignored.add(key)
+ }
+ const raw = (key: string): readonly unknown[] => {
+ if (Object.hasOwn(task, key)) return task[key]
+ const value = system[key]
+ return value === undefined || value === null
+ ? []
+ : Array.isArray(value)
+ ? value
+ : [value]
+ }
+ for (const key of Object.keys(system))
+ if (
+ !OPTIONS.has(key) &&
+ !LEGACY_REQUEST_OPTIONS.has(key) &&
+ (!LEGACY_PROXY_OPTIONS.has(key) || system[key] !== '')
+ )
+ ignore(key)
+ for (const key of LEGACY_REQUEST_OPTIONS) {
+ if (key === 'header') continue
+ const list = raw(key)
+ if (!list.length) continue
+ const value = list.at(-1)
+ if (key === 'no-netrc') {
+ if (value !== 'true' && value !== true) ignore(key)
+ continue
+ }
+ if (kind !== 'http') {
+ if (value !== '') ignore(key)
+ continue
+ }
+ if (!validRequestText(value)) {
+ ignore(key)
+ continue
+ }
+ if (
+ (key === 'referer' && value === '*') ||
+ (key === 'http-user' && value.includes(':'))
+ ) {
+ ignore(key)
+ continue
+ }
+ values[key] = [
+ value.trim() === '' && !key.endsWith('-user') && !key.endsWith('-passwd')
+ ? ''
+ : value,
+ ]
+ }
+ const inheritedHeaders =
+ system.header == null
+ ? []
+ : Array.isArray(system.header)
+ ? system.header
+ : [system.header]
+ const headers = [...inheritedHeaders, ...(task.header ?? [])]
+ if (kind !== 'http') {
+ if (headers.some((value) => value !== '')) ignore('header')
+ } else {
+ const byName = new Map<string, string[]>()
+ for (const line of headers) {
+ if (typeof line === 'string' && !line.trim()) continue
+ if (!validRequestText(line)) {
+ ignore('header')
+ continue
+ }
+ const colon = line.indexOf(':')
+ const name = line.slice(0, colon).trim().toLowerCase()
+ if (
+ colon <= 0 ||
+ !/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(name) ||
+ [
+ 'range',
+ 'if-range',
+ 'if-match',
+ 'accept-encoding',
+ 'host',
+ 'connection',
+ 'content-length',
+ 'transfer-encoding',
+ 'proxy-authorization',
+ ].includes(name)
+ ) {
+ ignore('header')
+ continue
+ }
+ const group = byName.get(name) ?? []
+ group.push(line)
+ byName.set(name, group)
+ }
+ for (const [name, group] of byName) {
+ if (group.length > 1) {
+ ignore('header')
+ byName.delete(name)
+ }
+ }
+ for (const [option, header] of [
+ ['referer', 'referer'],
+ ['http-user', 'authorization'],
+ ] as const) {
+ if (!values[option]?.[0] || !byName.has(header)) continue
+ ignore(option)
+ if (option === 'http-user') {
+ if (values['http-passwd']?.[0]) ignore('http-passwd')
+ delete values['http-passwd']
+ }
+ delete values[option]
+ }
+ if (!values['http-user']?.[0] && values['http-passwd']?.[0]) {
+ ignore('http-passwd')
+ delete values['http-passwd']
+ }
+ const accepted = [...byName.values()].flat()
+ if (accepted.length) values.header = accepted
+ }
+ return {
+ values,
+ requestOptions: Object.keys(values).filter(
+ (key) => key !== 'user-agent' && values[key].some((value) => value !== '')
+ ),
+ ignoredOptions: [...ignored],
+ }
+}
+
export interface LegacySessionEntry {
itemKey: string
digest: string
@@ -67,7 +238,7 @@ export interface LegacySessionEntry {
options: Record<string, string>
optionPairs: Array<readonly [string, string]>
requestOptions: string[]
- unsupportedOptions: string[]
+ ignoredOptions: string[]
reason: LegacyReason | null
}
@@ -91,8 +262,8 @@ export function parseLegacySession(bytes: Uint8Array): LegacySessionEntry[] {
const uris = lines[0].trim().split(/\t+/).filter(Boolean)
const options: Record<string, string> = Object.create(null)
const optionPairs: Array<readonly [string, string]> = []
- const requestOptions = new Set<string>()
- const unsupportedOptions = new Set<string>()
+ const requestValues: Record<string, string[]> = Object.create(null)
+ const ignoredOptions = new Set<string>()
let reason: LegacyReason | null =
lines.some((line) => line.length > MAX_LINE) || uris.length > 16
? 'invalid-record'
@@ -104,24 +275,25 @@ export function parseLegacySession(bytes: Uint8Array): LegacySessionEntry[] {
continue
}
const [, key, value] = match
- if (
- LEGACY_REQUEST_OPTIONS.has(key) ||
- (key === 'no-netrc' && value.trim() === 'false')
- ) {
- if (value.trim()) requestOptions.add(key)
- } else if (
- !OPTIONS.has(key) ||
- (key === 'no-netrc' && value.trim() !== 'true')
- ) {
- if (reason !== 'invalid-record') reason = 'unsupported-options'
- if (key.length <= 64 && unsupportedOptions.size < 64)
- unsupportedOptions.add(key)
+ if (LEGACY_REQUEST_OPTIONS.has(key)) {
+ if (key === 'no-netrc') {
+ if (value === 'true') options[key] = value
+ else delete options[key]
+ }
+ requestValues[key] ??= []
+ requestValues[key].push(value)
+ } else if (!OPTIONS.has(key)) {
+ if (
+ safeOptionName(key) &&
+ ignoredOptions.size < 64 &&
+ (!LEGACY_PROXY_OPTIONS.has(key) || value !== '')
+ )
+ ignoredOptions.add(key)
} else {
optionPairs.push([key, value])
options[key] = value
}
}
- if (!reason && requestOptions.size) reason = 'request-settings-required'
const gid =
options.gid && /^[a-f\d]{16}$/i.test(options.gid)
? options.gid.toLowerCase()
@@ -129,17 +301,29 @@ export function parseLegacySession(bytes: Uint8Array): LegacySessionEntry[] {
if (options.gid && !gid) reason = 'invalid-record'
const digest = digestBytes(raw)
const itemKey = gid ? `gid:${gid}` : `entry:${digest}`
- entries.push({
+ const entry: LegacySessionEntry = {
itemKey,
digest,
gid,
uris,
options,
optionPairs,
- requestOptions: [...requestOptions],
- unsupportedOptions: [...unsupportedOptions],
+ requestOptions: [],
+ ignoredOptions: [...ignoredOptions],
reason,
- })
+ }
+ privateRequestValues.set(entry, requestValues)
+ privateIgnoredOptions.set(entry, entry.ignoredOptions)
+ const request = resolveLegacyRequestSettings(
+ entry,
+ {},
+ /^https?:\/\//i.test(uris[0] ?? '') ? 'http' : 'bt'
+ )
+ entry.requestOptions = request.requestOptions
+ entry.ignoredOptions = request.ignoredOptions
+ if (!entry.reason && request.requestOptions.length)
+ entry.reason = 'request-settings-required'
+ entries.push(entry)
lines = []
}
for (const line of text.split(/\r?\n/)) {
diff --git a/src/core/legacy-import/source-scanner-adversarial.test.ts b/src/core/legacy-import/source-scanner-adversarial.test.ts
index 1e307f1c..517ccc05 100644
--- a/src/core/legacy-import/source-scanner-adversarial.test.ts
+++ b/src/core/legacy-import/source-scanner-adversarial.test.ts
@@ -3,6 +3,7 @@ import {
link,
mkdir,
mkdtemp,
+ readFile,
rename,
rm,
symlink,
@@ -121,7 +122,7 @@ describe('legacy source adversarial boundaries', () => {
name: '下载视频.mp4',
selectable: true,
reason: 'request-settings-required',
- requestOptions: ['header', 'referer'],
+ requestOptions: expect.arrayContaining(['header', 'referer']),
})
expect(JSON.stringify(scan.candidates.map(({ item }) => item))).not.toMatch(
/private-token|private-cookie|private\.test/
@@ -130,7 +131,7 @@ describe('legacy source adversarial boundaries', () => {
it('blocks HTTP mirrors that cannot be reconfigured through the fresh-download form', async () => {
const { source } = await fixture(
- 'https://example.test/file.zip\thttps://mirror.test/file.zip\n header=private\n'
+ 'https://example.test/file.zip\thttps://mirror.test/file.zip\n header=X-Test: private\n'
)
const scan = await scanLegacySource(source, () => false)
expect(scan.candidates[0].item).toMatchObject({
@@ -153,7 +154,7 @@ describe('legacy source adversarial boundaries', () => {
})
})
- it('requires new settings for inherited proxy and credentials without exposing them', async () => {
+ it('retains HTTP authentication but discards inherited proxies without exposing values', async () => {
const { root, sourceRoot, source } = await fixture()
await writeFile(
path.join(sourceRoot, 'system.json'),
@@ -169,11 +170,7 @@ describe('legacy source adversarial boundaries', () => {
type: 'http',
selectable: true,
reason: 'request-settings-required',
- requestOptions: expect.arrayContaining([
- 'http-user',
- 'http-passwd',
- 'all-proxy',
- ]),
+ requestOptions: expect.arrayContaining(['http-user', 'http-passwd']),
})
expect(JSON.stringify(scan.candidates.map(({ item }) => item))).not.toMatch(
/private-user|private-pass|private-proxy/
@@ -203,7 +200,7 @@ describe('legacy source adversarial boundaries', () => {
})
it.each([false, 'false'])(
- 'requires new settings for inherited no-netrc=%s',
+ 'strips inherited ambient netrc setting %s',
async (value) => {
const { root, sourceRoot, source } = await fixture()
await writeFile(
@@ -213,8 +210,8 @@ describe('legacy source adversarial boundaries', () => {
const scan = await scanLegacySource(source, () => false)
expect(scan.candidates[0].item).toMatchObject({
selectable: true,
- reason: 'request-settings-required',
- requestOptions: ['no-netrc'],
+ reason: 'verification-required',
+ ignoredOptions: ['no-netrc'],
})
}
)
@@ -225,17 +222,17 @@ describe('legacy source adversarial boundaries', () => {
'rpc-secret=private-secret',
'unknown-option=',
])(
- 'keeps unsafe HTTP option %s disabled while retaining its type',
+ 'strips unsafe HTTP option %s while retaining its type',
async (option) => {
const { source } = await fixture(
- `https://example.test/file.zip\n header=private-header\n ${option}\n`
+ `https://example.test/file.zip\n header=X-Test: private-header\n ${option}\n`
)
const scan = await scanLegacySource(source, () => false)
expect(scan.candidates[0].item).toMatchObject({
type: 'http',
- selectable: false,
- reason: 'unsupported-options',
- unsupportedOptions: [option.split('=')[0]],
+ selectable: true,
+ reason: 'request-settings-required',
+ ignoredOptions: [option.split('=')[0]],
})
expect(JSON.stringify(scan.candidates[0].item)).not.toContain('private')
}
@@ -250,7 +247,9 @@ describe('legacy source adversarial boundaries', () => {
])(
'still validates request-dependent task %s%s',
async (uri, options, reason) => {
- const { source } = await fixture(`${uri}\n header=private\n${options}`)
+ const { source } = await fixture(
+ `${uri}\n header=X-Test: private\n${options}`
+ )
const scan = await scanLegacySource(source, () => false)
expect(scan.candidates[0].item).toMatchObject({
selectable: false,
@@ -263,21 +262,23 @@ describe('legacy source adversarial boundaries', () => {
[
'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=bundle',
'magnet',
+ true,
+ 'bundle',
],
- ['/outside/metadata.torrent', 'bt'],
- ['metadata.torrent', 'bt'],
+ ['/outside/metadata.torrent', 'bt', false, 'metadata.torrent'],
])(
- 'keeps request-dependent %s blocked without reading metadata',
- async (uri, type) => {
- const { source } = await fixture(`${uri}\n header=private\n`)
+ 'strips non-proxy request settings from %s while retaining metadata safety',
+ async (uri, type, selectable, name) => {
+ const { source } = await fixture(`${uri}\n header=Cookie: private\n`)
const scan = await scanLegacySource(source, () => false)
expect(scan.candidates[0].item).toMatchObject({
type,
- selectable: false,
- reason: 'unsupported-options',
- requestOptions: ['header'],
- unsupportedOptions: ['header'],
+ name,
+ selectable,
+ reason: 'metadata-required',
+ ignoredOptions: ['header'],
})
+ expect(scan.candidates[0].item.requestOptions).toBeUndefined()
expect(scan.candidates[0].torrent).toBeNull()
expect(scan.files.map(({ relativePath }) => relativePath).sort()).toEqual(
['download.session', 'system.json', 'user.json']
@@ -285,6 +286,97 @@ describe('legacy source adversarial boundaries', () => {
}
)
+ it.each([
+ [
+ 'inherited proxy',
+ { 'all-proxy': 'http://localhost:7890' },
+ '',
+ ['all-proxy'],
+ ],
+ ['task proxy', {}, ' all-proxy=localhost:7890\n', ['all-proxy']],
+ ['empty default', { 'all-proxy': '' }, '', []],
+ ['invalid legacy proxy', { 'all-proxy': false }, '', ['all-proxy']],
+ ])(
+ 'imports magnets with %s and resolves the saved display name',
+ async (_label, inherited, options, ignoredOptions) => {
+ const magnet =
+ 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=Known-name'
+ const { root, sourceRoot, source } = await fixture(
+ `${magnet}\n${options}`
+ )
+ await writeFile(
+ path.join(sourceRoot, 'system.json'),
+ JSON.stringify({ dir: path.join(root, 'downloads'), ...inherited })
+ )
+ const scan = await scanLegacySource(source, () => false)
+ const item = scan.candidates[0].item
+ expect(item).toMatchObject({
+ type: 'magnet',
+ name: 'Known-name',
+ selectable: true,
+ reason: 'metadata-required',
+ })
+ expect(item.requestOptions ?? []).toEqual([])
+ expect(item.ignoredOptions ?? []).toEqual(ignoredOptions)
+ expect(JSON.stringify(item)).not.toMatch(/localhost|private/)
+ }
+ )
+
+ it('does not activate the old disabled proxy backup setting', async () => {
+ const { sourceRoot, source } = await fixture(
+ 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=bundle\n'
+ )
+ await writeFile(
+ path.join(sourceRoot, 'user.json'),
+ JSON.stringify({
+ theme: 'auto',
+ 'all-proxy-backup': 'localhost:7890',
+ 'use-proxy': false,
+ })
+ )
+ const scan = await scanLegacySource(source, () => false)
+ expect(scan.candidates[0].item).toMatchObject({
+ name: 'bundle',
+ selectable: true,
+ reason: 'metadata-required',
+ })
+ expect(scan.candidates[0].item.requestOptions).toBeUndefined()
+ })
+
+ it('parses torrent metadata and selection despite inherited proxy and stripped options', async () => {
+ const { root, sourceRoot, source } = await fixture(
+ 'metadata.torrent\n select-file=1\n header=Cookie: private-cookie\n on-download-complete=private-command\n'
+ )
+ const torrent = await readFile(
+ new URL(
+ '../../../tests/fixtures/legacy-v1/generated/downloads/a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent',
+ import.meta.url
+ )
+ )
+ await writeFile(path.join(sourceRoot, 'metadata.torrent'), torrent)
+ await writeFile(
+ path.join(sourceRoot, 'system.json'),
+ JSON.stringify({
+ dir: path.join(root, 'downloads'),
+ 'all-proxy': 'localhost:7890',
+ })
+ )
+ const scan = await scanLegacySource(source, () => false)
+ expect(scan.candidates[0].item).toMatchObject({
+ type: 'bt',
+ name: 'fixture-bundle',
+ selectable: true,
+ reason: 'verification-required',
+ ignoredOptions: expect.arrayContaining([
+ 'all-proxy',
+ 'header',
+ 'on-download-complete',
+ ]),
+ })
+ expect(scan.candidates[0].selectedFiles).toEqual([0])
+ expect(scan.candidates[0].torrent?.files).toHaveLength(2)
+ })
+
it('does not choose an arbitrary winner among conflicting entries with one old GID', async () => {
const { source } = await fixture(
'https://example.test/a.zip\n gid=0123456789abcdef\n out=a.zip\nhttps://example.test/b.zip\n gid=0123456789abcdef\n out=b.zip\n'
@@ -300,7 +392,7 @@ describe('legacy source adversarial boundaries', () => {
const original = await scanLegacySource(source, () => false)
await writeFile(
path.join(sourceRoot, 'download.session'),
- `${session} header=private\n`
+ `${session} header=X-Test: private\n`
)
const changed = await scanLegacySource(source, () => false)
expect(changed.candidates[0].item.itemId).toBe(
@@ -314,7 +406,7 @@ describe('legacy source adversarial boundaries', () => {
it('rejects duplicate task identities when only their request values differ', async () => {
const { source } = await fixture(
- 'https://example.test/file.zip\n header=first-private\nhttps://example.test/file.zip\n header=second-private\n'
+ 'https://example.test/file.zip\n header=X-Test: first-private\nhttps://example.test/file.zip\n header=X-Test: second-private\n'
)
const scan = await scanLegacySource(source, () => false)
expect(scan.candidates).toHaveLength(2)
diff --git a/src/core/legacy-import/source-scanner.ts b/src/core/legacy-import/source-scanner.ts
index bdfc3d72..83bbcada 100644
--- a/src/core/legacy-import/source-scanner.ts
+++ b/src/core/legacy-import/source-scanner.ts
@@ -11,10 +11,10 @@ import parseTorrent from 'parse-torrent'
import { parseBtFileLayout } from '../task/bt-storage-layout'
import {
digestBytes,
- LEGACY_REQUEST_OPTIONS,
type LegacySessionEntry,
MAX_LEGACY_BYTES,
parseLegacySession,
+ resolveLegacyRequestSettings,
safeLegacyComponent,
safeLegacyDirectory,
safeLegacyOutput,
@@ -278,16 +278,6 @@ function selection(
return { files: [...result].sort((a, b) => a - b), known: true }
}
-function hasRequestValue(value: unknown): boolean {
- const values = Array.isArray(value) ? value : [value]
- return values.some(
- (part) =>
- part !== undefined &&
- part !== null &&
- (typeof part !== 'string' || part.trim().length > 0)
- )
-}
-
function recognizableType(first: string | undefined): LegacyImportItem['type'] {
if (!first) return 'unknown'
if (/^https?:\/\//i.test(first)) return 'http'
@@ -324,28 +314,24 @@ export async function scanLegacySource(
pid > 0 &&
(await isProcessRunning(pid))
const candidates: LegacyCandidate[] = []
- const inheritedRequestOptions = [...LEGACY_REQUEST_OPTIONS].filter((key) =>
- hasRequestValue(system[key])
- )
- if (system['no-netrc'] === false || system['no-netrc'] === 'false')
- inheritedRequestOptions.push('no-netrc')
let snapshotBytes = files.reduce((sum, file) => sum + file.bytes.length, 0)
const torrentByPath = new Map<string, LegacySnapshotFile>()
for (const entry of parseLegacySession(session.bytes)) {
- const requestOptions = [
- ...new Set([...entry.requestOptions, ...inheritedRequestOptions]),
- ]
+ const type = recognizableType(entry.uris[0])
+ const { requestOptions, ignoredOptions } = resolveLegacyRequestSettings(
+ entry,
+ system,
+ type
+ )
const item: LegacyImportItem = {
itemId: entry.itemKey,
name: entry.options.out || '—',
saveDir: safeLegacyDirectory(entry.options.dir ?? (system.dir as string)),
- type: recognizableType(entry.uris[0]),
+ type,
selectable: true,
reason: 'fresh-download-required',
...(requestOptions.length ? { requestOptions } : {}),
- ...(entry.unsupportedOptions.length
- ? { unsupportedOptions: entry.unsupportedOptions }
- : {}),
+ ...(ignoredOptions.length ? { ignoredOptions } : {}),
}
const candidate: LegacyCandidate = {
item,
@@ -364,14 +350,6 @@ export async function scanLegacySource(
item.reason = entry.reason
continue
}
- if (requestOptions.length && item.type !== 'http') {
- // Request recovery is only implemented for HTTP. Do not open torrent
- // metadata or relax verification and activation for other task types.
- item.selectable = false
- item.reason = 'unsupported-options'
- item.unsupportedOptions = requestOptions
- continue
- }
const first = entry.uris[0]
if (!first) throw new Error('invalid')
const dir = entry.options.dir ?? (system.dir as string)
diff --git a/src/core/legacy-import/v1-generated-fixtures.test.ts b/src/core/legacy-import/v1-generated-fixtures.test.ts
index 471ee0a5..b6204dfd 100644
--- a/src/core/legacy-import/v1-generated-fixtures.test.ts
+++ b/src/core/legacy-import/v1-generated-fixtures.test.ts
@@ -13,7 +13,7 @@ import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { gunzipSync } from 'node:zlib'
import { afterEach, describe, expect, it } from 'vitest'
-import { parseLegacySession } from './session-parser'
+import { getLegacyRequestValues, parseLegacySession } from './session-parser'
import { authorizeLegacySource, scanLegacySource } from './source-scanner'
const fixtureRoot = fileURLToPath(
@@ -109,7 +109,8 @@ describe('Motrix v1.8.19 bundled-engine generated fixtures', () => {
'follow-metalink': 'true',
'bt-load-saved-metadata': 'true',
})
- expect(http?.optionPairs.some(([key]) => key === 'user-agent')).toBe(true)
+ expect(http && getLegacyRequestValues(http)['user-agent']).toBeDefined()
+ expect(http?.optionPairs.some(([key]) => key === 'user-agent')).toBe(false)
})
it('recognizes external saved torrent metadata without reading outside the profile grant', async () => {
diff --git a/src/core/task/bt-duplicate-policy.test.ts b/src/core/task/bt-duplicate-policy.test.ts
index 1ae13036..dd78fdc6 100644
--- a/src/core/task/bt-duplicate-policy.test.ts
+++ b/src/core/task/bt-duplicate-policy.test.ts
@@ -71,6 +71,57 @@ function btTask(
}
describe('inspectBtDuplicate', () => {
+ it.each([
+ 'untouched',
+ 'has-gid',
+ 'intent',
+ 'malformed',
+ 'activating',
+ ] as const)(
+ 'handles an imported BT %s record without dropping output reservations',
+ (state) => {
+ const task = btTask({ id: 'imported', status: TaskStatus.Paused })
+ task.engineTaskId = ''
+ task.instances[0].gid = state === 'has-gid' ? '0123456789abcdef' : null
+ task.instances[0].payload = {
+ legacyImport:
+ state === 'malformed'
+ ? { version: 1 }
+ : {
+ version: 1,
+ sourceId: 'source',
+ itemKey: 'item',
+ activation: state === 'activating' ? 'activating' : 'inactive',
+ storagePolicy: 'legacy-read-only',
+ reason: 'verification-required',
+ selectionKnown: true,
+ selectedFiles: [0, 2],
+ },
+ ...(state === 'intent'
+ ? { legacyBtActivation: { stage: 'create-uncertain' } }
+ : {}),
+ }
+ const request = {
+ infoHash: INFO_HASH,
+ saveDir: '/fresh-copy',
+ selectedFiles: [0, 2],
+ duplicatePolicy: 'reuse' as const,
+ }
+ expect(inspectBtDuplicate([task], request).action).toBe(
+ state === 'untouched' ? 'create' : 'conflict'
+ )
+ if (state === 'untouched') {
+ expect(
+ inspectBtDuplicate([task], { ...request, saveDir: '/downloads' })
+ .action
+ ).toBe('conflict')
+ }
+ expect(reservedBtFinalNames([task], '/downloads')).toContain(
+ task.finalName
+ )
+ }
+ )
+
it('reuses an exact active task without starting another info hash owner', () => {
const task = btTask({ id: 'seed', status: TaskStatus.Seeding })
diff --git a/src/core/task/bt-duplicate-policy.ts b/src/core/task/bt-duplicate-policy.ts
index 574aefaf..d490d70a 100644
--- a/src/core/task/bt-duplicate-policy.ts
+++ b/src/core/task/bt-duplicate-policy.ts
@@ -4,6 +4,7 @@ import type {
TaskCreateCommandResult,
TorrentDuplicateConflict,
} from '@shared/schemas/add-task'
+import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'
import type { DownloadTask } from '@shared/types/task'
import { TaskInstancePhase, TaskStatus, TaskType } from '@shared/types/task'
import { getBtOutputReservations } from './bt-output-reservation'
@@ -268,6 +269,26 @@ function conflict(
}
export function isBtInfoHashRegistered(task: DownloadTask): boolean {
+ // An untouched import is only a read-only record, never an engine owner.
+ // Keep it in same-directory/path reservations, but permit a separate copy.
+ const instance = task.instances[0]
+ if (
+ !task.engineTaskId &&
+ task.instances.length === 1 &&
+ !instance.gid &&
+ !Object.hasOwn(instance.payload, 'legacyBtActivation')
+ ) {
+ const marker = legacyTaskMetadataSchema.safeParse(
+ instance.payload.legacyImport
+ )
+ if (
+ marker.success &&
+ marker.data.activation === 'inactive' &&
+ marker.data.storagePolicy === 'legacy-read-only'
+ )
+ return false
+ }
+
// MetadataReady has already purged its metadata-only aria2 result. Error is
// deliberately conservative: a quarantined metadata cleanup can expose an
// Error task while its engine row is still alive, so a new owner must wait
diff --git a/src/main/index.ts b/src/main/index.ts
index 4dc93363..7407264a 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1882,6 +1882,7 @@ async function initializeMainProcess(): Promise<void> {
if (!legacyHttpActivationService) {
getLegacyImportService()
legacyHttpActivationService = new LegacyHttpActivationService({
+ proxyPolicy: appliedDownloadProxyPolicy,
db: motrixDb,
taskManager,
adapter,
diff --git a/src/renderer/features/legacy-import/import-task-info.tsx b/src/renderer/features/legacy-import/import-task-info.tsx
index e1c1ef3c..38f35a4e 100644
--- a/src/renderer/features/legacy-import/import-task-info.tsx
+++ b/src/renderer/features/legacy-import/import-task-info.tsx
@@ -26,6 +26,17 @@ export function ImportTaskInfo({
{ options: optionNames.join(', ') }
)
: t(`legacyImport.reasons.${item.reason}`)
+ const ignored = item.ignoredOptions?.length
+ ? t('legacyImport.ignoredOptions', {
+ options: item.ignoredOptions.join(', '),
+ })
+ : null
+ const detail = [
+ showReason && item.reason !== 'metadata-required' ? reason : null,
+ ignored,
+ ]
+ .filter(Boolean)
+ .join(' · ')
return (
<div className="min-w-0 flex-1 space-y-0.5">
<div className="flex min-w-0 items-center gap-2">
@@ -44,12 +55,12 @@ export function ImportTaskInfo({
t('legacyImport.page.pathUnavailable')
)}
</p>
- {showReason && item.reason !== 'metadata-required' && (
+ {detail && (
<p
- title={reason}
+ title={detail}
className="truncate text-xs leading-4 text-foreground/70"
>
- {reason}
+ {detail}
</p>
)}
</div>
diff --git a/src/renderer/features/legacy-import/legacy-fresh-download.tsx b/src/renderer/features/legacy-import/legacy-fresh-download.tsx
index 37055f85..14387e15 100644
--- a/src/renderer/features/legacy-import/legacy-fresh-download.tsx
+++ b/src/renderer/features/legacy-import/legacy-fresh-download.tsx
@@ -166,6 +166,9 @@ export function LegacyFreshDownload({ task }: { task: DownloadTask }) {
return (
<>
<div className="space-y-3 rounded-md border p-3">
+ <p className="text-xs leading-5 text-muted-foreground">
+ {t('legacyImport.currentProxyDescription')}
+ </p>
<p className="text-xs leading-5 text-muted-foreground">
{availability?.available
? t('legacyImport.verifyReady')
diff --git a/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx b/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx
index 99aa6664..d1b47f01 100644
--- a/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx
+++ b/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx
@@ -209,6 +209,64 @@ describe('legacy import dialog', () => {
)
})
+ it('keeps magnet records selectable and shows omitted option names', async () => {
+ const magnetItem = {
+ ...items[0],
+ name: 'legacy-magnet',
+ type: 'magnet',
+ reason: 'metadata-required',
+ requestOptions: ['all-proxy'],
+ ignoredOptions: ['header', 'on-download-complete'],
+ }
+ const originalInvoke = vi.mocked(transport.invoke).getMockImplementation()
+ vi.mocked(transport.invoke).mockImplementation(async (channel, payload) => {
+ if (channel === Queries.ScanLegacyImport)
+ return {
+ ...preview,
+ items: [magnetItem],
+ }
+ if (
+ channel === Commands.CommitLegacyImport ||
+ channel === Queries.GetLegacyImportRun
+ )
+ return {
+ ...report,
+ items: [{ ...magnetItem, outcome: 'imported', taskId: 'new-task' }],
+ }
+ return originalInvoke?.(channel, payload)
+ })
+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)
+ await continueFromSource()
+ expect(
+ screen.getByRole('checkbox', { name: 'legacy-magnet' })
+ ).toBeChecked()
+ expect(
+ screen.getByRole('checkbox', { name: 'legacy-magnet' })
+ ).not.toHaveAttribute('aria-disabled', 'true')
+ expect(
+ screen.getByText(
+ 'Unsupported options omitted: header, on-download-complete'
+ )
+ ).toBeVisible()
+ expect(
+ screen.queryByText('Unsupported options: all-proxy')
+ ).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Migrate' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.CommitLegacyImport,
+ { previewId, itemIds: [items[0].itemId] }
+ )
+ )
+ await screen.findByRole('heading', { name: 'Migration complete' })
+ fireEvent.click(screen.getByRole('button', { name: 'View details' }))
+ expect(
+ screen.getByText(
+ 'Unsupported options omitted: header, on-download-complete'
+ )
+ ).toBeVisible()
+ })
+
it('starts at source for manual entry and preserves deselection when returning to the same source', async () => {
render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)
expect(
diff --git a/src/renderer/features/legacy-import/legacy-import-dialog.tsx b/src/renderer/features/legacy-import/legacy-import-dialog.tsx
index ed56df62..66128c21 100644
--- a/src/renderer/features/legacy-import/legacy-import-dialog.tsx
+++ b/src/renderer/features/legacy-import/legacy-import-dialog.tsx
@@ -869,15 +869,20 @@ function LegacyImportDialogContent({
className="pt-4 pb-5"
/>
{errorNotice}
- {preview?.items.some(
- (item) => item.type === 'http' && item.selectable
- ) && (
+ {preview?.items.some((item) => item.selectable) && (
<Alert
role="note"
className="mx-auto mb-3 w-full max-w-160 shrink-0"
>
<AlertDescription className="text-xs">
- {t('legacyImport.httpResumeDescription')}
+ <p>{t('legacyImport.currentProxyDescription')}</p>
+ {preview.items.some(
+ (item) => item.type === 'http' && item.selectable
+ ) && (
+ <p className="mt-1">
+ {t('legacyImport.httpResumeDescription')}
+ </p>
+ )}
</AlertDescription>
</Alert>
)}
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 03da49cb..43d2ccf2 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -3251,6 +3251,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "بالنسبة إلى ملفات تعريف الارتباط القديمة، أدخل ترويسة Cookie المطلوبة. ولأسماء مستخدمي HTTP وكلمات مرورهم، أدخل ترويسة Authorization المكافئة. أدخل بيانات اعتماد الوكيل في عنوان URL للوكيل.",
"unsupportedOptions": "الخيارات غير المدعومة: {{options}}",
+ "ignoredOptions": "تم استبعاد الخيارات غير المدعومة: {{options}}",
+ "currentProxyDescription": "تستخدم التنزيلات المنقولة إعدادات وكيل التنزيل الحالية في Motrix. لا يتم الاحتفاظ بإعدادات الوكيل القديمة.",
"requestOptions": "إعدادات الطلب المحفوظة: {{options}}",
"requestSettingsDescription": "لم تُنسخ إعدادات الطلب القديمة. أدخلها مجددًا في الإعدادات المتقدمة قبل التنزيل إلى مجلد جديد.",
"reconfigureDownload": "إعادة الإعداد والتنزيل…",
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index de54c668..920d2c3f 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "За старите файлове с бисквитки въведете необходимата заглавка Cookie. За HTTP потребителски имена и пароли въведете еквивалентна заглавка Authorization. Въведете данните за достъп до прокси сървъра в неговия URL адрес.",
"unsupportedOptions": "Неподдържани опции: {{options}}",
+ "ignoredOptions": "Пропуснати неподдържани опции: {{options}}",
+ "currentProxyDescription": "Прехвърлените изтегляния използват текущите настройки за прокси на Motrix. Старите настройки не се запазват.",
"requestOptions": "Запазени настройки на заявките: {{options}}",
"requestSettingsDescription": "Старите настройки на заявките не са копирани. Въведете ги отново в разширените настройки, преди да изтеглите в нова папка.",
"reconfigureDownload": "Настройване отново и изтегляне…",
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 8cbae4f4..b393c382 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -3185,6 +3185,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Per als fitxers de galetes anteriors, introduïu la capçalera Cookie necessària. Per als noms d’usuari i contrasenyes HTTP, introduïu una capçalera Authorization equivalent. Introduïu les credencials del servidor intermediari a l’URL del servidor intermediari.",
"unsupportedOptions": "Opcions no compatibles: {{options}}",
+ "ignoredOptions": "Opcions no compatibles omeses: {{options}}",
+ "currentProxyDescription": "Les baixades migrades utilitzen la configuració actual del servidor intermediari de Motrix. No es conserva la configuració antiga.",
"requestOptions": "Configuració de petició desada: {{options}}",
"requestSettingsDescription": "La configuració antiga de petició no s’ha copiat. Torna-la a introduir a Avançat abans de baixar en una carpeta nova.",
"reconfigureDownload": "Torna a configurar i baixa…",
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index 13391184..eb917409 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Geben Sie für alte Cookie-Dateien den benötigten Cookie-Header ein. Geben Sie für HTTP-Benutzernamen und -Passwörter einen entsprechenden Authorization-Header ein. Tragen Sie Proxy-Zugangsdaten in die Proxy-URL ein.",
"unsupportedOptions": "Nicht unterstützte Optionen: {{options}}",
+ "ignoredOptions": "Nicht unterstützte Optionen ausgelassen: {{options}}",
+ "currentProxyDescription": "Migrierte Downloads verwenden die aktuellen Download-Proxy-Einstellungen von Motrix. Alte Proxy-Einstellungen werden nicht übernommen.",
"requestOptions": "Gespeicherte Anfrageeinstellungen: {{options}}",
"requestSettingsDescription": "Die alten Anfrageeinstellungen wurden nicht kopiert. Gib sie unter Erweitert erneut ein, bevor du in einen neuen Ordner herunterlädst.",
"reconfigureDownload": "Neu konfigurieren und herunterladen…",
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 4807aa8a..516fface 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Για παλιά αρχεία cookie, εισαγάγετε την απαιτούμενη κεφαλίδα Cookie. Για ονόματα χρήστη και κωδικούς HTTP, εισαγάγετε μια αντίστοιχη κεφαλίδα Authorization. Εισαγάγετε τα διαπιστευτήρια του διακομιστή μεσολάβησης στη διεύθυνση URL του.",
"unsupportedOptions": "Μη υποστηριζόμενες επιλογές: {{options}}",
+ "ignoredOptions": "Παραλείφθηκαν μη υποστηριζόμενες επιλογές: {{options}}",
+ "currentProxyDescription": "Οι μεταφερμένες λήψεις χρησιμοποιούν τις τρέχουσες ρυθμίσεις διακομιστή μεσολάβησης του Motrix. Οι παλιές ρυθμίσεις δεν διατηρούνται.",
"requestOptions": "Αποθηκευμένες ρυθμίσεις αιτήματος: {{options}}",
"requestSettingsDescription": "Οι παλιές ρυθμίσεις αιτήματος δεν αντιγράφηκαν. Εισαγάγετέ τις ξανά στις σύνθετες ρυθμίσεις πριν από τη λήψη σε νέο φάκελο.",
"reconfigureDownload": "Νέα ρύθμιση και λήψη…",
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index b0df754c..1e4bdc0c 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "For old cookie files, enter the needed Cookie header. For HTTP usernames and passwords, enter an equivalent Authorization header. Enter proxy credentials in the proxy URL.",
"unsupportedOptions": "Unsupported options: {{options}}",
+ "ignoredOptions": "Unsupported options omitted: {{options}}",
+ "currentProxyDescription": "Migrated downloads use Motrix’s current download proxy settings. Old proxy settings are not retained.",
"requestOptions": "Saved request settings: {{options}}",
"requestSettingsDescription": "The old request settings were not copied. Enter them again in Advanced before downloading in a new folder.",
"reconfigureDownload": "Reconfigure and download…",
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 68767e0e..8f2270a2 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -3185,6 +3185,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Para los archivos de cookies anteriores, introduce la cabecera Cookie necesaria. Para los nombres de usuario y contraseñas HTTP, introduce una cabecera Authorization equivalente. Introduce las credenciales del proxy en su URL.",
"unsupportedOptions": "Opciones no compatibles: {{options}}",
+ "ignoredOptions": "Opciones no compatibles omitidas: {{options}}",
+ "currentProxyDescription": "Las descargas migradas usan la configuración actual del proxy de descargas de Motrix. No se conserva la configuración anterior.",
"requestOptions": "Ajustes de solicitud guardados: {{options}}",
"requestSettingsDescription": "Los ajustes de solicitud anteriores no se copiaron. Vuelve a introducirlos en Avanzado antes de descargar en una carpeta nueva.",
"reconfigureDownload": "Volver a configurar y descargar…",
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index a936b7d1..22cc837a 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "برای فایل‌های کوکی قبلی، سرآیند Cookie موردنیاز را وارد کنید. برای نام کاربری و گذرواژهٔ HTTP، سرآیند Authorization معادل را وارد کنید. اطلاعات ورود پروکسی را در نشانی URL پروکسی وارد کنید.",
"unsupportedOptions": "گزینه‌های پشتیبانی‌نشده: {{options}}",
+ "ignoredOptions": "گزینه‌های پشتیبانی‌نشده حذف شدند: {{options}}",
+ "currentProxyDescription": "دانلودهای منتقل‌شده از تنظیمات فعلی پراکسی دانلود Motrix استفاده می‌کنند. تنظیمات قدیمی پراکسی حفظ نمی‌شوند.",
"requestOptions": "تنظیمات ذخیره‌شدهٔ درخواست: {{options}}",
"requestSettingsDescription": "تنظیمات قدیمی درخواست کپی نشده‌اند. پیش از دانلود در پوشه‌ای جدید، آن‌ها را دوباره در بخش پیشرفته وارد کنید.",
"reconfigureDownload": "تنظیم دوباره و دانلود…",
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index 38cb06ed..eff6c44e 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -3185,6 +3185,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Pour les anciens fichiers de cookies, saisissez l’en-tête Cookie nécessaire. Pour les identifiants HTTP, saisissez un en-tête Authorization équivalent. Saisissez les identifiants du proxy dans son URL.",
"unsupportedOptions": "Options non prises en charge : {{options}}",
+ "ignoredOptions": "Options non prises en charge ignorées : {{options}}",
+ "currentProxyDescription": "Les téléchargements migrés utilisent les paramètres actuels du proxy de téléchargement de Motrix. Les anciens paramètres ne sont pas conservés.",
"requestOptions": "Paramètres de requête enregistrés : {{options}}",
"requestSettingsDescription": "Les anciens paramètres de requête n’ont pas été copiés. Saisissez-les à nouveau dans Avancé avant de télécharger dans un nouveau dossier.",
"reconfigureDownload": "Reconfigurer et télécharger…",
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 71ce6e4e..bfea18d8 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "A korábbi sütifájlok helyett adja meg a szükséges Cookie fejlécet. A HTTP-felhasználónevek és -jelszavak helyett adjon meg egy megfelelő Authorization fejlécet. A proxy hitelesítési adatait a proxy URL-jében adja meg.",
"unsupportedOptions": "Nem támogatott beállítások: {{options}}",
+ "ignoredOptions": "Kihagyott, nem támogatott beállítások: {{options}}",
+ "currentProxyDescription": "Az áthozott letöltések a Motrix jelenlegi letöltési proxybeállításait használják. A régi beállításokat nem őrizzük meg.",
"requestOptions": "Mentett kérésbeállítások: {{options}}",
"requestSettingsDescription": "A régi kérésbeállítások nem lettek átmásolva. Add meg őket újra a Speciális részben, mielőtt új mappába töltenél le.",
"reconfigureDownload": "Újrakonfigurálás és letöltés…",
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index 518ac081..8ac79837 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -3141,6 +3141,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Untuk file cookie lama, masukkan header Cookie yang diperlukan. Untuk nama pengguna dan kata sandi HTTP, masukkan header Authorization yang setara. Masukkan kredensial proksi di URL proksi.",
"unsupportedOptions": "Opsi yang tidak didukung: {{options}}",
+ "ignoredOptions": "Opsi yang tidak didukung diabaikan: {{options}}",
+ "currentProxyDescription": "Unduhan yang dimigrasikan menggunakan pengaturan proxy unduhan Motrix saat ini. Pengaturan proxy lama tidak dipertahankan.",
"requestOptions": "Pengaturan permintaan tersimpan: {{options}}",
"requestSettingsDescription": "Pengaturan permintaan lama tidak disalin. Masukkan kembali di bagian Lanjutan sebelum mengunduh ke folder baru.",
"reconfigureDownload": "Atur ulang dan unduh…",
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index 50b67ece..0129407a 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -3185,6 +3185,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Per i vecchi file cookie, inserisci l’intestazione Cookie necessaria. Per nomi utente e password HTTP, inserisci un’intestazione Authorization equivalente. Inserisci le credenziali del proxy nel relativo URL.",
"unsupportedOptions": "Opzioni non supportate: {{options}}",
+ "ignoredOptions": "Opzioni non supportate omesse: {{options}}",
+ "currentProxyDescription": "I download migrati usano le impostazioni proxy di download attuali di Motrix. Le vecchie impostazioni non vengono mantenute.",
"requestOptions": "Impostazioni di richiesta salvate: {{options}}",
"requestSettingsDescription": "Le vecchie impostazioni di richiesta non sono state copiate. Reinseriscile in Avanzate prima di scaricare in una nuova cartella.",
"reconfigureDownload": "Riconfigura e scarica…",
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index 9c457e9d..a0e0a249 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -3141,6 +3141,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "以前の Cookie ファイルについては、必要な Cookie ヘッダーを入力してください。HTTP のユーザー名とパスワードについては、同等の Authorization ヘッダーを入力してください。プロキシの認証情報はプロキシ URL に入力してください。",
"unsupportedOptions": "未対応のオプション:{{options}}",
+ "ignoredOptions": "未対応のオプションを除外しました: {{options}}",
+ "currentProxyDescription": "移行したダウンロードには Motrix の現在のダウンロード用プロキシ設定を使用します。以前のプロキシ設定は引き継ぎません。",
"requestOptions": "保存されたリクエスト設定:{{options}}",
"requestSettingsDescription": "以前のリクエスト設定はコピーされていません。新しいフォルダーにダウンロードする前に、詳細設定で再入力してください。",
"reconfigureDownload": "再設定してダウンロード…",
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index 301130d0..8f76a483 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -3141,6 +3141,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "이전 쿠키 파일을 사용했다면 필요한 Cookie 헤더를 입력하세요. HTTP 사용자 이름과 비밀번호를 사용했다면 이에 해당하는 Authorization 헤더를 입력하세요. 프록시 인증 정보는 프록시 URL에 입력하세요.",
"unsupportedOptions": "지원하지 않는 옵션: {{options}}",
+ "ignoredOptions": "지원하지 않는 옵션 제외: {{options}}",
+ "currentProxyDescription": "이전한 다운로드에는 Motrix의 현재 다운로드 프록시 설정이 적용됩니다. 이전 프록시 설정은 유지되지 않습니다.",
"requestOptions": "저장된 요청 설정: {{options}}",
"requestSettingsDescription": "이전 요청 설정은 복사되지 않았습니다. 새 폴더에 다운로드하기 전에 고급 설정에서 다시 입력하세요.",
"reconfigureDownload": "다시 설정하고 다운로드…",
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index d218afe5..6f223c42 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "For gamle informasjonskapselfiler angir du den nødvendige Cookie-headeren. For HTTP-brukernavn og -passord angir du en tilsvarende Authorization-header. Angi proxyens påloggingsinformasjon i proxy-URL-en.",
"unsupportedOptions": "Alternativer som ikke støttes: {{options}}",
+ "ignoredOptions": "Alternativer som ikke støttes, er utelatt: {{options}}",
+ "currentProxyDescription": "Migrerte nedlastinger bruker de gjeldende proxyinnstillingene for nedlasting i Motrix. Gamle proxyinnstillinger beholdes ikke.",
"requestOptions": "Lagrede forespørselsinnstillinger: {{options}}",
"requestSettingsDescription": "De gamle forespørselsinnstillingene ble ikke kopiert. Skriv dem inn på nytt under Avansert før du laster ned til en ny mappe.",
"reconfigureDownload": "Konfigurer på nytt og last ned…",
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index 78f4fe44..c70e58a9 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Voer voor oude cookiebestanden de benodigde Cookie-header in. Voer voor HTTP-gebruikersnamen en -wachtwoorden een gelijkwaardige Authorization-header in. Voer proxy-inloggegevens in de proxy-URL in.",
"unsupportedOptions": "Niet-ondersteunde opties: {{options}}",
+ "ignoredOptions": "Niet-ondersteunde opties overgeslagen: {{options}}",
+ "currentProxyDescription": "Gemigreerde downloads gebruiken de huidige downloadproxyinstellingen van Motrix. Oude proxyinstellingen worden niet behouden.",
"requestOptions": "Opgeslagen verzoekinstellingen: {{options}}",
"requestSettingsDescription": "De oude verzoekinstellingen zijn niet gekopieerd. Vul ze opnieuw in bij Geavanceerd voordat je naar een nieuwe map downloadt.",
"reconfigureDownload": "Opnieuw configureren en downloaden…",
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index 4f6ebd73..92084163 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -3207,6 +3207,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "W przypadku starych plików cookie wprowadź wymagany nagłówek Cookie. W przypadku nazw użytkowników i haseł HTTP wprowadź równoważny nagłówek Authorization. Dane uwierzytelniające serwera proxy wpisz w jego adresie URL.",
"unsupportedOptions": "Nieobsługiwane opcje: {{options}}",
+ "ignoredOptions": "Pominięte nieobsługiwane opcje: {{options}}",
+ "currentProxyDescription": "Przeniesione pobierania używają bieżących ustawień proxy pobierania Motrix. Stare ustawienia nie są zachowywane.",
"requestOptions": "Zapisane ustawienia żądania: {{options}}",
"requestSettingsDescription": "Stare ustawienia żądania nie zostały skopiowane. Wprowadź je ponownie w ustawieniach zaawansowanych przed pobraniem do nowego folderu.",
"reconfigureDownload": "Skonfiguruj ponownie i pobierz…",
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 70cbfcae..5bafb9a2 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -3185,6 +3185,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Para arquivos de cookies antigos, insira o cabeçalho Cookie necessário. Para nomes de usuário e senhas HTTP, insira um cabeçalho Authorization equivalente. Insira as credenciais do proxy na URL do proxy.",
"unsupportedOptions": "Opções não compatíveis: {{options}}",
+ "ignoredOptions": "Opções não compatíveis omitidas: {{options}}",
+ "currentProxyDescription": "Os downloads migrados usam as configurações atuais de proxy de download do Motrix. As configurações antigas não são mantidas.",
"requestOptions": "Configurações de solicitação salvas: {{options}}",
"requestSettingsDescription": "As configurações antigas de solicitação não foram copiadas. Insira-as novamente em Avançado antes de baixar em uma nova pasta.",
"reconfigureDownload": "Reconfigurar e baixar…",
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index 2808c482..ff4e62d7 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -3185,6 +3185,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Pentru vechile fișiere cookie, introduceți antetul Cookie necesar. Pentru numele de utilizator și parolele HTTP, introduceți un antet Authorization echivalent. Introduceți datele de autentificare ale proxy-ului în URL-ul acestuia.",
"unsupportedOptions": "Opțiuni neacceptate: {{options}}",
+ "ignoredOptions": "Opțiuni neacceptate omise: {{options}}",
+ "currentProxyDescription": "Descărcările migrate folosesc setările proxy actuale pentru descărcare din Motrix. Setările vechi nu sunt păstrate.",
"requestOptions": "Setări de cerere salvate: {{options}}",
"requestSettingsDescription": "Setările vechi de cerere nu au fost copiate. Introdu-le din nou în Avansat înainte de a descărca într-un dosar nou.",
"reconfigureDownload": "Reconfigurați și descărcați…",
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index e0b8ccef..ded14357 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -3207,6 +3207,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Для прежних файлов cookie введите нужный заголовок Cookie. Для имён пользователей и паролей HTTP введите соответствующий заголовок Authorization. Укажите учётные данные прокси в его URL.",
"unsupportedOptions": "Неподдерживаемые параметры: {{options}}",
+ "ignoredOptions": "Неподдерживаемые параметры пропущены: {{options}}",
+ "currentProxyDescription": "Перенесённые загрузки используют текущие настройки прокси загрузок Motrix. Старые настройки не сохраняются.",
"requestOptions": "Сохранённые настройки запроса: {{options}}",
"requestSettingsDescription": "Прежние настройки запроса не скопированы. Введите их заново в расширенных настройках перед загрузкой в новую папку.",
"reconfigureDownload": "Настроить заново и скачать…",
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 380f1b0a..2517ad02 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -3141,6 +3141,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "สำหรับไฟล์คุกกี้เดิม ให้ป้อนส่วนหัว Cookie ที่จำเป็น สำหรับชื่อผู้ใช้และรหัสผ่าน HTTP ให้ป้อนส่วนหัว Authorization ที่เทียบเท่ากัน ป้อนข้อมูลรับรองพร็อกซีใน URL ของพร็อกซี",
"unsupportedOptions": "ตัวเลือกที่ไม่รองรับ: {{options}}",
+ "ignoredOptions": "ละเว้นตัวเลือกที่ไม่รองรับ: {{options}}",
+ "currentProxyDescription": "การดาวน์โหลดที่ย้ายมาใช้การตั้งค่าพร็อกซีดาวน์โหลดปัจจุบันของ Motrix โดยไม่เก็บการตั้งค่าพร็อกซีเดิม",
"requestOptions": "การตั้งค่าคำขอที่บันทึกไว้: {{options}}",
"requestSettingsDescription": "ไม่ได้คัดลอกการตั้งค่าคำขอเดิม โปรดกรอกอีกครั้งในขั้นสูงก่อนดาวน์โหลดลงโฟลเดอร์ใหม่",
"reconfigureDownload": "ตั้งค่าใหม่และดาวน์โหลด…",
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index d6f27d71..632bed0e 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -3163,6 +3163,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Eski çerez dosyaları için gerekli Cookie üstbilgisini girin. HTTP kullanıcı adları ve parolaları için eşdeğer bir Authorization üstbilgisi girin. Proxy kimlik bilgilerini proxy URL’sine girin.",
"unsupportedOptions": "Desteklenmeyen seçenekler: {{options}}",
+ "ignoredOptions": "Desteklenmeyen seçenekler atlandı: {{options}}",
+ "currentProxyDescription": "Taşınan indirmeler Motrix’in geçerli indirme proxy ayarlarını kullanır. Eski proxy ayarları korunmaz.",
"requestOptions": "Kaydedilmiş istek ayarları: {{options}}",
"requestSettingsDescription": "Eski istek ayarları kopyalanmadı. Yeni bir klasöre indirmeden önce Gelişmiş bölümünde yeniden girin.",
"reconfigureDownload": "Yeniden yapılandır ve indir…",
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index 788d6742..a38f0ccf 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -3207,6 +3207,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Для попередніх файлів cookie введіть потрібний заголовок Cookie. Для імен користувачів і паролів HTTP введіть відповідний заголовок Authorization. Вкажіть облікові дані проксі в його URL.",
"unsupportedOptions": "Непідтримувані параметри: {{options}}",
+ "ignoredOptions": "Непідтримувані параметри пропущено: {{options}}",
+ "currentProxyDescription": "Перенесені завантаження використовують поточні налаштування проксі завантажень Motrix. Старі налаштування не зберігаються.",
"requestOptions": "Збережені налаштування запиту: {{options}}",
"requestSettingsDescription": "Старі налаштування запиту не скопійовано. Введіть їх знову в розширених налаштуваннях перед завантаженням у нову теку.",
"reconfigureDownload": "Налаштувати знову та завантажити…",
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index e92319b7..fad4a263 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -3141,6 +3141,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "Với các tệp cookie cũ, hãy nhập tiêu đề Cookie cần thiết. Với tên người dùng và mật khẩu HTTP, hãy nhập tiêu đề Authorization tương đương. Nhập thông tin xác thực proxy trong URL proxy.",
"unsupportedOptions": "Tùy chọn không được hỗ trợ: {{options}}",
+ "ignoredOptions": "Đã bỏ qua các tùy chọn không được hỗ trợ: {{options}}",
+ "currentProxyDescription": "Các lượt tải được chuyển sang dùng cài đặt proxy tải xuống hiện tại của Motrix. Cài đặt proxy cũ không được giữ lại.",
"requestOptions": "Cài đặt yêu cầu đã lưu: {{options}}",
"requestSettingsDescription": "Các cài đặt yêu cầu cũ chưa được sao chép. Hãy nhập lại trong phần Nâng cao trước khi tải vào thư mục mới.",
"reconfigureDownload": "Cấu hình lại và tải xuống…",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index dc95e71f..3bd7d634 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -3141,6 +3141,8 @@
"chooseDestination": "选择其他位置…",
"requestSettingsHelp": "旧版 Cookie 文件中的信息,请填写为所需的 Cookie 请求头。旧版 HTTP 用户名和密码,请填写为等效的 Authorization 请求头。代理凭据请填写在代理 URL 中。",
"unsupportedOptions": "不支持的选项:{{options}}",
+ "ignoredOptions": "已剔除不支持的参数:{{options}}",
+ "currentProxyDescription": "迁移后的下载使用 Motrix 当前的下载代理设置,不保留旧代理设置。",
"requestOptions": "已保存的请求设置:{{options}}",
"requestSettingsDescription": "旧版请求设置未复制。请在“高级”中重新填写后,下载到新文件夹。",
"reconfigureDownload": "重新配置并下载…",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index fedfbdbe..b5b27a5f 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -3141,6 +3141,8 @@
"chooseDestination": "Choose another location…",
"requestSettingsHelp": "舊版 Cookie 檔案中的資訊,請填寫為所需的 Cookie 請求標頭。舊版 HTTP 使用者名稱和密碼,請填寫為等效的 Authorization 請求標頭。代理伺服器憑證請填寫在代理伺服器 URL 中。",
"unsupportedOptions": "不支援的選項:{{options}}",
+ "ignoredOptions": "已移除不支援的參數:{{options}}",
+ "currentProxyDescription": "遷移後的下載使用 Motrix 目前的下載代理設定,不保留舊代理設定。",
"requestOptions": "已儲存的請求設定:{{options}}",
"requestSettingsDescription": "舊版請求設定未複製。請在「進階」中重新填寫後,下載到新資料夾。",
"reconfigureDownload": "重新設定並下載…",
diff --git a/src/shared/schemas/legacy-import.ts b/src/shared/schemas/legacy-import.ts
index d116cae7..c3c58226 100644
--- a/src/shared/schemas/legacy-import.ts
+++ b/src/shared/schemas/legacy-import.ts
@@ -49,6 +49,7 @@ export const legacyImportItemSchema = z.object({
selectable: z.boolean(),
reason: legacyReasonSchema,
requestOptions: legacyOptionNamesSchema.optional(),
+ ignoredOptions: legacyOptionNamesSchema.optional(),
unsupportedOptions: legacyOptionNamesSchema.optional(),
})
export type LegacyImportItem = z.infer<typeof legacyImportItemSchema>
@@ -144,6 +145,7 @@ export const legacyTaskMetadataSchema = z
]),
reason: legacyReasonSchema,
requestOptions: legacyOptionNamesSchema.optional(),
+ ignoredOptions: legacyOptionNamesSchema.optional(),
selectionKnown: z.boolean(),
selectedFiles: z.array(z.number().int().nonnegative()).max(10000),
origin: z
diff --git a/src/test-utils/legacy-http-service.ts b/src/test-utils/legacy-http-service.ts
index 6679900a..ca6ffac8 100644
--- a/src/test-utils/legacy-http-service.ts
+++ b/src/test-utils/legacy-http-service.ts
@@ -17,6 +17,7 @@ import {
LegacyHttpActivationService,
} from '@core/legacy-import/http-activation-service'
import { authorizeLegacySource } from '@core/legacy-import/source-scanner'
+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'
import type {
MotrixDatabase,
TaskWithInstances,
@@ -191,7 +192,9 @@ export async function legacyHttpActivationFixture(options: {
} as unknown as MotrixDatabase
const taskManager = new TaskManager()
taskManager.set(taskId, taskRowToDownloadTask(row.task, row.instances))
+ const proxyPolicy = new AppliedDownloadProxyPolicy({ noProxy: '' })
const deps: LegacyHttpActivationDeps = {
+ proxyPolicy,
db,
taskManager,
adapter: options.adapter,
@@ -204,6 +207,7 @@ export async function legacyHttpActivationFixture(options: {
}
const service = new LegacyHttpActivationService(deps)
return {
+ proxyPolicy,
root,
profile,
downloads,